هذا الكتاب غير متوفر بعد باللغة العربية. النسخ المتوفرة: 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 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"),
}
}
&& 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
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
}
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); }
}
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
main’s parameter scope is empty.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
}
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.rsListing 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);
}
var resolves its initialiser first. code/bachelor-3/04-semantic-analysis/listings/resolve.rsOutput 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
ok.moor and the declaration it is bound to, by line and column.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 reads “with the variables of at their types, expression has type ”; chapter 6 makes these notions precise.
Moor’s rules for expressions are short. A few of them:
Statements have a judgement of their own, : the statement is correct in , and is the context after it, which a var extends. Writing for the result type of the enclosing function:
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).
if without else has the same rule without . 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
}
int or bool. code/bachelor-3/04-semantic-analysis/listings/typecheck.rsOne 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,
})
}
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 , 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 if each variable of holds a value of type , and array elements are integers. Claim: if , the environment agrees with , and the evaluation of ends without a runtime error, its value has type . By induction on , following the evaluation, which evaluates the subexpressions first. A literal has its type. A variable has type by the rule, and holds a value of that type by agreement. An array element is an integer by agreement. For , the rule gives , 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 to , and receives the value of , of type by the claim. An assignment requires . An array assignment requires an integer value. Leaving a block removes the same names from the environment and from . By induction on the number of statements executed, the environment always agrees with the current , 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;
}
$ 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;
^
count and the early use of total point at the other line involved.(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?
| 1 | var n: int = 1; |
| 2 | fn f(n: int) -> int { |
| 3 | var m = n; |
| 4 | { |
| 5 | var n = m + 1; |
| 6 | m = n; |
| 7 | } |
| 8 | return n + m; |
| 9 | } |
| 10 | fn 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 : , the inner , , and the result is ; 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.
The condition is a boolean, the body is checked in (its own declarations are local to it), and the context after the loop is 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);
}
}
$ rustc --edition 2021 -O -o scope_bug scope_bug.rs && ./scope_bug
x in the inner block: Some(17)
x after the block: None
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 that ends without a runtime error ends by a return, never by reaching the end of . 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 of returns in the sense of the function. An execution of runs in order; if it returns before we are done; otherwise it reaches , and runs it to its end or to a return. If 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 , and none reaches the end of . 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 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: maps at depth . A lookup searches from the top. A local of the innermost block: 1 probe. A parameter: . A global: . An undeclared name: , every map. In general a name declared maps below the top costs (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 , the Fibonacci number (exercise_9_recursive_output).
Exercise 4.10 ★★★
Extend the proof of Theorem 4.6 to programs with calls: show that a call of type that returns yields a value of type . 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 , gives a value of the expression’s type, and every call it makes, of a function with result type , returns a value of type . Induct on the length of the evaluation (the number of steps, finite since it ends). For with : the arguments are shorter evaluations, so they give values of types ; 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 , and by induction ’s value has type . 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 (), a lookup makes at most 14 comparisons, and an inner block that shadows one name and adds another allocates at most 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 comparisons whatever the depth, against one probe per enclosing scope; a declaration costs 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 be the set of definitely assigned variables at a point. A var x: int; adds x to the scope but not to ; var x = e; and x = e; first require that every variable read by is in , then add x. For if e B1 else B2: the condition is checked against , both branches start from , and after the statement is the intersection of the sets at the ends of the branches. Without else, the intersection with itself, which is . For while e B: the body is checked from , and after the loop is unchanged, since the body may run zero times. After a return, 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 reached, every variable of 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 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: nested blocks, declarations in each, every declaration var v = reg + ; 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 .
Part I — Scopes by hand.
- Write the script for and draw the stack of maps after each declaration.
- To which declaration does each use of
regrefer? Why must it be found from every block? - If the second block declared its own
regfirst, which uses would change their binding? - In a block that already sees a
v, whichvdoesvar v = v + 1;read? - Would any answer change if Moor used dynamic scope? Why not, for this script?
- How many declarations and how many uses does a script have, as functions of and ?
Part II — Three tables.
- With a list of (name, declaration) pairs searched from the newest end, how many name comparisons does the lookup of
regcost in the -th declaration of the script? - Deduce the total for the whole script. Does it depend on ?
- With the resolver’s stack of maps, how many probes does the lookup of
regcost at depth ? Deduce the total. - 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?
- How much memory does each table use at the deepest point of the script?
- For , compare the three totals.
Part III — Counted.
- For , run the counts for , 10, 100 and 1,000 and fill a table with the three totals.
- Explain from question 8 why the list’s column does not change.
- What is the ratio between the list and the stack of maps at ? At ?
- 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?
- The counts are of probes, not of time. Why is a probe in a hash map “constant time” only in expectation?
- Why does the book count operations rather than time them?
Part IV — Errors counted.
- The clerk misspells
regasrgein block 3 of a script with , . How many messages does the front end give? - Why is there no message about the
+in which each misspelt name appears? - If an undeclared name were given the type
intinstead of the error type, would the count change for this script? Give a statement for which it would. - How would you change the resolver to give one message per misspelt name in a function, and how many would this script then get?
- Sum up the costs of the three tables on scripts of declarations and depth , 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. declarations, reg included, and uses.
7. : the list holds, newest first, the declarations made since reg, then reg itself.
8. , whatever : a block’s exit truncates the list, but no block closes before the last declaration.
9. probes: the maps of blocks . In total .
10. One probe per lookup, in total. Leaving a block pops one declaration per name the block declared: operations.
11. All three hold the live declarations: the list pairs and marks; the stack maps with entries in all; the single map entries, with lists of names. Each is .
12. comparisons for the list, probes for the stack of maps (every use is found in the first map searched), for the single map.
13. For , 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 , 10, 100 and 1,000; the single map makes 10,000 probes at every depth.
14. Its count, , depends only on how many declarations are newer than reg at each use.
15. About 10 at (), and about 5,000 at .
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 declarations and depth , a list of pairs costs comparisons, whatever the depth; a stack of hash maps costs probes, ; one map from names to stacks of declarations costs probes, expected: only the last makes resolution linear in the size of the script. At and : 50,005,000, 5,005,000 and 10,000.