এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: 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}");
}
}
$ 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
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, not regular, closure of regular languages under intersection. The Year 1 volume: trees, their height, a binary tree of height has at most 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 : a finite set of nonterminals, an alphabet of terminals disjoint from , a finite set of productions with and , and a start symbol . Productions with the same left side are written together, .
Definition 23.2 (Derivation, generated language)
A word over is a sentential form. If is a production, is an immediate derivation; a derivation is a sequence of zero or more of them. The language generated by is . 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: , with standing for any number or name;
- propositional formulas over the variables , : ;
- a toy markup, where is a word, a link and bold text: .
The derivations of from include . 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 , until nothing changes.
Definition 23.3 (Right-linear grammar)
A grammar is right-linear if every production is or , with and : 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 , generated by , shows the inclusion is strict.
Proof. From a DFA, take one nonterminal per state, the start state as start symbol, a production per transition and per accepting state: a derivation follows a run, and ends in a word exactly when the run ends in an accepting state. Conversely, cut each production into a chain of transitions through new states, from state to state (a spontaneous one if ), and each 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 is an ordered tree whose root is , whose inner nodes are nonterminals, whose leaves are terminals or , and where the children of each inner node , read from left to right, are the right side of a production . 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 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
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 , has a tree that multiplies first and one that adds first, two different values:
The grammar of Output 23.2 removes the ambiguity with one nonterminal per level: an expression is a sum of terms , a term a product of factors , 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 has its recursion on the left, groups as . 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
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 for “if a condition then”, for “else” and for any other statement, gives two trees, the else belonging to either if.
else: in , 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 , , writes the rule down: between an and its only a matched statement , every of which has its , 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 with nonterminals, or with a terminal, except possibly when the start symbol appears in no right side. Its size 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:
- START: if derives and appears in a right side, add a new start ;
- TERM: in every right side of length at least 2, replace each terminal by a new nonterminal written
'c', with'c'; - BIN: cut every with into , , …, , with new nonterminals ;
- DEL: compute the nullable nonterminals (those that derive ); for every production, add each version with some nullable occurrences dropped; then remove every except ;
- UNIT: for each , find by a graph search the nonterminals with through productions with one nonterminal on the right; give every non-unit production of each such ; 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;
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);
}
}
}
Proposition 23.9 (The normal form)
The method returns a grammar in Chomsky normal form that generates , of size at most proportional to .
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 in , 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 in a derivation is replaced by the one production , 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 up to that point. UNIT gives each of at most nonterminals a copy of at most all the productions: at most . ∎
The order matters: DEL before BIN would make versions of a right side with nullable symbols. The expression grammar with levels has no 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
The unit productions and are gone: now has the productions of and 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 be in Chomsky normal form and nonempty. For the factor of length starting after position , compute the set of nonterminals that derive it: , and for , holds whenever there are a production and a split with and . Then if and only if .
/// 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)
}
$ 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
Theorem 23.11 (CYK)
The CYK algorithm decides whether . It examines split points, each against every production , so its time is proportional to .
Proof. By induction on , if and only if . For , in Chomsky normal form a nonterminal derives a letter only through a production . For , a derivation of the factor starts with some , and and then derive a nonempty prefix of length and the rest, which by the hypothesis is when and . For the count: a factor of length has split points, and there are factors of that length, so the number of split points is
∎
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 on with operands, a tree chooses the at its root and then trees for both sides, the recurrence of the Catalan numbers, :
$ 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
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 : a finite set of states , an input alphabet , a stack alphabet , a finite set of moves with , and , a start state , a bottom symbol , and accepting states . In state with on top of the stack, the move reads (nothing if ), goes to and replaces by , whose first symbol ends on top. A configuration is a state, the unread input and the stack. The automaton accepts if some sequence of moves leads from to a configuration with no input left and an accepting state.
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())
}
$ 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)
Theorem 23.13 (From a grammar to a pushdown automaton)
For every context-free grammar there is a PDA with three states that recognises .
Proof. Stack alphabet , states 0, 1, 2, accepting 2. Moves: ; for each production , ; for each terminal , ; and . The claim, by induction on the number of steps: in state 1, the automaton can go from to exactly when there is a leftmost derivation with the terminals already matched and 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 , and then state 2, exactly when . ∎
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 guesses the middle, though a deterministic one exists (the first 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 is context-free, there is such that every with can be written with and , so that for every .
Proof. Take a grammar for in Chomsky normal form, with nonterminals, and . A parse tree in this form is binary above its leaves: if its longest path from the root to a terminal has nonterminals, the word has at most letters. So for the tree has a path with at least nonterminals, and among the lowest of them some appears twice. Let the upper derive and the lower derive , and . The subtree of the upper has paths of at most nonterminals, so . The upper has two children, the lower lies under one of them, and the other derives a nonempty word that is part of or : . Replacing the lower subtree by a copy of the upper one, times, or the upper by the lower, gives trees of . ∎
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 is not context-free.
Proof. With start symbols , and disjoint nonterminals, , and give the union, the concatenation and the star. Intersection with a regular language is Exercise 23.12. For , take : since , meets at most two of the three blocks, so pumping with changes the number of at most two of the letters (or breaks their order) and leaves the word outside the language. Now and are context-free, by , , and a symmetric grammar, and their intersection is : no closure under intersection. Since is the complement of the union of the complements, closure under complement would give closure under intersection. ∎
A pushdown automaton has one stack, and needs to count twice. The same argument, applied after an intersection with , shows that 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 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
The tree: has one child ; that has the children , , ; the left goes down through to , whose goes down through and to ; the right is . Its nine inner nodes are the eight steps plus the start symbol .
Exercise 23.2 ★
Someone writes 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
. The grammar generates the words with as many as . Each production adds one of each, so every generated word has equal numbers. Conversely, let be nonempty with equal numbers, say starting with , and let be its shortest nonempty prefix with equal numbers: the difference between the numbers of and stays positive inside it, so it ends with , and and the rest both have equal numbers; by induction on the length they are generated, and gives . A word starting with is handled by in the same way.
Exercise 23.3 ★
Write a grammar for the palindromes over , 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
: 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 palindromes of length , and up to length 12.
Exercise 23.4 ★
Draw the parse trees of in . 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: , , , and ; this is . The grammar with levels gives one, the first, since puts the last addition at the root (Output 23.3).
Exercise 23.5 ★★
For , , , , fill the CYK tables of and . 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}
For : the letters give ; the middle is by ; is by ; the whole word is by . For the two are , but nothing derives , or the whole word. gives and wraps a word of the language in : the language is .
Exercise 23.6 ★★
A program removes unit productions by following them recursively from each nonterminal. What happens on , , ? 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
Following then leads back to , 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 it reaches and gives the productions , and ; and are then no longer reachable from and are dropped.
Exercise 23.7 ★★
Write a recogniser for , 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 .
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
}
$ 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"}
The two productions of start with different letters, or the of , so one letter decides; 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 succeeds and nothing is left. Every word of the language has a length .
Exercise 23.8 ★★
Prove that 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: is, and if and are, so is : its numbers are equal, a prefix inside has one more than a prefix of , and a prefix has as many of each as . Conversely, by strong induction on the length: let be balanced and nonempty. Its first letter is , since the prefix of length 1 cannot have more . Let be the shortest nonempty prefix with as many as ; inside it the difference stays positive, so is balanced, and the rest is balanced too (its prefixes add to a balanced prefix). Both are shorter than , so and , and .
Exercise 23.9 ★★
Build a PDA for the words over with as many as , 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 };
$ 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
The stack holds the surplus: symbols above the bottom if more than have been read, symbols if more . An pushes an unless a is on top, which it pops; symmetrically for . 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 is not context-free. Use Exercise 23.12 with the regular language .
Solution
Solution of Exercise 23.10.
Let and . If were context-free, so would be (Exercise 23.12). Take from Theorem 23.15 and . Since , lies inside one block or across two adjacent ones. If or contains two different letters, is not in . Otherwise pumping with 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 , 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))
}
$ 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
A number is a vector of 32-bit digits; a product of two digits plus a digit and a carry stays below , so each step is exact in 64 bits. Each cell maps a nonterminal to its number of trees: one per production at the bottom, and for each split and each the product of the counts of and , added to ’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 (into , ) keeps the trees in bijection. The Catalan numbers are computed by , a division that is always exact. 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 be a PDA with states and accepting states , and a complete DFA with states , start , transitions and accepting states . The product PDA has states , start , the same stack, accepting states , and the moves for each move of reading a letter, and for each spontaneous move. By induction on the number of moves, the product goes from to exactly when goes from to and with . So it accepts exactly when accepts it and 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: stands for a word, 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
Part I — A grammar.
- Give a leftmost derivation of in the first grammar.
- Describe the notices the first grammar generates.
- Prove that the set of notices is not regular, using the words .
- Write a right-linear grammar for the notices that use neither bold nor links.
- Draw the two parse trees of .
- List the four trees of
*w*w*w*, as bracketings.
Part II — Ambiguity found and removed.
- Which production makes ambiguous, and how does remove that ambiguity?
- With and , find two trees of
*w*w*w*. - Why does the second grammar write bold text between
<and>? - The program checks 516 notices. What does this prove about the second grammar, and what does it not prove?
- Are the first grammar and the grammar of question 8 weakly equivalent?
- Give a leftmost derivation of
<w>[w]in the second grammar.
Part III — Chomsky normal form and CYK.
- Which steps of Method 23.8 change the second grammar, and why is no new start needed?
- Why does receive the productions of ?
- Explain the bottom row of the table of
<w[w]>w. - Why does the cell of length 3 starting at hold and ?
- Which cell shows that
<w[w>]wis rejected, and why is it empty? - 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
- Prove that a word of length has split points.
- Check the formula against the output above.
- By how much does the time grow when doubles, and why?
- How many productions does the normal form of the second grammar have, and what is the cost per split point?
- Estimate the time for a notice of 20 000 letters.
- State the result: CYK’s cubic count, split points for a word of length .
Solution
Solution of Problem 23.1.
1. .
2. The nonempty sequences of items, an item being a word , a nonempty notice in bold between two , or a nonempty notice as a link between brackets.
3. Intersected with the regular language , the notices give ; for the words and have different residuals ( is in one only), so this is not regular, and since regular languages are closed under intersection, neither are the notices.
4. .
5. Both have the root : one with under the left child, , the other with under the right child, .
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. , which is associative but says nothing of the grouping. With , 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 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 , the first letter chooses the production; in , the item ends where its closing symbol matches its opening one (or after one ), 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 I D <D> D <I> D <w> D <w> I <w>[D] <w>[I] <w>[w].
13. TERM (the four symbols in the right sides of length 3), BIN (cutting <D> and [D] into '<' , '>' and the same with ) and UNIT (). No nonterminal derives , so START and DEL change nothing.
14. Because of the unit production : every item is also a notice.
15. Each letter’s cell holds the nonterminals with a production to it: '<' for <, and for (by , and from UNIT), '[', ']' and '>' for the three others.
16. It covers : derives by ']' (the cell of length 2 at ), and '[' is a right side of both and .
17. The top cell, of length 7, is empty, so 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 , , or ending there correctly.
18. and .
19. As in Theorem 23.11: .
20. The two columns agree on all five lines; for , .
21. About 7 to 8 times: the work is cubic, and ; for the smallest notices the time is too short to measure well.
22. Seven: , '<' , '[' , '<' , '[' , '>', ']'; each split point tests all seven, so the time is about tests.
23. Scaling the last line by : about 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 split points for a word of length , each against every production , so its time grows as ; the program counted exactly that number for notices of 21 to 336 letters, and its time grew about eightfold at each doubling.