علوم الحاسوب · الكتاب 5 · السنة الجامعية 3

University Computer Science — Year 3

هذا الكتاب غير متوفر بعد باللغة العربية. النسخ المتوفرة: English.

University Computer Science — Year 3 · السنة الجامعية 3

4Abstract Syntax and Semantic Analysis

The parser accepts var flag = count + true; without a murmur: it is a well-formed statement. It also accepts a call to a function that does not exist, a variable used three lines before it is declared, and an int function that forgets to return. None of these can be seen by a grammar, because each depends on something written elsewhere in the program: a declaration, a type, the rest of a function. This chapter adds the phase that sees them. It binds every use of a name to its declaration, gives every expression a type, checks the rules of the language, and reports what is wrong in a way a programmer can act on. It also writes the interpreter that says what a correct Moor program means, against which every later phase of the compiler will be tested.

4.1 What the tree must carry

You already know

A hash table maps keys to values in expected constant time per operation (Year 1 volume). The abstract syntax tree of Moor (chapter 2) has a node per construct and a span per node; it is frozen. Moor’s types are int and bool, as in the languages of the school volumes.

The phases after the parser need facts the tree does not hold: which declaration a name refers to, the type of each expression, later the place of each variable in memory. There are two ways to attach them. A compiler can add fields to the nodes, filled in as the phases run (in-tree annotation). Or it can keep the tree as the parser built it and store each fact in a side table, a map from a node’s identifier to the fact. Moor’s tree is frozen, so this book takes the second way, and it needs node identifiers. The spans give them for free: two uses of names never start at the same byte of the source, so the byte offset where a use of a name, or a declaring statement, starts identifies it. The side tables are keyed by those only: a general node would need more, since an expression such as a + b starts at the same byte as its left operand a. A side table also keeps the phases independent: the type checker reads the resolver’s table and writes its own, and a later phase can drop a table it no longer needs.

Definition 4.1 (Tree-walking interpreter)

A tree-walking interpreter runs a program by evaluating its abstract syntax tree directly, one node at a time, with a recursive function per kind of node.

The rest of this chapter checks which programs are correct. Before checking them, we fix what a correct one means. The interpreter interp.rs is a few recursive functions over the tree: stmt executes a statement, expr evaluates an expression, call pushes a frame of block scopes for the callee. It is slow, and it is the reference: the compiler of chapters 7 and 8 is correct when, on every program, its RISC-V code prints what the interpreter prints. That makes every detail of the interpreter a decision about the language. Integers are 32 bits and wrap, and division follows the machine the compiler targets (Listing 4.1): a quotient by zero is −1-1 and the remainder the dividend, so that compiled and interpreted programs agree even there.

/// The operators on 32-bit values, as RISC-V computes them.
pub fn binary(op: BinOp, x: V, y: V) -> V {
    use BinOp::*;
    if let (Eq | Ne, V::Bool(a), V::Bool(b)) = (op, x, y) {
        return V::Bool((a == b) == (op == Eq));
    }
    let (a, b) = (int(x), int(y));
    match op {
        Add => V::Int(a.wrapping_add(b)),
        Sub => V::Int(a.wrapping_sub(b)),
        Mul => V::Int(a.wrapping_mul(b)),
        Div => V::Int(if b == 0 { -1 } else { a.wrapping_div(b) }),
        Rem => V::Int(if b == 0 { a } else { a.wrapping_rem(b) }),
        Eq => V::Bool(a == b),
        Ne => V::Bool(a != b),
        Lt => V::Bool(a < b),
        Le => V::Bool(a <= b),
        Gt => V::Bool(a > b),
        Ge => V::Bool(a >= b),
        And | Or => unreachable!("short-circuit, handled by the caller"),
    }
}
Listing 4.1. The binary operators of Moor, as the interpreter computes them: wrapping 32-bit arithmetic, and the division of RISC-V. && and || never reach this function: they evaluate their right operand only when needed. code/bachelor-3/04-semantic-analysis/listings/interp.rs
$ rustc --edition 2021 -O -o interp_demo interp_demo.rs && ./interp_demo sieve.moor
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
exit status 15 after 247 statements
Output 4.1. The interpreter runs sieve.moor: the primes below 50, and main returns their number, which becomes the exit status.

4.2 Scopes and symbol tables

Definition 4.2 (Lexical scope, shadowing, dynamic scope)

Under lexical scope (or static scope), a declaration is visible in the region of the program text it belongs to: in Moor, from the declaration to the end of its block, inner blocks included. A declaration in an inner block shadows a declaration of the same name in an enclosing one: inside the inner block, the name refers to the inner declaration. Under dynamic scope, a name refers to the most recent declaration still active when the code runs, which depends on the chain of calls and not on the text.

The difference shows on two functions. With var x: int = 1; at the top of a program, fn show() { print(x); } and fn main() { var x = 2; show(); }, Moor prints 1: the x in show is the one the text of show can see. Under dynamic scope it would print 2, the x of the caller. A few old languages and some shell and macro languages use dynamic scope; it makes a function’s meaning depend on who calls it, and it cannot be checked before the program runs.

Definition 4.3 (Symbol table)

A symbol table maps the names visible at a point of the program to their declarations. For block structure it supports four operations: open a scope, close it (forgetting what it declared), declare a name in the innermost scope, and look a name up, finding the innermost declaration.

The simplest table that does this is a stack of hash maps (Listing 4.2). Opening a block pushes an empty map, closing it pops the map, and lookup searches from the top. Shadowing is automatic, since the inner map is searched first, and closing a block restores the outer declaration because it was never removed. Declaring a name twice in the same block is refused, and the first declaration returned so that the message can point at it. The counter of map probes will be used to compare tables.

    /// Declare in the innermost scope; a name already declared there is
    /// refused and its first declaration returned.
    pub fn declare(&mut self, name: &str, v: T) -> Result<(), T> {
        let top = self.frames.last_mut().unwrap();
        if let Some(old) = top.get(name) {
            return Err(old.clone());
        }
        top.insert(name.to_string(), v);
        Ok(())
    }
    /// The innermost declaration of `name`: search from the top of the stack.
    pub fn lookup(&mut self, name: &str) -> Option<T> {
        for frame in self.frames.iter().rev() {
            self.probes += 1;
            if let Some(v) = frame.get(name) {
                return Some(v.clone());
            }
        }
        None
    }
Listing 4.2. Declaring in the innermost scope, and looking up from the top of the stack. code/bachelor-3/04-semantic-analysis/listings/scope.rs

Output 4.2 prints the stack after each declaration of ok.moor (Listing 4.3). The first map holds the built-in functions and the program’s items; then each function opens a map for its parameters and one per block. The figure below draws the stack at three points of main.

// ok.moor -- a global, two functions that call each other, a shadowed x
var limit: int = 3;

fn even(n: int) -> bool {
    if n == 0 { return true; }
    return odd(n - 1);
}

fn odd(n: int) -> bool {
    if n == 0 { return false; }
    return even(n - 1);
}

fn main() {
    var x = 10;
    {
        var x = limit;
        print(x);
    }
    if even(x) { print(1); } else { print(0); }
}
Listing 4.3. A program to resolve: a global, two functions that call each other before the second is declared, and a shadowed x. code/bachelor-3/04-semantic-analysis/listings/ok.moor
$ rustc --edition 2021 -O -o scope_trace scope_trace.rs && ./scope_trace ok.moor
print      [print]
print_char [print print_char]
read       [print print_char read]
limit      [limit print print_char read]
even       [even limit print print_char read]
odd        [even limit odd print print_char read]
main       [even limit main odd print print_char read]
n          [even limit main odd print print_char read] [n]
n          [even limit main odd print print_char read] [n]
x          [even limit main odd print print_char read] [] [x]
x          [even limit main odd print print_char read] [] [x] [x]
11 declarations, 13 uses resolved
Output 4.2. The stack of scopes after each declaration, outermost first, each scope’s names sorted. main’s parameter scope is empty.
The symbol table of main at three points, top of the stack up; x:15 is the x declared on line 15. At line 18 the lookup of x finds the inner one, declared on line 17; at line 20 the inner block has been popped and the outer x is visible again.
The symbol table of main at three points, top of the stack up; x:15 is the x declared on line 15. At line 18 the lookup of x finds the inner one, declared on line 17; at line 20 the inner block has been popped and the outer x is visible again.

A stack of maps is not the only choice. A single list of (name, declaration) pairs with a mark per block is simpler, and lookup scans it from the newest end. A single hash map from each name to the stack of its visible declarations makes every lookup one probe, at the price of a more careful exit (exercise 4.5). A persistent map, which is never changed in place but copied along one path per insertion, makes leaving a block free, since the outer scope is simply the old version (exercise 4.11). The weekend problem counts what each costs.

4.3 Resolving names

Definition 4.4 (Name resolution, binding occurrence)

A binding occurrence of a name is the place where it is declared: a parameter, a var, a function or a global. Name resolution maps every other occurrence, every use, to the binding occurrence it refers to under the scope rules, or reports that there is none.

Moor’s functions are visible everywhere, so that even may call odd before odd is declared. The resolver therefore makes two passes (Listing 4.4). The first declares every item of the program in the outermost scope; the second walks each function’s body with a scope for its parameters and one per block. Each declaration gets a number, and two side tables map each use, and each declaring node, to that number.

pub fn resolve_traced(p: &Program, trace: &mut dyn FnMut(&str, &Scopes<usize>))
    -> Resolution {
    let mut rs = Resolver {
        r: Resolution::default(), scopes: Scopes::new(), later: vec![], trace,
    };
    for b in BUILTINS {
        rs.declare(b, Kind::Builtin, NOWHERE);
    }
    for item in &p.items {
        let id = match item {
            Item::Func(f) => rs.declare(&f.name, Kind::Func, f.span),
            Item::Global { name, span, .. } => rs.declare(name, Kind::Global, *span),
            Item::Array { name, span, .. } => rs.declare(name, Kind::Array, *span),
        };
        rs.r.items.push(id);
    }
    for item in &p.items {
        if let Item::Func(f) = item {
            rs.later.clear();
            collect_vars(&f.body, &mut rs.later);
            rs.scopes.push();
            for q in &f.params {
                let id = rs.declare(&q.name, Kind::Param, q.span);
                rs.r.defs.insert(q.span.start, id);
            }
            rs.block(&f.body);
            rs.scopes.pop();
        }
    }
    rs.r
}
Listing 4.4. The two passes. later lists the function’s local declarations, for a better message when a name is used before its declaration. code/bachelor-3/04-semantic-analysis/listings/resolve.rs

Listing 4.5 handles a use and a local declaration. The order of the two lines for var is a rule of the language: the initialiser is resolved before the name is declared, so in var x = x + 1; the x on the right is an outer one, or an error if there is none. When a lookup fails, the resolver looks for a declaration of the same name later in the function: if there is one, the programmer has most likely put the statements in the wrong order, and the message says so.

    fn use_name(&mut self, name: &str, span: Span) {
        if let Some(id) = self.scopes.lookup(name) {
            self.r.uses.insert(span.start, id);
            return;
        }
        let msg;
        let mut note = None;
        let later = self.later.iter().find(|(x, at)| x == name && at.start > span.start);
        if let Some((_, at)) = later {
            msg = format!("'{name}' is used before its declaration");
            note = Some(("it is declared here".to_string(), *at));
        } else {
            msg = format!("'{name}' is not declared");
        }
        self.r.errors.push(Diag { msg, span, note });
    }

    fn block(&mut self, b: &Block) {
        self.scopes.push();
        for s in &b.stmts {
            self.stmt(s);
        }
        self.scopes.pop();
    }

    fn stmt(&mut self, s: &Stmt) {
        match &s.kind {
            StmtKind::Var(x, _, e) => {
                self.expr(e); // the initialiser cannot see the new name
                let id = self.declare(x, Kind::Local, s.span);
                self.r.defs.insert(s.span.start, id);
            }
Listing 4.5. A use: found, used before its declaration, or not declared. A block opens and closes a scope; a var resolves its initialiser first. code/bachelor-3/04-semantic-analysis/listings/resolve.rs

Output 4.3 lists the resolution of ok.moor: thirteen uses, each with the kind and place of its declaration and, for variables, the type the checker of the next section gave it. The two x on lines 18 and 20 go to different declarations; the figure below draws the bindings of even.

$ rustc --edition 2021 -O -o check_demo check_demo.rs && ./check_demo ok.moor
 5:8   n      -> param at 4:9: int
 6:12  odd    -> func at 9:1
 6:16  n      -> param at 4:9: int
10:8   n      -> param at 9:8: int
11:12  even   -> func at 4:1
11:17  n      -> param at 9:8: int
17:17  limit  -> global at 2:1: int
18:9   print  -> built in
18:15  x      -> local at 17:9: int
20:8   even   -> func at 4:1
20:13  x      -> local at 15:5: int
20:18  print  -> built in
20:37  print  -> built in
4 items, 11 declarations, 13 uses: no error
Output 4.3. Every use in ok.moor and the declaration it is bound to, by line and column.
The tree of even with the resolution drawn as arrows from each use (red) to its declaration (blue). The arrows are not part of the tree: they are the entries of the side table uses. odd is declared after even, and is found because the first pass declared it.
The tree of even with the resolution drawn as arrows from each use (red) to its declaration (blue). The arrows are not part of the tree: they are the entries of the side table uses. odd is declared after even, and is found because the first pass declared it.

4.4 Checking types

Definition 4.5 (Static semantics, type checking)

The static semantics of a language is the set of rules a program must satisfy beyond its grammar, checked before it runs: every name declared, every operator applied to operands of the right types, every function returning on every path. Type checking is the part of it that gives every expression of a program a type and checks that each construct receives operands of the types it requires.

Each requirement is written as a typing rule, an inference: if the premises above the line hold, the conclusion below it holds. A premise or conclusion Γ⊢e:τ\Gamma \vdash e : \tau reads “with the variables of Γ\Gamma at their types, expression ee has type τ\tau”; chapter 6 makes these notions precise.

Moor’s rules for expressions are short. A few of them:

Γ(x)=τΓ⊢x:τΓ⊢e1:intΓ⊢e2:intΓ⊢e1+e2:intΓ⊢e1:intΓ⊢e2:intΓ⊢e1<e2:boolΓ⊢e1:τΓ⊢e2:ττ∈{int,bool}Γ⊢e1==e2:boolΓ⊢e1:boolΓ⊢e2:boolΓ⊢e1 && e2:boolΓ(f)=(τ1,…,τn)→τΓ⊢ei:τi (1≤i≤n)Γ⊢f(e1,…,en):τ\begin{gather*}{\dfrac{\Gamma(x) = \tau}{\Gamma \vdash x : \tau}} \qquad {\dfrac{\Gamma \vdash e_1 : \mathsf{int} \qquad \Gamma \vdash e_2 : \mathsf{int}}{\Gamma \vdash e_1 + e_2 : \mathsf{int}}} \qquad {\dfrac{\Gamma \vdash e_1 : \mathsf{int} \qquad \Gamma \vdash e_2 : \mathsf{int}}{\Gamma \vdash e_1 < e_2 : \mathsf{bool}}} \\[2ex] {\dfrac{\Gamma \vdash e_1 : \tau \qquad \Gamma \vdash e_2 : \tau \qquad \tau \in \{\mathsf{int}, \mathsf{bool}\}}{\Gamma \vdash e_1 == e_2 : \mathsf{bool}}} \qquad {\dfrac{\Gamma \vdash e_1 : \mathsf{bool} \qquad \Gamma \vdash e_2 : \mathsf{bool}}{\Gamma \vdash e_1\ \&\&\ e_2 : \mathsf{bool}}} \\[2ex] {\dfrac{\Gamma(f) = (\tau_1, \dots, \tau_n) \to \tau \qquad \Gamma \vdash e_i : \tau_i \ (1 \le i \le n)}{\Gamma \vdash f(e_1, \dots, e_n) : \tau}}\end{gather*}

Statements have a judgement of their own, Γ⊢s⊣Γ′\Gamma \vdash s \dashv \Gamma': the statement is correct in Γ\Gamma, and Γ′\Gamma' is the context after it, which a var extends. Writing ρ\rho for the result type of the enclosing function:

Γ⊢e:τΓ⊢var x=e;⊣Γ,x:τΓ(x)=τΓ⊢e:τΓ⊢x=e;⊣ΓΓ⊢e:boolΓ⊢B1Γ⊢B2Γ⊢if e B1 else B2⊣ΓΓ⊢e:ρΓ⊢return e;⊣Γ\begin{gather*}{\dfrac{\Gamma \vdash e : \tau}{\Gamma \vdash \mathtt{var}\ x = e; \dashv \Gamma, x{:}\tau}} \qquad {\dfrac{\Gamma(x) = \tau \qquad \Gamma \vdash e : \tau}{\Gamma \vdash x = e; \dashv \Gamma}} \qquad {\dfrac{\Gamma \vdash e : \mathsf{bool} \qquad \Gamma \vdash B_1 \qquad \Gamma \vdash B_2}{\Gamma \vdash \mathtt{if}\ e\ B_1\ \mathtt{else}\ B_2 \dashv \Gamma}} \\[2ex] {\dfrac{\Gamma \vdash e : \rho}{\Gamma \vdash \mathtt{return}\ e; \dashv \Gamma}}\end{gather*}

A program is well typed if a derivation exists for each function body; the figure below is one for a statement. The checker builds no derivation: it computes the type of each expression bottom-up, and each rule becomes a test. Listing 4.6 is the binary operators: the operands’ types first, then the operator’s requirement. The helper expect reports a type that is not the one required, unless it is Error, the type of an expression already reported (Section 4.5).

A typing derivation for one statement, with = x: int, y: int, limit: int. The leaves look names up in ; each line is one rule. An if without else has the same rule without B_2.
A typing derivation for one statement, with Γ=x:int,y:int,limit:int\Gamma = \mathtt{x}{:}\mathsf{int}, \mathtt{y}{:}\mathsf{int}, \mathtt{limit}{:}\mathsf{int}. The leaves look names up in Γ\Gamma; each line is one rule. An if without else has the same rule without B2B_2.
    fn binary(&mut self, op: BinOp, a: &Expr, b: &Expr) -> Ty {
        use BinOp::*;
        let (ta, tb) = (self.expr(a), self.expr(b));
        let sym = op.symbol();
        let (operand, result) = match op {
            Add | Sub | Mul | Div | Rem => (Ty::Int, Ty::Int),
            Lt | Le | Gt | Ge => (Ty::Int, Ty::Bool),
            And | Or => (Ty::Bool, Ty::Bool),
            Eq | Ne => {
                if ta == Ty::Unit || tb == Ty::Unit {
                    let at = if ta == Ty::Unit { a.span } else { b.span };
                    self.error(format!("'{sym}' cannot compare nothing"), at);
                } else if ta != tb && ta != Ty::Error && tb != Ty::Error {
                    let (x, y) = (article(ta), article(tb));
                    self.error(format!("'{sym}' compares {x} with {y}"), b.span);
                }
                return Ty::Bool;
            }
        };
        self.expect(ta, operand, a.span, &format!("the left operand of '{sym}'"));
        self.expect(tb, operand, b.span, &format!("the right operand of '{sym}'"));
        result
    }
Listing 4.6. The typing rules of the binary operators, as code. Equality accepts two operands of the same type, int or bool. code/bachelor-3/04-semantic-analysis/listings/typecheck.rs

One rule is about paths, not types: a function with a result type must return on every path, or the caller would read a value that was never produced. The checker decides it on the tree (Listing 4.7): a block returns if one of its statements does, and an if returns only if both branches do. A while never counts, even while true: the check is conservative, and it may refuse a function that always returns, but it never accepts one that can fall off its end (exercise 4.7).

pub fn returns(b: &Block) -> bool {
    b.stmts.iter().any(|s| match &s.kind {
        StmtKind::Return(_) => true,
        StmtKind::If(_, t, Some(f)) => returns(t) && returns(f),
        StmtKind::Block(b) => returns(b),
        _ => false,
    })
}
Listing 4.7. Return on every path, decided on the tree. code/bachelor-3/04-semantic-analysis/listings/typecheck.rs

What does the checker buy? The interpreter’s arithmetic in Listing 4.1 reads its operands as integers without looking; if a bool reached it, the interpreter would stop with an internal error, and compiled code would add a 0 or a 1 without any warning. The checker rules this out.

Theorem 4.6 (Well-typed Moor never adds a boolean)

In a well-typed Moor program, whenever the interpreter evaluates e1+e2e_1 + e_2, both operands evaluate to integers. The same holds for every arithmetic and comparison operator, and the operands of &&, || and ! evaluate to booleans.

Proof. We prove it for functions that make no calls; calls are exercise 4.10. Say that an environment agrees with Γ\Gamma if each variable xx of Γ\Gamma holds a value of type Γ(x)\Gamma(x), and array elements are integers. Claim: if Γ⊢e:τ\Gamma \vdash e : \tau, the environment agrees with Γ\Gamma, and the evaluation of ee ends without a runtime error, its value has type τ\tau. By induction on ee, following the evaluation, which evaluates the subexpressions first. A literal has its type. A variable has type Γ(x)\Gamma(x) by the rule, and holds a value of that type by agreement. An array element is an integer by agreement. For e1+e2e_1 + e_2, the rule gives Γ⊢ei:int\Gamma \vdash e_i : \mathsf{int}, so by induction both values are integers, which is the theorem’s statement for this node, and their wrapped sum is an integer. The other operators are the same, with the types of their rules; for && and || the right operand may not be evaluated, which changes nothing.

Agreement is kept by every statement. A var x = e; adds x:τx{:}\tau to Γ\Gamma, and xx receives the value of ee, of type τ\tau by the claim. An assignment x=ex = e requires Γ⊢e:Γ(x)\Gamma \vdash e : \Gamma(x). An array assignment requires an integer value. Leaving a block removes the same names from the environment and from Γ\Gamma. By induction on the number of statements executed, the environment always agrees with the current Γ\Gamma, so the claim applies to every expression evaluated, and with it the theorem. ∎

The theorem is a small case of type safety, which chapter 6 states and proves for a whole language, with the rules made formal.

4.5 Useful error messages

A checker that stops at the first error makes the programmer compile once per mistake. One that goes on must avoid the opposite trap: when zz is not declared, the expression (zz + 1) * 2 < 3 && true could produce a message at every level of the tree, each a consequence of the first. Users learn to read only the first message, and the others are noise.

Definition 4.7 (Error type)

An error type is a type given to an expression that has already been reported as wrong. Every rule accepts it in place of any type, without a message, and an operator whose operand has it gives it to its own result when the result type depends on the operand.

With the error type, each cause gives one message. zz is reported once by the resolver; its type is Error; zz + 1 is not reported, and has type int since + always gives an integer; the rest of the expression checks normally. The figure below compares the two behaviours. The other rules of good messages are as simple: point at the right place, with a caret under the column; say what was expected and what was found; add a note pointing at the other place involved, such as the first declaration of a name declared twice; and report all errors, in the order of the source. Output 4.4 is the front end on errors.moor: four errors, two with a note.

fn half(n: int) -> int {
    if n > 0 { return n / 2; }
}

fn main() {
    var count = 0;
    var flag = count + true;
    print(total);
    var total = count * 2;
    var count = 1;
}
Listing 4.8. Four mistakes. code/bachelor-3/04-semantic-analysis/listings/errors.moor
$ rustc --edition 2021 -O -o errors_demo errors_demo.rs && ./errors_demo errors.moor
errors.moor:1:1: error: 'half' can reach its end without returning an int
  fn half(n: int) -> int {
  ^
errors.moor:7:24: error: the right operand of '+' must be an int, found a bool
      var flag = count + true;
                         ^
errors.moor:8:11: error: 'total' is used before its declaration
      print(total);
            ^
errors.moor:9:5: note: it is declared here
      var total = count * 2;
      ^
errors.moor:10:5: error: 'count' is declared twice in the same scope
      var count = 1;
      ^
errors.moor:6:5: note: the first declaration is here
      var count = 0;
      ^
Output 4.4. The four messages, in source order, each with its line and caret; the second declaration of count and the early use of total point at the other line involved.
The expression (zz + 1) * 2 < 3 && true with zz undeclared. If an unknown name stopped every rule above it, each operator would complain about an operand it cannot type (red). With the error type, only the cause is reported; + still gives an int, and the rest of the tree is checked normally.
The expression (zz + 1) * 2 < 3 && true with zz undeclared. If an unknown name stopped every rule above it, each operator would complain about an operand it cannot type (red). With the error type, only the cause is reported; + still gives an int, and the rest of the tree is checked normally.

In practice — Messages are read by people in a hurry

The best compilers spend as much code on messages as on checks. A message names the construct as the programmer wrote it ('+', not BinOp::Add), and its first line should be enough. Order matters: sorting by position makes the first message the earliest cause, and tests should fix the exact text of messages, as this chapter’s do, so that a change in wording is a decision and not an accident.

History — Blocks

The report on ALGOL 60, published in May 1960, defined the block: a sequence of statements headed by declarations that are valid only inside it, and that may hide declarations of the same names outside it. Block structure and lexical scope, as in this chapter, come from that report into most of the languages that followed.

4.6 Exercises

Exercise 4.1 ★

In the program below, which declaration does each use of n and m refer to, on lines 3, 5, 6 and 8? What does it print?

1var n: int = 1;
2fn f(n: int) -> int {
3 var m = n;
4 {
5 var n = m + 1;
6 m = n;
7 }
8 return n + m;
9}
10fn main() { print(f(5)); }
Solution

Solution of Exercise 4.1.

Line 3: n is the parameter of line 2, which shadows the global of line 1. Line 5: m is the m of line 3; the new n is declared after its initialiser is resolved. Line 6: m is still line 3’s, n is line 5’s. Line 8: the inner block is closed, so n is the parameter again and m is line 3’s. The global n is never used. With f(5)f(5): m=5m = 5, the inner n=6n = 6, m=6m = 6, and the result is 5+6=115 + 6 = 11; the program prints 11 (exercise_1_and_4_scopes).

Exercise 4.2 ★

List the messages the checker gives for this program, in order, and say why there are not more:

fn f(a: int) -> bool { return a; } fn main() { var b = f(1) + 2; if 3 { print(true); } while f(0) == 1 { } }

Solution

Solution of Exercise 4.2.

Five messages, in source order (exercise_2_type_errors): the returned value must be a bool, found an int; the left operand of '+' must be an int, found a bool (f(1)); the condition of an if must be a bool, found an int; argument 1 of print must be an int, found a bool; '==' compares a bool with an int. There are no more because each rule reports only its own requirement: f(1) + 2 still has type int, since + always gives an integer, so b is an int and nothing later complains about it; and the ==, once reported, has type bool, so the while’s condition is accepted.

Exercise 4.3 ★

Write the typing rule of while, in the style of the rule of if.

Solution

Solution of Exercise 4.3.

Γ⊢e:boolΓ⊢BΓ⊢while e B⊣Γ\begin{gather*}{\dfrac{\Gamma \vdash e : \mathsf{bool} \qquad \Gamma \vdash B}{\Gamma \vdash \mathtt{while}\ e\ B \dashv \Gamma}}\end{gather*}

The condition is a boolean, the body is checked in Γ\Gamma (its own declarations are local to it), and the context after the loop is Γ\Gamma unchanged.

Exercise 4.4 ★

With var x: int = 1;, fn show() { print(x); } and fn main() { var x = 2; show(); }, what does the program print under lexical scope, and under dynamic scope? Which of the two could a compiler check for undeclared names before the program runs?

Solution

Solution of Exercise 4.4.

Under lexical scope, 1: the x in show is the global, the only x the text of show can see; the interpreter prints 1 (exercise_1_and_4_scopes). Under dynamic scope, 2: when show runs, the most recent active x is main’s. Only lexical scope can be checked before the program runs: under dynamic scope, whether a name is declared at a use depends on the calls that lead there, which in general depend on the input.

Exercise 4.5 ★★

Listing 4.9 keeps the whole symbol table in one hash map, and each block the list of the names it declared, removed when the block ends. Output 4.5 shows what goes wrong. Explain it and fix the structure so that every lookup is still a single probe.

    fn declare(&mut self, name: &str, line: u32) {
        self.map.insert(name.to_string(), line);
        self.blocks.last_mut().unwrap().push(name.to_string());
    }
    fn exit(&mut self) {
        for name in self.blocks.pop().unwrap() {
            self.map.remove(&name);
        }
    }
Listing 4.9. Declaring and closing a block in the one-map table. code/bachelor-3/04-semantic-analysis/listings/scope_bug.rs
$ rustc --edition 2021 -O -o scope_bug scope_bug.rs && ./scope_bug
x in the inner block: Some(17)
x after the block:    None
Output 4.5. An x declared on line 15, shadowed on line 17.
Solution

Solution of Exercise 4.5.

Declaring the inner x replaces the outer one in the map, and closing the block removes x altogether: the outer declaration is lost, and after the block x is not found. The fix (exercises/ex5_flat_fixed.rs) maps each name to the stack of its visible declarations. Declaring pushes onto the name’s stack and records the name in the block’s list; closing the block pops one declaration per recorded name, and removes the entry when its stack is empty. A lookup reads the top of one stack: one probe. The test replays the sequence of Output 4.5 and finds line 15 after the block, and nothing after the outer one.

Exercise 4.6 ★★

Write unused(p, r) in exercises/ex6_unused.rs: a warning for every local variable or parameter that is never read. Assigning to a variable does not read it. Test it on exercises/ex6.moor.

Solution

Solution of Exercise 4.6.

exercises/ex6_unused.rs. Walk every function and collect the declarations read: a Var expression’s entry in the uses table (the target of an assignment is a use in the table, but not a read, so the walk does not count it). Warn for each local or parameter not collected. On ex6.moor: unit (line 1, a parameter never used), spare (line 3, assigned but never read) and the inner total (line 10, shadowing the outer one, which print reads).

Exercise 4.7 ★★

Prove that the check of Listing 4.7 is sound: if returns(B) holds, every execution of BB that ends without a runtime error ends by a return, never by reaching the end of BB. Give a function the check refuses although it always returns.

Solution

Solution of Exercise 4.7.

By induction on the block. If returns(B) holds, some statement sks_k of BB returns in the sense of the function. An execution of BB runs s1,s2,…s_1, s_2, \dots in order; if it returns before sks_k we are done; otherwise it reaches sks_k, and runs it to its end or to a return. If sks_k is a return, it returns. If it is an if with both branches returning, the branch taken returns by induction (it is a smaller block). If it is a block, by induction again. So no execution gets past sks_k, and none reaches the end of BB. A function the check refuses although it always returns: fn f(n: int) -> int { if n > 0 { return 1; } if n <= 0 { return 2; } }, or any function ending in while true { return 1; }; deciding exactly which functions always return is undecidable in general, so a sound check must refuse some.

Exercise 4.8 ★★

A use sits inside dd nested blocks of a function, counting the body as the first. With the resolver’s stack of maps, how many map probes does its lookup cost if the name is a local of the innermost block, a parameter, a global, or undeclared?

Solution

Solution of Exercise 4.8.

The stack holds the globals’ map, the parameters’ map and one map per block: d+2d + 2 maps at depth dd. A lookup searches from the top. A local of the innermost block: 1 probe. A parameter: d+1d + 1. A global: d+2d + 2. An undeclared name: d+2d + 2, every map. In general a name declared kk maps below the top costs k+1k + 1 (exercise_8_probes_grow_with_depth checks the count on stacks of 1 to 20 maps).

Exercise 4.9 ★★

Predict, line by line, what the interpreter prints for exercises/ex9.moor, and its exit status:

fn f(n: int) -> int { if n <= 1 { print(n); return n; } var a = f(n - 1); print(n); return a + f(n - 2); } fn main() -> int { return f(4); }

Solution

Solution of Exercise 4.9.

f(4) calls f(3), which calls f(2), which calls f(1): it prints 1 and returns 1. f(2) prints 2 and calls f(0), which prints 0: f(2) returns 1. f(3) prints 3 and calls f(1), which prints 1: f(3) returns 2. f(4) prints 4 and calls f(2) again: 1, 2, 0. The output is 1, 2, 0, 3, 1, 4, 1, 2, 0, one per line, and the exit status is f(4)=2+1=3f(4) = 2 + 1 = 3, the Fibonacci number F4F_4 (exercise_9_recursive_output).

Exercise 4.10 ★★★

Extend the proof of Theorem 4.6 to programs with calls: show that a call f(e1,…,en)f(e_1, \dots, e_n) of type τ\tau that returns yields a value of type τ\tau. What do you need from the return-on-every-path check, and from the rule of return?

Solution

Solution of Exercise 4.10.

Strengthen the claim to: an evaluation that ends without error, in an environment that agrees with Γ\Gamma, gives a value of the expression’s type, and every call it makes, of a function with result type ρ\rho, returns a value of type ρ\rho. Induct on the length of the evaluation (the number of steps, finite since it ends). For f(e1,…,en)f(e_1, \dots, e_n) with Γ(f)=(τ1,…,τn)→τ\Gamma(f) = (\tau_1, \dots, \tau_n) \to \tau: the arguments are shorter evaluations, so they give values of types τi\tau_i; the callee’s environment, its parameters bound to them, agrees with the context in which its body was checked. Every statement of the body keeps agreement, as in the proof of Theorem 4.6, the calls inside being shorter evaluations. The body ends in one of two ways. By a return e: the rule of return gives Γ′⊢e:τ\Gamma' \vdash e : \tau, and by induction ee’s value has type τ\tau. By reaching its end: then the interpreter returns no value at all, and this is what the return-on-every-path check excludes (exercise 4.7) for every function with a result type. Calls of functions without one have type nothing, which no rule accepts as an operand, so they appear only as statements.

Exercise 4.11 ★★★

Implement persistent scopes in exercises/ex11_persistent.rs: a scope is an immutable balanced search tree, and declaring a name builds a new tree that shares all but one path with the old one. Entering a block keeps the old root; leaving it returns to that root. Count the nodes allocated per declaration and the comparisons per lookup, and compare with the stack of maps.

Solution

Solution of Exercise 4.11.

exercises/ex11_persistent.rs: an AVL tree whose insertion copies the nodes on the path from the root and rebalances on the way up, sharing every other subtree with the old tree. The test declares 1,000 names: the tree’s height is at most 14 (1.44log⁡21001<14.41.44 \log_2 1001 < 14.4), a lookup makes at most 14 comparisons, and an inner block that shadows one name and adds another allocates at most 2×3×142 \times 3 \times 14 nodes, while the outer tree still answers as before. Compared with the stack of maps: entering and leaving a block cost nothing (keep or drop a root), and a lookup costs O(log⁡n)O(\log n) comparisons whatever the depth, against one probe per enclosing scope; a declaration costs O(log⁡n)O(\log n) new nodes against one map insertion. The persistent table also lets several phases keep the scope of any program point alive at once, at no cost, which a mutable stack cannot.

Exercise 4.12 ★★★

Extend Moor with local declarations without an initialiser, var x: int;, and design rules that forbid reading a variable before it has been assigned: compute, for each point of a function, the set of variables definitely assigned there. Give the rules for assignment, if with and without else, while and return, and prove them sound: a variable in the set has been assigned on every path to that point.

Solution

Solution of Exercise 4.12.

Let DA\mathrm{DA} be the set of definitely assigned variables at a point. A var x: int; adds x to the scope but not to DA\mathrm{DA}; var x = e; and x = e; first require that every variable read by ee is in DA\mathrm{DA}, then add x. For if e B1 else B2: the condition is checked against DA\mathrm{DA}, both branches start from DA\mathrm{DA}, and after the statement DA\mathrm{DA} is the intersection of the sets at the ends of the branches. Without else, the intersection with DA\mathrm{DA} itself, which is DA\mathrm{DA}. For while e B: the body is checked from DA\mathrm{DA}, and after the loop DA\mathrm{DA} is unchanged, since the body may run zero times. After a return, DA\mathrm{DA} is the set of all variables in scope: no path goes on from there, so the intersection at the end of an if ignores that branch. Closing a block removes its variables. Soundness, by induction on the length of a path from the function’s entry: at each point pp reached, every variable of DA(p)\mathrm{DA}(p) has been assigned on the path. Each rule preserves this: an assignment adds only the variable it assigns; after an if, the path came through one branch, whose set contains the intersection; after a while, the set is the one at the loop’s entry, which the path passed through; after a return, no path continues. So a read of a variable in DA\mathrm{DA} never reads an unassigned one.

4.7 Weekend problem

Problem 4.1

Weekend problem — The parish register script

Brenmoor’s parish keeps its registers as nested records, and a clerk’s program writes them out as generated Moor scripts: dd nested blocks, mm declarations in each, every declaration var vi,j_{i,j} = reg + jj; reading a register reg declared first in the outermost block. Some scripts are 1,000 blocks deep. The file exercises/pb_register.rs writes them (script(d, m, None)) and resolves them with three symbol tables, counting the work. Write n=dmn = dm.

Part I — Scopes by hand.

  1. Write the script for d=m=2d = m = 2 and draw the stack of maps after each declaration.
  2. To which declaration does each use of reg refer? Why must it be found from every block?
  3. If the second block declared its own reg first, which uses would change their binding?
  4. In a block that already sees a v, which v does var v = v + 1; read?
  5. Would any answer change if Moor used dynamic scope? Why not, for this script?
  6. How many declarations and how many uses does a script have, as functions of dd and mm?

Part II — Three tables.

  1. With a list of (name, declaration) pairs searched from the newest end, how many name comparisons does the lookup of reg cost in the kk-th declaration of the script?
  2. Deduce the total for the whole script. Does it depend on dd?
  3. With the resolver’s stack of maps, how many probes does the lookup of reg cost at depth ii? Deduce the total.
  4. With a single map from each name to the stack of its declarations (exercise 4.5), what does a lookup cost? What does leaving a block cost?
  5. How much memory does each table use at the deepest point of the script?
  6. For d=1d = 1, compare the three totals.

Part III — Counted.

  1. For n=10,000n = 10{,}000, run the counts for d=1d = 1, 10, 100 and 1,000 and fill a table with the three totals.
  2. Explain from question 8 why the list’s column does not change.
  3. What is the ratio between the list and the stack of maps at d=1,000d = 1{,}000? At d=1d = 1?
  4. Real programs are rarely more than ten blocks deep, and most uses refer to names declared nearby. Which table would you choose for Moor’s compiler, and why do many compilers use a stack of maps anyway?
  5. The counts are of probes, not of time. Why is a probe in a hash map “constant time” only in expectation?
  6. Why does the book count operations rather than time them?

Part IV — Errors counted.

  1. The clerk misspells reg as rge in block 3 of a script with d=5d = 5, m=4m = 4. How many messages does the front end give?
  2. Why is there no message about the + in which each misspelt name appears?
  3. If an undeclared name were given the type int instead of the error type, would the count change for this script? Give a statement for which it would.
  4. How would you change the resolver to give one message per misspelt name in a function, and how many would this script then get?
  5. Sum up the costs of the three tables on scripts of nn declarations and depth dd, and say which one makes the resolution linear in the size of the script.
Solution

Solution of Problem 4.1.

The counts are asserted in tests/pb_test.rs.

1. The generator’s script(2, 2, None) (its text is fixed by a test) has var reg = 0; and two declarations in the body, then a block with two more, one statement per line. Below the parameters’ map (empty), the body’s map grows {reg}, {reg, v1_1}, {reg, v1_1, v1_2}; then the block pushes a map that grows {v2_1}, {v2_1, v2_2}. The globals’ map holds main and the three built-ins.

2. Every use is bound to the reg of the outermost block. Every declaration’s initialiser reads it, at every depth, and an inner block sees every declaration of the blocks around it.

3. The uses in the second block after its own reg, and in every block inside it; the uses of the first block keep the outer one.

4. The outer v: the initialiser is resolved before the new name is declared.

5. No. Lexical and dynamic scope differ only when a function reads a name declared outside it and is called from elsewhere; the script is one function with no calls.

6. n+1=dm+1n + 1 = dm + 1 declarations, reg included, and nn uses.

7. kk: the list holds, newest first, the k−1k - 1 declarations made since reg, then reg itself.

8. ∑k=1nk=n(n+1)/2\sum_{k=1}^{n} k = n(n+1)/2, whatever dd: a block’s exit truncates the list, but no block closes before the last declaration.

9. ii probes: the maps of blocks i,i−1,…,1i, i - 1, \dots, 1. In total ∑i=1dm i=m d(d+1)/2=n(d+1)/2\sum_{i=1}^{d} m\,i = m\,d(d+1)/2 = n(d+1)/2.

10. One probe per lookup, nn in total. Leaving a block pops one declaration per name the block declared: mm operations.

11. All three hold the n+1n + 1 live declarations: the list n+1n + 1 pairs and dd marks; the stack d+2d + 2 maps with n+5n + 5 entries in all; the single map n+1n + 1 entries, with dd lists of names. Each is Θ(n+d)\Theta(n + d).

12. n(n+1)/2n(n+1)/2 comparisons for the list, nn probes for the stack of maps (every use is found in the first map searched), nn for the single map.

13. For n=10,000n = 10{,}000, the list makes 50,005,000 comparisons at every depth; the stack of maps makes 10,000, 55,000, 505,000 and 5,005,000 probes for d=1d = 1, 10, 100 and 1,000; the single map makes 10,000 probes at every depth.

14. Its count, n(n+1)/2n(n+1)/2, depends only on how many declarations are newer than reg at each use.

15. About 10 at d=1,000d = 1{,}000 (50,005,000/5,005,00050{,}005{,}000 / 5{,}005{,}000), and about 5,000 at d=1d = 1.

16. The stack of maps: its cost per lookup is the number of blocks between a use and its declaration, which is small in real programs, and it is the simplest to write and to get right, since closing a block drops one map. The single map wins only on deep nesting with far references, as in this script.

17. A probe hashes the name and inspects one bucket; its cost depends on how many keys share the bucket. With a good hash function and a bounded load factor, the expected number is constant; in the worst case every name collides.

18. Times depend on the machine, its caches and its load, and change from run to run; counts are deterministic, reproducible anywhere, and predicted exactly by the formulas above.

19. Four: one “'rge' is not declared” per use in block 3.

20. Each rge has the error type; + accepts it silently and gives int, so the declared variable is an int and nothing after it complains.

21. Not for this script: rge + j would be int + int. It would for var ok = rge && true;, which would then add a message about the left operand of &&, a consequence of the same cause.

22. Keep the set of undeclared names already reported in the current function, and report only the first use of each (possibly with a count of the others). The script would get one message.

23. On a script of nn declarations and depth dd, a list of pairs costs n(n+1)/2n(n+1)/2 comparisons, Θ(n2)\Theta(n^2) whatever the depth; a stack of hash maps costs n(d+1)/2n(d+1)/2 probes, Θ(nd)\Theta(nd); one map from names to stacks of declarations costs nn probes, Θ(n)\Theta(n) expected: only the last makes resolution linear in the size of the script. At n=10,000n = 10{,}000 and d=1,000d = 1{,}000: 50,005,000, 5,005,000 and 10,000.

المصطلحات المعرَّفة في هذا الفصل

عرض كل المصطلحات (1050) في المسرد