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

Milestone M8

Structs, Methods, and Traits

Part IX gave Bridger named products and the operations attached to them. Structs with methods added struct declarations, literals, field access, inherent impl blocks, and associated functions. Dispatch and encapsulation added traits, bounds, and the rule that picks a method by the receiver’s head, and Traits vs. inheritance restated the prelude over Ord and Len and gave ? its conversion through From. This milestone builds all of it. Every M1–M7 test must still pass.

The work is in the files you have already edited: the evaluator in src/interp/eval.rs, the checker in src/types/check.rs, and the purity judgment in src/relations/check.rs.

To-dos

grep -rn 'todo_m8!' src lists the holes:

// src/interp/eval.rs
Expr::Struct(..) => todo_m8!("E-Struct"),
Expr::Field(..) => todo_m8!("E-Field (struct field access)"),
Expr::Method(..) => todo_m8!("E-Method (head-type dispatch)"),

// src/types/check.rs
Expr::Struct(..) => todo_m8!("T-Struct"),
Expr::Field(..) => todo_m8!("T-Field"),
Expr::Method(..) => todo_m8!("T-Method (dispatch on the receiver's type; bounds)"),

Before you start, paste the three modules in The helper modules below, one at the end of each file you edit. They do the bookkeeping that connects objects to the rest of the interpreter: the key a value’s head has in the method table, the search for the method a call names, and the method nodes of the purity judgment’s call graph. What remains is the part of Part IX that the rules describe.

Three changes have no todo_m8! marker of their own:

  1. The checker’s Try arm accepts a ? whose error type differs from the function’s, when an impl From converts it, as described below.
  2. The evaluator’s Try arm runs that conversion.
  3. Your purity judgment from M6 and M7 meets struct literals, field access, method calls, and a ? that converts, which no earlier program could reach. Purity below says how the provided calls module fits into the walk you already have.

How to know it works suggests an order for the work.

Milestone specification

The forms, the rules that give them meaning, and the cases in which evaluation is stuck or the checker rejects them:

FormRulesStuck whenRejected when
S { f1: e1, …, fn: en } E-Struct, T-Struct a field is named twice (DuplicateField); S is not a struct (NotAStruct); a declared field is missing (MissingField); a field is not declared (NoSuchField); each at the literal S is unknown (UnknownType) or not a struct (NotAStruct); a field is named twice (DuplicateField) or not declared (NoSuchField), at that field's value; a declared field is missing (MissingField), at the literal; a field's value has the wrong type
e.f E-Field, T-Field e's value is not a struct with a field f (NoSuchField, at the access) e's type is not a struct (FieldOfNonStruct); the struct has no field f (NoSuchField); e's type is undetermined (Ambiguous)
e.m(e1, …, en), T.m(e1, …, en) E-Method, T-Method neither an impl nor a built-in conformance gives the head a method m (NoSuchMethod); a method with self is called on a type name (NoReceiver) or one without on a value (NotAMethod); the count differs (ArityMismatch); each at the call the type has no method m (NoSuchMethod), or a field m (FieldNotMethod); the self pairings (NoReceiver, NotAMethod); T is a type parameter (TypeParamCall); several instances fit the arguments (AmbiguousMethod); the count differs (ArityMismatch); an argument has the wrong type; an impl's own bound is not met (UnsatisfiedBound)
e? desugars to match, return, and E.from as at M7 as at M7, except that two different error types are accepted when an impl From converts one into the other

E-Struct, E-Field, and E-Method are in Appendix D, T-Struct, T-Field, and T-Method under its typing rules, and the static errors are catalogued by name. A struct value holds its fields in declaration order, whatever order its literal wrote them in, as E-Struct’s permutation premise says.

The declarations themselves are checked by provided code before any expression is: every trait impl conforms to its trait (MissingMethod, NotInTrait, SignatureMismatch), coherence holds (DuplicateImpl, DuplicateMethod, OverlappingImpls, BuiltinImpl), an impl’s target has a head (ImplTarget), and a bound is not met at several instances (AmbiguousInstance). The obligations your arms register with require_trait are discharged by provided code too, which reports UnsatisfiedBound.

Implementing Milestone M8

The provided runtime

A struct value is Value::Struct(name, fields), with its fields as name and value pairs in an Rc<[(Name, Value)]>, and a bare type name is Value::Type(name), which your M7 Ctor arm already builds. Printing, ==, and your matcher’s struct arm already handle struct values.

When a program loads, the provided code builds two tables on the Interpreter:

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

methods holds every impl’s methods under the key of the type the impl extends. Where a head implements a trait at several instances, it holds the first impl’s body. conversions holds the checker’s choices by span: the method a call runs where its head did not determine it, and the from a ? converts through. It is empty when a program runs unchecked, as run_program runs one. A Method carries has_self, params, and body.

The built-in conformances have no impl. prelude::builtin_method(&receiver, m) returns the native for cmp on an Int, String, or Bool, or for length on a String or a list, and self.eval_prelude(id, args, span) runs it with the receiver as the first argument.

The evaluator’s arms

  • Struct evaluates the field expressions in the order the literal writes them, before any check. It then reports, at the literal, a field named twice (DuplicateField), a name whose declaration is not a struct (NotAStruct), the first declared field the literal omits (MissingField), and a field the declaration lacks (NoSuchField). The value holds the fields in the declaration’s order, so Pos { y: 2, x: 1 } and Pos { x: 1, y: 2 } are one value.

  • Field evaluates its receiver and returns the named field. A value with no such field, including any value that is not a struct, is NoSuchField at the access.

  • Method evaluates the receiver, then the arguments left to right. The method to run is the one conversions holds at the call’s span, if there is one, and otherwise the one methods holds under the receiver’s head key, which head_key from the head module gives, and the method’s name. With a method in hand:

    • A receiver that is a Value::Type makes the call an associated call. A method with self called that way is NoReceiver, and one without self called on a value is NotAMethod, with ty the receiver’s head key.
    • A count that differs from the method’s parameters is ArityMismatch.
    • The body runs in a scope built from env.root(), extended with self bound to the receiver when the method takes one, then with each parameter. It runs between enter_call and leave_call, and a Return from it is the call’s value, as your Call arm does.

    With no method from either table, a built-in conformance answers through builtin_method, and anything else is NoSuchMethod. The errors are all at the call.

The checker’s arms

Each arm ends as M5’s did, with the final unification against the expected type and the record. The helpers named here are in the objects module.

  • Struct looks the name up with struct_decl, which gives the declaration’s generics and fields. A name it does not find is NotAStruct when some other declaration has it and UnknownType when none does. The arm then rejects a repeated field with DuplicateField, at that field’s value, and a missing one with MissingField, at the literal. instantiate_struct gives the literal’s type, with fresh inference variables for the struct’s parameters, together with the instantiation that maps each parameter to its variable. Check each field’s value against its declared type with that instantiation applied by Ty::substitute. A field the declaration lacks is NoSuchField, at its value.
  • Field infers the receiver’s type and resolves it. For a struct type, the field’s type is its declared type with the struct’s parameters replaced by the type’s arguments, and a missing field is NoSuchField. An unsolved inference variable goes to M5’s undetermined, and any other type is FieldOfNonStruct { field, found, span }.
  • Method first decides what the receiver is.
    • A receiver that is a bare name with no arguments and is in type_params is TypeParamCall, since a type parameter has no head at run time. For any other bare name, type_receiver gives the type an associated call is made on, with fresh variables for its parameters, or None when the name is not a struct, a type, Int, Bool, or String. A type from type_receiver makes the call an associated call. Any other receiver is inferred and resolved, and an unsolved variable makes the call’s type undetermined.
    • find_method(&recv_ty, m, args, ctx, span) finds what the call can run: an impl’s method for the receiver’s head, a built-in conformance’s, or the method a bounded type parameter’s trait declares. Where several instances of a generic trait provide m, it chooses by the arguments and records the choice for the evaluator. With nothing found, a receiver that is not a type name and is a struct with a field m is FieldNotMethod, and anything else is NoSuchMethod.
    • A found method’s has_self gives the pairings: a method with self on a type name is NoReceiver, and one without self on a value is NotAMethod, whose ty and is_param are the found method’s fields of those names.
    • method_sig(&found, &recv_ty, m, span) gives the method’s parameter types and result type with Self read as the receiver’s type and an impl’s parameters solved from it. It reports NoSuchMethod for an impl at another instance than the receiver’s and registers the impl’s own bounds. Then check the count (ArityMismatch) and each argument against its parameter type. The call’s type is the result type.

The conversion in ?

M7’s Try arm compared the operand’s error type with the function’s and reported Mismatch when they differed. From M8, before it reports that, it calls find_from(&have, &want, span) with the operand’s error type and the function’s. When that gives a from, pass it to record_conversion at the ?’s span and give the form the operand’s Ok type. Before M8, find_from always gives None, so one arm is right at both milestones, and when the error types already agree nothing is recorded, so a program from M7 checks and runs as it did.

The evaluator’s Try arm changes only for an Err. If conversions holds a method at the ?’s span, run its body with its parameter bound to the Err’s payload, in a scope built from env.root() and between enter_call and leave_call, and return the result inside a new Err. With no entry, the payload passes through unchanged, which is what a program run unchecked does.

Purity

A rule filter and a match guard may now contain struct literals, field accesses, method calls, and ?. A struct literal and a field access are pure when their parts are, so your walks need only descend into their subexpressions: a literal’s field values, an access’s receiver, and a call’s receiver and arguments.

A method call or a ? is a call to a callee key, which plays the part a function’s name plays in your M6 judgment. The calls module computes it:

  • calls::method_callee(program, e) is the key of a method call or a ? anywhere in the program. It is Head.m when the declarations settle the receiver’s head, as in Pos.sum, and .m, every impl’s method of that name, when they do not. A ? is .from. None means a built-in conformance or a ? with no impl From, and either is pure apart from its parts.
  • calls::method_bodies(program, key) gives the bodies behind a key, each with the names its declaration binds, self and then the parameters, which are locals in that body.
  • calls::method_params(program, key) gives their parameter types, for the higher-order check.
  • calls::method_keys(program) lists every key, so your impurity fixpoint can range over methods along with functions.
  • calls::is_prelude_fn(program, name) holds for the prelude’s Bridger-written min, max, minimum, maximum, and len. They are trusted to be total, so they are exempt from the recursion and higher-order checks, and the methods they reach are judged like any other.

With these, a key is a callee like a function: impure when one of its bodies reaches an effect, in a recursive cycle when its bodies reach it again, and named by its key in a witness. Your check_guards also walks every method body in program.impls, since a guard can sit in a method.

The helper modules

The starter leaves out the three modules below. Paste each at the end of the file it serves, after everything else in the file. Each brings its own use lines, so it cannot clash with the imports your arms add, and an item you have not called yet raises no warning. None of them contains a typing or evaluation rule. The checker’s module can read the Checker’s private fields because check.rs is part of the types module.

The head module

The evaluator looks a method up under its receiver’s head, and the key the table uses for a head is a string. Paste this module at the end of src/interp/eval.rs:

mod head {
    use crate::ast::Decl;
    use crate::interp::value::Value;
    use crate::interp::Interpreter;

    impl Interpreter {
        /// The key of `v`'s head in `self.methods`: a struct's name, the
        /// name a `Value::Type` carries, the type that declares a
        /// constructor, or a built-in head ("Int", "Bool", "String", "()",
        /// "[]"). A tuple, reference, closure, or relation has no head.
        pub fn head_key(&self, v: &Value) -> Option<String> {
            let key = match v {
                Value::Struct(n, _) | Value::Type(n) => n.clone(),
                Value::Ctor(c, _) => self.declaring_type(c)?,
                Value::Int(_) => "Int".to_string(),
                Value::Bool(_) => "Bool".to_string(),
                Value::Str(_) => "String".to_string(),
                Value::Unit => "()".to_string(),
                Value::List(_) => "[]".to_string(),
                _ => return None,
            };
            Some(key)
        }

        /// The name of the `type` declaration with a constructor `c`.
        fn declaring_type(&self, c: &str) -> Option<String> {
            let declares = |d: &Decl| match d {
                Decl::Type(_, vs) => vs.iter().any(|x| x.name == c),
                _ => false,
            };
            let (name, _) = self.program.decls.iter().find(|(_, d)| declares(d))?;
            Some(name.clone())
        }
    }
}

A Value::Type and a struct value of the same name have the same key, so an associated call Pos.zero() and a method call on a Pos look in the same place. Which of the two kinds of method a call may run is the Method arm’s decision.

The objects module

Paste this module at the end of src/types/check.rs, after M5’s helpers:

  • struct_decl(name) is the generics and fields of the struct name, or None.
  • type_receiver(name) is the type a bare name stands for as the receiver of an associated call, or None.
  • instantiate_struct(name, generics, expected, span) is a struct literal’s type and instantiation, with the struct’s declared bounds registered and an expected type of the same head unified in, so the field checks see what the context already knows.
  • find_method(recv, m, args, ctx, span) is the method a call can run, as a Found with has_self, ty, and is_param, or None.
  • method_sig(found, recv, m, span) is a found method’s parameter types and result type at this receiver.
  • find_from(src, tgt, span) is the from that converts the error type src into tgt, or None, and always None before M8.
/// Provided helpers (Milestone M8): finding the method a call names, and
/// the instantiation a struct literal needs. Paste this module at the end
/// of the file, unchanged.
mod objects {
    use crate::ast::{Decl, Expr, Field, Generics, Method, Name, Sig, Span};
    use crate::ast::{TraitRef, Ty, TyKind};
    use crate::types::{builtin_conforms, head_key, Checker, Ctx, TyError};
    use std::collections::HashMap;

    type Res<T> = Result<T, TyError>;
    type Subst = HashMap<Name, Ty>;
    /// The `from` a `?` converts through, if one applies.
    type Conversion = Option<Method>;

    /// A method a call can run, as [`Checker::find_method`] found it.
    pub struct Found {
        /// whether the method takes `self`
        pub has_self: bool,
        /// the receiver as a `NotAMethod` error names it
        pub ty: String,
        /// whether it was found through a type parameter's bound
        pub is_param: bool,
        how: How,
    }

    enum How {
        /// a method of an `impl`: its generics, the type it extends, and it
        Impl(Box<(Generics, Ty, Method)>),
        /// a trait's signature: a built-in conformance, or a bound
        Sig(Sig),
    }

    impl Checker {
        /// The generics and fields of the struct `name`, if it is one.
        pub fn struct_decl(&self, name: &str) -> Option<(Generics, Vec<Field>)> {
            match self.decl(name) {
                Some(Decl::Struct(g, fields)) => Some((g.clone(), fields.clone())),
                _ => None,
            }
        }

        /// The type a bare name stands for as the receiver of an associated
        /// call: a struct or `type` with fresh variables for its parameters,
        /// or `Int`, `Bool`, `String`. `None` for any other name.
        pub fn type_receiver(&mut self, name: &str) -> Option<Ty> {
            match name {
                "Int" => return Some(Ty::int()),
                "Bool" => return Some(Ty::bool()),
                "String" => return Some(Ty::str()),
                _ => {}
            }
            let generics = match self.decl(name) {
                Some(Decl::Struct(g, _)) | Some(Decl::Type(g, _)) => g.clone(),
                _ => return None,
            };
            let map = self.fresh_for(&generics);
            Some(Ty::named(name.to_string(), args_of(&generics, &map)))
        }

        /// A struct literal's type, with fresh variables for the struct's
        /// parameters, its declared bounds required, and an expected type of
        /// the same head unified in. Also returns the instantiation, to apply
        /// to each field's declared type with `Ty::substitute`.
        pub fn instantiate_struct(
            &mut self,
            name: &str,
            generics: &Generics,
            expected: Option<&Ty>,
            span: Span,
        ) -> Res<(Ty, Subst)> {
            let map = self.fresh_for(generics);
            self.require_bounds(generics, &map, span);
            let ty = Ty::named(name.to_string(), args_of(generics, &map));
            if let Some(want) = expected.map(|t| self.resolve(t)) {
                if same_head(&ty, &want) {
                    self.unify(&ty, &want, span)?;
                }
            }
            Ok((ty, map))
        }

        /// The method `m` that a call on a receiver of type `recv` can run:
        /// an `impl`'s method for the receiver's head, a built-in
        /// conformance's, or the trait method a bounded type parameter
        /// promises. Where several instances of a generic trait provide `m`,
        /// the arguments choose, and the choice is recorded for the
        /// evaluator. `None` when nothing provides `m`.
        pub fn find_method(
            &mut self,
            recv: &Ty,
            m: &str,
            args: &[Expr],
            ctx: &Ctx,
            span: Span,
        ) -> Res<Option<Found>> {
            let mut cands = self.impl_methods(recv, m);
            if cands.len() > 1 {
                cands = self.choose_instance(cands, recv, m, args, ctx, span)?;
            }
            if let Some((generics, impl_ty, method)) = cands.into_iter().next() {
                let ty = head_key(recv).unwrap_or_else(|| "T".to_string());
                return Ok(Some(Found {
                    has_self: method.has_self,
                    ty,
                    is_param: false,
                    how: How::Impl(Box::new((generics, impl_ty, method))),
                }));
            }
            if let Some(sig) = self.builtin_sig(recv, m) {
                return Ok(Some(self.found_sig(sig, recv)));
            }
            if let Some(sig) = self.bound_sig(recv, m) {
                return Ok(Some(self.found_sig(sig, recv)));
            }
            Ok(None)
        }

        /// The parameter types and the result type of a found method, with
        /// `Self` read as `recv` and an `impl`'s parameters solved from
        /// `recv`. An `impl` at another instance than `recv`'s is
        /// `NoSuchMethod`; an `impl`'s own bounds are required at the call.
        pub fn method_sig(
            &mut self,
            found: &Found,
            recv: &Ty,
            m: &str,
            span: Span,
        ) -> Res<(Vec<Ty>, Ty)> {
            let (map, params, ret): (Subst, Vec<Ty>, Ty) = match &found.how {
                How::Sig(sig) => {
                    let ps = sig.params.iter().map(|p| p.ty.clone()).collect();
                    (Subst::new(), ps, sig.ret.clone())
                }
                How::Impl(b) => {
                    let (generics, impl_ty, method) = &**b;
                    let map = self.fresh_for(generics);
                    let impl_ty = impl_ty.substitute(&map).with_self(recv);
                    let saved = self.metas.clone();
                    if self.unify(&impl_ty, recv, span).is_err() {
                        self.metas = saved;
                        return Err(TyError::NoSuchMethod {
                            method: m.to_string(),
                            span,
                        });
                    }
                    self.require_bounds(generics, &map, span);
                    let ps = method.params.iter().map(|p| p.ty.clone()).collect();
                    (map, ps, method.ret.clone())
                }
            };
            let inst = |t: &Ty| t.substitute(&map).with_self(recv);
            Ok((params.iter().map(inst).collect(), inst(&ret)))
        }

        /// The `from` of the `impl From<src> for tgt` that converts a `?`'s
        /// error type `src` into the function's `tgt`, with the impl's own
        /// bounds required. Always `None` before M8, where the two error
        /// types must agree.
        pub fn find_from(&mut self, src: &Ty, tgt: &Ty, span: Span) -> Conversion {
            if !cfg!(feature = "m8") {
                return None;
            }
            let impls = self.program().impls.clone();
            for imp in &impls {
                let Some(tr) = &imp.trait_ else { continue };
                if tr.name != "From" || tr.args.len() != 1 {
                    continue;
                }
                let saved = self.metas.clone();
                let map = self.fresh_for(&imp.generics);
                let covers = self.unify(&imp.ty.substitute(&map), tgt, span).is_ok()
                    && self.unify(&tr.args[0].substitute(&map), src, span).is_ok();
                if !covers {
                    self.metas = saved;
                    continue;
                }
                self.require_bounds(&imp.generics, &map, span);
                return imp.methods.iter().find(|m| m.name == "from").cloned();
            }
            None
        }

        /// Every `impl` method named `m` for the receiver's head.
        fn impl_methods(&self, recv: &Ty, m: &str) -> Vec<(Generics, Ty, Method)> {
            let Some(key) = head_key(recv) else {
                return Vec::new();
            };
            let mut out = Vec::new();
            for imp in &self.program().impls {
                if head_key(&imp.ty).as_deref() != Some(key.as_str()) {
                    continue;
                }
                if let Some(meth) = imp.methods.iter().find(|x| x.name == m) {
                    out.push((imp.generics.clone(), imp.ty.clone(), meth.clone()));
                }
            }
            out
        }

        /// Of several instances' methods, the one the arguments fit, recorded
        /// at the call; none fitting keeps the first, for its argument check
        /// to report. A lambda fits any function type of its arity.
        fn choose_instance(
            &mut self,
            candidates: Vec<(Generics, Ty, Method)>,
            recv: &Ty,
            m: &str,
            args: &[Expr],
            ctx: &Ctx,
            span: Span,
        ) -> Res<Vec<(Generics, Ty, Method)>> {
            let mut atys: Vec<Result<Ty, usize>> = Vec::with_capacity(args.len());
            for a in args {
                atys.push(match a {
                    Expr::Lambda(ps, _, _) => Err(ps.len()),
                    _ => Ok(self.check_expr(a, ctx, None)?),
                });
            }
            let mut fits = Vec::new();
            for c in &candidates {
                let saved = self.metas.clone();
                let ok = self.fits(c, recv, &atys, span);
                self.metas = saved;
                if ok {
                    fits.push(c.clone());
                }
            }
            match fits.len() {
                0 => Ok(candidates.into_iter().take(1).collect()),
                1 => {
                    self.record_conversion(span, fits[0].2.clone());
                    Ok(fits)
                }
                _ => Err(TyError::AmbiguousMethod {
                    method: m.to_string(),
                    span,
                }),
            }
        }

        /// Whether a candidate's signature fits the receiver and arguments.
        fn fits(
            &mut self,
            c: &(Generics, Ty, Method),
            recv: &Ty,
            atys: &[Result<Ty, usize>],
            span: Span,
        ) -> bool {
            let map = self.fresh_for(&c.0);
            let inst = |t: &Ty| t.substitute(&map).with_self(recv);
            if self.unify(&inst(&c.1), recv, span).is_err() {
                return false;
            }
            if c.2.params.len() != atys.len() {
                return false;
            }
            for (p, t) in c.2.params.iter().zip(atys) {
                let pty = self.resolve(&inst(&p.ty));
                let ok = match t {
                    Ok(t) => self.unify(&pty, t, span).is_ok(),
                    Err(arity) => match &pty.kind {
                        TyKind::Fn(ps, _) => ps.len() == *arity,
                        TyKind::Meta(_) => true,
                        _ => false,
                    },
                };
                if !ok {
                    return false;
                }
            }
            true
        }

        /// The signature of `m` in a trait the receiver's built-in type
        /// conforms to (`1.cmp(2)`).
        fn builtin_sig(&self, recv: &Ty, m: &str) -> Option<Sig> {
            let key = head_key(recv)?;
            for (name, decl) in &self.program().decls {
                let Decl::Trait(_, sigs) = decl else { continue };
                if !builtin_conforms(name, Some(&key)) {
                    continue;
                }
                if let Some(sig) = sigs.iter().find(|s| s.name == m) {
                    return Some(sig.clone());
                }
            }
            None
        }

        /// The signature of `m` in the bound of a type parameter `recv`,
        /// with the trait's own parameters read as the bound's arguments.
        fn bound_sig(&self, recv: &Ty, m: &str) -> Option<Sig> {
            let TyKind::Named(tvar, _) = &recv.kind else {
                return None;
            };
            let bound: TraitRef = self.bound_of(tvar)?.clone();
            let Some(Decl::Trait(tg, sigs)) = self.decl(&bound.name) else {
                return None;
            };
            let sig = sigs.iter().find(|s| s.name == m)?;
            let names = tg.params.iter().map(|p| p.name.clone());
            let map: Subst = names.zip(bound.args.iter().cloned()).collect();
            let mut sig = sig.clone();
            for p in &mut sig.params {
                p.ty = p.ty.substitute(&map);
            }
            sig.ret = sig.ret.substitute(&map);
            Some(sig)
        }

        fn found_sig(&self, sig: Sig, recv: &Ty) -> Found {
            Found {
                has_self: sig.has_self,
                ty: recv.to_string(),
                is_param: self.is_type_param(recv),
                how: How::Sig(sig),
            }
        }

        /// A fresh variable for each of a declaration's type parameters.
        fn fresh_for(&mut self, generics: &Generics) -> Subst {
            let names = generics.params.iter().map(|p| p.name.clone());
            names.map(|n| (n, self.fresh_meta())).collect()
        }

        /// The bounds a declaration's parameters carry, required of `map`.
        fn require_bounds(&mut self, generics: &Generics, map: &Subst, span: Span) {
            for tp in &generics.params {
                if let Some(bound) = &tp.bound {
                    let tr = TraitRef {
                        name: bound.name.clone(),
                        args: bound.args.iter().map(|a| a.substitute(map)).collect(),
                        span: bound.span,
                    };
                    self.require_trait(tr, map[&tp.name].clone(), span);
                }
            }
        }
    }

    /// Whether two types are applications of one named type.
    fn same_head(a: &Ty, b: &Ty) -> bool {
        match (&a.kind, &b.kind) {
            (TyKind::Named(x, _), TyKind::Named(y, _)) => x == y,
            _ => false,
        }
    }

    /// The type arguments of an instantiation, in declaration order.
    fn args_of(generics: &Generics, map: &Subst) -> Vec<Ty> {
        generics
            .params
            .iter()
            .map(|p| map[&p.name].clone())
            .collect()
    }
}

The calls module

Paste this module at the end of src/relations/check.rs. Purity describes its functions. It is declared pub, which keeps an unused function from raising a warning.

/// Provided helpers (Milestone M8): the call graph's method nodes. A method
/// call or a `?` names a callee key, as a call names a function: `H.m` for
/// the method head `H`'s `impl` provides, `.m` for every `impl`'s method of
/// that name, `.from` for a `?`. Paste this module at the end of the file,
/// unchanged.
pub mod calls {
    use crate::ast::{Decl, Expr, Lit, Name, Program, QArg, Rel, Span, SrcId};
    use crate::ast::{Method, Rule, Stmt, Ty, TyKind};
    use std::collections::{HashMap, HashSet};

    type Types = HashMap<Name, Ty>;
    type Head = Option<String>;
    type Roots<'a> = (Vec<&'a Expr>, Vec<(Name, Ty)>);
    type Bodies<'a> = Vec<(&'a Expr, Vec<Name>)>;
    type Methods<'a> = Vec<(&'a Ty, &'a Method)>;

    /// The callee key of a method call or a `?` anywhere in `program`, or
    /// `None`: for any other node, for a method no `impl` provides (a
    /// built-in conformance, pure), and for a `?` with no `impl From`. A
    /// receiver the declarations settle reaches its head's method alone:
    /// `self`, a parameter or generator variable the body does not rebind,
    /// a literal, a type or struct name, a struct literal, or a field
    /// chain from one of these.
    pub fn method_callee(program: &Program, e: &Expr) -> Option<Name> {
        match e {
            Expr::Method(recv, m, _, _) => {
                let types = enclosing_types(program, e.span());
                let head = receiver_head(program, recv, &types);
                let key = format!("{}.{m}", head.as_deref().unwrap_or(""));
                provides(program, head.as_deref(), m).then_some(key)
            }
            Expr::Try(..) => provides(program, None, "from").then(|| ".from".into()),
            _ => None,
        }
    }

    /// The bodies behind a method key, each with the names its
    /// declaration binds there (`self`, then the parameters).
    pub fn method_bodies<'a>(program: &'a Program, key: &str) -> Bodies<'a> {
        let mut out = Vec::new();
        for (_, meth) in methods_of(program, key) {
            let mut names = vec!["self".to_string()];
            names.extend(meth.params.iter().map(|p| p.name.clone()));
            out.push((&meth.body, names));
        }
        out
    }

    /// The declared parameter types behind a method key, `self` aside.
    pub fn method_params<'a>(program: &'a Program, key: &str) -> Vec<&'a Ty> {
        let ms = methods_of(program, key);
        ms.into_iter()
            .flat_map(|(_, m)| m.params.iter().map(|p| &p.ty))
            .collect()
    }

    /// Every method key of the program: `H.m` and `.m` for each method.
    pub fn method_keys(program: &Program) -> Vec<Name> {
        let mut keys = Vec::new();
        for imp in &program.impls {
            let head = head_of_ty(&imp.ty).unwrap_or_default();
            for meth in &imp.methods {
                keys.push(format!("{head}.{}", meth.name));
                keys.push(format!(".{}", meth.name));
            }
        }
        keys.sort();
        keys.dedup();
        keys
    }

    /// Whether `name` is one of the prelude's Bridger-written functions
    /// (`min`, `max`, `minimum`, `maximum`, `len` from M8): trusted to be
    /// total, so they are exempt from the recursion and higher-order
    /// checks, though the methods they reach are judged like any other.
    pub fn is_prelude_fn(program: &Program, name: &str) -> bool {
        matches!(program.decls.get(name), Some(Decl::Fn(..)))
            && program.spans.get(name).is_some_and(|s| s.src == SrcId(0))
    }

    /// The `impl` methods behind a key, with the type each extends.
    fn methods_of<'a>(program: &'a Program, key: &str) -> Methods<'a> {
        let Some((head, m)) = key.split_once('.') else {
            return Vec::new();
        };
        let mut out = Vec::new();
        for imp in &program.impls {
            if !head.is_empty() && head_of_ty(&imp.ty).as_deref() != Some(head) {
                continue;
            }
            out.extend(
                imp.methods
                    .iter()
                    .filter(|x| x.name == m)
                    .map(|x| (&imp.ty, x)),
            );
        }
        out
    }

    /// Whether some `impl` (for `head`, if given) provides `m`.
    fn provides(program: &Program, head: Option<&str>, m: &str) -> bool {
        program.impls.iter().any(|imp| {
            head.is_none_or(|h| head_of_ty(&imp.ty).as_deref() == Some(h))
                && imp.methods.iter().any(|x| x.name == m)
        })
    }

    /// The head key of a written type, as an `impl` extends it.
    fn head_of_ty(ty: &Ty) -> Option<String> {
        Some(match &ty.kind {
            TyKind::Int => "Int".to_string(),
            TyKind::Bool => "Bool".to_string(),
            TyKind::Str => "String".to_string(),
            TyKind::Unit => "()".to_string(),
            TyKind::List(_) => "[]".to_string(),
            TyKind::Named(n, _) => n.clone(),
            _ => return None,
        })
    }

    /// Whether `head` is a type an `impl` can extend (no type parameter).
    fn is_head(program: &Program, head: &str) -> bool {
        matches!(head, "Int" | "Bool" | "String" | "()" | "[]")
            || matches!(
                program.decls.get(head),
                Some(Decl::Struct(..) | Decl::Type(..))
            )
    }

    /// The head of a receiver the declarations settle, if they do.
    fn receiver_head(program: &Program, recv: &Expr, types: &Types) -> Head {
        let head = match recv {
            Expr::Var(x, _) => head_of_ty(types.get(x)?)?,
            Expr::Lit(Lit::Int(_), _) => "Int".to_string(),
            Expr::Lit(Lit::Bool(_), _) => "Bool".to_string(),
            Expr::Lit(Lit::Str(_), _) => "String".to_string(),
            Expr::Lit(Lit::Unit, _) => "()".to_string(),
            Expr::Ctor(n, a, _) if a.is_empty() && is_head(program, n) => n.clone(),
            Expr::Struct(name, _, _) => name.clone(),
            Expr::Field(e, f, _) => {
                let s = receiver_head(program, e, types)?;
                let Some(Decl::Struct(_, fields)) = program.decls.get(&s) else {
                    return None;
                };
                head_of_ty(&fields.iter().find(|fd| fd.name == *f)?.ty)?
            }
            _ => return None,
        };
        is_head(program, &head).then_some(head)
    }

    /// The declared types in force at `span`: those of the declaration
    /// whose body contains it, less every name that body rebinds.
    fn enclosing_types(program: &Program, span: Span) -> Types {
        let inside = |e: &Expr| {
            let s = e.span();
            s.src == span.src && s.start <= span.start && span.end <= s.end
        };
        let mut found: Option<Roots> = None;
        for decl in program.decls.values() {
            if let Decl::Fn(_, params, _, body) = decl {
                if inside(body) {
                    let b = params.iter().map(|p| (p.name.clone(), p.ty.clone()));
                    found = Some((vec![&**body], b.collect()));
                }
            }
        }
        for imp in &program.impls {
            for meth in imp.methods.iter().filter(|x| inside(&x.body)) {
                let mut b = vec![("self".to_string(), imp.ty.clone())];
                let ps = meth.params.iter();
                b.extend(ps.map(|p| (p.name.clone(), p.ty.with_self(&imp.ty))));
                found = Some((vec![&meth.body], b));
            }
        }
        for rule in &program.rules {
            if rule.body.iter().any(inside) {
                let b = generator_types(program, rule);
                found = Some((rule.body.iter().collect(), b));
            }
        }
        let Some((roots, bindings)) = found else {
            return HashMap::new();
        };
        let mut rebound = HashSet::new();
        for r in roots {
            bound_names(r, &mut rebound);
        }
        bindings
            .into_iter()
            .filter(|(x, _)| !rebound.contains(x))
            .collect()
    }

    /// A rule's generator-bound variables at their columns' types.
    fn generator_types(program: &Program, rule: &Rule) -> Vec<(Name, Ty)> {
        let mut out: Vec<(Name, Ty)> = Vec::new();
        for conjunct in &rule.body {
            let Expr::Call(callee, args, _) = conjunct else {
                continue;
            };
            let Expr::Var(rel, _) = &**callee else {
                continue;
            };
            let Some(Decl::Relation(tys)) = program.decls.get(rel) else {
                continue;
            };
            for (a, ty) in args.iter().zip(tys) {
                if let Expr::Var(x, _) = a {
                    if !out.iter().any(|(y, _)| y == x) {
                        out.push((x.clone(), ty.clone()));
                    }
                }
            }
        }
        out
    }

    /// The names `e` binds within itself.
    fn bound_names(e: &Expr, out: &mut HashSet<Name>) {
        match e {
            Expr::Block(stmts, _, _) => {
                for s in stmts {
                    if let Stmt::Let(x, ..) = s {
                        out.insert(x.clone());
                    }
                }
            }
            Expr::Lambda(ps, _, _) => out.extend(ps.iter().map(|p| p.name.clone())),
            Expr::Match(_, arms, _) => {
                for arm in arms {
                    out.extend(arm.pat.binders());
                }
            }
            Expr::For(x, ..) => {
                out.insert(x.clone());
            }
            Expr::ForQuery(q, ..) => {
                for a in &q.args {
                    if let QArg::Hole(Some(x)) = a {
                        out.insert(x.clone());
                    }
                }
            }
            _ => {}
        }
        for c in children(e) {
            bound_names(c, out);
        }
    }

    /// The immediate subexpressions of `e`.
    fn children(e: &Expr) -> Vec<&Expr> {
        let mut cs: Vec<&Expr> = Vec::new();
        match e {
            Expr::Lit(..) | Expr::Var(..) => {}
            Expr::Unary(_, e1, _)
            | Expr::Field(e1, _, _)
            | Expr::Proj(e1, _, _)
            | Expr::Return(e1, _)
            | Expr::Try(e1, _)
            | Expr::Lambda(_, e1, _) => cs.push(e1),
            Expr::Binary(_, l, r, _) | Expr::Assign(l, r, _) => {
                cs.extend([&**l, &**r]);
            }
            Expr::If(c, t, els, _) => {
                cs.extend([&**c, &**t]);
                cs.extend(els.as_deref());
            }
            Expr::While(c, b, _) | Expr::For(_, c, b, _) => cs.extend([&**c, &**b]),
            Expr::Call(f, args, _) | Expr::Method(f, _, args, _) => {
                cs.push(f);
                cs.extend(args.iter());
            }
            Expr::Tuple(es, _) | Expr::List(es, _) | Expr::Ctor(_, es, _) => {
                cs.extend(es);
            }
            Expr::Struct(_, fields, _) => cs.extend(fields.iter().map(|(_, e)| e)),
            Expr::Match(scrut, arms, _) => {
                cs.push(scrut);
                for a in arms {
                    cs.extend(a.guard.as_ref());
                    cs.push(&a.body);
                }
            }
            Expr::Block(stmts, tail, _) => {
                for s in stmts {
                    match s {
                        Stmt::Let(_, _, e1, _) | Stmt::Expr(e1) => cs.push(e1),
                    }
                }
                cs.extend(tail.as_deref());
            }
            Expr::ForQuery(q, b, _) => {
                cs.extend(query_args(q));
                cs.push(b);
            }
            Expr::Relation(rel, _) => match rel {
                Rel::Add(q) | Rel::Solutions(q) | Rel::Query(q) => {
                    cs.extend(query_args(q));
                }
                Rel::Clear(_) => {}
            },
        }
        cs
    }

    /// The bound (non-hole) arguments of a query.
    fn query_args(q: &crate::ast::Query) -> impl Iterator<Item = &Expr> {
        q.args.iter().filter_map(|a| match a {
            QArg::Expr(e) => Some(e),
            QArg::Hole(_) => None,
        })
    }
}

Running a program

cargo run --features m8 runs the static checks and then main. media.brg has two structs that implement one trait, and one function written over the trait:

$ cat media.brg
struct Book { title: String, pages: Int }
struct Song { title: String, secs: Int }

trait Describe { fn describe(self) -> String; }

impl Book {
    fn new(title: String, pages: Int) -> Self =
        Book { title: title, pages: pages };
}
impl Describe for Book {
    fn describe(self) -> String =
        self.title ++ ", " ++ to_string(self.pages) ++ " pp.";
}
impl Describe for Song {
    fn describe(self) -> String =
        self.title ++ " (" ++ to_string(self.secs) ++ " s)";
}

fn catalogue<T: Describe>(xs: [T]) -> [String] =
    map(xs, |x: T| x.describe());

fn main() {
    println(catalogue([Book.new("Dune", 412), Book.new("Emma", 474)]));
    println(catalogue([Song { title: "Blue", secs: 191 }]));
}

$ cargo run -q --features m8 -- media.brg
["Dune, 412 pp.", "Emma, 474 pp."]
["Blue (191 s)"]

The line x.describe() inside catalogue runs Book’s method during the first call and Song’s during the second. Writing impl Song in place of impl Describe for Song leaves the method in place but takes Song out of the trait, and the program no longer starts:

$ cargo run -q --features m8 -- media.brg
  × no `impl Describe for Song`, so the bound is not satisfied
    ╭─[media.brg:24:23]
 23 │     println(catalogue([Book.new("Dune", 412), Book.new("Emma", 474)]));
 24 │     println(catalogue([Song { title: "Blue", secs: 191 }]));
    ·                       ─────────────────┬─────────────────
    ·                                        ╰── here
 25 │ }
    ╰────

The exit status is 1. As at M7, the checker runs first, so no program with a struct literal or a method call runs under --features m8 until the checker’s arms are written.

Worked examples

The expressions below are checked and run after these declarations:

struct Pos { x: Int, y: Int }
struct Tag<T> { label: String, item: T }
type Light = Red | Amber | Green;

impl Pos {
    fn zero() -> Pos = Pos { x: 0, y: 0 };
    fn sum(self) -> Int = self.x + self.y;
    fn shift(self, d: Int) -> Self = Pos { x: self.x + d, y: self.y + d };
}
impl Light {
    fn advance(self) -> Light =
        match self { Red => Green, Green => Amber, Amber => Red };
}
impl String { fn shout(self) -> String = self ++ "!"; }

Each expression has the value at its right:

Pos { y: 2, x: 1 }                            Pos { x: 1, y: 2 }
Pos { y: 2, x: 1 } == Pos { x: 1, y: 2 }      true
Pos.zero().shift(3).sum()                     6
Tag { label: "n", item: [1, 2] }.item         [1, 2]
Green.advance()                                Amber
"hi".shout()                                  "hi!"
[3, 1, 2].length()                            3
"b".cmp("a")                                  Greater
match (Pos { x: 1, y: 2 }) { Pos { y } => y } 2

Green.advance() dispatches under Light, the type that declares the constructor, and "hi".shout() under String. The checker rejects each of these:

Pos { x: 1 }                       MissingField (y), at the literal
Pos { x: 1, y: 2, z: 3 }           NoSuchField (z), at 3
Pos { x: 1, x: 2, y: 3 }           DuplicateField (x), at 2
Pos { x: 1, y: true }              Mismatch (expected Int, found Bool), at true
Spot { x: 1 }                      UnknownType (Spot)
Light { x: 1 }                     NotAStruct (Light)
Pos.zero().z                       NoSuchField (z), at the access
(1, 2).x                           FieldOfNonStruct (x, found (Int, Int))
Pos.sum()                          NoReceiver (sum)
Pos.zero().zero()                  NotAMethod (zero, on Pos)
Pos.zero().norm()                  NoSuchMethod (norm)
Pos.zero().shift(1, 2)             ArityMismatch (shift: 1, given 2)
Tag { label: "n", item: 1 }.item + "s"
                                   Mismatch (expected Int, found String), at "s"

A trait at two instances needs the checker’s choice. Log records a string as it is and an integer with a mark before it:

struct Log { lines: [String] }

trait Record<T> { fn record(self, x: T) -> Log; }

impl Record<String> for Log {
    fn record(self, x: String) -> Log = Log { lines: self.lines ++ [x] };
}
impl Record<Int> for Log {
    fn record(self, x: Int) -> Log = self.record("#" ++ to_string(x));
}

fn main() {
    let l = Log { lines: [] }.record("start").record(7);
    println(l.lines);
}

Checked and run, it prints ["start", "#7"]. Both calls have the head Log and the name record, and only the recorded choice sends the second to the Int instance. Run unchecked, with conversions empty, the second call takes the first impl declared and prints ["start", 7].

A ? that converts its error:

struct NotFound { key: String }
type AppError = Missing(String) | TooBig(Int);

impl From<NotFound> for AppError {
    fn from(e: NotFound) -> Self = Missing(e.key);
}

fn lookup(k: String) -> Result<Int, NotFound> =
    if k == "a" { Ok(40) } else if k == "b" { Ok(2) }
    else { Err(NotFound { key: k }) };

fn add(j: String, k: String) -> Result<Int, AppError> {
    let s = lookup(j)? + lookup(k)?;
    if s > 100 { Err(TooBig(s)) } else { Ok(s) }
}

fn main() {
    println(add("a", "b"));
    println(add("a", "z"));
}

This prints Ok(42) and then Err(Missing("z")). Without the impl, each ? in add is Mismatch with expected AppError and found NotFound, as at M7. Run unchecked, the second line is Err(NotFound { key: "z" }), since no conversion was recorded.

How to know it works

cargo m8 runs the provided milestone M8 tests and, with them, every earlier milestone’s. Some run a whole program with run_program, which skips the static checks, so the evaluator meets programs the checker would have refused and has no recorded choices to read. Some call Checker::check_program on a loaded program, and some call check_rules and check_guards. A rejection is tested by its error variant and, where it matters, by its payload, and the text of a message is never tested.

Paste the helper modules, then write the evaluator’s Struct and Field arms, then its Method arm, since whole-program tests reach them without the checker. Then write the checker’s Struct and Field arms and its Method arm. The ? conversion and the purity cases can come at any point after that.

Design problems

catalogue takes a list of one type. Make one catalogue hold a book and a song, and say what each of these extensions then costs: a new struct Film that implements Describe, and a new operation length_in_minutes on all three.

A list holds one type, so the mixture needs a sum whose constructors hold the structs, with its own impl:

type Media = B(Book) | S(Song);

impl Describe for Media {
    fn describe(self) -> String =
        match self { B(b) => b.describe(), S(s) => s.describe() };
}

// catalogue([B(Book.new("Dune", 412)), S(Song { title: "Blue", secs: 191 })])
//   is ["Dune, 412 pp.", "Blue (191 s)"]

Film costs one struct and one impl Describe, and nothing existing changes until a film has to share a catalogue with the others. Then Media gains a constructor, and its match gains an arm, which exhaustiveness checking insists on. length_in_minutes as a new trait costs one impl per struct, plus one for Media that matches and delegates, and edits nothing. Added to Describe instead, it fails conformance for every existing impl until each provides it. This is the trade Traits vs. inheritance calls the Expression Problem, with Media as the place where the two directions meet.

Write a stack of integers whose contents no other code can reach, with operations to push, pop, and report its size. Then say what a private modifier on a struct field would let you write instead, and what it would cost in Bridger.

The contents can live in a reference that only closures capture:

struct Stack { push: fn(Int) -> (), pop: fn() -> Option<Int>, size: fn() -> Int }

fn stack() -> Stack {
    ref items = [];
    Stack {
        push: |x: Int| { items := x :: deref items; },
        pop: || match deref items {
            [] => None,
            h :: t => { items := t; Some(h) },
        },
        size: || len(deref items),
    }
}

fn main() {
    let s = stack();
    (s.push)(1);
    (s.push)(2);
    println((s.pop)());
    println((s.size)());
}

It prints Some(2) and 1. Each call of stack allocates its own items, and no name for it exists outside the closures. The calls need the parentheses, since s.push(1) is a method call and push is a field.

With a private items: ref<[Int]> field and ordinary methods, the stack would be one struct with an impl, dispatched like any other, and two stacks could be compared or printed. In a language without modules, the only boundary such a field could have is the impl, so a literal or a struct pattern naming it would be rejected everywhere else, including in the tests of the type that declares it. Dispatch and encapsulation follows that argument through.

Rewrite catalogue without a bound, so that the caller supplies the description. What does the caller gain, and how does this relate to the program that a bound at two instances cannot express?
fn catalogue_with<T>(xs: [T], d: fn(T) -> String) -> [String] = map(xs, d);

// catalogue_with([Book.new("Dune", 412)], |b: Book| b.describe())
//   is ["Dune, 412 pp."]
// catalogue_with([Book.new("Dune", 412)], |b: Book| b.title)
//   is ["Dune"]

The function now carries the operation it needs as an argument, and the caller may pass any function of the right type, including one that is not the type’s method. This is dictionary passing by hand, with one method in the dictionary. A bound such as S: Record<Int> on a type that implements Record at two instances is rejected because the body dispatches by head and name alone. If the caller passed the chosen method along, as here, the body would never have to choose, and the restriction would go away. The cost is an extra argument at every call, which the bound supplies implicitly.

A rule filter calls same(b).describe(), where same returns its Book argument unchanged and b is a generator variable over a relation of books. The filter is rejected as impure, although Book's describe has no effect. Why, and what change makes it pure?

The receiver is a call’s result, and the purity judgment settles a receiver’s head only from self, a parameter, a generator variable, a literal, a type name, or a field chain from one of them, never through a call. So the filter reaches every impl’s describe, and if Song’s prints something, the filter is rejected with a witness that begins .describe. Writing b.describe() lets the relation’s column type settle the head as Book, the filter reaches Book.describe alone, and it is accepted. The checker knows that same(b) has type Book. The purity judgment runs on the declarations alone, a cheaper analysis that answers a coarser question and errs toward rejecting.