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 M6

Relations

Part VII added a second language inside Bridger. A program declares relations, states facts and rules about them, and asks queries whose answers are the least fixpoint of the rules over the facts. The unification chapter matched a rule’s atoms against facts, and the fixpoint repeated that matching in rounds until nothing new appeared. Rule bodies separated generators from filters and required filters to be pure, and the host-language forms let ordinary code ask queries, walk their solutions, and change the facts. This milestone builds all of it. Every M1–M5 test must still pass.

The work spreads across more files than before. The evaluator in src/interp/eval.rs and the checker in src/types/check.rs gain the relation forms. Three files are new: src/relations/unify.rs matches one atom against one fact, src/relations/engine.rs computes the fixpoint and answers queries, and src/relations/check.rs holds the static checks on rules. From this milestone on, the interpreter runs the rule checks and the type checker before main, and a program that fails either prints nothing. The helper module below provides the walker over expressions and the free-variable computation. Paste it at the end of src/relations/check.rs.

To-dos

grep -rn 'todo_m6!' src lists the holes. Each names the rules it implements:

// src/interp/eval.rs
Expr::Relation(..) => todo_m6!("E-Add / E-Clear / E-Solutions / E-Query"),
Expr::ForQuery(..) => todo_m6!("E-ForQuery (iterate a query's solutions)"),

// src/types/check.rs
Expr::Relation(..) => todo_m6!("T-Add / T-Clear / T-Solutions / T-Query"),
Expr::ForQuery(..) => todo_m6!("T-ForQuery"),
pub fn check_rule(&mut self, rule: &Rule) -> Result<(), TyError>

// src/relations/unify.rs, engine.rs, check.rs
pub fn unify(&self, pattern: &[Term], fact: &[Value]) -> Option<Subst>
pub fn solutions(&mut self, q: &Query, span: Span, env: &Env)
    -> Result<Vec<Subst>, Control>
pub fn check_generators(program: &Program, rule: &Rule)
    -> Result<Vec<bool>, RuleError>
pub fn check_range_restriction(program: &Program, rule: &Rule, generators: &[bool])
    -> Result<(), RuleError>
pub fn check_pure(program: &Program, rule: &Rule, generators: &[bool])
    -> Result<(), RuleError>

Each stub’s let _ = (…); line keeps the compiler quiet until the body reads its parameters. Two changes have no todo_m6! marker of their own:

  1. In the Call arm of both the evaluator and the checker, a call whose callee is a relation is a hole-free query.
  2. In the checker’s Var arm, a relation’s name used as a value is rejected with RelationNotAValue.

check_guards, in the same file as the rule checks, stays a hole until M7.

Milestone specification

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

FormRulesStuck whenRejected when
add R(e1, …, en) E-AddFact, T-Add R is not a relation in scope; an argument is a hole; the count differs from R's columns; it runs inside a filter R is not a relation in scope; the count differs; an argument is a hole or is not of its column's type
clear R E-Clear, T-Clear R is not a relation in scope; it runs inside a filter R is not a relation in scope
R(a1, …, an), and R(e1, …, en) in call syntax E-Query-True, E-Query-False, T-Query R is not a relation in scope; the count differs; it runs inside a filter R is not a relation in scope; the count differs; a bound argument is not of its column's type; a hole named twice stands over columns of different types
solutions q E-Solutions, T-Solutions as for the query q as for the query q
for q { e } E-For-Query, T-For-Query as for the query q as for the query q; the body is not ()
R on its own — — always: a relation is not a value

The checks every rule must pass before the program runs, and the error each failure gives:

CheckRejected whenError, at
generators the head names no declared relation, or has the wrong number of terms; a generator has the wrong number of arguments, or an argument that is neither a variable nor a literal; a conjunct calls a name nothing declares NotARelation or Arity at the head; Arity at the generator; ArgumentNotATerm at the argument; NotARelation at the call
range restriction a head variable that no generator binds; a name a filter reads that no generator binds and that is not declared at the top level Unbound at the head, or at the filter
purity a filter reaches a function with a function-typed parameter; a filter reaches an effect; a filter reaches a recursive function HigherOrder, Impure { witness }, Recursive, at the filter
typing a variable stands over columns of different types; a literal is not of its column's type; a head term is not of its column's type; a filter is not Bool Mismatch at the argument, the head, or the filter

The rules are in Appendix D: evaluation, typing, and purity and effects. The runtime errors and static errors by name give the variant a test expects for each case. The “Building it” sections of the Part VII chapters describe the algorithms; these tables are the checklist your code is measured against.

The provided driver runs the rule checks on each rule in the order generators, range restriction, purity, and runs check_rule from the type checker’s driver. Across all the static checks, the error reported is the earliest in the file. The driver also rejects a relation whose column type admits no equality, with RelationColumn.

These contracts hold across the files:

  • A query form evaluates its arguments once, left to right, after it has resolved the relation’s name and before it judges the argument count. An argument’s effect happens even when the form then turns out to have the wrong number of arguments. A for evaluates them a single time, before its first solution.
  • The solutions are distinct and in canonical order. Two matches that agree on every named hole are one solution, whatever stood at a bound argument or an anonymous hole. They are sorted with the provided compare on their hole values, first hole first.
  • The checks stop at the first failure, in source order. The head is checked before the body, and the conjuncts left to right. Within a generator, the argument count is checked before the arguments. Range restriction checks the head’s variables in the order written, then each filter’s free names in order of first appearance.
  • The database cannot change, and cannot be read, while a fixpoint is being computed. A query, add, or clear reached from a filter is stuck with QueryInFilter. The purity check rejects every such filter before the program runs, so only a program run without the checks reaches this state, and the tests run some programs that way.

Implementing Milestone M6

The two new Expr variants and the types a rule is made of:

TypeFields
Expr::Relation(Rel, Span)
Expr::ForQuery(Query, Box<Expr>, Span)
RelAdd(Query), Clear(Name), Solutions(Query), Query(Query)
Query{ name: Name, args: Vec<QArg> }
QArgExpr(Expr), Hole(Option<Name>)
Rule{ head: Atom, body: Vec<Expr>, span: Span }
Atom{ name: Name, terms: Vec<ast::Term>, span: Span }
ast::TermVar(Name), Lit(Lit)
Decl::Relation(Vec<Ty>), the column types

Two types are called Term. The one in ast.rs is a term as written in a rule head. The one in relations/term.rs is what the engine matches with, a variable or a Value. A file that needs both can import one under another name, as in use crate::ast::Term as AstTerm;.

The provided runtime

Unification shows Term and Subst, Declarative programming shows RelationDb’s add and clear, and Evaluating relations shows how the engine reaches the rules and the stored closure. The rest of what the M6 files use:

impl Subst {
    fn iter(&self) -> impl Iterator<Item = (&Name, &Value)>; // every binding
}

impl RelationDb {
    fn facts(&self, relation: &str) -> &[Tuple];      // Δ's facts for one relation
    fn relations(&self) -> impl Iterator<Item = &str>; // relations Δ has facts in
}

impl Interpreter {
    pub(crate) db: RelationDb,       // Δ
    pub(crate) materializing: bool,  // set while a fixpoint is computed
    pub fn program(&self) -> &Program;
}

impl Env {
    pub fn root(&self) -> Env;       // the program's top-level environment
}

pub fn compare(a: &Value, b: &Value) -> Ordering;   // crate::interp::value
pub fn type_of(v: &Value) -> Ty;                    // crate::interp
pub(crate) fn native_names() -> impl Iterator<Item = &'static str>;
                                                    // crate::interp::prelude

The provided eval_program binds every declared relation in the root environment to a Value::Relation(name), beside the functions, so a relation’s name is resolved like any other.

Matching

Subst::unify is Unification’s algorithm. A variable not yet bound, in self or at an earlier position of the same pattern, is bound to the fact’s value at its position. A variable already bound must equal that value, and so must a constant. Patterns and facts of different lengths do not match. On any mismatch the answer is None. On success it is a new, extended Subst. Since unify takes &self, the substitution it was called on is left as it was, and the caller can try it against the next fact.

The engine

solutions does three things in order: it reads the query, computes the fixpoint, and matches the query against it.

  • The query. If self.materializing is set, the query is stuck with QueryInFilter at span. Otherwise the relation’s name is looked up in env. A Value::Relation gives the relation, any other value is NotARelation { name, span }, and no binding is UnboundVariable { name, span }. Each argument becomes a term, left to right: a bound argument is evaluated in env to a constant, a named hole ?x is Term::Var("x"), and each anonymous hole is a variable with a fresh name no identifier can spell, such as ?0 and ?1. Then an argument count other than the relation’s column count is ArityMismatch { expected, found, span }.
  • The fixpoint. The starting facts are those in self.db and the head of every rule with no body. The rules with bodies are then fired in rounds, as in Evaluating relations, until a round adds nothing. Set self.materializing before the rounds and clear it after them, before any error from them is returned, so that one stuck filter does not leave every later query stuck. Clone the program’s rules before the rounds begin, since evaluating a filter borrows the interpreter mutably. Storing the closure with set_derived and reusing it is optional.
  • Firing one rule. A conjunct is a generator when it is a call whose callee is a variable naming a declared relation in self.program().decls. Its arguments become terms: a variable becomes Term::Var and a literal becomes the constant it denotes. The join starts from one empty substitution and extends it through each generator in turn with unify. Each filter is then evaluated, left to right, for each remaining substitution, in env.root() extended with that substitution’s bindings. true keeps the substitution, false drops it, and the filters after a false are not evaluated. A filter that yields a value other than a Bool is TypeError { expected: Bool, found, span } at the filter, with found from type_of. A Control::Return out of a filter is ReturnOutsideFunction at the filter. Each substitution that survives grounds the head, a variable to its binding and a literal to its value.
  • The answer. The query’s pattern is matched against every fact of its relation. Each match is cut down to the named holes, duplicates are removed, and the rest are sorted as the contracts say. A hole-free query has one empty substitution as its answer when its fact is derivable, and none when it is not.

The evaluator’s arms

Declarative programming and Querying relations from the host language describe the arms. A test also holds them to the following:

  • add is stuck with QueryInFilter when self.materializing is set, before it does anything else. It then resolves the relation’s name as a query does, and evaluates its arguments left to right. A hole is HoleInAdd at the whole form, raised when the evaluation reaches it, so an earlier argument’s effects have happened. The argument count is checked after the arguments run, with ArityMismatch at the whole form. The fact goes to self.db.add, and the form’s value is ().
  • clear checks materializing and resolves its name the same way, then calls self.db.clear. Its value is ().
  • A query is true when solutions returns anything. solutions q builds one value per substitution from the query’s named holes, each distinct name once, in order of first appearance: () when there are none, the hole’s value when there is one, a tuple in hole order otherwise.
  • for q { e } calls solutions once and, for each substitution, runs the body in the environment at the for extended with that substitution’s bindings. A return in the body passes straight out, and the form’s value is ().
  • The Call arm evaluates its callee first, as before. A Value::Relation makes the call a hole-free query: the unevaluated arguments become QArg::Exprs, solutions evaluates them, and the call is true when there is a solution. A local that shadows a relation’s name has its own value, so a call through it is an ordinary call.

The checker’s arms

Querying relations from the host language describes the typing of the query forms, and Typing a rule the typing of a rule. In detail:

  • The relation a form names is resolved in this order, and each error is at the whole form:
    1. A name the Ctx binds is NotARelation, since a local shadows the relation.
    2. Otherwise, a name decl finds as a relation gives the column types.
    3. A name decl finds as anything else, or a native function’s name, is NotARelation.
    4. A name found nowhere is UndeclaredRelation.
  • add R(…) compares the argument count with the column count first, with RelationArity { name, expected, found } at the whole form. It then checks each argument against its column type, left to right. A hole is HoleInAdd at the whole form. The form has type (). clear R resolves its name and has type ().
  • A query checks its argument count as add does. Each bound argument is checked against its column type, in order. A named hole takes its column’s type where it first appears, and the same name at a later position unifies that type with its own column’s, at the whole form. A query has type Bool. solutions q has type [()] with no named holes, [τ] with one, and a list of tuples of the holes’ types, in order of first appearance, with more.
  • for q { e } checks the query, extends the Ctx with each named hole at its type, checks the body against (), and has type ().
  • Var. After the Ctx, the functions, and the globals, a name decl finds as a relation is RelationNotAValue { name } at the name.
  • Call. Before check_callee, a callee that is a variable the Ctx does not bind and that names a declared relation makes the call a query, typed as above with the arguments as bound arguments, of type Bool.
  • check_rule starts from an empty Ctx with no enclosing function, so a return in a filter is ReturnOutsideFunction. It walks the generators in body order. Each variable argument seen for the first time is bound in the Ctx at its column’s type. A variable seen again unifies the type it was bound at with this column’s, and a literal unifies its own type with its column’s, both at the argument. Then each head term is unified with the head relation’s column type at the head’s span, a variable at the type its generator gave it and a literal at its own type. Last, each filter is checked against Bool, in body order.

Each arm ends as at M5: unify with the expected type, if there is one, then resolve the type and record it at the arm’s span.

The rule checks

Rule bodies and safety describes what each check does. A test holds them to the following:

  • check_generators checks the head first. A head that names no declared relation is NotARelation, and one with the wrong number of terms is Arity, both at the head’s span. Then each conjunct, in order. A call whose callee is a variable naming a declared relation is a generator. A generator with the wrong argument count is Arity { name, expected, found } at the call, and one with an argument that is neither a variable nor a literal is ArgumentNotATerm at that argument. A call whose callee names no relation, function, global, or native is NotARelation at the call: it could neither generate nor test. Every other conjunct is a filter.
  • check_range_restriction collects the variables the generators’ arguments name. A head variable outside that set is Unbound { var } at the head. A name a filter reads, from free_vars, that is outside the set and is not a global, a function, or a native is Unbound { var } at the filter. A generator’s variable shadows a top-level name of the same spelling.
  • check_pure first computes the impure set over every function in the program, as the least fixpoint in Which functions are pure. Then it judges each filter in body order, making three checks in this order, each at the filter’s span. If a function the filter reaches has a parameter whose type contains a function type, the error is HigherOrder { name }. If the filter reaches an effect, it is Impure { witness }. If a function it reaches can reach itself, the error is Recursive { name }.

What counts as reaching an effect, for a function’s body and for a filter alike:

  • The forms with no purity rule: ref, deref, :=, while, for, add, clear, solutions, a query in either syntax, and a relational for.
  • Calls, by what the callee is. A callee that is a local is an effect, whatever function shares its name. In a function’s body the locals are its parameters and every name bound_names finds in the body. In a filter they are the generators’ variables and every name bound_names finds in any of the rule’s conjuncts. A call to a top-level function is an effect when the function is in . A call to a native is an effect when the native is print, println, to_string, or one of the read_* family. A call to map, filter, or fold is also an effect when its callback (the second argument of map and filter, the third of fold) is anything but a lambda, a top-level function, or a native outside that list. The callback is still one of the call’s parts, so a lambda’s body is judged with the rest. A call through anything else, such as a relation, a global, or a computed closure, is an effect.
  • A top-level function named as a value, as in fold(xs, 0, add_up), counts as called.

A function is reached from a filter when the filter calls it or names it as a value, directly or through functions it reaches. The witness is the path to the first effect found, walking each expression’s parts in source order with subexprs, outermost name first:

  • Empty when the effect is a form of the filter’s own (a deref, an applied lambda).
  • One name, that of the impure native, the local, or the relation or global called through.
  • A function’s name, then its body’s witness, for a call to a function in or a mention of one as a value.

So the filter far(a, b), with far calling note and note calling println, has the witness ["far", "note", "println"].

The helper module

The starter leaves the module below out. Paste it at the end of src/relations/check.rs and import what you use, as in use helpers::{free_vars, subexprs};. It is public, so a helper you have not called yet raises no warning, and it brings its own use lines.

  • subexprs(e) is the parts of e one level down, in source order: an operator’s operands, a call’s callee and arguments, a block’s initializers and expressions and tail, a query’s bound arguments. A check that treats most forms alike, being pure when all their parts are, handles its own cases and recurses through subexprs for the rest. It covers the forms of later milestones too. Unlike free_vars, it includes a direct call’s callee, so a check that has already judged f(x) by f meets f again as a variable if it then recurses into the call’s parts.
  • query_exprs(q) is a query’s arguments other than its holes.
  • free_vars(e) is the names e reads and does not bind within itself, each once, in order of first appearance. A let binds over the rest of its block, and a lambda, a for, a relational for, and a match arm bind over their bodies. A direct call’s callee is left out, so f in f(x) is not counted, and x is.
  • bound_names(e) is every name bound anywhere within e, by the same forms.
/// Provided helpers (Milestone M6): walks over expressions that no rule
/// describes. Paste this module at the end of the file, unchanged.
pub mod helpers {
    use crate::ast::{Expr, Name, QArg, Query, Rel, Stmt};
    use std::collections::HashSet;

    /// The immediate subexpressions of `e`, in source order. A query
    /// contributes its bound arguments, never its holes.
    pub fn subexprs(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.push(l);
                cs.push(r);
            }
            Expr::If(c, t, els, _) => {
                cs.push(c);
                cs.push(t);
                if let Some(e1) = els {
                    cs.push(e1);
                }
            }
            Expr::While(c, b, _) | Expr::For(_, c, b, _) => {
                cs.push(c);
                cs.push(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.iter());
            }
            Expr::Struct(_, fields, _) => cs.extend(fields.iter().map(|(_, e)| e)),
            Expr::Match(scrut, arms, _) => {
                cs.push(scrut);
                for a in arms {
                    if let Some(g) = &a.guard {
                        cs.push(g);
                    }
                    cs.push(&a.body);
                }
            }
            Expr::Block(stmts, tail, _) => {
                for s in stmts {
                    match s {
                        Stmt::Let(_, _, e1, _) | Stmt::Expr(e1) => cs.push(e1),
                    }
                }
                if let Some(t) = tail {
                    cs.push(t);
                }
            }
            Expr::ForQuery(q, b, _) => {
                cs.extend(query_exprs(q));
                cs.push(b);
            }
            Expr::Relation(rel, _) => match rel {
                Rel::Add(q) | Rel::Solutions(q) | Rel::Query(q) => {
                    cs.extend(query_exprs(q));
                }
                Rel::Clear(_) => {}
            },
        }
        cs
    }

    /// The bound arguments of a query: every argument that is not a hole.
    pub fn query_exprs(q: &Query) -> impl Iterator<Item = &Expr> {
        q.args.iter().filter_map(|a| match a {
            QArg::Expr(e) => Some(e),
            QArg::Hole(_) => None,
        })
    }

    /// The names `e` reads and does not bind itself, each once, in order of
    /// first appearance: every variable in value position, minus those bound
    /// within `e` (a `let` over the rest of its block, a lambda's parameters,
    /// a `for` variable, a relational `for`'s named holes, a pattern's
    /// names). A direct call's callee, `f` in `f(x)`, is not counted; its
    /// arguments are.
    pub fn free_vars(e: &Expr) -> Vec<Name> {
        let mut out = Vec::new();
        free_vars_into(e, &HashSet::new(), &mut out);
        out
    }

    fn free_vars_into(e: &Expr, bound: &HashSet<Name>, out: &mut Vec<Name>) {
        match e {
            Expr::Var(x, _) => {
                if !bound.contains(x) && !out.contains(x) {
                    out.push(x.clone());
                }
            }
            Expr::Call(callee, args, _) => {
                if !matches!(&**callee, Expr::Var(..)) {
                    free_vars_into(callee, bound, out);
                }
                for a in args {
                    free_vars_into(a, bound, out);
                }
            }
            Expr::Lambda(params, body, _) => {
                let mut inner = bound.clone();
                inner.extend(params.iter().map(|p| p.name.clone()));
                free_vars_into(body, &inner, out);
            }
            Expr::Block(stmts, tail, _) => {
                let mut inner = bound.clone();
                for s in stmts {
                    match s {
                        Stmt::Let(x, _, rhs, _) => {
                            free_vars_into(rhs, &inner, out);
                            inner.insert(x.clone());
                        }
                        Stmt::Expr(e1) => free_vars_into(e1, &inner, out),
                    }
                }
                if let Some(t) = tail {
                    free_vars_into(t, &inner, out);
                }
            }
            Expr::For(x, iter, body, _) => {
                free_vars_into(iter, bound, out);
                let mut inner = bound.clone();
                inner.insert(x.clone());
                free_vars_into(body, &inner, out);
            }
            Expr::Match(scrut, arms, _) => {
                free_vars_into(scrut, bound, out);
                for arm in arms {
                    let mut inner = bound.clone();
                    inner.extend(arm.pat.binders());
                    if let Some(g) = &arm.guard {
                        free_vars_into(g, &inner, out);
                    }
                    free_vars_into(&arm.body, &inner, out);
                }
            }
            Expr::ForQuery(q, body, _) => {
                let mut inner = bound.clone();
                for a in &q.args {
                    match a {
                        QArg::Expr(e1) => free_vars_into(e1, bound, out),
                        QArg::Hole(Some(x)) => {
                            inner.insert(x.clone());
                        }
                        QArg::Hole(None) => {}
                    }
                }
                free_vars_into(body, &inner, out);
            }
            _ => {
                for c in subexprs(e) {
                    free_vars_into(c, bound, out);
                }
            }
        }
    }

    /// Every name bound anywhere within `e`: `let` names, lambda
    /// parameters, `for` variables, a relational `for`'s named holes, and
    /// the names a `match` arm's pattern binds.
    pub fn bound_names(e: &Expr) -> HashSet<Name> {
        let mut out = HashSet::new();
        bound_names_into(e, &mut out);
        out
    }

    fn bound_names_into(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(params, _, _) => {
                out.extend(params.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 subexprs(e) {
            bound_names_into(c, out);
        }
    }
}

Running a program

cargo run --features m6 runs the rule checks and the type checker before main. deps.brg builds a dependency graph from a list with an ordinary loop and asks the relation what it implies:

$ cat deps.brg
relation needs : (String, String);
relation uses : (String, String);

rule uses(a, b) :- needs(a, b);
rule uses(a, c) :- needs(a, b) and uses(b, c);

fn main() {
    let edges = [("app", "ui"), ("ui", "gfx"), ("app", "net"), ("net", "io")];
    for e in edges { add needs(e.0, e.1); }
    println(solutions uses("app", ?m));
    println(uses("io", "app"));
    for uses(?m, "io") { println(m); }
}

$ cargo run -q --features m6 -- deps.brg
["gfx", "io", "net", "ui"]
false
app
net

In hops.brg the filter calls a function that recurses. The function always returns, but the check reads the call graph and never the arguments, so the program never starts:

$ cat hops.brg
relation link : (String, String);
relation near : (String, String);

fn hops(n: Int) -> Bool = if n <= 0 { true } else { hops(n - 1) };

rule near(a, b) :- link(a, b) and hops(2);

fn main() {
    println("start");
    add link("a", "b");
    println(solutions near(?a, ?b));
}

$ cargo run -q --features m6 -- hops.brg
  × `hops` is recursive, so a filter calling it might not terminate
   ╭─[hops.brg:6:35]
 5 │ 
 6 │ rule near(a, b) :- link(a, b) and hops(2);
   ·                                   ───┬───
   ·                                      ╰── here
 7 │ 
   ╰────

The exit status is 1. A filter rejected as impure has its witness printed in a help line under the diagnostic. For the filter far(a, b) of the rule checks, the help line names the path far → note → println and then says what a filter may use.

The checker runs first, so no program that uses a relation runs under --features m6 until the checker’s relation arms are written: the first todo_m6! it meets stops the run.

Worked examples

After deps.brg’s four adds, the queries below have these values:

solutions uses("app", ?m)                    ["gfx", "io", "net", "ui"]
solutions uses(?a, "gfx")                    ["app", "ui"]
solutions needs(?a, ?)                       ["app", "net", "ui"]
solutions uses("app", "io")                  [()]
uses(?m, "app")                              false
solutions uses(?m, ?m)                       []
{ clear needs; solutions uses(?a, ?b) }      []
{ add uses("io", "disk");                    ["disk", "gfx", "io", "net", "ui"]
  solutions uses("app", ?m) }

The last example adds a fact directly to uses. From it, the second rule derives uses("net", "disk") and then uses("app", "disk").

Forms the checker rejects, in a main after the declarations of deps.brg:

add uses("app", ?m)                       HoleInAdd, at the whole form
add uses("app")                           RelationArity (uses takes 2, given 1)
solutions uses(1, ?m)                     Mismatch (expected String, found Int), at 1
clear depends                             UndeclaredRelation (depends)
{ let f = uses; f("a", "b") }             RelationNotAValue (uses), at uses
{ let needs = 1; solutions needs(?a, ?b) }
                                          NotARelation (needs), at the whole form
for uses(?a, ?b) { 1 }                    Mismatch (expected (), found Int), at 1

{ let uses = |a, b| true; uses("a", 2) } is accepted: the local shadows the relation, so the call is an ordinary call to a lambda.

Rules the checks reject, given relation size : (String, Int);, relation leaf : (String);, a global let cap = 3;, a global ref budget = 3;, and fn note(s: String) -> Bool { println(s); true }:

rule uses(a, c) :- needs(a, b);                 Unbound (c), at the head
rule tall(a) :- size(a, n);                     NotARelation (tall), at the head
rule leaf(a) :- needs(a, b) and uses(b);        Arity (uses: 2, given 1)
rule leaf(a) :- size(a, n + 1);                 ArgumentNotATerm, at n + 1
rule leaf(a) :- size(a, n) and m > cap;         Unbound (m), at the filter
rule leaf(a) :- size(a, n) and n > deref budget;
                                                Impure, witness []
rule leaf(a) :- size(a, n) and note(a);         Impure, witness [note, println]
rule leaf(a) :- size(a, n) and not uses(a, a);  Impure, witness [uses]
rule leaf(a) :- size(a, n) and n;               Mismatch (expected Bool, found Int)
rule leaf(a) :- size(a, "big");                 Mismatch (expected Int,
                                                found String), at "big"

These are accepted: n > cap reads a global constant, and in { let m = n * 2; m > cap } the block binds m itself.

How to know it works

cargo m6 runs the provided milestone M6 tests and, with them, every earlier milestone’s. The M6 tests come in four kinds. Some call Subst::unify directly on terms and values. Some run a whole program with run_program, which skips the static checks, so the engine meets filters the checks would have refused. Some run check_rules alone on a loaded program, and some run the type checker on one:

// path(?x, ?y) against (0, 1) binds x and y
let got = Subst::new()
    .unify(&[Term::Var("x".into()), Term::Var("y".into())], &[v(0), v(1)])
    .unwrap();
assert_eq!(got.get("x"), Some(&v(0)));

// a whole program, run without the static checks
let src = format!("{GRAPH} fn main() -> Bool {{ setup(); path(0, 3) }}");
assert_eq!(run_program(&src).0, Value::Bool(true));

A rejection is tested by its RuleError or TyError variant and, where it matters, by its payload: the name in Unbound, the path in Impure. The text of the message is never tested. Write unify first, since the engine calls it for every pairing of an atom and a fact. Then write the engine and the evaluator’s arms, which the whole-program tests reach without the checker. The checker’s arms and the rule checks can follow in either order.

Design problems

A rule's terms are variables and literals, so rule within(a, c, n) :- within(a, b, m) and link(b, c) and n == m + 1; is rejected with n unbound. Without changing the language, compute for every node the number of links on the shortest path from "a" to it. Why does your version terminate on a graph with a cycle?

The rule cannot compute m + 1, so the host computes it ahead of time. A relation step holds pairs of consecutive integers, added by an ordinary loop, and the rule looks the successor up through a generator:

relation link : (String, String);
relation step : (Int, Int);
relation within : (String, String, Int);

rule within(a, b, 1) :- link(a, b);
rule within(a, c, n) :- within(a, b, m) and link(b, c) and step(m, n);

fn main() {
    let edges = [("a", "b"), ("b", "c"), ("c", "a"), ("a", "c")];
    for e in edges { add link(e.0, e.1); }
    for i in range(1, 4) { add step(i, i + 1); }
    for link(?x, ?) {
        println((x, minimum(solutions within("a", x, ?n))));
    }
}

It prints ("a", Some(2)), ("b", Some(1)), and ("c", Some(1)). within holds every walk length up to the bound, and the host takes the least, since a rule cannot aggregate. Every value in a derived fact comes from a fact already present: node names from link, lengths from step. Those are finite, so within is too, whatever cycles the graph has, and the rounds stop. The cycle a → b → c → a gives a walks of every length, and the largest step in step is where they stop. The bound is the host’s choice. Too small a bound gives a wrong answer silently, and the number of nodes is always enough.

Canonical order says the solutions depend on M(P, Δ) alone. Design a test that checks this for your engine without a list of expected answers, and say which engine bugs it cannot find.

Run one program several times, adding the same facts in a different order each time, and require every solutions list to be identical across the runs, element for element. The order of adds changes which facts each round finds first, and so the order in which a naive or semi-naive engine derives the closure. An engine that returns solutions in derivation order gives different lists, and the test reports it. It needs no answer key, so the programs can come from a generator. It finds nothing that every order gets wrong in the same way. An engine that fires each rule once and stops before the fixpoint, or that drops a filter, gives the same wrong list every time. So does a unify that ignores a repeated variable. Comparing against an answer key, or against a second engine written as directly as possible, finds those.

The purity check rejects rule three(a) :- size(a, n) and to_string(n) == "3";, although n is an Int and converting an integer reads nothing. What does the check not know that would let it accept this filter, and what would accepting it cost?

to_string is impure because it can read the store: to_string(r) on a reference prints what the reference holds now. Whether a call reads the store depends on its argument’s type, and the purity check judges a call by its callee alone. To accept this filter it would need the type of every argument of every call the filter reaches, and only the type checker computes those. Either the purity check would read the types the checker records, or purity would be judged inside the type checker, with an effect recorded beside each type, the design that Tracking effects describes. The judgment would be more precise, and it would apply to every helper the filter calls, at the types each call uses. A generic helper fn show<T>(x: T) -> String = to_string(x); would be pure at Int and impure at ref<Int>, so purity, which the check now decides once for each function, would have to be decided again at each call.

The purity check rejects every filter that queries, before the program runs. Why does the engine also refuse a query while it computes a fixpoint, and what would happen to this program, run without the checks, if it did not?
relation q : (Int);
relation r : (Int);
relation p : (Int);

rule r(x) :- q(x) and x > 1;
rule p(x) :- q(x) and not r(x);

fn main() {
    add q(1); add q(2);
    println(solutions p(?x));
}

The checks are a pass that a program can skip: the tests run programs without them, and the evaluator must give every program a meaning, checked or not. To answer solutions p(?x), the engine fires the rule for p, and its filter asks r(x). Answered as a query, r(x) would need the fixpoint of every rule over the same facts, so the engine would start computing it again. That fixpoint fires the rule for p too, whose filter asks r(x) again, and so on without end. The reference interpreter with the guard removed overflows its stack on this program. With the guard it stops at r(x) with QueryInFilter. Making the query work would take more than avoiding the loop. not r(x) asks for r to be complete before p’s rule reads it, which is the layering of relations that Absence in a body describes. An engine that ran the inner query against the facts derived so far would get an answer that depends on the order of the rounds.