---
title: "Top-Down Parsing"
book: "University Computer Science — Year 3"
subject: computer-science
language: en
chapter: 2
exercises: 12
source: https://one-course.com/books/computer-science/5/en/chapter/2-top-down-parsing
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 2 — Top-Down Parsing

The [scanner](https://one-course.com/books/computer-science/5/en/chapter/1-lexical-analysis#def-b3-lexical-analysis-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 $(1 - 2) - 3$ and not $1 - (2 - 3)$, 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 \to \alpha$. 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:

$$
E \to E + T \mid T \qquad T \to T * F \mid F \qquad F \to (\,E\,) \mid \mathit{id}.
$$

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 $b$ was derived through $F$ and $T$ 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.

![The parse tree and the abstract syntax tree of a + b * c. The AST keeps the operators and their operands and drops the nonterminals that only encoded precedence.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-top-down-parsing/fig-03a96403856b.svg)

*The parse tree and the [abstract syntax tree](#def-b3-top-down-parsing-ast) of `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](#lst-b3-top-down-parsing-ast). 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.

```rust
#[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),
}

```

***Listing 2.1.** The expressions and statements of Moor’s AST. Frozen. code/bachelor-3/02-top-down-parsing/listings/ast.rs*

## 2.2 Nullable, FIRST and FOLLOW

A top-down parser builds the tree from the root. Facing a nonterminal $A$ and the next token $a$, it must choose a production of $A$. Three sets, computed once from the grammar, tell it which productions can possibly start with $a$.

**Definition 2.2 (Nullable, FIRST, FOLLOW).**

Let $G$ be a grammar and $\alpha$ a string of terminals and nonterminals. $\alpha$ is *nullable* if $\alpha \Rightarrow^* \varepsilon$. The *FIRST set* $\mathrm{FIRST}(\alpha)$ is the set of terminals $a$ such that $\alpha \Rightarrow^* a\beta$ for some $\beta$. For a nonterminal $A$, the *FOLLOW set* $\mathrm{FOLLOW}(A)$ is the set of terminals $a$ such that $S \Rightarrow^* \beta A a \gamma$ for some $\beta, \gamma$, where $S$ is the start symbol; it contains the end marker $ if $S \Rightarrow^* \beta A$.

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 $A \to X_1 \dots X_n$:

- $A$ is [nullable](#def-b3-top-down-parsing-first-follow) if every $X_i$ is;
- $\mathrm{FIRST}(A) \supseteq \mathrm{FIRST}(X_i)$ whenever $X_1 \dots X_{i-1}$ is [nullable](#def-b3-top-down-parsing-first-follow) (and $\mathrm{FIRST}(a) = \{a\}$ for a terminal);
- for each nonterminal $X_i$ , $\mathrm{FOLLOW}(X_i)$ contains $\mathrm{FIRST}(X_{i+1} \dots X_n)$ , and also $\mathrm{FOLLOW}(A)$ if $X_{i+1} \dots X_n$ is [nullable](#def-b3-top-down-parsing-first-follow) .

**Method 2.3 (Sets by iteration).**

Start with every set empty and no nonterminal [nullable](#def-b3-top-down-parsing-first-follow), and $\$ \in \mathrm{FOLLOW}(S)$. Pass over the productions, applying each inclusion above and growing the sets; repeat until a whole pass changes nothing. Do [nullable](#def-b3-top-down-parsing-first-follow) 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](#exo-b3-top-down-parsing-7)). Chapter 8 meets this pattern again, as a fixed point of dataflow equations. [Listing 2.2](#lst-b3-top-down-parsing-compute) is the method over a grammar read from a text file.

```rust

/// 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
}
```

***Listing 2.2.** [Nullable](#def-b3-top-down-parsing-first-follow), FIRST and FOLLOW as least fixed points. `first_seq` computes FIRST of a sequence and tells whether it is [nullable](#def-b3-top-down-parsing-first-follow). code/bachelor-3/02-top-down-parsing/listings/grammar.rs*

The 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.

```text
# 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
```

***Listing 2.3.** Sums and products, with [left recursion](#def-b3-top-down-parsing-left-recursion) removed: $E'$ is “the rest of a sum”. code/bachelor-3/02-top-down-parsing/listings/expr.grammar*

```
$ 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
```

***Output 2.1.** [Nullable](#def-b3-top-down-parsing-first-follow), FIRST and FOLLOW of [Listing 2.3](#lst-b3-top-down-parsing-exprgrammar).*

Read the [FOLLOW sets](#def-b3-top-down-parsing-first-follow) as “what may come after”. A product $T$ may be followed by `+` (more sum), by `)` (the end of a parenthesised sum) or by the end of input. A factor $F$ 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 $A \to \alpha$ is put in cell $[A, a]$ for every $a \in \mathrm{FIRST}(\alpha)$, and, if $\alpha$ is [nullable](#def-b3-top-down-parsing-first-follow), for every $a \in \mathrm{FOLLOW}(A)$. 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 $A \to \alpha \mid \beta$: $\mathrm{FIRST}(\alpha)$ and $\mathrm{FIRST}(\beta)$ are disjoint, at most one of them is [nullable](#def-b3-top-down-parsing-first-follow), and if $\beta$ is [nullable](#def-b3-top-down-parsing-first-follow) then $\mathrm{FIRST}(\alpha)$ and $\mathrm{FOLLOW}(A)$ 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 $A$ and the next token is $a$, look up $[A, a]$: if it is empty, report an error; otherwise pop $A$ 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](#out-b3-top-down-parsing-driver) 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
```

***Output 2.2.** The predictive parser of [Listing 2.3](#lst-b3-top-down-parsing-exprgrammar) on `id + id * id`: each line shows the stack, the input left, and what the table said.*

![The first eight stacks of the predictive parser, bottom to top: each column is the stack after the action written under it. Predicting a production replaces a nonterminal by its right side; matching pops a terminal.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-top-down-parsing/fig-6a37cd0836d5.svg)

*The first eight stacks of the predictive parser, bottom to top: each column is the stack after the action written under it. Predicting a production replaces a nonterminal by its right side; matching pops a terminal.*

**Theorem 2.6 (Predictive parsing is correct for LL(1) grammars).**

If $G$ is LL(1), the predictive parser accepts a word $w$ if and only if $w \in L(G)$, and then the productions it predicts, in order, are those of the leftmost derivation of $w$.

**Proof.** At every step the stack, read from top to bottom, is a sentential form $\gamma$ such that $S \Rightarrow^*_{\mathrm{lm}} u\gamma$ where $u$ is the input already matched: this holds at the start ($u = \varepsilon$, $\gamma = S$), and each prediction or match keeps it. So an accepted word is derived by the predicted productions, leftmost first. Conversely, let $w \in L(G)$ with leftmost derivation $D$. Suppose the parser has followed $D$ so far and $D$ next rewrites the top nonterminal $A$ by $A \to \alpha$, with $a$ the next token. Either $\alpha$ derives a word starting with $a$, so $a \in \mathrm{FIRST}(\alpha)$, or $\alpha$ derives $\varepsilon$ in $D$ and $a$ comes from what follows $A$, so $a \in \mathrm{FOLLOW}(A)$ and $\alpha$ is [nullable](#def-b3-top-down-parsing-first-follow). Either way $A \to \alpha$ is in cell $[A, a]$, and it is alone there because $G$ is LL(1): the parser predicts the production of $D$. By induction it follows $D$ to the end and accepts. ∎

Two features of grammars put two productions in one cell. The first is the one that made $E \to E + T$ unusable.

**Definition 2.7 (Left recursion, left factoring).**

A grammar has *left recursion* if some nonterminal $A$ derives $A\alpha$ in one or more steps. *Left factoring* replaces productions $A \to \beta\gamma_1 \mid \beta\gamma_2$ that share a prefix $\beta$ by $A \to \beta A'$ and $A' \to \gamma_1 \mid \gamma_2$, with a new nonterminal $A'$.

A left-recursive production $A \to A\alpha \mid \beta$ puts both productions in every cell of $\mathrm{FIRST}(\beta)$: whatever starts a $\beta$ also starts an $A\alpha$. The standard rewrite replaces it by $A \to \beta A'$ and $A' \to \alpha A' \mid \varepsilon$, which generates the same words, $\beta\alpha^*$, from the left; [Listing 2.3](#lst-b3-top-down-parsing-exprgrammar) is that rewrite applied twice. [Left factoring](#def-b3-top-down-parsing-left-recursion) 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](#out-b3-top-down-parsing-table) 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)
```

***Output 2.3.** The table of `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](#def-b3-top-down-parsing-ll1): `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($k$) 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](#def-b3-top-down-parsing-precedence), the method this chapter calls [precedence climbing](#def-b3-top-down-parsing-precedence).

## 2.4 Recursive descent

**Definition 2.8 (Recursive descent).**

A *recursive descent* parser has one function per nonterminal. The function for $A$ looks at the next token (or the next few), chooses a production of $A$, 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](#lst-b3-top-down-parsing-func): it follows the production `fn id ( params ) [-> type] block` symbol by symbol, with a loop where the grammar has a repetition.

```rust
    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 })
    }
```

***Listing 2.4.** [Recursive descent](#def-b3-top-down-parsing-descent) for a function definition: each line is one symbol of the production. code/bachelor-3/02-top-down-parsing/listings/parser.rs*

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.

```rust
            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()) })
```

***Listing 2.5.** The end of the statement function: two-token lookahead for `x = e;`, and the check of an assignment’s target. code/bachelor-3/02-top-down-parsing/listings/parser.rs*

Expressions are where the classic layout of [recursive descent](#def-b3-top-down-parsing-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](#def-b3-top-down-parsing-precedence) 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 $m$ as follows: parse an operand; then, while the next token is an operator of power $p \ge m$, consume it, parse the right operand as an expression of minimum power $p + 1$, and combine.

```rust
    /// 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)) })
    }
```

***Listing 2.6.** [Precedence climbing](#def-b3-top-down-parsing-precedence) and the prefix operators. `bp + 1` makes every binary operator left-associative. code/bachelor-3/02-top-down-parsing/listings/parser.rs*

**Theorem 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 $p$ has a left child of power at least $p$ and a right child of power greater than $p$ (an operand counts as power $\infty$). So operators of higher power are deeper, and operators of equal power group to the left.

**Proof.** A call `expr_bp($m$)` returns a tree all of whose operators have power at least $m$: it only combines operators with $p \ge m$, and their right operands come from calls with minimum $p + 1 > m$; this is an induction on the depth of calls. Now take a node built by the loop for an operator of power $p$. Its right child came from `expr_bp($p + 1$)`, so its root has power at least $p + 1$. Its left child is the tree built so far in the same call: either the first operand, or a node for an operator $q$ combined earlier in the same loop. When the loop combined $q$, the right operand of $q$ stopped at our operator, so $p < q + 1$, that is $q \ge p$. ∎

```
$ 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
```

***Output 2.4.** Trees built by [precedence climbing](#def-b3-top-down-parsing-precedence). The last expression is refused: Moor indexes only a name, not the result of a call.*

The figure below compares the calls of the two layouts on `a + b * c`. [Precedence climbing](#def-b3-top-down-parsing-precedence) 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.

![Call trees for a + b * c. Left: one function per level of ||, &&, equality, comparison, sum, product, then the prefix operators and the primary. Right: the parser of , where the right side of + is parsed with minimum power 6 and that of * with 7.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-top-down-parsing/fig-a4fa4c6c426c.svg)

*Call trees for `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](#lst-b3-top-down-parsing-climb), where the right side of `+` is parsed with minimum power 6 and that of `*` with 7.*

[Output 2.5](#out-b3-top-down-parsing-fib) runs the whole parser on the Fibonacci program and prints its tree, one statement per line.

```text
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; }
}
```

***Listing 2.7.** `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)
```

***Output 2.5.** The [abstract syntax tree](#def-b3-top-down-parsing-ast) of `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](#def-b3-top-down-parsing-recovery) for statements. A statement function that fails returns an error marker up to the block function, which calls [Listing 2.8](#lst-b3-top-down-parsing-sync) and then tries the next statement. At the top level, `fn`, `var` and `array` play the same part.

```rust
    /// 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();
                }
            }
        }
    }
```

***Listing 2.8.** Panic mode: skip to the end of the statement, or to the start of the next one. code/bachelor-3/02-top-down-parsing/listings/parser.rs*

```text
fn main() {
    var x = (1 + 2;
    x = x * ;
    if x > 3 { print(x) }
    print(x);
}
```

***Listing 2.9.** Three syntax errors. code/bachelor-3/02-top-down-parsing/listings/errors.moor*

```
$ 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)
```

***Output 2.6.** All three are reported, each once, and the tree is built for the rest.*

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](#out-b3-top-down-parsing-recover) 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](#def-b3-top-down-parsing-descent).

## 2.6 Exercises

**Exercise 2.1 ★.**

Compute [nullable](#def-b3-top-down-parsing-first-follow) and FIRST for the grammar $S \to A\,B\,c \mid d$, $A \to a\,A \mid \varepsilon$, $B \to b \mid \varepsilon$.

**Solution of Exercise 2.1.**

$A$ and $B$ are [nullable](#def-b3-top-down-parsing-first-follow) ($A \to \varepsilon$, $B \to \varepsilon$); $S$ is not, since both its productions contain a terminal. $\mathrm{FIRST}(A) = \{a\}$, $\mathrm{FIRST}(B) = \{b\}$. For $S \to A\,B\,c$: $A$ contributes $a$, and since $A$ is [nullable](#def-b3-top-down-parsing-first-follow) $B$ contributes $b$, and since $B$ is [nullable](#def-b3-top-down-parsing-first-follow) too, $c$ is in; $S \to d$ adds $d$. So $\mathrm{FIRST}(S) = \{a, b, c, d\}$. 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 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 $S \to A\,a \mid b$, $A \to a \mid \varepsilon$ LL(1)? Fill its table and say which cell decides. Describe the language it generates and give an [LL(1) grammar](#def-b3-top-down-parsing-ll1) for it.

**Solution of Exercise 2.3.**

No. $\mathrm{FIRST}(A\,a) = \{a\}$, $\mathrm{FIRST}(b) = \{b\}$: the row of $S$ has no conflict. But $A$ is [nullable](#def-b3-top-down-parsing-first-follow) and $\mathrm{FOLLOW}(A) = \{a\}$, so cell $[A, a]$ holds both $A \to a$ (by FIRST) and $A \to \varepsilon$ (by FOLLOW). Seeing an `a`, the parser cannot tell whether it is $A$’s or the one after $A$. The language is $\{aa, a, b\}$, and $S \to a\,S' \mid b$, $S' \to a \mid \varepsilon$ is an [LL(1) grammar](#def-b3-top-down-parsing-ll1) for it: after the first `a`, the next token is `a` or the end.

**Exercise 2.4 ★.**

Remove the [left recursion](#def-b3-top-down-parsing-left-recursion) from $L \to L\,,\,\mathit{id} \mid \mathit{id}$ (a comma-separated list), and write the recursive-descent function for the result as a loop.

**Solution of Exercise 2.4.**

$L \to \mathit{id}\,L'$, $L' \to ,\,\mathit{id}\,L' \mid \varepsilon$. 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 $L'$ becomes the loop; FOLLOW of $L'$ 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](#lst-b3-top-down-parsing-minus) is a calculator for one-digit numbers. Three of its five answers in [Output 2.7](#out-b3-top-down-parsing-minus) are wrong. Find the bug, explain the wrong answers, and fix it.

```rust
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));
    }
}
```

***Listing 2.10.** A calculator by [precedence climbing](#def-b3-top-down-parsing-precedence). code/bachelor-3/02-top-down-parsing/listings/minus_bug.rs*

```
$ 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
```

***Output 2.7.** Its answers.*

**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. $8 - 4 - 2$ is computed as $8 - (4 - 2) = 6$, $8/4/2$ as $8/(4/2) = 4$, and $9 - 2 \times 3 - 1$ as $9 - (6 - 1) = 4$. 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](#thm-b3-top-down-parsing-climb) 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 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](#met-b3-top-down-parsing-iterate) terminates, after at most $|N|\,(|T| + 1) + 1$ passes for FOLLOW, where $N$ and $T$ 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 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 $|N|$ FOLLOW sets, each a subset of $T \cup \{\$\}$, so at most $|N|(|T| + 1)$ passes add something, and one more pass sees no change. The same argument bounds the FIRST phase with $|N|\,|T| + |N|$ (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 $A \to \dots X_i \beta$ and $a \in \mathrm{FIRST}(\beta)$, a derivation reaching $A$ continues to $X_i a\dots$; if $\beta$ is nullable, anything after $A$ comes after $X_i$), so they contain the least solution. Conversely, if $a \in \mathrm{FOLLOW}(X)$ by a derivation $S \Rightarrow^* \beta X a \gamma$, an induction on the length of that derivation shows that $a$ enters the computed set: the step that put $X$ next to the symbols that produce $a$ 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:

```text
fn main() {
    var y = 3 +* 4;
    while y > 0 { y = y - 1
    print(y);
}
```

***Listing 2.11.** A file with mistakes. code/bachelor-3/02-top-down-parsing/exercises/ex8.moor*

**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](#lst-b3-top-down-parsing-climb) makes (of `expr_bp`, `prefix` and `primary`) on a chain of $n$ 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 of Exercise 2.9.**

[Precedence climbing](#def-b3-top-down-parsing-precedence): on $n$ operands joined by `+`, `expr_bp` is called once for the whole expression and once for each of the $n - 1$ right operands, $n$ times in all; each of those parses one operand through `prefix` and `primary`, $n$ times each: $3n$ calls. A chain of products costs the same $3n$: [precedence climbing](#def-b3-top-down-parsing-precedence) 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: $3n + 5$. For products, the six functions down to the product are called once and prefix and primary once per operand: $2n + 6$. The weekend problem counts the general case.

**Exercise 2.10 ★★★.**

Prove that an [LL(1) grammar](#def-b3-top-down-parsing-ll1) is unambiguous. Is the converse true?

**Solution of Exercise 2.10.**

Let $G$ be LL(1) and $w \in L(G)$ with two parse trees. They give two different leftmost derivations of $w$. Consider the first step at which they differ: both rewrite the same leftmost nonterminal $A$ in the same sentential form $u A \gamma$, where $u$ is a prefix of $w$, one by $A \to \alpha$ and the other by $A \to \beta$, $\alpha \ne \beta$. Let $a$ be the token of $w$ after $u$ (or $). As in the proof of [Theorem 2.6](#thm-b3-top-down-parsing-ll1), each derivation puts its production in cell $[A, a]$: if the production derives a word starting with $a$, through FIRST; if it derives $\varepsilon$ in that derivation, through FOLLOW. So the cell holds two productions, a contradiction. The converse is false: $E \to E + T \mid T$, $T \to \mathit{id}$ is unambiguous but left-recursive, hence not LL(1); and some unambiguous languages have no [LL(1) grammar](#def-b3-top-down-parsing-ll1) at all (exercise [2.11](#exo-b3-top-down-parsing-11)).

**Exercise 2.11 ★★★.**

Show that the grammar $S \to A \mid B$, $A \to a\,A\,b \mid c$, $B \to a\,B\,b\,b \mid d$ is not LL($k$) for any $k$: no fixed number of tokens of lookahead lets a top-down parser choose between $A$ and $B$. 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 of Exercise 2.11.**

The language is $\{a^n c b^n\} \cup \{a^n d b^{2n}\}$. To choose between $S \to A$ and $S \to B$ a top-down parser must predict at the very first token. With $k$ tokens of lookahead it sees at most $a^k$ on the inputs $a^k c b^k$ and $a^k d b^{2k}$, which agree on their first $k$ tokens but need different first predictions; so no LL($k$) table can have a single production in cell $[S, a^k]$. (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 `a`s, see `c` or `d`, and then check that $n$ or $2n$ `b`s 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](#def-b3-top-down-parsing-precedence) 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 of Exercise 2.12.**

`exercises/ex12_userops.rs`. The table maps each operator to its power and associativity. The loop of [precedence climbing](#def-b3-top-down-parsing-precedence) is unchanged, except for the minimum of the recursive call: $p + 1$ for a left-associative operator, $p$ 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 $p$; 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.**

1. Write a grammar for formulas with one nonterminal per level, in the style $E \to E + T \mid T$ . Which productions are left-recursive, and which one is right-recursive, and why?
2. Remove the [left recursion](#def-b3-top-down-parsing-left-recursion) , as in [Listing 2.3](#lst-b3-top-down-parsing-exprgrammar) . How many nonterminals does the result have?
3. The power level is $P \to U\,\text{\textasciicircum}\,P \mid U$ . Left-factor it.
4. A name may be followed by `(` for a call. Write the productions of the primary so that the grammar stays LL(1).
5. Draw the [abstract syntax tree](#def-b3-top-down-parsing-ast) of `2 ^ late ^ 2 * (items > 3)` .
6. What is the value of the example formula for days 20, rate 3, late 1, items 4, lost 0 and damaged 1 ( `and` and `or` give 1 or 0)?

**Part II — Sets and table.**

7. Compute FIRST of the primary and of every level’s nonterminal. Why are they all equal?
8. Compute FOLLOW of the primary, and of the “rest of a sum” nonterminal.
9. Fill the row of the “rest of a sum” nonterminal in the table. Which columns hold its $\varepsilon$ -production?
10. Check that the grammar is LL(1) with `grammar.rs` .
11. The clerk asks for the unary minus `-x` . Add it at the right level and check that the grammar stays LL(1).
12. Would a comparison chain `a < b < c` parse? What does it mean with 0 and 1 as truth values, and should the grammar allow it?

**Part III — Recursive descent, counted.**

13. The layered parser has a function per level plus one for the primary: $p + 1 = 8$ functions. Show that the function of level $k$ (from 0, loosest) is called $1 + \sum_{j < k} o_j$ times on a formula without parentheses, calls or powers, where $o_j$ is the number of operators of level $j$ .
14. Deduce the number of calls on a chain of $n$ operands joined by `or` , by `+` , and by `^` .
15. Which chain is the worst case for a fixed $n$ , and how many calls does it take with $p$ levels?
16. How are parentheses and the arguments of a call counted?
17. Count the calls on the example formula, and check with the program.
18. Where does the time go: how many of these calls find no operator of their own level?

**Part IV — Precedence climbing.**

19. Give the [binding powers](#def-b3-top-down-parsing-precedence) that make [precedence climbing](#def-b3-top-down-parsing-precedence) build the same trees, and say what the right-associative power changes in the recursive call.
20. Show that [precedence climbing](#def-b3-top-down-parsing-precedence) 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.
21. Count its calls on the three chains of question 14 and on the example formula.
22. The program parses 2,000 random formulas both ways. What must it check, and why is that enough to trust the counts?
23. Adding an eighth level to the language: what does it cost each parser, per primary?
24. State the result: calls of each parser on a chain of $n$ operands at the loosest level with $p$ levels, and on the example formula.

**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.** $E \to E\ \texttt{or}\ A \mid A$, $A \to A\ \texttt{and}\ Q \mid Q$, and likewise for equality, comparison, sum and product, each level’s operand being the next level; $P \to U\,\text{\textasciicircum}\,P \mid U$; $U \to \mathit{num} \mid \mathit{name} \mid \mathit{name}\,(\,\mathit{args}\,) \mid (\,E\,)$. The six left-associative levels are left-recursive: $E \to E\ \texttt{or}\ A$ makes the left operand the larger tree. The power is right-recursive, so that `2 ^ 3 ^ 2` is $2^{(3^2)} = 512$.

**2.** Each left-recursive level $X \to X\,\mathit{op}\,Y \mid Y$ becomes $X \to Y X'$, $X' \to \mathit{op}\,Y X' \mid \varepsilon$: 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.** $P \to U\,P'$, $P' \to \text{\textasciicircum}\,P \mid \varepsilon$.

**4.** $U \to \mathit{num} \mid (\,E\,) \mid \mathit{name}\ \mathit{Call}$, $\mathit{Call} \to (\,E\,\mathit{MoreA}\,) \mid \varepsilon$, $\mathit{MoreA} \to ,\,E\,\mathit{MoreA} \mid \varepsilon$: 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.** $\max(0, 6) \times 3 = 18$; $2^{1^2} = 2$ times $(4 > 3) = 1$ gives 2; `damaged and items >= 1` is 1, so the `or` is 1 and the last term is 10. The fine is $18 + 2 + 10 = 30$.

**7.** Every level’s nonterminal starts with its operand, down to the primary, so all have $\mathrm{FIRST} = \{\mathit{num}, \mathit{name}, (\}$: no level is [nullable](#def-b3-top-down-parsing-first-follow), and an expression must start with a primary.

**8.** $\mathrm{FOLLOW}(U)$ is everything that may follow an operand: every binary operator, `)`, the comma of an argument list, and $. The “rest of a sum” $S'$ is followed by what follows a sum: the comparison and equality operators, `and`, `or`, `)`, the comma and $, eleven terminals.

**9.** $[S', +]$ and $[S', -]$ hold the productions that continue the sum; the eleven columns of $\mathrm{FOLLOW}(S')$ hold $S' \to \varepsilon$; 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.** $U \to -\,U \mid \dots$: the unary minus applies to a primary and binds tighter than the power, or $P \to -\,P$ if $-2\text{\textasciicircum}2$ should be $-4$, 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 $c$; for $a = 5$, $b = 3$, $c = 2$ it gives 1, which no clerk means. The grammar should refuse it: make comparison non-associative, $C \to S\,C'$, $C' \to \mathit{cmp}\,S \mid \varepsilon$, which allows at most one comparison.

**13.** Level $k$ is first called once, for the whole formula. A left-associative level $j$ calls level $j + 1$ once for its first operand and once for each operator of level $j$ it consumes. By induction on $k$, level $k$ is called once more for each operator of any looser level: $1 + \sum_{j<k} o_j$.

**14.** A chain of $n$ operands by `or`: level 0 once, the seven others $n$ times each: $7n + 1$. By `+` (level 4): levels 0 to 4 once each, levels 5, 6 and the primary $n$ times: $3n + 5$. By `^`: levels 0 to 5 once, the power level once plus once per recursion ($n$), the primary $n$: $2n + 6$.

**15.** The loosest operator: every operand then passes through every level. With $p$ levels, $pn + 1$ calls.

**16.** A parenthesised expression and each argument of a call start again at level 0: each costs $p + 1$ 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 $80 - 17 - 12 = 51$ calls return having done nothing but call the next level.

**19.** Power $k + 1$ for level $k$: 1 for `or` up to 7 for `^`. For a left-associative operator of power $p$ the right operand is parsed with minimum $p + 1$; for the power, with minimum $p$, 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.** $2n$ for each of the three chains; 34 for the example formula, $2 \times 17$.

**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](#def-b3-top-down-parsing-precedence), whose cost does not depend on $p$, only one more row in its table.

**24.** With $p$ levels and $n$ operands joined by the loosest operator, layered [recursive descent](#def-b3-top-down-parsing-descent) makes $pn + 1$ calls and [precedence climbing](#def-b3-top-down-parsing-precedence) $2n$: $7n + 1$ against $2n$ for the library’s seven levels. On the fines formula, 80 calls against 34.
