Types as tests that would take forever
The design of disp's type system, explained from the bottom up. A type is a program that answers one question about two trees. Checking a claim honestly means running that program over every tree there is, which never finishes. Every checker disp ships is a shortcut, and every shortcut comes with a reason it agrees with the honest run. Every code block on this page is a definition from the library or a test line that npm test runs. The shortcuts live in lib/confirm.disp; the tests are lib/tests/refuter.test.disp (the honest checker, 22 tests), lib/tests/confirmer.test.disp (the shortcuts, 189 tests) and lib/tests/types_doc.test.disp (this page's own snippets, 31 tests). The one block that is not a program is marked as such.
1. A type claim is a claim about infinitely many trees
Everything in disp is a tree: a number, a program, a type. Today a type is a program that says yes or no to one tree, and checking a value means applying the type to it. That works perfectly for data: Nat 3 runs a shape check and answers yes.
It stops working the moment the claim is about a function. succ : Nat -> Nat says: for every tree that is a Nat, succ of it is a Nat. No single run visits every Nat. The honest way to check it is to list every tree in order of size, keep the Nats, and run succ on each. disp already has that list, Trees, and IDEAS.disp already has the honest checker:
Arrow :: {Dom : Tree -> Bool, Cod : Tree -> Bool, fuel : Nat, fn : Tree} -> Bool :=> {
let members := Trees.as_items.bounded(fuel).s_filter(Dom)
let outputs := members.s_map({arg} => fn(arg))
outputs.s_all(Cod)
}
Run it and two things are visible at once. It can find a bad input and stop: that is a real refutation, with a witness anyone can re-run. And when it finds nothing it has not proved anything, because the budget ran out before the list did. Two runs at Bool -> Bool, 25 probes each:
BoolFn :: {fn : Tree} -> Bool :=> Arrow(Bool, Bool, 25, fn)
test BoolFn(t(t, t)) = true // the constant true: no counterexample in 25 probes
test BoolFn(t) = false // the leaf is not a Bool function
So there are three answers, not two, and the third one is not a failure. Refuted means here is an input the claim fails on. Proved means the checker holds a short argument that the list would never turn up a bad input. Open means neither, within the budget, and it always says why.
The rest of this page is about what the short argument is, and what a type has to be for the argument to make sense.
2. The one question a type answers
Here is the change of view that makes everything else fall out. A type is not a program that says yes or no to one tree. It is a program that answers one question about two trees:
Do these two count as the same, as far as this type cares?
A tree belongs to a type when the type says it is the same as itself. That is the whole definition of membership; there is no second notion. For a data type the two-argument program is just the old one-argument program run on both sides, plus identity:
rel_of :: {recognize : Tree -> Bool} -> Tree -> Tree -> Bool :=> {x, y} => ((recognize(x)) && (recognize(y))) && (x == y)
NatRel := rel_of(NatR)
test NatRel(2, 2) = true
test NatRel(2, 3) = false
test NatRel(t(t), t(t)) = false // a stem is not the same as itself at Nat: it is not a Nat
member :: {rel : Tree -> Tree -> Bool, v : Tree} -> Bool :=> rel(v, v)
test member(NatRel, 2) = true
test member(NatRel, t(t)) = false
Notice the last NatRel line. The relation is deliberately not reflexive. If it only compared the trees, every tree would be the same as itself and the stem would belong to Nat. The recognizer conjunct on both arguments is what keeps non-members out, and it is what makes membership the diagonal of the relation rather than something separate. In mathematics this object has a name, a partial equivalence relation: symmetric, transitive, reflexive only on its own carrier.
For data types nothing about your code changes. You still write a recognizer, and the relation is derived from it. Where the relation carries more than the recognizer is in exactly two places, quotients and function types, and those are the next two sections.
| type | "the same" means | who belongs |
|---|---|---|
Nat, any data type | the same tree, and both number-shaped | number-shaped trees |
Tree | bit for bit | every tree |
QuotC(NatR, parity) | same parity | number-shaped trees |
Nat -> Nat | same outputs on inputs Nat calls the same | whatever is the same as itself in that sense |
Stream(Nat) | every item and every step agree, forever | a stepper and a state that keep producing Nats |
3. Function types: sameness is judged at a type
Two functions are the same at A -> B when, fed any two inputs that A calls the same, they return outputs that B calls the same. Written out, and this is the one block on the page that is a specification rather than a program, because the "for all" ranges over an infinite list:
// not a program: the arrow relation, as a specification
f ~[A -> B] g iff for all a, a' with a ~[A] a': (f a) ~[B] (g a')
Three things follow immediately, and each one used to be a separate feature.
- Function extensionality is not an axiom and not a theorem. It is this definition. Two functions that agree on every input are the same function at that type, because that is what "the same" means at that type.
- Membership is respect. A function belongs to
A -> Bwhen it is the same as itself, which unfolds to: it maps inputsAcalls the same to outputsBcalls the same. At a data domain that is just "maps members to members". At a quotient domain it is strictly more, as section 4 shows. - Sameness is always judged at a type. The identity function and a function that rebuilds its argument are the same at
Nat -> Natand different atTree -> Tree, because atTreesameness is bit for bit and a stem is rebuilt into a fork.
id := {n} => n
shift := {n} => if (is_zero(n)) { zero } else { succ(nat_pred(n)) }
test eq_arrow(NatR, id, shift) = "Proved" // every Nat comes back as itself
test eq_arrow(TreeR, id, shift) = refuted(t(t)) // a stem does not
test id(t(t)) = t(t)
test shift(t(t)) = t(t, t)
That last pair of lines is the whole reason this design can coexist with an inspecting substrate. The functions really are different trees, and at the type of trees that difference is visible. At the type of numbers it is not, and the checker says so.
4. Quotients: the same trees, a coarser question
A quotient keeps a type's members and changes what "the same" means. The simplest way to declare one is a normalizer, a function that picks a canonical representative:
rec parity :: {n : Tree} -> Tree :=> if (is_zero(n)) { zero } else if (is_zero(nat_pred(n))) { succ(zero) } else { parity(nat_pred(nat_pred(n))) }
ParityRel := {x, y} => ((NatR(x)) && (NatR(y))) && (parity(x) == parity(y))
test ParityRel(2, 0) = true
test ParityRel(2, 1) = false
test ParityRel(t(t), t(t)) = false
A quotient can only coarsen: two trees the carrier already calls the same stay the same, and some others join them. That one sentence turned out to matter more than it looks. An earlier draft let a quotient over a function type refine sameness back to bit-for-bit identity, and that reopened the transport paradox through the equality of types. So the rule is: at Quotient A nf, x and y are the same when nf x and nf y are the same at A. Quotienting by the identity normalizer gives you A back.
Now the payoff of section 3's pair-of-inputs definition. A function from the quotient belongs only if it cannot tell identified inputs apart:
is_even_step := {ie, n} => if (is_zero(n)) { true } else if (is_zero(nat_pred(n))) { false } else { ie(nat_pred(nat_pred(n))) }
id_step := {_self, n} => n
test respects_nf(is_even_step, parity, Bool) = "Proved" // is_even : Parity -> Bool
test respects_nf(id_step, parity, NatR) = refuted(pair(0, 2)) // id : Parity -> Nat cannot tell 0 from 2
Nothing here is a separate "respect obligation" bolted onto the type. It is membership, computed from the definition of sameness at an arrow whose domain is a quotient. The checker discharges it by the same induction it uses for everything else, with the recursive call assumed on the normalized sub-input; section 6 explains that machinery.
5. The honest checker, precisely: the refuter
The refuter is the type's relation run over the domain's list of related pairs instead of over a placeholder. It is IDEAS.disp's Arrow generalized from members to pairs, and it is the ground truth every shortcut is measured against.
// Related pairs of a domain, smallest first. For a data type the pairs are the diagonal;
// for a quotient they are (a, nf a). Both are bounded, so they finish spent, never exhausted.
diag_pairs :: {recognize : Tree -> Bool, fuel : Nat} -> Items(Pair(Tree, Tree)) :=>
Trees.as_items.bounded(fuel).s_filter(recognize).s_map({a} => pair(a, a))
quot_pairs :: {recognize : Tree -> Bool, nf : Tree -> Tree, fuel : Nat} -> Items(Pair(Tree, Tree)) :=>
Trees.as_items.bounded(fuel).s_filter(recognize).s_map({a} => pair(a, nf(a)))
// Open carries how many related pairs were checked: evidence, never a verdict
open_after :: {probes : Nat} -> Verdict :=> open_on(probes)
// refute: walk the related pairs; the first pair the function does not carry to a
// related pair is a concrete witness. The ending says the rest: an exhausted
// stream was the domain's own generator (Proved), a spent one was a budget (Open).
refute :: {pairs : Bounded(Items(Pair(Tree, Tree))), cod_rel : Tree -> Tree -> Bool, fn : Tree, probes : Nat} -> Verdict :=> c_fold({recurse, step, checked} => {
let p := step.step_draw.yielded_item
if (step.is_finished) { if (step.finished_result.is_spent) { open_after(checked) } else { "Proved" } }
else if (not(step.step_draw.is_yield)) { recurse(step.step_rest, checked) }
else if (cod_rel(fn(p.fst), fn(p.snd))) { recurse(step.step_rest, succ(checked)) }
else { refuted(p) }
}, pairs, probes)
refute_arrow :: {dom : Tree -> Bool, cod_rel : Tree -> Tree -> Bool, fuel : Nat, fn : Tree} -> Verdict :=>
refute(diag_pairs(dom, fuel), cod_rel, fn, zero)
test refute_arrow(NatR, NatRel, 40, succ) = open_after(3)
test refute_arrow(NatR, NatRel, 40, {n} => pair(n, n)) = refuted(pair(1, 1))
test refute(quot_pairs(NatR, parity, 40), NatRel, {n} => n, zero) = refuted(pair(2, 0))
bool_pairs := s_from_list([pair(true, true), pair(false, false)])
test refute(bool_pairs, BoolRel, not, zero) = "Proved"
What it can say, exactly:
| outcome | when | strength |
|---|---|---|
| Refuted with a pair | the function carries a related pair to an unrelated pair | a proof: re-run the pair yourself |
| Proved | the domain's own finite generator ran out, as for Bool | a proof by exhaustion; only finite types get it |
| Open after n probes | the budget ran out first | evidence, never a verdict |
Two limits are permanent. It cannot refute divergence: an input on which the function never answers exhausts its per-run budget and is Open, not a witness. And at a function-typed domain there is no exact list of members at all, so the refuter there can only draw on functions already certified, and can never Prove by exhaustion.
The refuter also has a second job: whenever a shortcut believes it has found a counterexample symbolically, the refuter re-runs it concretely before anything is reported. A symbolic "these differ" is only ever a suggestion.
6. The shortcut: one run on a placeholder
Instead of running succ on every number, run it once on a piece, a placeholder that means "some Nat, I will not say which". If the run finishes without ever needing the piece's shape, it is a template: substitute any real number and you get that number's real run. One run stands for all of them.
The checker's values make this concrete. A partly known value is a plain tree with holes in it, and a fully known value is just itself. A hole is a tree carrying a fixed marker, and here it is one of two things: a piece of the challenge, or an application nobody can run yet (a neutral term). Two more kinds come up later: a forged hole (below) and a lemma (section 12). Applying a hole gives the hole for that application, which is how the marker is written:
hole_marker := fix({self, what, arg} => wait(self, pair("App", pair(wait(self, what), arg))))
hole :: {what : Tree} -> Val :=> wait(hole_marker, what)
piece_named :: {T : Code, name : Pair(Tree, List(Tree))} -> Val :=> hole(pair("Piece", pair(T, name)))
piece_at :: {T : Code, root : Tree, path : List(Tree)} -> Val :=> piece_named(T, pair(root, path))
piece :: {T : Code, path : List(Tree)} -> Val :=> piece_at(T, 0, path)
app_val :: {head : Val, arg : Val} -> Val :=> hole(pair("App", pair(head, arg)))
test run(succ, piece(NatR, [])) = answered(succ(piece(NatR, [])))
A piece has a name, a root and a path of destructor steps, so two occurrences of the same unknown compare equal and different unknowns do not; that is what makes pair(n, n) refutable and what makes "f n equals g n" expressible at all. And it has a type, which is all that says what may be done with it: split it when the type has cases, apply it when the type is a function type. Every unknown the checker needs is one of these, because every lens it uses makes one: the case split's cases have pieces, the induction hypothesis is a piece of a function type (below), and asking a recognizer or tree_eq about a piece is an application.
A hole is a plain tree, so a program under check could build one and pass it off as a piece. Wherever a program's tree enters the checker (the program itself, the answer of a native run, a fork the evaluator builds), any marker-shaped part is wrapped whole as a Forged hole, which every judge treats as opaque. A program that forges a piece gets Open, never Proved.
The evaluator is the machine of lib/machine.disp run on these values: the same step function that runs plain trees. Its rules copy pieces by name, and an application that would read a hole's shape is held back from them and answered separately. An application whose function and argument are both fully known runs on the native machine, against the same step budget. Only one rule looks inside its argument, and that is the only place a piece can be needed. A run therefore ends in one of three ways:
answered :: {v : Val} -> Res :=> pair("Answered", v)
need :: {s : Val} -> Res :=> pair("Need", s)
stuck :: Res := "Stuck"
stuck_on :: {reason : Tree} -> Res :=> pair("Stuck", reason)
Need means a case split can resolve it: the run wanted to know whether the piece is zero or a successor. Stuck means nothing can, and it carries a reason: fuel, a piece of a type with no cases, a missing licence. This distinction is the difference between an Open the user can act on and an Open they cannot.
Splitting on demand
When the run needs a piece's shape, the search substitutes each case of its type with fresh smaller pieces and runs each case. Nobody writes the cases down. A type that a program can test is a recognizer, and its cases are derived by running it once on an unknown tree: where it looks, the tree splits into leaf, stem and fork, and a branch that answers true is a case. When it asks about a strictly smaller piece (its own recursion, or another type through is_a), that piece becomes a member of the type asked about. Nat's cases come out as zero and the successor of a Nat, Bool's as its two values, and a data type's as its constructors. Tree is the one type given by hand: every tree is a leaf, a stem or a fork. The table is optional:
test table(StemR, {s} => piece(StemR, [s])) = some([t(piece(TreeR, ["child"]))])
test table(FalseR, id) = some([])
test table(LoopR, id) = none
test cases_of(Bool) = [t, t(t)]
The difference between some [] and none is not pedantry. An empty case list means a type with no members, and a claim over an empty domain is vacuously Proved. No case list at all, which is what a function type or a recognizer that loops has, means the search must not split and the verdict is Open with a reason. A first probe conflated the two and Proved {f} => tree_eq(f, id) at a function-typed domain, which is precisely the transport paradox this whole design exists to refuse.
// `checks` are the exact check, then any that read more by type. `ground` reads a case as a
// concrete counterexample: some(tree), or none while unknowns that matter remain. An item is
// a case and the splits left for it; a Step is an item with what settled it.
settle_case :: {checks : List(Val -> Res), ground : Val -> Option(Tree), instances : Val -> List(Val), item : Pair(Val, Nat)} -> Outcome(Tree, Pair(Val, Nat)) :=> {
let input := item.fst
let exact := checks.head
let r := exact(input)
if (is_yes(r)) { settled_on(grounds_of(r)) }
else {
let g := ground(input)
let bad := if (if (is_none(g)) { true } else { not(r == "No") }) { instances(input).filter({i} => exact(i) == "No") } else { [] }
if (if (is_none(g)) { false } else { r == "No" }) { yield(g.snd) }
else if (not(bad.is_nil)) { yield(ground(bad.head).snd) }
else {
let r2 := weigh(checks.tail, input, r)
let target := if (is_none(g)) { split_target(r2, input) } else { "None" }
if (is_yes(r2)) { settled_on(grounds_of(r2)) }
else if (target == "None") { noted(explain(r2)) }
else if (is_zero(item.snd)) { noted("split depth exhausted") }
else {
let cases := alternatives(input, target)
if (is_none(cases)) { noted(pair("no split table", target)) }
else { split_on(target, cases.snd.map({c} => pair(c, nat_pred(item.snd)))) }
}
}
}
}
search_g :: {checks : List(Val -> Res), ground : Val -> Option(Tree), instances : Val -> List(Val), input : Val, depth : Nat} -> Verdict :=>
steps_verdict(search_steps(checks, ground, instances, [pair(input, depth)]))
Read settle_case top down; it settles one case. A Yes on a symbolic case covers every instance of its pieces, so the case is done, and the Yes says what it rests on besides the run: the hypothesis, a lemma. A No on a known case is its own witness, and is yielded. A case left with only type arguments, their abstract values and functions is re-run on two concrete stand-ins: each type a type of one member, and each function one of the stored pair of members of its type (id and shift at Nat -> Nat). So a program that looks inside an abstract value is still caught, and one that fails on a real function is refuted with that function. Then any later checks are asked: the same run with definitions already Proved read by their types (section 12). They can answer Yes or name a better piece to split, and they never refute. Otherwise the piece a run needed is split, and its cases go to the front of the work list. search_g runs that list as a stream (s_steps in lib/stream.disp), every case with what settled it, and reads the verdict off its counterexamples the same way the refuter of section 5 does: the first counterexample refutes, a list that runs out with nothing noted proves, and anything else is Open with the first reason noted. The same list read back as data is derivation in lib/rules.disp, and as a lens steps_lens: each split sends a tree to the case that covers it.
Recursion: the call may assume the claim, on a smaller piece
When the program calls itself, the symbolic run reaches a call it cannot unfold forever. The checker replaces the recursive call with the induction hypothesis: a piece of the function type from the strictly smaller pieces of the input to the codomain. Calling it is an ordinary application, and the licence is the arrow rule itself: the argument must be in the domain, and the domain is "strictly smaller". Recursion on a strictly smaller piece must bottom out, and that is the only termination argument the checker knows.
hypothesis_over :: {Dom : Code, fam : Tree, root : List(Tree), partner : Val -> Val} -> Val :=>
piece_at(fn_c(below_c(Dom, root, partner), fam), "hypothesis", root)
// the piece an argument of the hypothesis stands for, or "None": a strict descendant of the
// root input, an input piece of the domain (after folding succ^k back), or the partner of one
licensed_with :: {tbl : Tree, B : Code, x : Val} -> Val :=> {
let Dom := B.snd.fst
let root := B.snd.snd.fst
let partner := B.snd.snd.snd
let ok := {c} => if (c.is_piece) { ((c.piece_type == Dom) && (c.piece_root == 0)) && (is_strict_ext(c.piece_path, root)) } else { false }
let direct := canon_with(tbl, x)
if (ok(direct)) { direct }
else {
let peeled := match_val(partner(pattern_piece("a")), x, [])
let found := if ((peeled.is_answered) && (not(peeled.answer.is_nil))) { canon_with(tbl, peeled.answer.head.snd) } else { none }
if (ok(found)) { found } else { "None" }
}
}
Three checks in the domain, each closing a real hole: the argument must be a piece of the input being inducted on (root 0), of the domain's type, and strictly below it in the destructor order. Miss the last one and a step function whose recursion never descends is Proved; miss the first and a piece of another input, or the hypothesis's own answer, counts as smaller than the input. Both were live bugs in earlier probes. A call outside the domain stops the run at once, even if its answer is thrown away, since the real call would never return.
dbl_step := {dbl2, n} => if (is_zero(n)) { zero } else { succ(succ(dbl2(nat_pred(n)))) }
bad_step := {bad2, n} => if (is_zero(n)) { zero } else { succ(bad2(n)) } // fix(bad_step)(1) loops forever
test check_by_structure(succ) = "Proved"
test check_by_structure({n} => pair(n, n)) = refuted(1)
test check_by_induction(dbl_step) = "Proved"
test check_by_induction(bad_step) = "Open"
test check_by_induction(two_base_step) = "Proved" // course-of-values: the licence folds succ(smaller piece) back to the piece
So the short argument behind a Proved is always one of three: the run never looked at the piece; the run looked, the cases were split, and every case closed; the program recursed, and every recursive call was on a strictly smaller input-derived piece. The certificate names which.
Which part is the specification
The symbolic evaluator in lib/confirm.disp is the reference: a readable disp program whose behaviour is the meaning of every verdict on this page. Fully known work already runs on the native machine, in chunks that double, so the budget is still respected. What remains slow is stepping the machine in disp on values with holes. The intended fast path for that is a native mode of the host's machine stepper that holds an application reading a hole, as held does, validated against the reference by differential testing, or a rewrite of the reference in an .opt.disp overlay.
The hook is on the rule, not on the text
A fair test of the model: a function whose text contains no inspection, but which builds a case-analysis at runtime and applies it to its input. If the checker's guard were on the syntax, this would slip through.
runtime_triage := {n} => t(t(zero, succ), id)(n)
runtime_id := {n} => t(t(zero, {_} => zero), {_l, r} => succ(r))(n)
test runtime_triage(1) = t(t)
test run(runtime_triage, piece(NatR, [])) = need(piece(NatR, []))
test check_by_structure(runtime_triage) = refuted(1)
test check_by_structure(runtime_id) = "Proved"
The run reports that it needed the piece's shape, because the built triage is applied to the piece and the triage rule is where the evaluator looks. The first function then turns out not to be a member at all: it sends the number one to the stem t t, and the search finds that by splitting and re-running the case concretely. The second, a Nat identity written the same way, is Proved after the split. The first confirmer could not split, and gave both Open: never Proved, never a false verdict.
7. Streams: the same trick facing the other way
A stream is a stepper and a state; a step finishes with an ending, or runs on with an item (a yield) or without one (a skip). Two streams are the same when every item and every step agree, forever. The honest check is prefix comparison and never ends; the shortcut is one symbolic step. Run each stepper on a symbolic state, compare the items, and check that the next states are again a pair the relation covers. The assumption "these states are related" may only be used on the next states, after both sides have taken a step; using it on the current states would prove any two streams equal.
naturals := nats.as_items
nats_add := s_new({n} => running(emit(yield(n), add(1, n))), zero)
by_two := s_new({n} => running(emit(yield(n), succ(succ(n)))), zero)
nats_pair := s_new({p} => running(emit(yield(p.fst), pair(succ(p.fst), t))), pair(zero, t))
pair_states := {x} => pair(x, pair(x, t))
test stream_eq(NatR, same_states, naturals, nats_add) = "Proved"
test stream_eq(NatR, same_states, naturals, by_two) = refuted(pair([0, 1, 2, 3], [0, 2, 4, 6]))
test stream_eq(NatR, pair_states, naturals, nats_pair) = "Proved"
The third line relates two streams with different state spaces through a user-supplied relation between states; the coinductive hypothesis is discharged by matching the next states against that pattern.
Two notions of the same, and why the finer one is the type's
What section 7 checks is strong bisimulation: a skip is a step, and a skip must meet a skip. A stream that skips before every item is therefore not the same as one that does not (slow versus naturals is refuted in the probe). That is deliberate. The library's bounded spends budget on skips, so under any looser sameness it would carry equal streams to unequal prefixes and fail to belong to its own type.
The optimizer still needs a sameness to appeal to when it removes a skip, and it gets one without a new mechanism: a quotient. The weak stream type is Items(V) quotiented by the skip-removal normalizer, exactly as Parity was Nat quotiented by parity. A function belongs to an arrow out of the weak type only if it cannot count skips, which bounded cannot claim and a consumer that only reads items can. The normalizer is partial on a stream that skips forever, so forming the quotient carries a productivity obligation, a certificate that skips are finitely many between items, parallel to the termination obligation on functions. Skip removal is then licensed as a rewrite at the weak type and scored as a measured improvement, and a context that counts skips is simply not a member of the weak arrow, so the rewrite does not fire there.
8. Tree is the type of code
disp's substrate lets any program take any tree apart, including a function. That is the reflection the whole project is built on, and it is also why no untyped notion of "same behaviour" survives: a program that compares trees bit for bit tells any two different trees apart. The design does not fight this. It gives the ability a type.
At Tree sameness is bit for bit and every tree belongs, so inspecting functions are perfectly good members there:
test check_arrow(TreeR, Bool, is_leaf) = "Proved"
test check_arrow(TreeR, Bool, {x} => tree_eq(x, t)) = "Proved"
At Nat -> Nat sameness is extensional, so a piece of that type is a value the checker will not let anyone look inside, and will not let anyone embed at a position whose sameness is finer than its own. That second half is the subtle one. It is not enough to refuse the function that compares f with the identity. Wrapping f in a stem, pairing it with zero, or returning it unchanged at type Tree would let bit-for-bit sameness leak back in through the codomain, and an earlier probe accepted all three. The rule that closes every spelling: a value carrying a piece of a coarser type is never "the same as itself" at a finer position. Where a certified pair of same-but-different functions is stored, the checker grounds the piece on it and refutes concretely.
NatFn := ArrowC(NatR, NatR)
sniff := {f} => tree_eq(f, id)
wrap := {f} => t(f)
test check_arrow(NatFn, Bool, sniff) = refuted(pair(id, shift))
test check_arrow(NatFn, TreeR, wrap) = refuted(pair(id, shift))
test check_arrow(NatFn, NatR, {f} => f(0)) = "Proved" // applying a function piece is fine
test check_arrow(NatFn, TreeR, {f} => f(id)) = refuted(pair(id, shift)) // applying it outside its domain is not
This is why function extensionality at Nat -> Nat is consistent with bit-for-bit comparison at Tree. The two never meet, because there is no member of (Nat -> Nat) -> Tree other than the constant functions and the ones that go through an application first. The old kernel tried to police this with an unforgeable hypothesis token and a provenance ledger, and it leaked through a reader that could tell a hypothesis from a value. Here a program never sees a hole: a run with a hole in it goes through the evaluator, which stops at any rule that would look inside one, and only hole-free runs go native. A program that builds the marker itself has its tree escaped as a forgery (section 6).
9. The contract: every shortcut agrees with the honest run
Put together, the checkers form a ladder. Each rung is a procedure plus the claim that its verdict never disagrees with the refuter, and a note on how far that claim is proved.
| rung | what it does | why it agrees | status |
|---|---|---|---|
| identity | two identical trees are the same at any type they belong to | every relation is reflexive on members | theorem |
| exhaustion | run every member of a finite type | the generator is the type | theorem |
| one symbolic run | section 6 | a run that never inspects the piece instantiates to the real run for every member | theorem (sketch below), property-tested as well |
| split | cases derived by running the recognizer | the cases cover the members exactly: every tree is a leaf, a stem or a fork, plus the run lemma and induction | theorem; search attacks both directions (cover_law, exact_law) |
| induction | the licence of section 6 | strong induction on the size of the input piece | theorem for structural descent |
| equality | both sides on one piece, judged at the codomain | every case pair related under every instantiation; one side a member | bisimulation up-to techniques, plus the run lemma |
| rewrite licence | swap programs inside a context | the context must itself belong to the arrow between the two types | immediate from the definition |
Why one run stands for all
Call a value partly known when some of its leaves are pieces, and call an instantiation the tree you get by substituting a member for every piece. The evaluator fires the substrate's rules on partly known values, and each rule examines a fixed part of its operands: applying a leaf or a stem reads nothing; applying a fork reads the shape of its left branch to choose between the constant rule, the sharing rule, and the case rule; and only the case rule reads the shape of the argument. Whenever the part a rule needs is known, the same rule fires with the same result for every instantiation, because substitution reaches under a known node without changing its shape; that is one line per rule. Whenever the part is a piece, nothing fires: the evaluator answers Need or Stuck. Two more one-line cases: the case-analysis whose three arms are all leaves rebuilds any argument, so it may pass a piece through, and a fully known application runs natively, which is the real run itself. By induction on the sequence of firings, if the symbolic run answers a value, then for every instantiation the real run reaches that value's instantiation. The real run may take more steps, and it is at least as willing to finish, since the host discards an unused argument the symbolic evaluator would have evaluated.
Two things sit outside this sketch. A piece or a neutral term in function position makes a neutral term rather than firing; instantiating one means applying the instantiated head, and the lemma extends exactly when that application terminates, which is what the head's stored membership certifies. And the induction licence is a separate argument, ordinary strong induction on the size of the input piece, whose one genuinely open claim is that a single piece per input establishes respect when the domain's sameness is coarser than identity. That is the fundamental lemma of logical relations for the judge, and it is tested rather than proved.
The contract is not just stated; it runs. Every probe file ends with the honest checker running against its own verdicts:
agrees :: {verdict : Verdict, enumerated : Bool} -> Bool :=>
if (verdict.is_proved) { enumerated } else if (verdict.is_open) { true } else { not(enumerated) }
test agrees(check_by_structure(succ), Arrow(NatR, NatR, 40, succ)) = true
sweep := candidates.map({fn} => pair(check_by_structure(fn), Arrow(NatR, NatR, 40, fn)))
test sweep.all({p} => agrees(p.fst, p.snd)) = true // 40 candidate trees
Two rules keep the verdicts honest at the edges. A symbolic "No" is never reported as Refuted until the offending case has been instantiated by its smallest members and re-run for real, so an uninhabited case can never refute. And a recognizer that loops on some input makes membership Open there, never a verdict either way:
rec LoopR :: {v : Tree} -> Bool :=> if (is_zero(v)) { true } else { LoopR(v) }
test check_arrow(LoopR, NatR, id) = "Open"
10. What the optimizer gets
The optimizer's job is to replace a program by a different, faster one that is the same at the type the specification names. Under this design that is one certificate of section 6's equality rung, plus one membership check: the surrounding context must belong to the arrow from the type where the two programs are the same to the type of the whole. A context that inspects its hole does not belong to that arrow, so the rewrite is refused there, and a context that only applies its hole does.
Every verdict is stored as replayable data: which piece, which cases, which recursive calls were licensed, and for a refutation the concrete pair. Replay never searches; it re-runs the named steps and checks the licences. Refuted witnesses are kept as a regression battery every later candidate must pass. Cost is judged by measured native steps, not by the symbolic run's step count, because the two are not proportional; the symbolic count only gives the asymptotic direction. Correctness gates, cost ranks. The stream case shows the two channels apart: removing a skip is not an equality at Items(V), it is an equality at the weak quotient and an improvement at the strong type, and the rewrite fires only inside contexts that belong to the arrow out of the weak type.
11. What stays Open on purpose, and how to read an Open
Membership at Nat -> Nat is undecidable, so some true claims stay Open forever. The design does not hide this; it names the budget or the rule that stopped the run.
| reason | what it means | what to do |
|---|---|---|
| fuel | the symbolic run spent its dispatch budget | raise it, or check that the program terminates on the case shown |
| split depth | the search split as deep as allowed | raise it; the claim needed more cases than the depth |
| no descent | a recursive call was not on a strictly smaller input piece | restructure the recursion, or supply a measure (a later rung) |
| no split table | the run inspected a piece of a type with no cases, such as a function | the program looks inside a function; it belongs at a Tree-typed domain instead |
| coarse at a fine position | a function-typed value was placed where bit-for-bit sameness is required | apply it first, or change the codomain |
| no certificate | a called function has no stored membership yet | annotate the callee before the caller: a Proved callee is a lemma (section 12) |
Two things are conjectures rather than theorems, stated as such and tested: that one piece per binder suffices, meaning membership judged at the codomain implies respect for the domain's relation; and that the enumeration lists every tree exactly once. The run lemma of section 9 is a theorem, and it is property-tested anyway: instantiate the pieces of a symbolic answer at random and compare with the real run. Each conjecture has a one-line falsifier of the same shape.
Two ceilings are stated rather than hidden. Equality of types is structural on their codes: two types with the same members but different declarations are different types, and moving a program between representations is a pair of certified translations, never a type equation. And a law quantified over all types is judged with the type erased: a program receives the leaf for every type argument, so it cannot case on it, and a value of that type is a piece no program can look inside. What is left is re-run on two stand-in types (section 12), so a program that is not parametric is refuted, and one that looks at its type argument stays Open.
12. Writing it down: checked annotations
A module that opens lib/theories/checked.disp has its : annotations checked by judge when it is used. The language needs nothing new for this. The elaborator turns {x : A} -> B into Pi(A, {x} => B) with whatever Pi is in scope, and a module with check_module in scope hands it every annotated definition when it loads. The file binds both, and the names of the types (Nat, Bool, Tree, Unit, Empty, Type, List, Eq). From lib/theories/checked_example.disp:
next : Nat -> Nat := {n} => succ(n)
rec twice : {n : Nat} -> Nat :=> if (is_zero(n)) { 0 } else { succ(succ(twice(nat_pred(n)))) }
ident : {A : Type} -> A -> A := {_a, x} => x
pick : {n : Nat} -> if (is_zero(n)) { Unit } else { Nat } := {n} => if (is_zero(n)) { t } else { n }
count : {A : Type} -> List(A) -> Nat := {_a, xs} => length(xs)
| you write | it becomes | what judge does with it |
|---|---|---|
Nat -> Nat | Pi(Nat, {_} => Nat), the plain arrow ArrowC(NatR, NatR) | splits the argument where the run looks at it |
{A : Type} -> A -> A | pi_t over universe_t, the type passed straight in | gives the program the leaf, and the type a fresh abstract type |
{n : Nat} -> if (is_zero(n)) { Unit } else { Nat } | pi_t over nat_t, the family run on the argument by by_value | the type asks for n to be split |
rec f : T :=> body | a fix of the body | induction on strictly smaller pieces |
name : T := v | an entry handed to check_module | must be Proved |
There is one function type, fn_c (pi_t is its name among the theories), and ArrowC(a, b) is it with a family that ignores its argument. So a plain arrow is one code however it was built, which is how the stored pair of functions at Nat -> Nat is found. A definition that is not Proved is a load error that names it and prints its verdict, such as failing entry: dup (t("Refuted", …)). A type alias is written without an annotation (Pred := Nat -> Nat), because at the universe a program sees every type as the leaf.
Data may hold an abstract type. No known tree is a member of one, and a derived case of List(A) holds a piece of A, so count above is Proved for every A. Types that are neither first-order nor stood in for, such as functions, stay opaque inside data.
Lemmas
A recursive definition that calls another one gets stuck where the callee looks at the hypothesis's answer, which no run can see into. So the check goes in file order, and every function Proved before a definition is a lemma for it. Each case is run exactly first, so a lemma hides no counterexample; a case that run does not settle is run again with the lemmas in place. A lemma is a hole that runs as the definition itself. Where that run does not answer, it answers as a piece of the definition's type applied to the arguments, and the definition's own verdict licenses that once each argument is in its domain. That is how rev is Proved after cat:
rec cat : {xs : List(Nat), ys : List(Nat)} -> List(Nat) :=> if (is_leaf(xs)) { ys } else { cons(xs.fst, cat(xs.snd, ys)) }
rec rev : {xs : List(Nat)} -> List(Nat) :=> if (is_leaf(xs)) { [] } else { cat(rev(xs.snd), [xs.fst]) }
A definition the size of a combinator is never a lemma. It runs through exactly anyway, and its tree could be part of the compiled code around a call, where a hole would stop the run.
A lemma need not always be written. When a definition is still Open, each recursive definition inside its tree is tried at the function types its own type is built from, innermost first, and one that is Proved there is a lemma like any other. Those guesses are finitely many. Here plus has no annotation, and times is Proved because its own type fits plus:
rec plus := {a, b} => if (is_zero(a)) { b } else { succ(plus(nat_pred(a), b)) }
rec times : {a : Nat, b : Nat} -> Nat :=> if (is_zero(a)) { 0 } else { plus(b, times(nat_pred(a), b)) }
cat above is annotated because its type has two list arguments and List(Nat) -> List(Nat), the type of rev, is not built from it. A callee whose type is not among the goal's own is where an annotation is needed.
Eliminators and equations
A type with cases comes with its eliminator, the one program that holds the recursion for the type. It is derived from the type's cases, as the cases were derived from the type, so nothing is given beside the type. It takes a member and a handler per case. Definitions written with it have no recursion of their own, and each is a single run:
count_down := eliminator(Nat)
sum : Nat -> Nat -> Nat := {a, b} => count_down(a, b, {_k, r} => succ(r))
product : Nat -> Nat -> Nat := {a, b} => count_down(a, 0, {_k, r} => sum(b, r))
square : Nat -> Nat := {k} => product(k, k)
ackermann : Nat -> Nat -> Nat := {m} => count_down(m, succ, {_k, f, n} => count_down(n, f(1), {_j, r} => f(r)))
Compare times above, which needed a guess for plus, and squaring it, which needs an annotation. On an unknown number the eliminator cannot run, so the run keeps that use as a stuck term, and the check reads it by its type, like any other call nobody can run. The eliminator's type is its own statement: what is eliminated is a member, and each handler takes its case's pieces, and the answer below each piece of the type, into the result type. That statement is case split and induction, applied to a part of the program, and the same recursion written out plainly is Proved at it (fold_statement, lib/theories/types.test.disp). A handler such as {_k, r} => succ(r) is judged as a function: it is run on a fresh piece of its domain and split where it looks. The result type is the one expected where the use stands, a number in sum and a function in the outer use in ackermann.
The result type may depend on what is eliminated, which is what a proof by induction needs. And an equation computes by shape: where both sides are known they must agree, so succ(a) = succ(b) is a = b. Together these prove n + 0 = n, with the step's hypothesis as its own proof:
sum_zero : {n : Nat} -> Eq(sum(n, 0), n) := {n} => count_down(n, t, {_k, ih} => ih)
zero_sum : {n : Nat} -> Eq(n, sum(n, 0)) := {n} => cast(sum_zero(n), t)
At zero both sides run to zero. At a successor the goal runs to the hypothesis's own equation. The second line uses an equation already Proved: cast(e, d) is d, at the type with the two sides of e put one for the other. It is equality's own eliminator, and the equality type says what d must be (lib/theories/types.disp). The rewritten goal runs again, so a side that was stuck on what was replaced goes on. The same proof of a false equation is refuted with a number, and a proof that eliminates nothing stays Open.
An equation is at a type, and the type says what equal means there. Eq is the same tree. EqAt(A, x, y) asks A: at a function type the two are equal on every argument, so the equation is itself a function type and a proof by induction proves it; at a quotient their normal forms are equal. An equation over two arguments is then one between two programs, and adding is commutative from the two equations before it:
sum_succ : EqAt(Nat -> Nat -> Nat, {a, b} => sum(a, succ(b)), {a, b} => succ(sum(a, b))) := {n, _m} => count_down(n, t, {_k, ih} => ih)
sum_swap : EqAt(Nat -> Nat -> Nat, {a, b} => sum(a, b), {a, b} => sum(b, a)) := {n, m} => count_down(n, cast(sum_zero(m), t), {k, ih} => cast(sum_succ(m, k), cast(ih, t)))
Settings, and what Open means at load
A module picks how it is checked by binding check_module itself:
check_module := check_with{ on_open := "assume" }
The settings are the search's budgets, depth and fuel, and what an Open definition does. No setting can produce a wrong verdict: every counterexample is re-run, and Proved needs the search to run out of cases, so a budget only moves a verdict between Open and an answer. The default rejects an Open definition. With on_open := "assume" it loads with a note, and stands as a lemma; a later definition Proved with lemmas while an assumption stands is reported as resting on it. A refuted definition fails either way.
13. Glossary
| word | meaning here |
|---|---|
| relation of a type | the two-argument program that says whether two trees count as the same at that type; symmetric and transitive, reflexive only on members |
| member | a tree the type's relation says is the same as itself |
| recognizer | the one-argument program that decides membership for a data type; the relation's diagonal |
| generator | the stream of a type's members, smallest first; for a recognizer it is its derived cases, unfolded |
| refuter | the type's relation run over the generator; the honest check |
| piece | a placeholder for "some member, unnamed": a piece of the challenge, with a type, a root and a path |
| Need, Stuck | a run that wants a piece's shape (a split can help) versus one that cannot proceed (with a reason) |
| licence | the check that a recursive call is on a strictly smaller, input-derived piece |
| neutral term | an application nobody can run, kept as a term so it can be compared and judged at its codomain |
| eliminator | the one program that holds a type's recursion, derived from the type's cases; a use of it that cannot run is read by its type, which is its own statement with the result type read off the goal |
| certificate | the replayable record behind a Proved: which trick, which cases, which licences |
| the code type | Tree: every tree belongs, sameness is bit for bit, inspection is legal |
Companion files, all run by npm test: lib/confirm.disp (the confirmer), lib/rules.disp (the rules a certified verdict stands on, as lenses), lib/tests/refuter.test.disp (the honest checker, 22 tests), lib/tests/confirmer.test.disp (the shortcuts, 189 tests), lib/tests/types_doc.test.disp (this page's snippets, 31 tests), lib/theories/checked.test.disp with checked_example.disp (section 12's module), test/checked.test.ts (its rejections and settings).
Step-through: JUDGE.html runs judge case by case on ten small definitions, from recorded traces, and shows the two places a run needs a lemma.