কম্পিউটার বিজ্ঞান · বই 4 · স্নাতক দ্বিতীয় বর্ষ

University Computer Science — Year 2

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।

University Computer Science — Year 2 · স্নাতক দ্বিতীয় বর্ষ

23Context-Free Grammars and Pushdown Automata

Chapter 22 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:

    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 and 22: words, languages, DFAs and NFAs, regular expressions, the pumping lemma for regular languages, {anbn}\{a^nb^n\} not regular, closure of regular languages under intersection. The Year 1 volume: trees, their height, a binary tree of height hh has at most 2h2^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,Σ,P,S)G = (N, \Sigma, P, S): a finite set NN of nonterminals, an alphabet Σ\Sigma of terminals disjoint from NN, a finite set PP of productions A→αA \to \alpha with A∈NA \in N and α∈(N∪Σ)∗\alpha \in (N \cup \Sigma)^*, and a start symbol S∈NS \in N. Productions with the same left side are written together, A→α∣βA \to \alpha \mid \beta.

Definition 23.2 (Derivation, generated language)

A word over N∪ΣN \cup \Sigma is a sentential form. If A→αA \to \alpha is a production, βAγ⇒βαγ\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 GG is L(G)={w∈Σ∗:S⇒∗w}L(G) = \{w \in \Sigma^* : S \Rightarrow^* w\}. A language is context-free if some context-free grammar generates it.

“Context-free” says that a nonterminal is replaced whatever surrounds it. The listings write a grammar one nonterminal per line, a name with a capital for a nonterminal, 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→E+E∣E∗E∣(E)∣aE \to E + E \mid E * E \mid (E) \mid a, with aa standing for any number or name;
  • propositional formulas over the variables pp, qq: F→F∨F∣F∧F∣¬F∣(F)∣p∣qF \to F \vee F \mid F \wedge F \mid \neg F \mid (F) \mid p \mid q;
  • a toy markup, where ww is a word, [ ⋯ ][\,\cdots] a link and ∗⋯∗*\cdots* bold text: D→D D∣w∣∗D∗∣[D]D \to D\,D \mid w \mid *D* \mid [D].

The derivations of ()()()() from S→(S)S∣εS \to (S)S \mid \varepsilon include S⇒(S)S⇒()S⇒()(S)S⇒()()S⇒()()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 the concatenations of what the symbols of its right sides already derive, cut at a length nn, until nothing changes.

Definition 23.3 (Right-linear grammar)

A grammar is right-linear if every production is A→uBA \to uB or A→uA \to u, with u∈Σ∗u \in \Sigma^* and B∈NB \in N: a nonterminal, if any, comes last.

Proposition 23.4 (Regular languages are context-free)

A language is regular if and only if a right-linear grammar generates it. So every regular language is context-free, and {anbn:n≥0}\{a^nb^n : n \ge 0\}, generated by S→aSb∣εS \to aSb \mid \varepsilon, shows the inclusion is strict.

Proof. From a DFA, take one nonterminal per state, the start state as start symbol, a production q→a δ(q,a)q \to a\,\delta(q, a) per transition and q→εq \to \varepsilon per accepting state: a derivation q0⇒a1q1⇒a1a2q2⇒⋯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. Conversely, cut each production A→a1⋯akBA \to a_1 \cdots a_k B into a chain of kk transitions through k−1k - 1 new states, from state AA to state BB (a spontaneous one if k=0k = 0), and each A→a1⋯akA \to a_1 \cdots a_k into a chain to one new accepting state: the NFA’s runs follow the derivations, and Chapter 21 makes it deterministic. ∎

23.2 Parse trees and ambiguity

Definition 23.5 (Parse tree, leftmost and rightmost derivation)

A parse tree for GG is an ordered tree whose root is SS, whose inner nodes are nonterminals, whose leaves are terminals or ε\varepsilon, and where the children of each inner node AA, read from left to right, are the right side of a production A→αA \to \alpha. Its yield is its leaves read from left to right. A derivation is leftmost if each step replaces the leftmost nonterminal, and rightmost if each replaces the rightmost one.

A word is in L(G)L(G) exactly when it is the yield of a parse tree, and parse trees, leftmost derivations and rightmost derivations of a word are in bijection: a tree is turned into its leftmost derivation by expanding its nodes in preorder, and a derivation into a tree by hanging each production’s right side under the node it expands. The method leftmost finds a leftmost derivation by a breadth-first search over sentential forms, dropping those whose first terminals 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 per level of priority, and the leftmost derivation of a+a∗aa + a * a.

Definition 23.6 (Ambiguous grammar, weak equivalence)

A grammar is ambiguous if some word has two different parse trees. 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→E+E∣E∗E∣(E)∣aE \to E + E \mid E * E \mid (E) \mid a, a+a∗aa + 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. 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.
Two parse trees of a+a∗aa + a * a in the grammar E→E+E∣E∗E∣(E)∣aE \to E + E \mid E * E \mid (E) \mid a. Left: a+(a∗a)a + (a * a); right: (a+a)∗a(a + a) * a.

The grammar of Output 23.2 removes the ambiguity with one nonterminal per level: an expression EE is a sum of terms TT, a term a product of factors FF, 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→E+TE \to E + T has its recursion on the left, a+a+aa + a + a groups as (a+a)+a(a + a) + a. The function trees of count.rs counts parse trees 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 counted in the flat and the levelled expression grammars, then in two grammars of if…else.

The two expression grammars are weakly equivalent, as the program checks up to length 7. The second pair is the dangling else: with ii for “if a condition then”, ee for “else” and xx for any other statement, S→iS∣iSeS∣xS \to iS \mid iSeS \mid x gives iixexiixex 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). The dangling else: in iixex, the else belongs to the inner if (left) or to the outer one (right).
The dangling else: in iixexiixex, 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→M∣US \to M \mid U, M→iMeM∣xM \to iMeM \mid x, U→iS∣iMeUU \to iS \mid iMeU writes the rule down: between an ii and its ee only a matched statement MM, every ii of which has its ee, may appear. It is weakly equivalent to the first and unambiguous on every word the program tried. Some context-free languages have no unambiguous grammar at all, and no program can decide in general whether a grammar is 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→BCA \to BC with B,CB, C nonterminals, or A→aA \to a with aa a terminal, except possibly S→εS \to \varepsilon when the start symbol SS appears in no right side. Its size ∣G∣|G| is the sum over the productions of one plus the length of the right side.

Method 23.8 (Conversion to Chomsky normal form)

Apply in this order:

  1. START: if SS derives ε\varepsilon and appears in a right side, add a new start S0→SS_0 \to S;
  2. TERM: in every right side of length at least 2, replace each terminal cc by a new nonterminal written 'c', with 'c' →c\to c;
  3. BIN: cut every A→X1X2⋯XkA \to X_1 X_2 \cdots X_k with k≥3k \ge 3 into A→X1Y1A \to X_1 Y_1, Y1→X2Y2Y_1 \to X_2 Y_2, …, Yk−2→Xk−1XkY_{k-2} \to X_{k-1} X_k, with new nonterminals YiY_i;
  4. DEL: compute the nullable nonterminals (those that derive ε\varepsilon); for every production, add each version with some nullable occurrences dropped; then remove every A→εA \to \varepsilon except S→εS \to \varepsilon;
  5. UNIT: for each AA, find by a graph search the nonterminals BB with A⇒∗BA \Rightarrow^* B through productions with one nonterminal on the right; give AA every non-unit production of each such BB; remove the unit productions.
    /// 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 and for the pieces of long right sides code/bachelor-2/23-context-free-languages/listings/grammar.rs
        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 that generates L(G)L(G), of size at most proportional to ∣G∣2|G|^2.

Proof. START, TERM and BIN keep the language: each new nonterminal derives exactly the piece it replaces. DEL: if a version drops nullable symbols, the dropped symbols could derive ε\varepsilon in GG, so nothing new is generated; conversely, in a 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 A⇒B⇒⋯⇒C⇒αA \Rightarrow B \Rightarrow \cdots \Rightarrow C \Rightarrow \alpha in a derivation is replaced by the one production A→αA \to \alpha, and every new production stands for such a chain; the search stops on a cycle of unit productions because it visits each nonterminal 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∣|G| up to that point. UNIT gives each of at most ∣G∣|G| nonterminals a copy of at most all the productions: at most ∣G∣2|G|^2. ∎

The order matters: DEL before BIN would make 2k2^k versions of a right side with kk 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, and a check of its words.

The unit productions E→TE \to T and T→FT \to F are gone: EE now has the productions of TT and FF as well.

23.4 The CYK algorithm

In Chomsky normal form, a nonterminal derives a word of length at least 2 by splitting it into two nonempty parts, derived by the two nonterminals 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 GG be in Chomsky normal form and w=a1⋯anw = a_1 \cdots a_n nonempty. For the factor of length ℓ\ell starting after position ii, compute the set T[i][ℓ]T[i][\ell] of nonterminals that derive it: T[i][1]={A:A→ai+1}T[i][1] = \{A : A \to a_{i+1}\}, and for ℓ=2,…,n\ell = 2, \dots, n, T[i][ℓ]T[i][\ell] holds AA whenever there are a production A→BCA \to BC and a split 1≤k<ℓ1 \le k < \ell with B∈T[i][k]B \in T[i][k] and C∈T[i+k][ℓ−k]C \in T[i + k][\ell - k]. Then w∈L(G)w \in L(G) if and only if S∈T[0][n]S \in T[0][n].

    /// 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∗aa + 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.
The CYK table of a+a∗aa + a * a as a pyramid: each cell sits above the factor it covers. The top cell holds EE, so the word is an expression; the cell over a+aa + a holds EE, and the one over a∗aa * a holds EE and TT.

Theorem 23.11 (CYK)

The CYK algorithm decides whether w∈L(G)w \in L(G). It examines (n3−n)/6(n^3 - n)/6 split points, each against every production A→BCA \to BC, so its time is proportional to n3∣G∣n^3 |G|.

Proof. By induction on ℓ\ell, A∈T[i][ℓ]A \in T[i][\ell] if and only if A⇒∗ai+1⋯ai+ℓA \Rightarrow^* a_{i+1} \cdots a_{i+\ell}. For ℓ=1\ell = 1, in Chomsky normal form a nonterminal derives a letter only through a production A→aA \to a. For ℓ≥2\ell \ge 2, a derivation of the factor starts with some A→BCA \to BC, and BB and CC then derive a nonempty prefix of length kk and the rest, which by the hypothesis is when B∈T[i][k]B \in T[i][k] and C∈T[i+k][ℓ−k]C \in T[i + k][\ell - k]. For the count: a factor of length ℓ\ell has ℓ−1\ell - 1 split points, and there are n−ℓ+1n - \ell + 1 factors of that length, so the number of split points is

∑ℓ=2n(n−ℓ+1)(ℓ−1)=∑j=1n−1(n−j)j=n(n−1)n2−(n−1)n(2n−1)6=n3−n6.\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, a product for each split and a sum over splits and productions, counts the parse trees of the word. For E→E+E∣aE \to E + E \mid a on a+a+⋯+aa + a + \cdots + a with kk operands, a tree chooses the ++ at its root and then trees for both sides, the recurrence of the Catalan numbers, Ck−1=1k(2k−2k−1)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 of a sum of kk operands in the ambiguous grammar, against the Catalan numbers.

One 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).

History

Noam Chomsky described phrase-structure grammars, the context-free 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,Σ,Γ,Δ,q0,Z0,F)(Q, \Sigma, \Gamma, \Delta, q_0, Z_0, F): a finite set of states QQ, an input alphabet Σ\Sigma, a stack alphabet Γ\Gamma, a finite set Δ\Delta of moves (q,x,Z)→(q′,γ)(q, x, Z) \to (q', \gamma) with x∈Σ∪{ε}x \in \Sigma \cup \{\varepsilon\}, Z∈ΓZ \in \Gamma and γ∈Γ∗\gamma \in \Gamma^*, a start state q0q_0, a bottom symbol Z0∈ΓZ_0 \in \Gamma, and accepting states F⊆QF \subseteq Q. In state qq with ZZ on top of the stack, the move reads xx (nothing if x=εx = \varepsilon), goes to q′q' and replaces ZZ by γ\gamma, whose first symbol ends on top. A configuration is a state, the unread input and the stack. The automaton accepts ww if some sequence of moves leads from (q0,w,Z0)(q_0, w, Z_0) to a configuration with no input left and an accepting state.

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.
A PDA for {anbn}\{a^nb^n\}. A label x,Z/γx, Z / \gamma reads xx with ZZ on top and replaces it by γ\gamma. State 0 pushes an AA per aa; the move to 1 guesses the middle; state 1 pops an AA per bb; state 2 is reached when only the bottom ZZ 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:

    /// 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→(S)S∣εS \to (S)S \mid \varepsilon by Theorem 23.13.

Theorem 23.13 (From a grammar to a pushdown automaton)

For every context-free grammar GG there is a PDA with three states that recognises L(G)L(G).

Proof. Stack alphabet N∪Σ∪{$}N \cup \Sigma \cup \{\$\}, states 0, 1, 2, accepting 2. Moves: (0,ε,$)→(1,S$)(0, \varepsilon, \$) \to (1, S\$); for each production A→αA \to \alpha, (1,ε,A)→(1,α)(1, \varepsilon, A) \to (1, \alpha); for each terminal aa, (1,a,a)→(1,ε)(1, a, a) \to (1, \varepsilon); and (1,ε,$)→(2,ε)(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$)(1, xy, S\$) to (1,y,α$)(1, y, \alpha\$) exactly when there is a leftmost derivation S⇒∗xαS \Rightarrow^* x\alpha with xx the terminals already matched and α\alpha empty or starting with a nonterminal (or, between two steps, with a terminal still to match). An expansion move is a step of the derivation; a matching move reads a letter that the derivation has already produced. So the automaton reaches (1,ε,$)(1, \varepsilon, \$), and then state 2, exactly when S⇒∗wS \Rightarrow^* w. ∎

Theorem 23.14 (From a pushdown automaton to a grammar)

For every PDA there is a context-free grammar that generates the language it recognises. So the context-free languages are exactly the languages recognised by pushdown automata.

Proof. Admitted at this level. ∎

The proof builds a nonterminal 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 {anbn}\{a^nb^n\} guesses the middle, though a deterministic one exists (the first bb 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 LL is context-free, there is pp such that every z∈Lz \in L with ∣z∣≥p|z| \ge p can be written z=uvwxyz = uvwxy with ∣vwx∣≤p|vwx| \le p and vx≠εvx \ne \varepsilon, so that uviwxiy∈Luv^iwx^iy \in L for every i≥0i \ge 0.

Proof. Take a grammar for LL in Chomsky normal form, with kk nonterminals, and p=2kp = 2^k. A parse tree in this form is binary above its leaves: if its longest path from the root to a terminal has hh nonterminals, the word has at most 2h−12^{h-1} letters. So for ∣z∣≥2k|z| \ge 2^k the tree has a path with at least k+1k + 1 nonterminals, and among the lowest k+1k + 1 of them some AA appears twice. Let the upper AA derive vwxvwx and the lower AA derive ww, and z=uvwxyz = uvwxy. The subtree of the upper AA has paths of at most k+1k + 1 nonterminals, so ∣vwx∣≤2k=p|vwx| \le 2^k = p. The upper AA has two children, the lower AA lies under one of them, and the other derives a nonempty word that is part of vv or xx: vx≠εvx \ne \varepsilon. Replacing the lower subtree by a copy of the upper one, i−1i - 1 times, or the upper by the lower, gives trees of uviwxiyuv^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.
A long word has a tall tree, and a tall path repeats a nonterminal AA. The upper AA derives vwxvwx, the lower one ww; either subtree can stand in for the other, which pumps vv and xx together.

Proposition 23.16 (Closure)

Context-free languages are closed under union, concatenation and star, and under intersection with a regular language. They are not closed under intersection or complement. The language {anbncn:n≥0}\{a^nb^nc^n : n \ge 0\} is not context-free.

Proof. With start symbols S1S_1, S2S_2 and disjoint nonterminals, S→S1∣S2S \to S_1 \mid S_2, S→S1S2S \to S_1 S_2 and S→S1S∣εS \to S_1 S \mid \varepsilon give the union, the concatenation and the star. Intersection with a regular language is Exercise 23.12. For {anbncn}\{a^nb^nc^n\}, take z=apbpcpz = a^pb^pc^p: since ∣vwx∣≤p|vwx| \le p, vwxvwx meets at most two of the three blocks, so pumping with i=2i = 2 changes the number of at most two of the letters (or breaks their order) and leaves the word outside the language. Now {anbncm}\{a^nb^nc^m\} and {ambncn}\{a^mb^nc^n\} are context-free, by S→TCS \to TC, T→aTb∣εT \to aTb \mid \varepsilon, C→cC∣εC \to cC \mid \varepsilon and a symmetric grammar, and their intersection is {anbncn}\{a^nb^nc^n\}: no closure under intersection. Since L∩ML \cap M is the complement of the union of the complements, closure under complement would give closure under intersection. ∎

A pushdown automaton has one stack, and anbncna^nb^nc^n needs to count twice. The same argument, applied after an intersection with a+b+a+b+a^+b^+a^+b^+, shows that {ww}\{ww\} is not context-free either (Exercise 23.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 of (a)∗a(a) * a in the grammar with levels of Output 23.2, and draw its parse tree.

Solution

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 of (a)∗a(a) * a.

The tree: EE has one child TT; that TT has the children TT, ∗*, FF; the left TT goes down through FF to (E)(E), whose EE goes down through TT and FF to aa; the right FF is aa. Its nine inner nodes are the eight steps plus the start symbol EE.

Exercise 23.2 ★

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

Solution

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⇒(S)S⇒()S⇒())S(S⇒())(S⇒())(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 word has equal numbers. Conversely, let ww be nonempty with equal numbers, say starting with ((, and let (u)(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 uu and the rest vv both have equal numbers; by induction on the length they are generated, and S→(S)SS \to (S)S gives ww. A word starting with )) is handled by S→)S(SS \to )S(S in the same way.

Exercise 23.3 ★

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

Solution

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→aPa∣bPb∣a∣b∣ε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. There are 2⌈n/2⌉2^{\lceil n/2 \rceil} palindromes of length nn, and 1+2+2+4+4+⋯+64+64=2531 + 2 + 2 + 4 + 4 + \cdots + 64 + 64 = 253 up to length 12.

Exercise 23.4 ★

Draw the parse trees of a+a+a+aa + a + a + a in E→E+E∣E∗E∣(E)∣aE \to E + E \mid E * E \mid (E) \mid a. How many are there, and how many does the grammar with levels give?

Solution

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, (a+a)+(a+a)(a + a) + (a + a), a+((a+a)+a)a + ((a + a) + a) and a+(a+(a+a))a + (a + (a + a)); this is C3=5C_3 = 5. The grammar with levels gives one, the first, since E→E+TE \to E + T puts the last addition at the root (Output 23.3).

Exercise 23.5 ★★

For S→AB∣ACS \to AB \mid AC, C→SBC \to SB, A→aA \to a, B→bB \to b, fill the CYK tables of aabbaabb and abababab. Which language does the grammar generate?

Solution

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 aabbaabb: the letters give A,A,B,BA, A, B, B; the middle abab is SS by S→ABS \to AB; abbabb is CC by C→SBC \to SB; the whole word is SS by S→ACS \to AC. For abababab the two abab are SS, but nothing derives abaaba, babbab or the whole word. S→ABS \to AB gives abab and S→AC→aSbS \to AC \to aSb wraps a word of the language in a⋯ba \cdots b: the language is {anbn:n≥1}\{a^nb^n : n \ge 1\}.

Exercise 23.6 ★★

A program removes unit productions by following them recursively from each nonterminal. What happens on S→A∣abS \to A \mid ab, A→B∣aA \to B \mid a, B→A∣bB \to A \mid b? How does Method 23.8 avoid it, and what does it produce?

Solution

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→BA \to B then B→AB \to A leads back to AA, 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 and visits each nonterminal at most once, so from SS it reaches {S,A,B}\{S, A, B\} and gives SS the productions abab, aa and bb; AA and BB are then no longer reachable from SS and are dropped.

Exercise 23.7 ★★

Write a recogniser for S→TS∣cS \to TS \mid c, T→aSbT \to aSb with one function per nonterminal, each reading one word of its nonterminal 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}\{a, b, c\}.

Solution

Solution of Exercise 23.7.

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 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 of SS start with different letters, cc or the aa of TT, so one letter decides; TT has one production. Each function returns whether it read one word of its nonterminal, moving the position past it, and the whole word is accepted when SS succeeds and nothing is left. Every word of the language has a length 3k+13k + 1.

Exercise 23.8 ★★

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

Solution

Solution of Exercise 23.8.

Every generated word is balanced, by induction on the derivation: ε\varepsilon is, and if uu and vv are, so is (u)v(u)v: its numbers are equal, a prefix inside (u(u has one more (( than a prefix of uu, and a prefix (u)v′(u)v' has as many of each as v′v'. Conversely, by strong induction on the length: let ww be balanced and nonempty. Its first letter is ((, since the prefix of length 1 cannot have more )). Let (u)(u) be the shortest nonempty prefix with as many )) as ((; inside it the difference stays positive, so uu is balanced, and the rest vv is balanced too (its prefixes add to a balanced prefix). Both are shorter than ww, so S⇒∗uS \Rightarrow^* u and S⇒∗vS \Rightarrow^* v, and S⇒(S)S⇒∗(u)v=wS \Rightarrow (S)S \Rightarrow^* (u)v = w.

Exercise 23.9 ★★

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

Solution

Solution of Exercise 23.9.

    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: kk symbols AA above the bottom if kk more aa than bb have been read, kk symbols BB if kk more bb. An aa pushes an AA unless a BB is on top, which it pops; symmetrically for bb. 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, 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∈{a,b}∗}\{ww : w \in \{a, b\}^*\} is not context-free. Use Exercise 23.12 with the regular language a+b+a+b+a^+b^+a^+b^+.

Solution

Solution of Exercise 23.10.

Let L={ww}L = \{ww\} and R=a+b+a+b+R = a^+b^+a^+b^+. If LL were context-free, so would be L∩R={aibjaibj:i,j≥1}L \cap R = \{a^ib^ja^ib^j : i, j \ge 1\} (Exercise 23.12). Take pp from Theorem 23.15 and z=apbpapbpz = a^pb^pa^pb^p. Since ∣vwx∣≤p|vwx| \le p, vwxvwx lies inside one block or across two adjacent ones. If vv or xx contains two different letters, uv2wx2yuv^2wx^2y is not in RR. Otherwise pumping with i=2i = 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 uv2wx2y∉L∩Ruv^2wx^2y \notin L \cap R, a contradiction.

Exercise 23.11 ★★★

Write the CYK algorithm that counts parse trees, 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

Solution of Exercise 23.11.

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 2642^{64}, so each step is exact in 64 bits. Each cell maps a nonterminal to its number of trees: one per production A→aA \to a at the bottom, and for each split and each A→BCA \to BC the product of the counts of BB and CC, added to AA’s count. In Chomsky normal form 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→E+E∣aE \to E + E \mid a (into E→E X0E \to E\,X_0, X0→’+’ EX_0 \to \text{\texttt{'+'}}\,E) keeps the trees in bijection. The Catalan numbers are computed by Ck=Ck−1⋅2(2k−1)/(k+1)C_k = C_{k-1} \cdot 2(2k - 1)/(k + 1), a division that is always exact. C99C_{99} has 57 digits.

Exercise 23.12 ★★★

Prove that the intersection of a context-free language and a regular language is context-free, by running a PDA and a DFA side by side.

Solution

Solution of Exercise 23.12.

Let PP be a PDA with states QQ and accepting states FF, and DD a complete DFA with states RR, start r0r_0, transitions δ\delta and accepting states F′F'. The product PDA has states Q×RQ \times R, start (q0,r0)(q_0, r_0), the same stack, accepting states F×F′F \times F', and the moves ((q,r),a,Z)→((q′,δ(r,a)),γ)((q, r), a, Z) \to ((q', \delta(r, a)), \gamma) for each move (q,a,Z)→(q′,γ)(q, a, Z) \to (q', \gamma) of PP reading a letter, and ((q,r),ε,Z)→((q′,r),γ)((q, r), \varepsilon, Z) \to ((q', r), \gamma) for each spontaneous move. By induction on the number of moves, the product goes from ((q0,r0),w,Z0)((q_0, r_0), w, Z_0) to ((q,r),y,γ)((q, r), y, \gamma) exactly when PP goes from (q0,w,Z0)(q_0, w, Z_0) to (q,y,γ)(q, y, \gamma) and r=δ∗(r0,x)r = \delta^*(r_0, x) with w=xyw = xy. So it accepts ww exactly when PP accepts it and DD does. A product of two PDAs would need two stacks, which is why the intersection of two context-free languages can fail to be context-free.

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: ww 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, and CYK on three notices.

Part I — A grammar.

  1. Give a leftmost derivation of [w]w[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 [nw ]n[^n w\, ]^n.
  4. Write a right-linear grammar for the notices that use neither bold nor links.
  5. Draw the two parse trees of wwwwww.
  6. List the four trees of *w*w*w*, as bracketings.

Part II — Ambiguity found and removed.

  1. Which production makes wwwwww ambiguous, and how does D→ID∣ID \to ID \mid I remove that ambiguity?
  2. With D→ID∣ID \to ID \mid I and I→w∣∗D∗∣[D]I \to w \mid *D* \mid [D], find two trees of *w*w*w*.
  3. Why does the second grammar write bold text between < and >?
  4. The program checks 516 notices. What does this prove about the second grammar, and what does it not prove?
  5. Are the first grammar and the grammar of question 8 weakly equivalent?
  6. Give a leftmost derivation of <w>[w] in the second grammar.

Part III — Chomsky normal form and CYK.

  1. Which steps of Method 23.8 change the second grammar, and why is no new start needed?
  2. Why does DD receive the productions of II?
  3. Explain the bottom row of the table of <w[w]>w.
  4. Why does the cell of length 3 starting at [[ hold DD and II?
  5. Which cell shows that <w[w>]w is rejected, and why is it empty?
  6. 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.
  1. Prove that a word of length nn has (n3−n)/6(n^3 - n)/6 split points.
  2. Check the formula against the output above.
  3. By how much does the time grow when nn doubles, and why?
  4. How many productions A→BCA \to BC does the normal form of the second grammar have, and what is the cost per split point?
  5. Estimate the time for a notice of 20 000 letters.
  6. State the result: CYK’s cubic count, (n3−n)/6(n^3 - n)/6 split points for a word of length nn.
Solution

Solution of Problem 23.1.

1. D⇒D D⇒[D] D⇒[w] D⇒[w]wD \Rightarrow D\,D \Rightarrow [D]\,D \Rightarrow [w]\,D \Rightarrow [w]w.

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

3. Intersected with the regular language [∗w ]∗[^*w\,]^*, the notices give {[nw ]n}\{[^nw\,]^n\}; for i≠ji \ne j the words [i[^i and [j[^j have different residuals (w ]iw\,]^i is in one only), so this is not regular, and since regular languages are closed under intersection, neither are the notices.

4. D→wD∣wD \to wD \mid w.

5. Both have the root D→D DD \to D\,D: one with wwww under the left child, (ww)w(ww)w, the other with wwww under the right child, w(ww)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→D DD \to D\,D, which is associative but says nothing of the grouping. With D→ID∣ID \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 DD 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 II, the first letter chooses the production; in D→ID∣ID \to ID \mid I, the item ends where its closing symbol matches its opening one (or after one ww), 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 '<' X0X_0, X0→DX_0 \to D '>' and the same with X1X_1) and UNIT (D→ID \to I). No nonterminal derives ε\varepsilon, so START and DEL change nothing.

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

15. Each letter’s cell holds the nonterminals with a production to it: '<' for <, DD and II for ww (by I→wI \to w, and D→wD \to w from UNIT), '[', ']' and '>' for the three others.

16. It covers [w][w]: X1X_1 derives w]w] by X1→DX_1 \to D ']' (the cell of length 2 at ww), and '[' X1X_1 is a right side of both II and DD.

17. The top cell, of length 7, is empty, so DD 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 DD, II, X0X_0 or X1X_1 ending there correctly.

18. (73−7)/6=56(7^3 - 7)/6 = 56 and (63−6)/6=35(6^3 - 6)/6 = 35.

19. As in Theorem 23.11: ∑ℓ=2n(n−ℓ+1)(ℓ−1)=∑j=1n−1(n−j)j=(n3−n)/6\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=21n = 21, (9 261−21)/6=1 540(9\,261 - 21)/6 = 1\,540.

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

22. Seven: D→IDD \to ID, D→D \to '<' X0X_0, D→D \to '[' X1X_1, I→I \to '<' X0X_0, I→I \to '[' X1X_1, X0→DX_0 \to D '>', X1→DX_1 \to D ']'; each split point tests all seven, so the time is about 7×(n3−n)/67 \times (n^3 - n)/6 tests.

23. Scaling the last line by (20 000/336)3≈211 000(20\,000/336)^3 \approx 211\,000: about 0.078×211 000≈16 0000.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, CYK examines (n3−n)/6(n^3 - n)/6 split points for a word of length nn, each against every production A→BCA \to BC, so its time grows as n3n^3; the program counted exactly that number for notices of 21 to 336 letters, and its time grew about eightfold at each doubling.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো