计算机科学 · 第 5 册 · 本科三年级

University Computer Science — Year 3

本书暂未推出简体中文版。现有版本: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 (1−2)−3(1 - 2) - 3 and not 1−(2−3)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→α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→E+T∣TT→T∗F∣FF→( E )∣id.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 bb was derived through FF and TT 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.
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.

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),
}
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 AA and the next token aa, it must choose a production of AA. Three sets, computed once from the grammar, tell it which productions can possibly start with aa.

Definition 2.2 (Nullable, FIRST, FOLLOW)

Let GG be a grammar and α\alpha a string of terminals and nonterminals. α\alpha is nullable if α⇒∗ε\alpha \Rightarrow^* \varepsilon. The FIRST set FIRST(α)\mathrm{FIRST}(\alpha) is the set of terminals aa such that α⇒∗aβ\alpha \Rightarrow^* a\beta for some β\beta. For a nonterminal AA, the FOLLOW set FOLLOW(A)\mathrm{FOLLOW}(A) is the set of terminals aa such that S⇒∗βAaγS \Rightarrow^* \beta A a \gamma for some β,γ\beta, \gamma, where SS is the start symbol; it contains the end marker $ if S⇒∗βAS \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→X1…XnA \to X_1 \dots X_n:

  • AA is nullable if every XiX_i is;
  • FIRST(A)⊇FIRST(Xi)\mathrm{FIRST}(A) \supseteq \mathrm{FIRST}(X_i) whenever X1…Xi−1X_1 \dots X_{i-1} is nullable (and FIRST(a)={a}\mathrm{FIRST}(a) = \{a\} for a terminal);
  • for each nonterminal XiX_i, FOLLOW(Xi)\mathrm{FOLLOW}(X_i) contains FIRST(Xi+1…Xn)\mathrm{FIRST}(X_{i+1} \dots X_n), and also FOLLOW(A)\mathrm{FOLLOW}(A) if Xi+1…XnX_{i+1} \dots X_n is nullable.

Method 2.3 (Sets by iteration)

Start with every set empty and no nonterminal nullable, and $∈FOLLOW(S)\$ \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 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
}
Listing 2.2. Nullable, FIRST and FOLLOW as least fixed points. first_seq computes FIRST of a sequence and tells whether it is nullable. 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.

# 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 removed: E′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, FIRST and FOLLOW of Listing 2.3.

Read the FOLLOW sets as “what may come after”. A product TT may be followed by + (more sum), by ) (the end of a parenthesised sum) or by the end of input. A factor FF 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→αA \to \alpha is put in cell [A,a][A, a] for every a∈FIRST(α)a \in \mathrm{FIRST}(\alpha), and, if α\alpha is nullable, for every a∈FOLLOW(A)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→α∣βA \to \alpha \mid \beta: FIRST(α)\mathrm{FIRST}(\alpha) and FIRST(β)\mathrm{FIRST}(\beta) are disjoint, at most one of them is nullable, and if β\beta is nullable then FIRST(α)\mathrm{FIRST}(\alpha) and FOLLOW(A)\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 AA and the next token is aa, look up [A,a][A, a]: if it is empty, report an error; otherwise pop AA 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
Output 2.2. The predictive parser of Listing 2.3 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.
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 GG is LL(1), the predictive parser accepts a word ww if and only if w∈L(G)w \in L(G), and then the productions it predicts, in order, are those of the leftmost derivation of ww.

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

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

Definition 2.7 (Left recursion, left factoring)

A grammar has left recursion if some nonterminal AA derives AαA\alpha in one or more steps. Left factoring replaces productions A→βγ1∣βγ2A \to \beta\gamma_1 \mid \beta\gamma_2 that share a prefix β\beta by A→βA′A \to \beta A' and A′→γ1∣γ2A' \to \gamma_1 \mid \gamma_2, with a new nonterminal A′A'.

A left-recursive production A→Aα∣βA \to A\alpha \mid \beta puts both productions in every cell of FIRST(β)\mathrm{FIRST}(\beta): whatever starts a β\beta also starts an AαA\alpha. The standard rewrite replaces it by A→βA′A \to \beta A' and A′→αA′∣εA' \to \alpha A' \mid \varepsilon, which generates the same words, βα∗\beta\alpha^*, 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)
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: 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(kk) 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 AA looks at the next token (or the next few), chooses a production of AA, 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 })
    }
Listing 2.4. Recursive 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.

            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 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 mm as follows: parse an operand; then, while the next token is an operator of power p≥mp \ge m, consume it, parse the right operand as an expression of minimum power p+1p + 1, 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)) })
    }
Listing 2.6. Precedence climbing 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 pp has a left child of power at least pp and a right child of power greater than pp (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(mm) returns a tree all of whose operators have power at least mm: it only combines operators with p≥mp \ge m, and their right operands come from calls with minimum p+1>mp + 1 > m; this is an induction on the depth of calls. Now take a node built by the loop for an operator of power pp. Its right child came from expr_bp(p+1p + 1), so its root has power at least p+1p + 1. Its left child is the tree built so far in the same call: either the first operand, or a node for an operator qq combined earlier in the same loop. When the loop combined qq, the right operand of qq stopped at our operator, so p<q+1p < q + 1, that is q≥pq \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. 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 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.
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, 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; }
}
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 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 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();
                }
            }
        }
    }
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
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 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 S→A B c∣dS \to A\,B\,c \mid d, A→a A∣εA \to a\,A \mid \varepsilon, B→b∣εB \to b \mid \varepsilon.

Solution

Solution of Exercise 2.1.

AA and BB are nullable (A→εA \to \varepsilon, B→εB \to \varepsilon); SS is not, since both its productions contain a terminal. FIRST(A)={a}\mathrm{FIRST}(A) = \{a\}, FIRST(B)={b}\mathrm{FIRST}(B) = \{b\}. For S→A B cS \to A\,B\,c: AA contributes aa, and since AA is nullable BB contributes bb, and since BB is nullable too, cc is in; S→dS \to d adds dd. So FIRST(S)={a,b,c,d}\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

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→A a∣bS \to A\,a \mid b, A→a∣ε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 for it.

Solution

Solution of Exercise 2.3.

No. FIRST(A a)={a}\mathrm{FIRST}(A\,a) = \{a\}, FIRST(b)={b}\mathrm{FIRST}(b) = \{b\}: the row of SS has no conflict. But AA is nullable and FOLLOW(A)={a}\mathrm{FOLLOW}(A) = \{a\}, so cell [A,a][A, a] holds both A→aA \to a (by FIRST) and A→εA \to \varepsilon (by FOLLOW). Seeing an a, the parser cannot tell whether it is AA’s or the one after AA. The language is {aa,a,b}\{aa, a, b\}, and S→a S′∣bS \to a\,S' \mid b, S′→a∣εS' \to a \mid \varepsilon 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 L→L , id∣idL \to L\,,\,\mathit{id} \mid \mathit{id} (a comma-separated list), and write the recursive-descent function for the result as a loop.

Solution

Solution of Exercise 2.4.

L→id L′L \to \mathit{id}\,L', L′→, 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′L' becomes the loop; FOLLOW of L′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 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));
    }
}
Listing 2.10. A calculator by precedence climbing. 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

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−28 - 4 - 2 is computed as 8−(4−2)=68 - (4 - 2) = 6, 8/4/28/4/2 as 8/(4/2)=48/(4/2) = 4, and 9−2×3−19 - 2 \times 3 - 1 as 9−(6−1)=49 - (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 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 ∣N∣ (∣T∣+1)+1|N|\,(|T| + 1) + 1 passes for FOLLOW, where NN and TT 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 ∣N∣|N| FOLLOW sets, each a subset of T∪{$}T \cup \{\$\}, so at most ∣N∣(∣T∣+1)|N|(|T| + 1) passes add something, and one more pass sees no change. The same argument bounds the FIRST phase with ∣N∣ ∣T∣+∣N∣|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→…XiβA \to \dots X_i \beta and a∈FIRST(β)a \in \mathrm{FIRST}(\beta), a derivation reaching AA continues to Xia…X_i a\dots; if β\beta is nullable, anything after AA comes after XiX_i), so they contain the least solution. Conversely, if a∈FOLLOW(X)a \in \mathrm{FOLLOW}(X) by a derivation S⇒∗βXaγS \Rightarrow^* \beta X a \gamma, an induction on the length of that derivation shows that aa enters the computed set: the step that put XX next to the symbols that produce aa 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);
}
Listing 2.11. A file with mistakes. code/bachelor-3/02-top-down-parsing/exercises/ex8.moor
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 nn 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 nn operands joined by +, expr_bp is called once for the whole expression and once for each of the n−1n - 1 right operands, nn times in all; each of those parses one operand through prefix and primary, nn times each: 3n3n calls. A chain of products costs the same 3n3n: 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: 3n+53n + 5. For products, the six functions down to the product are called once and prefix and primary once per operand: 2n+62n + 6. 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 GG be LL(1) and w∈L(G)w \in L(G) with two parse trees. They give two different leftmost derivations of ww. Consider the first step at which they differ: both rewrite the same leftmost nonterminal AA in the same sentential form uAγu A \gamma, where uu is a prefix of ww, one by A→αA \to \alpha and the other by A→βA \to \beta, α≠β\alpha \ne \beta. Let aa be the token of ww after uu (or $). As in the proof of Theorem 2.6, each derivation puts its production in cell [A,a][A, a]: if the production derives a word starting with aa, through FIRST; if it derives ε\varepsilon in that derivation, through FOLLOW. So the cell holds two productions, a contradiction. The converse is false: E→E+T∣TE \to E + T \mid T, T→idT \to \mathit{id} 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 S→A∣BS \to A \mid B, A→a A b∣cA \to a\,A\,b \mid c, B→a B b b∣dB \to a\,B\,b\,b \mid d is not LL(kk) for any kk: no fixed number of tokens of lookahead lets a top-down parser choose between AA and BB. 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 {ancbn}∪{andb2n}\{a^n c b^n\} \cup \{a^n d b^{2n}\}. To choose between S→AS \to A and S→BS \to B a top-down parser must predict at the very first token. With kk tokens of lookahead it sees at most aka^k on the inputs akcbka^k c b^k and akdb2ka^k d b^{2k}, which agree on their first kk tokens but need different first predictions; so no LL(kk) table can have a single production in cell [S,ak][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 as, see c or d, and then check that nn or 2n2n 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: p+1p + 1 for a left-associative operator, pp 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 pp; 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→E+T∣TE \to E + T \mid T. Which productions are left-recursive, and which one is right-recursive, and why?
  2. Remove the left recursion, as in Listing 2.3. How many nonterminals does the result have?
  3. The power level is P→U ^ P∣UP \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 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.

  1. Compute FIRST of the primary and of every level’s nonterminal. Why are they all equal?
  2. Compute FOLLOW of the primary, and of the “rest of a sum” nonterminal.
  3. Fill the row of the “rest of a sum” nonterminal in the table. Which columns hold its ε\varepsilon-production?
  4. Check that the grammar is LL(1) with grammar.rs.
  5. The clerk asks for the unary minus -x. Add it at the right level and check that the grammar stays LL(1).
  6. 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.

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

Part IV — Precedence climbing.

  1. Give the binding powers that make precedence climbing build the same trees, and say what the right-associative power changes in the recursive call.
  2. 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.
  3. Count its calls on the three chains of question 14 and on the example formula.
  4. The program parses 2,000 random formulas both ways. What must it check, and why is that enough to trust the counts?
  5. Adding an eighth level to the language: what does it cost each parser, per primary?
  6. State the result: calls of each parser on a chain of nn operands at the loosest level with pp 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. E→E or A∣AE \to E\ \texttt{or}\ A \mid A, A→A and Q∣QA \to A\ \texttt{and}\ Q \mid Q, and likewise for equality, comparison, sum and product, each level’s operand being the next level; P→U ^ P∣UP \to U\,\text{\textasciicircum}\,P \mid U; U→num∣name∣name ( args )∣( E )U \to \mathit{num} \mid \mathit{name} \mid \mathit{name}\,(\,\mathit{args}\,) \mid (\,E\,). The six left-associative levels are left-recursive: E→E or AE \to E\ \texttt{or}\ A makes the left operand the larger tree. The power is right-recursive, so that 2 ^ 3 ^ 2 is 2(32)=5122^{(3^2)} = 512.

2. Each left-recursive level X→X op Y∣YX \to X\,\mathit{op}\,Y \mid Y becomes X→YX′X \to Y X', X′→op YX′∣ε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→U P′P \to U\,P', P′→^ P∣εP' \to \text{\textasciicircum}\,P \mid \varepsilon.

4. U→num∣( E )∣name CallU \to \mathit{num} \mid (\,E\,) \mid \mathit{name}\ \mathit{Call}, Call→( E MoreA )∣ε\mathit{Call} \to (\,E\,\mathit{MoreA}\,) \mid \varepsilon, MoreA→, E MoreA∣ε\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)×3=18\max(0, 6) \times 3 = 18; 212=22^{1^2} = 2 times (4>3)=1(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=3018 + 2 + 10 = 30.

7. Every level’s nonterminal starts with its operand, down to the primary, so all have FIRST={num,name,(}\mathrm{FIRST} = \{\mathit{num}, \mathit{name}, (\}: no level is nullable, and an expression must start with a primary.

8. FOLLOW(U)\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′S' is followed by what follows a sum: the comparison and equality operators, and, or, ), the comma and $, eleven terminals.

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

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

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

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

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

19. Power k+1k + 1 for level kk: 1 for or up to 7 for ^. For a left-associative operator of power pp the right operand is parsed with minimum p+1p + 1; for the power, with minimum pp, 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. 2n2n for each of the three chains; 34 for the example formula, 2×172 \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, whose cost does not depend on pp, only one more row in its table.

24. With pp levels and nn operands joined by the loosest operator, layered recursive descent makes pn+1pn + 1 calls and precedence climbing 2n2n: 7n+17n + 1 against 2n2n for the library’s seven levels. On the fines formula, 80 calls against 34.

本章定义的术语

在术语表中查看全部 1050 个术语