本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 3 · 本科三年级
2Top-Down Parsing
The scanner hands over x = x * ; as six well-formed tokens. Something must now notice that a multiplication has lost its right operand, say so at the right column, and carry on to find the next mistake rather than stop at the first. The same something must read 1 - 2 - 3 as and not , which differ by 4, and a + b * c with the product inside the sum. This chapter builds the parser of Moor: a grammar, the sets that tell a parser which rule to use by looking at one token, the table those sets fill, and the hand-written parser that production compilers use, one function per rule with a loop for operators. Its output is a tree, frozen here for the rest of the book.
2.1 A grammar for Moor
You already know
A context-free grammar has terminals, nonterminals, a start symbol and productions . A derivation rewrites one nonterminal at a time; a leftmost derivation always rewrites the leftmost one. A parse tree records a derivation without its order; a grammar is ambiguous when some word has two parse trees. A pushdown automaton is a finite automaton with a stack, and recognises exactly the context-free languages (Year 2 volume, Context-Free Grammars and Pushdown Automata). Rust’s enums with data are sum types, and match takes them apart (Year 2 volume).
A parser reads tokens and checks them against a grammar. Here is a small one for sums and products, with id standing for any identifier:
Its parse tree for a + b * c has eight interior nodes, one per rule used. Most of them carry nothing the later phases need: that was derived through and says only that it is an operand. What the compiler needs is the structure: a sum whose right operand is a product.
Definition 2.1 (Abstract syntax tree)
The abstract syntax tree (AST) of a program is a tree whose nodes are the constructs of the language (an addition, a call, an if statement), each with its operands as children and its span. It omits what the grammar needed only to be unambiguous or easy to parse: parentheses, separators, the chains of nonterminals that encode precedence.
a + b * c. The AST keeps the operators and their operands and drops the nonterminals that only encoded precedence.Moor’s AST is Listing 2.1. An expression is a kind and a span; a statement likewise. A call names its function and an index names its array: Moor has no function values and no array values, so the thing called or indexed is always a name. The rest of the file (blocks, functions, the items of a program, and a printer that writes an expression as an S-expression such as (+ a (* b c))) follows the same pattern. Every later chapter of Part I reads this tree, and none changes it.
#[derive(Clone, Debug, PartialEq)]
pub enum ExprKind {
Int(i64),
Bool(bool),
Var(String),
Unary(UnOp, Box<Expr>),
Binary(BinOp, Box<Expr>, Box<Expr>),
Call(String, Vec<Expr>),
Index(String, Box<Expr>), // a[e]: arrays are global and named
}
#[derive(Clone, Debug, PartialEq)]
pub struct Expr {
pub kind: ExprKind,
pub span: Span,
}
#[derive(Clone, Debug, PartialEq)]
pub enum StmtKind {
Var(String, Option<Type>, Expr), // var x [: T] = e;
Assign(String, Expr), // x = e;
AssignIndex(String, Expr, Expr), // a[i] = e;
If(Expr, Block, Option<Block>), // else if ... is an else block holding one if
While(Expr, Block),
Return(Option<Expr>),
Expr(Expr),
Block(Block),
}
2.2 Nullable, FIRST and FOLLOW
A top-down parser builds the tree from the root. Facing a nonterminal and the next token , it must choose a production of . Three sets, computed once from the grammar, tell it which productions can possibly start with .
Definition 2.2 (Nullable, FIRST, FOLLOW)
Let be a grammar and a string of terminals and nonterminals. is nullable if . The FIRST set is the set of terminals such that for some . For a nonterminal , the FOLLOW set is the set of terminals such that for some , where is the start symbol; it contains the end marker $ if .
The definitions quantify over all derivations, which are infinitely many. The sets are computed instead as the least solution of equations read off the productions. For each production :
- is nullable if every is;
- whenever is nullable (and for a terminal);
- for each nonterminal , contains , and also if is nullable.
Method 2.3 (Sets by iteration)
Start with every set empty and no nonterminal nullable, and . Pass over the productions, applying each inclusion above and growing the sets; repeat until a whole pass changes nothing. Do nullable and FIRST first, then FOLLOW, which needs them.
Each pass can only add, and the sets are bounded by the number of terminals, so the iteration stops; what it computes is the least solution, the one the definitions describe (exercise 2.7). Chapter 8 meets this pattern again, as a fixed point of dataflow equations. Listing 2.2 is the method over a grammar read from a text file.
/// Start from empty sets and apply every rule until nothing changes: the
/// result is the least solution of the equations.
pub fn compute(g: &Grammar) -> Sets {
let empty = || g.nonterms.iter().map(|n| (n.clone(), Set::new())).collect();
let mut s = Sets { nullable: Set::new(), first: empty(), follow: empty(), rounds: (0, 0) };
let mut changed = true;
while changed {
changed = false;
s.rounds.0 += 1;
for (a, rhs) in &g.rules {
let (f, null) = s.first_seq(g, rhs);
let before = s.first[a].len();
s.first.get_mut(a).unwrap().extend(f);
changed |= s.first[a].len() != before;
if null && s.nullable.insert(a.clone()) {
changed = true;
}
}
}
s.follow.get_mut(g.start()).unwrap().insert("$".into());
changed = true;
while changed {
changed = false;
s.rounds.1 += 1;
for (a, rhs) in &g.rules {
for (i, b) in rhs.iter().enumerate().filter(|(_, b)| g.is_nt(b)) {
let (mut f, null) = s.first_seq(g, &rhs[i + 1..]);
if null {
f.extend(s.follow[a].iter().cloned());
}
let before = s.follow[b].len();
s.follow.get_mut(b).unwrap().extend(f);
changed |= s.follow[b].len() != before;
}
}
}
s
}
first_seq computes FIRST of a sequence and tells whether it is nullable. code/bachelor-3/02-top-down-parsing/listings/grammar.rsThe grammar of sums and products above cannot be parsed top-down as it stands, for a reason the next section gives. Here it is rewritten into an equivalent one that can, and its sets.
# expr.grammar -- sums and products, left recursion removed
E -> T E'
E' -> + T E' | eps
T -> F T'
T' -> * F T' | eps
F -> ( E ) | id
$ rustc --edition 2021 -O -o first_follow first_follow.rs && ./first_follow expr.grammar
nullable FIRST FOLLOW
E no {(, id} {$, )}
E' yes {+} {$, )}
T no {(, id} {$, ), +}
T' yes {*} {$, ), +}
F no {(, id} {$, ), *, +}
passes until stable: FIRST 4, FOLLOW 3
Read the FOLLOW sets as “what may come after”. A product may be followed by + (more sum), by ) (the end of a parenthesised sum) or by the end of input. A factor may in addition be followed by *.
2.3 LL(1) grammars
Definition 2.4 (LL(1) grammar, predictive parsing table)
The predictive parsing table of a grammar has a row per nonterminal and a column per terminal (and $). Production is put in cell for every , and, if is nullable, for every . A grammar is an LL(1) grammar if no cell of its table holds two productions.
The name says how such a grammar is parsed: from Left to right, building a Leftmost derivation, with 1 token of lookahead. Equivalently, for any two productions : and are disjoint, at most one of them is nullable, and if is nullable then and are disjoint.
Method 2.5 (The predictive parser)
Keep a stack of grammar symbols, initially $ below the start symbol, and the input followed by $. Repeat: if the top is a terminal, it must equal the next input token; pop it and advance. If the top is a nonterminal and the next token is , look up : if it is empty, report an error; otherwise pop and push the production’s right side, its first symbol on top. Accept when both the stack and the input are down to $.
This is a pushdown automaton whose transitions are read from the table. Output 2.2 runs it on id + id * id, and the figure after it draws the first stacks.
$ rustc --edition 2021 -O -o ll1_driver ll1_driver.rs && ./ll1_driver expr.grammar
stack (top right) input action
$ E id + id * id $ predict E -> T E'
$ E' T id + id * id $ predict T -> F T'
$ E' T' F id + id * id $ predict F -> id
$ E' T' id id + id * id $ match id
$ E' T' + id * id $ predict T' -> eps
$ E' + id * id $ predict E' -> + T E'
$ E' T + + id * id $ match +
$ E' T id * id $ predict T -> F T'
$ E' T' F id * id $ predict F -> id
$ E' T' id id * id $ match id
$ E' T' * id $ predict T' -> * F T'
$ E' T' F * * id $ match *
$ E' T' F id $ predict F -> id
$ E' T' id id $ match id
$ E' T' $ predict T' -> eps
$ E' $ predict E' -> eps
$ $ accept
id + id * id: each line shows the stack, the input left, and what the table said.Theorem 2.6 (Predictive parsing is correct for LL(1) grammars)
If is LL(1), the predictive parser accepts a word if and only if , and then the productions it predicts, in order, are those of the leftmost derivation of .
Proof. At every step the stack, read from top to bottom, is a sentential form such that where is the input already matched: this holds at the start (, ), and each prediction or match keeps it. So an accepted word is derived by the predicted productions, leftmost first. Conversely, let with leftmost derivation . Suppose the parser has followed so far and next rewrites the top nonterminal by , with the next token. Either derives a word starting with , so , or derives in and comes from what follows , so and is nullable. Either way is in cell , and it is alone there because is LL(1): the parser predicts the production of . By induction it follows to the end and accepts. ∎
Two features of grammars put two productions in one cell. The first is the one that made unusable.
Definition 2.7 (Left recursion, left factoring)
A grammar has left recursion if some nonterminal derives in one or more steps. Left factoring replaces productions that share a prefix by and , with a new nonterminal .
A left-recursive production puts both productions in every cell of : whatever starts a also starts an . The standard rewrite replaces it by and , which generates the same words, , from the left; Listing 2.3 is that rewrite applied twice. Left factoring handles the second problem. A Moor statement can be x = e; or an expression e;, and both can start with an identifier. Output 2.3 prints the table of a small grammar with exactly that conflict, before and after factoring out the common id.
$ rustc --edition 2021 -O -o ll1_table ll1_table.rs && ./ll1_table stmt.grammar stmt_factored.grammar
== stmt.grammar
[E, (] E -> ( E )
[E, id] E -> id
[E, num] E -> num
[S, (] S -> E ;
[S, id] S -> id = E ; / S -> E ; <-- conflict
[S, num] S -> E ;
6 cells, 1 with a conflict: not LL(1)
== stmt_factored.grammar
[E, (] E -> ( E )
[E, id] E -> id
[E, num] E -> num
[S, (] S -> ( E ) ;
[S, id] S -> id S'
[S, num] S -> num ;
[S', ;] S' -> ;
[S', =] S' -> = E ;
8 cells, 0 with a conflict: LL(1)
S -> id = E ; | E ; (one conflict), and of its left-factored form, which is LL(1).The whole of Moor can be written as an LL(1) grammar: moor.grammar in this chapter’s listings does it in 37 nonterminals, and its table of 278 cells has no conflict (the tests check it). But the factoring needed for statements spreads through every precedence level: after x has been read as the start of an expression statement, the grammar needs a nonterminal for “the rest of an expression whose first operand was a name”, which is the tail of a product, then of a sum, of a comparison, and so on up to ||. Nobody writes a parser from that grammar by hand. The parser of the next section reads one token further instead.
History — LL and Pratt
Philip Lewis and Richard Stearns defined the LL() grammars in July 1968, in a paper on syntax-directed translation. Vaughan Pratt presented “top down operator precedence” at the first Principles of Programming Languages symposium in 1973: a parser in which each token carries its own binding power, the method this chapter calls precedence climbing.
2.4 Recursive descent
Definition 2.8 (Recursive descent)
A recursive descent parser has one function per nonterminal. The function for looks at the next token (or the next few), chooses a production of , and runs through its right side: it consumes each terminal and calls the function of each nonterminal. The call stack of the program plays the part of the parser’s stack.
The function for a Moor function definition is Listing 2.4: it follows the production fn id ( params ) [-> type] block symbol by symbol, with a loop where the grammar has a repetition.
fn func(&mut self) -> R<Func> {
let start = self.bump(); // fn
let (name, _) = self.ident()?;
self.expect(T::LParen, "'('")?;
let mut params = Vec::new();
while *self.peek() != T::RParen {
let (pname, pspan) = self.ident()?;
self.expect(T::Colon, "':' and a type")?;
let ty = self.ty()?;
params.push(Param { name: pname, ty, span: join(pspan, self.prev()) });
if *self.peek() != T::Comma {
break;
}
self.bump();
}
self.expect(T::RParen, "')'")?;
let ret = if *self.peek() == T::Arrow {
self.bump();
Some(self.ty()?)
} else {
None
};
let body = self.block()?;
Ok(Func { name, params, ret, span: join(start, body.span), body })
}
Where Moor is not LL(1) as written, the parser looks two tokens ahead. An identifier followed by = starts an assignment; anything else starts an expression. An assignment to an array element, a[i] = e;, is found differently: the parser reads an expression, and if an = follows, checks that the expression it read was an element. This “parse, then check the target” is how most hand-written parsers handle assignment, and it gives a better message for f(x) = 1; than a grammar could.
T::LBrace => StmtKind::Block(self.block()?),
T::Ident(_) if *self.peek2() == T::Assign => {
let (name, _) = self.ident()?;
self.bump(); // =
let e = self.expr()?;
self.expect(T::Semi, "';'")?;
StmtKind::Assign(name, e)
}
_ => {
let e = self.expr()?;
if *self.peek() == T::Assign {
let ExprKind::Index(a, i) = e.kind else {
return self.error("only a name or an array element can be assigned to".into());
};
self.bump();
let v = self.expr()?;
self.expect(T::Semi, "';'")?;
StmtKind::AssignIndex(a, *i, v)
} else {
self.expect(T::Semi, "';'")?;
StmtKind::Expr(e)
}
}
};
Ok(Stmt { kind, span: join(start, self.prev()) })
x = e;, and the check of an assignment’s target. code/bachelor-3/02-top-down-parsing/listings/parser.rsExpressions are where the classic layout of recursive descent is wasteful. With one function per precedence level, as the grammar of sums and products suggests, a single number in a Moor condition goes through eight calls: ||, &&, equality, comparison, sum, product, prefix, and primary, each finding no operator of its own and returning. Precedence climbing replaces all the levels by one function and a table.
Definition 2.9 (Binding power, precedence climbing)
The binding power of a binary operator is a positive integer, higher for operators that bind more tightly: in Moor, 1 for ||, 2 for &&, 3 for == and !=, 4 for the comparisons, 5 for + and -, 6 for *, / and %. Precedence climbing parses an expression whose operators all have binding power at least as follows: parse an operand; then, while the next token is an operator of power , consume it, parse the right operand as an expression of minimum power , and combine.
/// An expression whose operators all bind at least as tightly as `min`.
fn expr_bp(&mut self, min: u8) -> R<Expr> {
let mut lhs = self.prefix()?;
while let Some((op, bp)) = binop(self.peek()) {
if bp < min {
break;
}
self.bump();
let rhs = self.expr_bp(bp + 1)?; // + 1: the operators are left-associative
let span = join(lhs.span, rhs.span);
lhs = Expr { kind: ExprKind::Binary(op, Box::new(lhs), Box::new(rhs)), span };
}
Ok(lhs)
}
fn prefix(&mut self) -> R<Expr> {
let op = match self.peek() {
T::Minus => UnOp::Neg,
T::Bang => UnOp::Not,
_ => return self.primary(),
};
let start = self.bump();
let e = self.prefix()?;
Ok(Expr { span: join(start, e.span), kind: ExprKind::Unary(op, Box::new(e)) })
}
bp + 1 makes every binary operator left-associative. code/bachelor-3/02-top-down-parsing/listings/parser.rsTheorem 2.10 (Precedence climbing respects the table)
In the tree that expr_bp(1) builds from operands and binary operators, every operator node of power has a left child of power at least and a right child of power greater than (an operand counts as power ). So operators of higher power are deeper, and operators of equal power group to the left.
Proof. A call expr_bp() returns a tree all of whose operators have power at least : it only combines operators with , and their right operands come from calls with minimum ; this is an induction on the depth of calls. Now take a node built by the loop for an operator of power . Its right child came from expr_bp(), so its root has power at least . Its left child is the tree built so far in the same call: either the first operand, or a node for an operator combined earlier in the same loop. When the loop combined , the right operand of stopped at our operator, so , that is . ∎
$ rustc --edition 2021 -O -o prec_demo prec_demo.rs && ./prec_demo
1 - 2 - 3 * 4 => (- (- 1 2) (* 3 4))
a + b * c => (+ a (* b c))
-x * y => (* (neg x) y)
!p && q || r => (|| (&& (! p) q) r)
a < b == c < d => (== (< a b) (< c d))
f(x, y + 1)[2] => error: unexpected '[' after the expression
The figure below compares the calls of the two layouts on a + b * c. Precedence climbing makes a call per operand and a call per operator’s right side; the layered parser makes a call per level for each operand, whether or not an operator of that level appears.
a + b * c. Left: one function per level of ||, &&, equality, comparison, sum, product, then the prefix operators and the primary. Right: the parser of Listing 2.6, where the right side of + is parsed with minimum power 6 and that of * with 7.Output 2.5 runs the whole parser on the Fibonacci program and prints its tree, one statement per line.
fn fib(n: int) -> int {
if n < 2 { return n; }
return fib(n - 1) + fib(n - 2);
}
fn main() {
var i = 0;
while i < 10 { print(fib(i)); i = i + 1; }
}
fib.moor. code/bachelor-3/02-top-down-parsing/listings/fib.moor$ rustc --edition 2021 -O -o parse_demo parse_demo.rs && ./parse_demo fib.moor
fn fib(n: int) -> int
if (< n 2)
return n
return (+ (call fib (- n 1)) (call fib (- n 2)))
fn main()
var i = 0
while (< i 10)
(call print (call fib i))
i = (+ i 1)
fib.moor.2.5 Recovering from errors
A parser that stops at the first error makes its user fix one mistake per compilation. A parser that carries on blindly reports a cascade of errors that are all the first one in disguise. The usual compromise is cheap and works well.
Definition 2.11 (Panic-mode recovery, synchronising token)
In panic-mode recovery, a parser that meets an error records it, then skips tokens until it reaches a synchronising token: a token after which parsing can resume in a known state. It then resumes from the function that handles that state.
In Moor, a statement ends at ;, and var, if, while, return and } begin or end one: these are the synchronising tokens for statements. A statement function that fails returns an error marker up to the block function, which calls Listing 2.8 and then tries the next statement. At the top level, fn, var and array play the same part.
/// Panic mode: skip to a synchronising token. A ';' is consumed; a
/// token that starts a statement, a '}' or 'fn' is left for the caller.
fn sync_stmt(&mut self) {
loop {
match self.peek() {
T::Semi => {
self.bump();
return;
}
T::RBrace | T::Eof | T::Fn | T::Var | T::If | T::While | T::Return => return,
_ => {
self.bump();
}
}
}
}
fn main() {
var x = (1 + 2;
x = x * ;
if x > 3 { print(x) }
print(x);
}
$ rustc --edition 2021 -O -o recover recover.rs && ./recover errors.moor
errors.moor:2:19: error: expected ')', found ';'
var x = (1 + 2;
^
errors.moor:3:13: error: expected an expression, found ';'
x = x * ;
^
errors.moor:4:25: error: expected ';', found '}'
if x > 3 { print(x) }
^
3 errors; the tree still has 1 function(s)
The third error shows a limit: the missing semicolon is after print(x), but the parser can only notice it at the } that follows. An error is always reported where the parser first finds the input impossible, which may be after the mistake. Panic mode also loses whatever a skipped region contained, so an error inside a skipped region goes unreported until the next compilation.
In practice — Error messages are part of the language
The messages of Output 2.6 name what was expected and what was found, and point at a column. That is most of what a programmer needs. Production parsers add two things: a guess at the fix when one is likely (“missing ;?”), and care to report an error once even when several functions notice it. Both are easier in a hand-written parser than in a generated one, which is the main reason most compilers of widely used languages parse by recursive descent.
2.6 Exercises
Exercise 2.1 ★
Compute nullable and FIRST for the grammar , , .
Solution
Solution of Exercise 2.1.
and are nullable (, ); is not, since both its productions contain a terminal. , . For : contributes , and since is nullable contributes , and since is nullable too, is in; adds . So . The file exercises/ex1.grammar holds the grammar and tests/grammar_test.rs checks the sets.
Exercise 2.2 ★
Write the S-expression that the parser of this chapter builds for a - -b * c % d || !e.
Solution
Solution of Exercise 2.2.
(|| (- a (% (* (neg b) c) d)) (! e)). The loosest operator, ||, is the root. Its left side is a difference; the right operand of the minus is -b * c % d, in which the prefix minus binds tightest, and * and % have the same power and group to the left. The test precedence_and_associativity checks this tree.
Exercise 2.3 ★
Is the grammar , LL(1)? Fill its table and say which cell decides. Describe the language it generates and give an LL(1) grammar for it.
Solution
Solution of Exercise 2.3.
No. , : the row of has no conflict. But is nullable and , so cell holds both (by FIRST) and (by FOLLOW). Seeing an a, the parser cannot tell whether it is ’s or the one after . The language is , and , is an LL(1) grammar for it: after the first a, the next token is a or the end.
Exercise 2.4 ★
Remove the left recursion from (a comma-separated list), and write the recursive-descent function for the result as a loop.
Solution
Solution of Exercise 2.4.
, . The function reads an id, then loops: while the next token is a comma, it consumes the comma and an id. The tail recursion of becomes the loop; FOLLOW of is whatever follows a list, and seeing it ends the loop. The grammar tests of the chapter check that the first grammar has a conflict and the second none.
Exercise 2.5 ★★
Listing 2.10 is a calculator for one-digit numbers. Three of its five answers in Output 2.7 are wrong. Find the bug, explain the wrong answers, and fix it.
fn expr(toks: &[char], pos: &mut usize, min: u8) -> i64 {
let mut lhs = toks[*pos].to_digit(10).unwrap() as i64;
*pos += 1;
while let Some(&op) = toks.get(*pos) {
let Some(p) = bp(op) else { break };
if p < min {
break;
}
*pos += 1;
let rhs = expr(toks, pos, p);
lhs = match op { '+' => lhs + rhs, '-' => lhs - rhs, '*' => lhs * rhs, _ => lhs / rhs };
}
lhs
}
fn main() {
for s in ["1+2*3", "2*3+1", "8-4-2", "8/4/2", "9-2*3-1"] {
let toks: Vec<char> = s.chars().collect();
println!("{s} = {}", expr(&toks, &mut 0, 1));
}
}
$ rustc --edition 2021 -O -o minus_bug minus_bug.rs && ./minus_bug
1+2*3 = 7
2*3+1 = 7
8-4-2 = 6
8/4/2 = 4
9-2*3-1 = 4
Solution
Solution of Exercise 2.5.
The recursive call parses the right operand with minimum power p instead of p + 1, so an operator of the same power is allowed inside the right operand, and equal operators group to the right. is computed as , as , and as . The other two have no two operators of the same power in a row, so the bug cannot show. The fix is expr(toks, pos, p + 1) (exercises/ex5_minus_fixed.rs, tested): by Theorem 2.10 the right child then has a strictly higher power.
Exercise 2.6 ★★
Add to moor.grammar a loop for i = a to b { … }, with an optional step c before the block, and check with the chapter’s tools that the grammar stays LL(1). Then say how a parser can build this loop from the existing AST nodes alone, and which choice the language designer must make about b.
Solution
Solution of Exercise 2.6.
The file exercises/ex6_moor_for.grammar adds an alternative and a nonterminal:
Stmt -> … | for id = E to E Step Block Step -> step E | eps
and the table still has no conflict (tests/grammar_test.rs). for is a new token, so it collides with no other statement, and after the second expression the parser sees step or {, neither of which can continue an expression. The parser can build, for for i = a to b step c { body }, a block containing var i = a; and while i <= b { body; i = i + c; }: no new node is needed. The designer must decide whether b is evaluated once, before the loop (then the desugaring stores it in a hidden variable first), or at every test, as the plain while does; the two differ when the body changes what b reads. A negative c also needs a decision, since <= is then the wrong test.
Exercise 2.7 ★★
Prove that Method 2.3 terminates, after at most passes for FOLLOW, where and are the sets of nonterminals and terminals, and that the sets it computes are the least ones satisfying the inclusions. Then prove that the least solution is the FOLLOW of the definition.
Solution
Solution of Exercise 2.7.
Termination: each pass either changes nothing, and the method stops, or adds at least one terminal to some set. There are FOLLOW sets, each a subset of , so at most passes add something, and one more pass sees no change. The same argument bounds the FIRST phase with (the nullable flags count too). Least solution: call a family of sets a solution if it satisfies all the inclusions. Every solution contains the sets of the iteration at every pass, by induction: initially all are empty (except $, which every solution contains), and each step adds to a set only what an inclusion forces, given sets that are already inside the solution. So the final sets are below every solution, and they are a solution since a pass changes nothing. It is FOLLOW: the true FOLLOW sets satisfy each inclusion (if and , a derivation reaching continues to ; if is nullable, anything after comes after ), so they contain the least solution. Conversely, if by a derivation , an induction on the length of that derivation shows that enters the computed set: the step that put next to the symbols that produce is a production whose inclusion adds it.
Exercise 2.8 ★★
Predict the messages, with line and column, of the parser on this file (lines numbered from 1), and say what panic mode skips after each:
fn main() {
var y = 3 +* 4;
while y > 0 { y = y - 1
print(y);
}
Solution
Solution of Exercise 2.8.
Three messages, which the parser tests check. Line 2, column 16: expected an expression, found '*'; panic mode skips * 4 and consumes the ;. Line 4, column 5: expected ';', found name 'print', because the newline after y - 1 means nothing to the parser and print is read as the continuation of the assignment; panic mode skips print(y) and consumes its ;, so the print is lost from the tree. The } on line 5 then closes the while’s block, not main’s, and line 6, column 1 reports expected ’}’, found end of file. The mistake (a missing ; and a missing }) is on line 3; both messages point later.
Exercise 2.9 ★★
Count the calls the parser of Listing 2.6 makes (of expr_bp, prefix and primary) on a chain of operands joined by +, and the calls a layered recursive-descent parser makes (one function per level as in the figure of call trees). Do the same for a chain of products.
Solution
Solution of Exercise 2.9.
Precedence climbing: on operands joined by +, expr_bp is called once for the whole expression and once for each of the right operands, times in all; each of those parses one operand through prefix and primary, times each: calls. A chain of products costs the same : precedence climbing does not care which level an operator has. The layered parser (eight functions as in the figure) calls the functions of ||, &&, equality, comparison and sum once each, and product, prefix and primary once per operand: . For products, the six functions down to the product are called once and prefix and primary once per operand: . The weekend problem counts the general case.
Exercise 2.10 ★★★
Prove that an LL(1) grammar is unambiguous. Is the converse true?
Solution
Solution of Exercise 2.10.
Let be LL(1) and with two parse trees. They give two different leftmost derivations of . Consider the first step at which they differ: both rewrite the same leftmost nonterminal in the same sentential form , where is a prefix of , one by and the other by , . Let be the token of after (or $). As in the proof of Theorem 2.6, each derivation puts its production in cell : if the production derives a word starting with , through FIRST; if it derives in that derivation, through FOLLOW. So the cell holds two productions, a contradiction. The converse is false: , is unambiguous but left-recursive, hence not LL(1); and some unambiguous languages have no LL(1) grammar at all (exercise 2.11).
Exercise 2.11 ★★★
Show that the grammar , , is not LL() for any : no fixed number of tokens of lookahead lets a top-down parser choose between and . Give a parser that does recognise its language by reading the input once, and say why it is not top-down in the sense of this chapter.
Solution
Solution of Exercise 2.11.
The language is . To choose between and a top-down parser must predict at the very first token. With tokens of lookahead it sees at most on the inputs and , which agree on their first tokens but need different first predictions; so no LL() table can have a single production in cell . (Every grammar for this language has the same trouble, for the same reason, but that is harder to prove.) A parser that reads the input once can count the as, see c or d, and then check that or bs follow: it postpones the choice until it has seen the distinguishing token. That is what a bottom-up parser does in general (chapter 3): it builds the tree from the leaves and decides which production applies only when all of its right side has been read.
Exercise 2.12 ★★★
Some languages let the programmer declare new operators with a precedence and an associativity. Write a precedence-climbing parser whose operator table is given at run time: each operator has a binding power and is left-associative, right-associative, or non-associative (a == b == c is then an error). Test it on a table with a right-associative power and a list constructor ::.
Solution
Solution of Exercise 2.12.
exercises/ex12_userops.rs. The table maps each operator to its power and associativity. The loop of precedence climbing is unchanged, except for the minimum of the recursive call: for a left-associative operator, for a right-associative one (an operator of the same power may then appear in the right operand, so equal operators group to the right). A non-associative operator is parsed as a left-associative one, and the loop remembers that it has just combined a non-associative operator of power ; a second operator of the same power in the same loop is an error. The tests check a - b - c, a ^ b ^ c, x :: y :: z, mixed powers, parentheses, a == b == c refused, and two malformed inputs.
2.7 Weekend problem
Problem 2.1
Weekend problem — The library’s fines formula
Brenmoor’s library computes a late fine with a formula typed by a clerk, for instance
max(0, days - 14) * rate + 2 ^ late ^ 2 * (items > 3) + 10 * (lost or damaged and items >= 1)
Formulas have numbers, names, calls max(…) and min(…), parentheses, and seven levels of binary operators, loosest first: or; and; == !=; < <= > >=; + -; * /; and ^, the power, which is right-associative. The file exercises/pb_fines.rs parses formulas in two ways and counts the calls; reason each answer out before running it.
Part I — The grammar.
- Write a grammar for formulas with one nonterminal per level, in the style . Which productions are left-recursive, and which one is right-recursive, and why?
- Remove the left recursion, as in Listing 2.3. How many nonterminals does the result have?
- The power level is . Left-factor it.
- A name may be followed by
(for a call. Write the productions of the primary so that the grammar stays LL(1). - Draw the abstract syntax tree of
2 ^ late ^ 2 * (items > 3). - What is the value of the example formula for days 20, rate 3, late 1, items 4, lost 0 and damaged 1 (
andandorgive 1 or 0)?
Part II — Sets and table.
- Compute FIRST of the primary and of every level’s nonterminal. Why are they all equal?
- Compute FOLLOW of the primary, and of the “rest of a sum” nonterminal.
- Fill the row of the “rest of a sum” nonterminal in the table. Which columns hold its -production?
- Check that the grammar is LL(1) with
grammar.rs. - The clerk asks for the unary minus
-x. Add it at the right level and check that the grammar stays LL(1). - Would a comparison chain
a < b < cparse? What does it mean with 0 and 1 as truth values, and should the grammar allow it?
Part III — Recursive descent, counted.
- The layered parser has a function per level plus one for the primary: functions. Show that the function of level (from 0, loosest) is called times on a formula without parentheses, calls or powers, where is the number of operators of level .
- Deduce the number of calls on a chain of operands joined by
or, by+, and by^. - Which chain is the worst case for a fixed , and how many calls does it take with levels?
- How are parentheses and the arguments of a call counted?
- Count the calls on the example formula, and check with the program.
- Where does the time go: how many of these calls find no operator of their own level?
Part IV — Precedence climbing.
- Give the binding powers that make precedence climbing build the same trees, and say what the right-associative power changes in the recursive call.
- Show that precedence climbing makes exactly two calls per primary: one to parse the primary and one to parse an expression that starts with it, or the whole formula.
- Count its calls on the three chains of question 14 and on the example formula.
- The program parses 2,000 random formulas both ways. What must it check, and why is that enough to trust the counts?
- Adding an eighth level to the language: what does it cost each parser, per primary?
- State the result: calls of each parser on a chain of operands at the loosest level with levels, and on the example formula.
Solution
Solution of Problem 2.1.
The counts and values below are asserted in tests/pb_test.rs; the grammar facts are checked on exercises/fines.grammar by the grammar tests.
1. , , and likewise for equality, comparison, sum and product, each level’s operand being the next level; ; . The six left-associative levels are left-recursive: makes the left operand the larger tree. The power is right-recursive, so that 2 ^ 3 ^ 2 is .
2. Each left-recursive level becomes , : twelve nonterminals for the six levels. With the power (two, after question 3), the primary, and two for calls, the grammar has 17 nonterminals.
3. , .
4. , , : a name is read first, and the next token decides between a call and a plain name.
5. A product whose left operand is (^ 2 (^ late 2)) and whose right operand is (> items 3); the parentheses leave no node.
6. ; times gives 2; damaged and items >= 1 is 1, so the or is 1 and the last term is 10. The fine is .
7. Every level’s nonterminal starts with its operand, down to the primary, so all have : no level is nullable, and an expression must start with a primary.
8. is everything that may follow an operand: every binary operator, ), the comma of an argument list, and $. The “rest of a sum” is followed by what follows a sum: the comparison and equality operators, and, or, ), the comma and $, eleven terminals.
9. and hold the productions that continue the sum; the eleven columns of hold ; the others are empty, and an operator such as * in that row is an error, since a product has already been read in full.
10. grammar.rs finds no cell with two productions (fines_grammars_are_ll1).
11. : the unary minus applies to a primary and binds tighter than the power, or if should be , as in mathematics. Either way the new production starts with -, which is in FIRST of no other production of that nonterminal: the grammar stays LL(1) (exercises/fines_neg.grammar takes the first choice).
12. It parses, as (a < b) < c, which compares a truth value 0 or 1 with ; for , , it gives 1, which no clerk means. The grammar should refuse it: make comparison non-associative, , , which allows at most one comparison.
13. Level is first called once, for the whole formula. A left-associative level calls level once for its first operand and once for each operator of level it consumes. By induction on , level is called once more for each operator of any looser level: .
14. A chain of operands by or: level 0 once, the seven others times each: . By + (level 4): levels 0 to 4 once each, levels 5, 6 and the primary times: . By ^: levels 0 to 5 once, the power level once plus once per recursion (), the primary : .
15. The loosest operator: every operand then passes through every level. With levels, calls.
16. A parenthesised expression and each argument of a call start again at level 0: each costs calls before its first primary, as a whole formula would.
17. 80 calls, for 17 primaries (counting max(…) and each parenthesis as one).
18. Most of them. A call finds an operator of its own level only when one follows; the formula has 12 binary operators, and of the 80 calls 17 parse a primary, so at least calls return having done nothing but call the next level.
19. Power for level : 1 for or up to 7 for ^. For a left-associative operator of power the right operand is parsed with minimum ; for the power, with minimum , so that another ^ may appear inside the right operand.
20. Every call of expr parses one primary first, and every primary is the first primary of exactly one expr call: the whole formula’s, an operator’s right operand’s, a parenthesised expression’s, or an argument’s. So there are as many expr calls as primaries, and with the primary calls, two calls per primary.
21. for each of the three chains; 34 for the example formula, .
22. That both parsers return the same tree on every formula. Equal trees mean both parsers have read the same structure; the counts then measure the same work, and a bug that built wrong trees would show as a mismatch.
23. One more call per primary for the layered parser in the worst case (one more function to pass through), and one more function to write; nothing for precedence climbing, whose cost does not depend on , only one more row in its table.
24. With levels and operands joined by the loosest operator, layered recursive descent makes calls and precedence climbing : against for the library’s seven levels. On the fines formula, 80 calls against 34.