Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Dispatch and Encapsulation

Structs with methods attached methods to a single struct, and a call like s.area() ran the one area that Size’s impl provides. The program below has two structs and one method name shared between them. Circle holds a radius r, and Square holds the length of a side. A trait named Shape declares the signature of a method area, with no body, and each struct supplies a body in its own impl Shape for … block. The area of a circle is rounded by taking π as 3. total adds up the areas of a list of shapes, and its type parameter S carries the requirement S: Shape, written in angle brackets where Function types and polymorphism wrote bare type parameters:

struct Circle { r: Int }
struct Square { side: Int }

trait Shape { fn area(self) -> Int; }

impl Shape for Circle { fn area(self) -> Int = 3 * self.r * self.r; }
impl Shape for Square { fn area(self) -> Int = self.side * self.side; }

fn total<S: Shape>(xs: [S]) -> Int = fold(xs, 0, |a: Int, s: S| a + s.area());

fn main() {
    println(total([Circle { r: 1 }, Circle { r: 2 }]));
    println(total([Square { side: 3 }]));
}

It prints:

15
9

The same line of total, s.area(), ran the circle’s formula during the first call and the square’s during the second. A third call that mixes the two, total([Circle { r: 1 }, Square { side: 3 }]), is rejected before the program runs, with type mismatch: expected Circle, found Square at the square.

The program raises these questions:

  • Which area does s.area() run? The body of total names neither struct.
  • When is that decided? The checker sees s at type S, while the evaluator sees a particular struct value.
  • What makes s.area() legal at all? Inside total, S could be any type that a caller supplies.
  • Why can one list not hold both shapes? Both structs implement Shape.

Messages and methods

Simula 67 gave a class’s procedures the option of being declared virtual, so that a procedure called on an object would run the version belonging to the object’s actual class, which can be a more specific class than the one the calling code was written against. Nygaard and Dahl’s history describes classes built for simulation, in which each entity of a modelled system carries its own state and its own behaviour.

Smalltalk, built by Alan Kay, Dan Ingalls, Adele Goldberg, and others at Xerox PARC in the 1970s, made that choice the only kind of call. In Smalltalk a call is a message sent to an object. The message carries a name, called a selector, and its arguments, and the receiving object decides what code answers it. Kay’s “The Early History of Smalltalk” (1993) describes the goal as computers in miniature, cells “interacting only through messages”, and places the messages, more than the objects themselves, at the centre of the design. A Smalltalk interpreter answered a message by looking the selector up in the receiver’s class, and then in that class’s ancestors, each time the message was sent.

That lookup sits on the path of every call, so its cost mattered. L. Peter Deutsch and Allan Schiffman’s “Efficient Implementation of the Smalltalk-80 System” (1984) observed that the receiver at a given call site usually has the same class as at the previous call there. Their implementation remembered, at each call site, the class it last saw and the method it found, so that a repeated send could skip the search after a single comparison.

Choosing a method

A method call e.m(args) names an operation, and the language has to pick the code that performs it. Picking that code is called dispatch. In every language in this chapter the choice depends on the receiver e, and on nothing else that the call supplies: single dispatch.

The choice can be made at two times. Static dispatch makes it before the program runs, from the receiver’s type as the checker knows it. When the type is Circle, the call can only mean Circle’s area, and a compiler can emit a direct call to that code. Dynamic dispatch makes the choice at the moment of the call, from the receiver’s value. Each method call then pays for a lookup, whose cost depends on how the language keeps its methods: a search through dictionaries in an early Smalltalk, a cached comparison after Deutsch and Schiffman, or an index into a table in the compiled languages of the design space.

The two times agree when the receiver’s static type determines its runtime value’s type, as it does for a struct: an expression of type Circle evaluates to a Circle. Inside total they come apart. The checker knows only that s has type S and that S meets Shape. The value of s is a circle during one call of total and a square during another, and only that value says which area to run.

Traits in Bridger

Declaring a trait

A trait declaration names a set of method signatures, with no bodies. The grammar is in Appendix B:

trait_def   ::= 'trait' UpperIdent [ generics ] '{' { fn_sig ';' } '}' ;
fn_sig      ::= 'fn' ident '(' [ 'self' [ ',' params ] | params ] ')' [ '->' type ] ;

A signature may mention Self, which stands for whichever type implements the trait. This trait describes things that can grow and return something of their own type:

trait Grow { fn grow(self, by: Int) -> Self; }

A trait is a name for a requirement. Bridger does not accept it as a type: a parameter declared xs: [Shape] is rejected with the message that Shape is an unknown type, because a trait is not a type of values. Traits appear in two places, after impl and in a bound.

Implementing a trait

An impl block that names a trait with for supplies the trait’s methods for one type:

impl_def    ::= 'impl' [ generics ] [ trait_ref 'for' ] type
                '{' { method } '}' ;

The block must conform to the trait. It provides every method the trait declares, it provides no method the trait lacks, and each method has the trait’s signature with Self replaced by the implementing type. Each failure has its own message:

impl Shape for Circle { }
// `impl Shape` lacks the trait's method `area`

impl Shape for Circle { fn area(self) -> Int = 1; fn perim(self) -> Int = 2; }
// trait `Shape` declares no method `perim`

impl Shape for Circle { fn area(self) -> String = "big"; }
// `area` has signature `fn area(self) -> String`, but the trait declares
//   `fn area(self) -> Int`

The substitution for Self makes the third check specific to each implementing type. An impl Grow for Square must have grow return a Square, and one that returns a Circle is reported as fn grow(self, _: Int) -> Circle against the trait’s fn grow(self, _: Int) -> Square. Within the impl, a signature may write either Self or Square.

Bounds

A type parameter may carry one bound, a trait it must implement:

tparam      ::= UpperIdent [ ':' trait_ref ] ;

A bound is a requirement on callers. Where total is called, the checker instantiates S as T-Inst does and then requires that the type it found satisfy Shape, here by an impl Shape for it. A call on a list of integers finds none:

total([1, 2])
// no `impl Shape for Int`, so the bound is not satisfied

A bound is also a promise to the body. With S: Shape in scope, the checker types s.area() from the trait’s signature, with Self read as S:

T-Method finds its method in an impl for the receiver’s type, and this rule finds it in the bound. With the bound deleted, fn total<S>(…) has nothing to type s.area() against, and the checker reports at the call that there is no such method area. Function types and polymorphism described a type parameter as a type the body may store and pass along but cannot inspect. A bound adds a list of operations the body may apply to it.

An impl can be generic and bounded as well. This one makes a list of shapes a Shape whose area is the sum of its elements’ areas:

impl<S: Shape> Shape for [S] {
    fn area(self) -> Int = fold(self, 0, |a: Int, s: S| a + s.area());
}

With the earlier declarations, [Square { side: 1 }, Square { side: 2 }].area() is 5, and [[Square { side: 3 }]].area() is 9: the outer list’s S is [Square], which is a shape by this same impl, since Square is one.

Evaluating a method call

A method call evaluates its receiver and its arguments, left to right, then runs the method that the receiver’s runtime type provides. Appendix D writes for that type and for the method found under it:

The head of a value is the outermost name its type is known by:

ValueHead
Circle { r: 1 }Circle
Add(Num(3), Num(4))Arith, the type declaring Add
7, true, "s", ()Int, Bool, String, ()
[1, 2], []the list head, written [T]
(1, 2), a function, a referencenone

A value’s head can be read off the value itself, with no type information, because struct and constructor values carry their names. The method body runs in the environment where it was declared, which is the program’s top level, extended with self and the parameters. As in E-App, a return inside the body ends the method call, which is what records.

When the receiver is the bare name of a struct, a type, or Int, Bool, or String, the call is an associated call like Point.origin() from Structs with methods. Its head is that name, the method found must be one declared without self, and the body runs with only the arguments bound. The two mismatched pairings are stuck at run time and rejected by the checker. With that chapter’s Point and a point p:

Point.move_by(1, 2)  // `move_by` takes `self`; call it on a value of the type
p.origin()           // `origin` takes no `self`, so it is not called on a value

An impl can extend a type with a head, so a program can implement Shape for Int or for its own Arith. An impl for a tuple has no head to be found under, and the checker refuses it:

impl Shape for (Int, Int) { fn area(self) -> Int = self.0 * self.1; }
// `impl` for (Int, Int): an impl extends a declared type, struct, or built-in
//   type (`Int`, `Bool`, `String`, `()`, or a list `[T]`)

Coherence

E-Method is deterministic only if is a partial function, taking a head and a method name to at most one body. For a trait without type parameters, Bridger’s coherence conditions guarantee it. A head has at most one impl of a given trait, and a method name is defined at most once for a head, across all of its impl blocks, inherent or not:

impl Shape for Circle { fn area(self) -> Int = 1; }
impl Shape for Circle { fn area(self) -> Int = 2; }
// `impl Shape for Circle` is given more than once

impl Circle { fn area(self) -> Int = 1; }
impl Shape for Circle { fn area(self) -> Int = 2; }
// method `area` is defined more than once for Circle

The second rule also stops two different traits from both providing area on Circle: a call c.area() would name two bodies, and the call gives no way to say which trait is meant.

Bridger has no way to replace one method body with another. A trait supplies no default bodies, and no type inherits methods from another type. Every body for a pair of head and name is therefore the only one, and the evaluator never has to choose between candidates, only find the one that exists.

The same conditions make dispatch by head agree with any static choice. Where the checker knows the receiver is a Circle, it can name Circle’s area, and the evaluator, looking up the head Circle and the name area, finds that very body. Inside total the checker knows only S; the evaluator finds the body under whichever head the value has, and the bound has already established that one exists.

All of this assumes the trait has no type parameters. A trait that takes one can be implemented more than once for the same head, and the pair of head and name then stops determining a body.

When the head is not enough

The full coherence rule counts impls per instance of a trait, the trait with its type arguments filled in. A head may implement a generic trait at several instances, as long as their type arguments have different heads, and a method name still belongs to one trait per head. Here a distance scales by an integer factor or by a boolean switch:

struct Meters { m: Int }

trait Scale<T> { fn scale(self, by: T) -> Meters; }

impl Scale<Int> for Meters {
    fn scale(self, by: Int) -> Meters = Meters { m: self.m * by };
}
impl Scale<Bool> for Meters {
    fn scale(self, by: Bool) -> Meters = if by { self } else { Meters { m: 0 } };
}

fn main() {
    let d = Meters { m: 5 };
    println(d.scale(3));
    println(d.scale(false));
}

This prints:

Meters { m: 15 }
Meters { m: 0 }

Both calls have the head Meters and the name scale, so the pair no longer determines a body. The argument does. The checker sees an Int in the first call and a Bool in the second, and picks the instance each one fits. The evaluator cannot redo that choice from the head alone, so the checker records the method it chose for that call, keyed by the call’s source span, and the evaluator runs the recorded method in place of a lookup. Dynamic and gradual typing described Bridger’s checker as passing the evaluator nothing. This is the first thing it passes: a method chosen from types that no runtime value carries.

A call through a bound has no checker choice to record, because the checker does not know which type will arrive. Bridger therefore rejects a bound that its type meets at more than one instance:

fn twice<S: Scale<Int>>(s: S) -> Meters = s.scale(2);

twice(Meters { m: 5 })
// Meters implements `Scale` at more than one instance, so a call through
//   the bound cannot choose one

Meters does implement Scale<Int>. But inside twice the call s.scale(2) is answered by head and name, and under the head Meters the name scale has two bodies. Traits vs. inheritance describes an implementation of bounds that passes the chosen impl along with the call, under which this program would run.

A program can also be run with no checker at all, as Parts II through V ran. The evaluator then has no recorded choices, and a lookup takes the first impl declared for the head.

One list, several shapes

A list has one element type, and a bound is satisfied by one type at a time, so total sums a list of circles or a list of squares. A collection that holds both is a value of a sum type, built with the constructors of Sum and product types. Giving the sum its own impl Shape lets it into total:

type AnyShape = C(Circle) | Sq(Square);

impl Shape for AnyShape {
    fn area(self) -> Int = match self { C(c) => c.area(), Sq(s) => s.area() };
}

// total([C(Circle { r: 1 }), Sq(Square { side: 3 })]) is 12

The head of C(Circle { r: 1 }) is AnyShape, so the outer call finds AnyShape’s area. Its match selects a constructor, and the inner call finds Circle’s. AnyShape lists its alternatives once, so a third struct implementing Shape reaches total only after a new constructor and a new arm are added to AnyShape. Traits vs. inheritance compares that cost with the cost of adding an operation.

Building it

The parser delivers traits and impls in the shapes given in The abstract syntax tree:

Trait(Generics, Vec<Sig>),                     // trait Tr<T> { fn m(…); … }
struct Sig { name: Name, has_self: bool, params: Vec<Param>, ret: Ty, span: Span }

struct Impl {
    generics: Generics,        // impl<T> …
    trait_: Option<TraitRef>,  // the trait implemented, if any
    ty: Ty,                    // the type being extended
    methods: Vec<Method>,
    span: Span,
    head: Span,                // the header, `impl<T> Tr for T`
}

Method(Box<Expr>, Name, Vec<Expr>, Span),      // method call: e.m(e, …)

When a program loads, the provided code gathers every impl into one table on the Interpreter, keyed by a head and a method name:

methods: HashMap<(String, Name), Rc<Method>>,  // (head, name) -> first body

A head’s key in the table is the struct or type name, or "Int", "Bool", "String", "()", or "[]" for every list, the head the table above writes [T]. A constructor value’s key is the name of the type that declares the constructor, found among the program’s declarations. Where a head has several instances of a trait, the table holds the first impl’s body, and the checker’s choice overrides it. The checker collects those choices, by span, into self.conversions, a table named for the other choice it holds: the conversion a ? applies, which Traits vs. inheritance covers. The provided declaration checks run before any expression is checked: conformance of every trait impl, coherence, and the rule that an impl’s target has a head.

The evaluator’s Method arm follows E-Method. It evaluates the receiver and the arguments in order, then looks first in self.conversions at the call’s span and otherwise in self.methods under the receiver’s head. With a method in hand it checks the self pairing and the arity, binds self and the parameters in a scope built from env.root(), the program’s top level, and runs the body between enter_call and leave_call, catching a Return as the Call arm does. A receiver whose head has no such method, among the impls and the built-in methods, is stuck with NoSuchMethod.

The checker’s Method arm types the receiver first. A receiver of known type has its method found among that head’s impls, using the arguments where several instances provide the name, and records the choice with record_conversion when the head alone does not determine it. A receiver whose type is a type parameter has its method found in the parameter’s bound, through bound_of, as in T-Method-Bound. At a call of a bounded function, the instantiated bound becomes an obligation through require_trait, which the provided code discharges once the declaration’s types are solved.

Encapsulation

A Range with fields lo and hi is meaningful only when lo <= hi. A property that every value of a type must have is an invariant of the type, and a type keeps its invariant if every value of the type is built and changed by code that respects it. Making the rest of the program unable to reach the fields is called encapsulation, and it moves the burden of the invariant from every use of the type to the code that defines it.

David Parnas’s “On the Criteria to Be Used in Decomposing Systems into Modules” (1972) argued for dividing a program by the design decisions likely to change, with each module concealing one such decision from the others, so that changing the decision changes one module. He called the principle information hiding. CLU, from Barbara Liskov’s group, enforced it for data. A CLU cluster defined an abstract type together with its operations, and only the code inside the cluster could see the representation underneath (Liskov et al., 1977). A Smalltalk object’s instance variables were visible only to its own methods, so other objects could reach its state only by sending it messages.

Bridger’s fields are public

Bridger has no visibility modifiers. Any code that can name a struct can build one with a literal, read its fields, and take it apart with a struct pattern.

The language has no modules, so the only boundary a privacy rule could use is the impl block: fields readable and literals writable only inside impl Range. Code elsewhere could still build a Range through Range.new, but Range { lo: 2, hi: 7 } and every pattern of the form Range { lo, hi } would be errors outside the impl, so no other function could match on a Range at all. Struct patterns arrived with Part VIII, and the rule would take them away for every struct with a private field. With no module boundary, the functions that work closely with a type, and the tests that check it, would lose access along with everything else.

Encapsulation in Bridger is a convention. A type provides an associated constructor that checks the invariant, and methods for everything else:

struct Range { lo: Int, hi: Int }

impl Range {
    fn new(lo: Int, hi: Int) -> Option<Range> =
        if lo <= hi { Some(Range { lo: lo, hi: hi }) } else { None };
    fn width(self) -> Int = self.hi - self.lo;
}

fn main() {
    println(Range.new(2, 7));
    println(Range.new(7, 2));
    let bad = Range { lo: 7, hi: 2 };
    println(bad.width());
}

This prints:

Some(Range { lo: 2, hi: 7 })
None
-5

Range.new refuses the reversed bounds, and a literal accepts them. Struct values cannot change, so a Range built through new keeps its invariant for as long as it exists. A struct with a reference field is different, since anyone holding the struct can assign through the field:

struct Tally { n: ref<Int> }

impl Tally {
    fn new() -> Tally = Tally { n: ref(0) };
    fn tick(self) { self.n := deref self.n + 1; }
    fn read(self) -> Int = deref self.n;
}

fn main() {
    let t = Tally.new();
    t.tick();
    t.tick();
    t.n := 100;
    println(t.read());
}

It prints 100.

Hiding state in a closure

Closures give Bridger a boundary that a struct does not. A closure captures the variables in scope where it is created, and code outside that scope has no name for them. A counter can be a struct whose fields are closures over a reference that only they can reach:

struct Counter { tick: fn() -> (), read: fn() -> Int }

fn counter() -> Counter {
    ref n = 0;
    Counter {
        tick: || { n := deref n + 1; },
        read: || deref n,
    }
}

fn main() {
    let c = counter();
    (c.tick)();
    (c.tick)();
    println((c.read)());
    let d = counter();
    println((d.read)());
}

This prints 2 and then 0. Each call of counter allocates a fresh n, and the only operations on it are the two closures. A caller can replace a field of c by building a new Counter, but has no way to reach n itself. The parentheses in (c.tick)() are required: c.tick() is a method call, and the checker reports that tick is a field of Counter, with the hint that a function held in a field is called as (e.tick)(…).

The counter’s two closures are an object in Smalltalk’s sense, state reachable only through its operations, assembled from parts of Part V. They are not reached through dispatch: each field holds one function, chosen when the counter is built.

The design space

Static dispatch by specialization

C++ templates and Rust generics compile a generic function once for each type it is used at, a technique called monomorphization. A Rust fn total<S: Shape>(xs: &[S]) called on circles and on squares becomes two functions, and in each, s.area() is a direct call to one known body, which the compiler can then inline. The lookup is gone, and the price is a larger program, with a copy of total per type and the work of compiling each.

Bridger’s reference interpreter keeps one copy of total and looks up each call by head, a hash lookup per call. Coherence ensures that both strategies run the same area.

Values that carry their methods

In C++, a class with virtual member functions gives each object a hidden pointer to a table of its class’s implementations, the vtable. A virtual call loads that pointer and calls through a fixed slot in the table. Rust’s dyn Shape builds the same arrangement on demand: a reference to a value travels with a pointer to the table of Shape methods for its type, and Vec<Box<dyn Shape>> holds circles and squares side by side. A Go interface value is a pair of a type’s method table and the data, and a Java variable of an interface type can refer to an object of any class implementing the interface.

Each of these turns a trait into a type of values, which is what Bridger’s [Shape] would need. Bridger’s sum type AnyShape reaches a similar collection by listing its members in one place, while a trait object admits any type implementing the trait, including one written later.

Choosing on more than the receiver

Single dispatch inspects the receiver alone. Common Lisp’s CLOS and Julia dispatch on the runtime types of all the arguments, so an operation like intersect(a, b) can have one body for two circles and another for a circle and a square. A call then selects the most specific body that applies, and the language needs a rule for when no body is most specific. Bridger’s instances, told apart by the heads of their type arguments, are chosen by the checker from static types, and the evaluator uses the receiver alone.

Access control

Java and C++ attach private, protected, and public to each member of a class, and the boundary of privacy is the class. Rust puts the boundary at the module: a field without pub is visible throughout the module that declares the struct and nowhere outside it, so code in the same module may still build the struct with a literal. Python enforces nothing, and a leading underscore on a name signals that it is internal. A leading double underscore makes the interpreter rename the attribute, which makes accidental access unlikely without preventing deliberate access. JavaScript added fields named with #, which code outside the class body cannot read at all.

These choices place a boundary somewhere in the program text. Bridger places none, and its one enforced boundary is the scope of a closure.

Further reading

Smalltalk: Kay’s “The Early History of Smalltalk” (1993) runs from Simula and Sketchpad to Smalltalk-80, with the design decisions of each version of the language along the way.

Making dispatch fast: Deutsch and Schiffman’s “Efficient Implementation of the Smalltalk-80 System” (1984) describes translating Smalltalk to machine code as methods are first run, and the per-call-site cache of the last class seen.

Information hiding: Parnas’s “On the Criteria to Be Used in Decomposing Systems into Modules” (1972) works through two decompositions of one small program, a keyword-in-context index, and compares what each must change when a design decision changes. Liskov and colleagues’ “Abstraction Mechanisms in CLU” (1977) presents clusters, with complete examples.

Concept checks

total([Circle { r: 1 }, Square { side: 3 }]) is rejected, while total([C(Circle { r: 1 }), Sq(Square { side: 3 })]) is accepted. What did AnyShape add?

A list literal’s elements share one type, and the first is a Circle, so the Square is a mismatch before the bound is consulted. AnyShape is one type whose values are circles or squares under a tag, so the list has element type AnyShape, and its impl Shape satisfies the bound. The match in that impl is where the choice between the two shapes is made.

Why is twice(Meters { m: 5 }) rejected, when Meters implements Scale<Int> and d.scale(3) runs?

At d.scale(3) the checker sees the argument is an Int, picks the Scale<Int> method, and records the choice for the evaluator. Inside twice it cannot record a choice, since S is unknown there, so the evaluator would look up scale under the head Meters alone, where there are two bodies. A bound is accepted only when the head and name lead to one.

Suppose Bridger allowed two impl Shape for Circle blocks in one program. What would E-Method need that it does not have?

A way to choose between two bodies for one head and one name: an order among impls, a name for the impl at the call, or a rule preferring one. Without one, is not a function and the rule does not say which body runs.

Compare the closure counter with the Tally struct. What can a caller do to each, and what would a private modifier on Tally's field cost Bridger?

A caller can assign t.n := 100 and break any invariant Tally means to keep, while the counter’s n has no name outside counter. A field private to impl Tally would close that, but code outside the impl could then neither write a Tally literal nor match a Tally { n } pattern. Languages with modules draw the line at the module, which leaves room for helper code beside the type. Bridger has no modules to draw it at.