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

Proofs

Implemented (plan/FINISHED/V5_PROOF.md). fol code check and fol code build check every theorem of a package and its dependencies with a kernel that implements Lean 4’s type theory. Every proof in this chapter is checked by the book audit.

FOL has a prover in the style of Lean. Propositions are types, proofs are terms, tactics build terms, and a small kernel checks every term. fol code check rejects a program whose proofs do not check and prints the goal that is left. Proofs, propositions, and proof-only definitions are erased before lowering, so they cost nothing at run time: a program emits byte-identical Rust with and without them.

Three modes

ModeDeclarationsReaches the backendMay call
execfun, pro, log, typ, var, conyesexec only
ghostfun[gho], typ[gho], log[gho]noghost, and reflectable exec fun
proofthmnoghost, and exec fun (reflected)

Executable code that names a ghost or proof declaration is error V1001. Ghost and proof declarations are never compiled; they exist for the checker alone.

Declarations

A ghost type with constructor fields is an inductive type, and it may be recursive because it has no memory layout. A ghost fun is total and expression-bodied; recursion on a constructor field is structural, and any other recursion takes a measure, fun[gho, dec = m]. A ghost log is an inductive predicate whose clauses are its constructors, named by label =>.

typ[gho] lst(T): ent = {
    con nil;
    con cons(head: T, tail: lst[T]);
};

fun[gho] len(T)(xs: lst[T]): nat = when(xs) {
    is nil -> 0;
    is cons(_, tail) -> len(tail) + 1;
};

log[gho] even(n: nat) = {
    zero => n == 0;
    step => exi k: nat, n == k + 2 and even(k);
};

A theorem states a proposition and proves it:

thm[exp] even_four: even(4) = prf {
    app even::step;
    app even::step;
    app even::zero;
};

Its generic parameters and value parameters are universally quantified. prp is the sort of propositions, nat the unbounded naturals, and big the unbounded integers; all three exist only in proofs. thm[axm] states a proposition without proof; it is the only way to skip one, and fol code check reports every theorem that rests on it.

A ghost body names other declarations by path, the prelude’s included, as a theorem statement does; a path that nothing declares is V1007:

fun[gho] magnitude(x: big): nat = big::nat_abs(x);

thm magnitude_neg: magnitude(-3) == 3 = prf { evl; };

Propositions

Propositions reuse the expression grammar and add three looser levels on top:

Level, loosest firstFormAssociativity
binderall x: T, P and exi x: T, Pthe body extends as far right as possible
iffP <-> Qnone
implicationP -> Qright
the expression ladderor, xor, and, not, comparisons, arithmeticas today

In a proposition == is equality at any type and != its negation. Source is ASCII only; editors may render all as ∀, exi as ∃, and -> as →.

Tactics

A proof block prf { ... } is a list of tactic statements. Every tactic has one shape, a name followed by optional options and arguments, and the names are looked up in a registry rather than reserved, so app, fix, and gen stay ordinary identifiers outside prf.

thm[exp] zero_add(n: nat): 0 + n == n = prf {
    ind n {
        is zero -> rfl;
        is succ(k, ih) -> { rew nat::add_succ, ih; };
    };
};

thm[exp] and_swap(p, q: prp): p and q -> q and p = prf {
    fix h;
    cas h { is intro(hp, hq) -> { ctr; qed hq; qed hp; }; };
};

In ind arms the hypothesis comes after the constructor fields. An argument can also bind a name: hav h: P = t adds the proof t of P as h, hav h: P opens P as a new goal first, gen x = e names a term, and ind h, odd = fun(n: big): prp => ... gives the motive of another member of a mutual block (see Logicals in proofs).

thm[exp] modus(p, q: prp): p -> (p -> q) -> q = prf {
    fix hp, hpq;
    hav hq: q = hpq(hp);
    qed hq;
};

The set is three-letter throughout: fix (intro), qed (exact), app (apply), rfl, rew (rewrite), unf (unfold), cas (cases), ind (induction), ctr (constructor), lft, rgt, wit (exists), hav (have), shw (show), exf (exfalso), abs (contradiction), asm (assumption), trv, spc, gen, rvt, spl, and the automation tier smp (simp), lia (linear arithmetic over nat, big, and int), evl (decide), and clc (calc).

lia reasons over the integers, not only over the rationals. Before and during its elimination it divides each constraint by the gcd of its coefficients and rounds the constant toward feasibility, so an equality whose constant the gcd does not divide is refuted at once, and parity and divisibility facts are in reach:

thm no_half(n: nat): n + n != 1 = prf { lia; };

thm third(x: int): 3 * x == 6 -> x == 2 = prf { lia; };

It does not split on the values a variable can take, as the Omega test’s dark and grey shadows do. A system with no integer solution that only such a split shows is out of reach: 27 <= 11 * x + 13 * y, 11 * x + 13 * y <= 45, 9 * y <= 7 * x + 10, and 7 * x <= 9 * y + 4 over nat.

Calculation chains

clc proves a goal from a chain of steps a R1 b, b R2 c, ..., y Rn z, each relation one of ==, <=, and < over nat, big, or int, where every step starts where the one before it ends. The steps compose by transitivity: the chain is < when any step is, <= when any step is an order, and == otherwise. A goal the chain implies without spelling it, such as a <= z from a < chain, is closed by lia from the chain. Each step is justified by the first of rfl, asm, lia, and smp that closes it:

thm le_chain(a, b, c, d: nat): a <= b -> b <= c -> c < d -> a < d = prf {
    fix hab, hbc, hcd;
    clc a <= b, b <= c, c < d;
};

thm int_chain(x, y: int): x <= y -> x < y + 2 = prf {
    fix h;
    clc x <= y, y < y + 2;
};

An arm names a step by its number, from 1, and justifies it with its own tactics; the other steps stay automatic:

thm by_steps(a, b, c: nat): a == b -> b <= c -> a <= c = prf {
    fix hab, hbc;
    clc a == b, b <= c {
        is 1 -> qed hab;
        is 2 -> { qed hbc; };
    };
};

A step that nothing justifies is V1004 at that step, with its goal:

tactic `clc` failed in `gap`: no tactic among `rfl`, `asm`, `lia`, and `smp`
proves the step `b <= c`; justify it with an arm `is <step> -> { ... };`
    a, b, c: nat
    hab: a <= b
    |- b <= c

Theorems about exec code

A theorem may name an exec fun. The checker reflects it from the same lowered code the backend compiles, so the proof is about the program that ships. A call has three outcomes: it returns, it reports an error, or it breaks (overflow, division by zero, an index out of bounds, assert, panic). An atomic proposition over calls says every call returns and the relation holds of the results; .ret(f(x)), .brk(f(x)), and .rpt(f(x), e) state an outcome directly.

fun[exp] half_sum(a, b: int): int = {
    return (a + b) / 2;
};

thm half_sum_breaks: .brk(half_sum(9223372036854775807, 1)) = prf { evl; };

thm half_sum_le(a, b: int): 0 <= a and a <= b and b <= 1000000 -> half_sum(a, b) <= b = prf {
    fix h;
    unf half_sum;
    lia;
};

The upper bound on b is needed: without it a + b can overflow, and half_sum breaks instead of returning. In a proposition, arithmetic on int is exact; only the reflected exec code is checked.

A loop in a reflected routine needs a termination measure into nat that falls on every iteration, written loop[dec = m]. The measure is proof-only and erased like every ghost; lia proves that it falls when the routine is reflected, and the error shows the goal when it cannot.

fun[exp] count_up(n: int): int = {
    var[mut] i: int = 0;
    loop[dec = big::nat_abs(n - i)](i < n) {
        i = i + 1;
    };
    return i;
};

thm count_three: count_up(3) == 3 = prf { evl; };

A reflected loop is also named in proofs, as count_up::loop0, so a property of every input is proven by induction over the loop. The showcase test/apps/showcases/proven_nums proves this way that std::nums::clamp_int stays in range, that std::nums::sign_int matches the sign, and that std::nums::gcd is never negative when its inputs’ .abs fit.

A routine that cannot be reflected (a pro, an effect, flt, recursion, a loop without a measure) is error V1003 when a theorem names it. A receiver routine is reflected like any other, with the receiver as its first parameter, so x.m(y) in a proposition is the routine T::m of x’s type T.

Reflected values are bol, every integer width, chr, str, records, opt, and vec, arr, and seq, which are lists. A width’s value is a big with the width’s range as hypotheses, and its arithmetic breaks outside that range: i8 from -128 to 127, u64 from 0 to 18446744073709551615, and int[arch] and int[uarch] at the 64 bits of every certified target. .widen reflects, and so does .narrow from a width int holds, which reports the value as an int. In a proposition, arithmetic on every width is exact.

fun[exp] add_bytes(a, b: i8): i8 = {
    return a + b;
};

thm add_bytes_fits: add_bytes(100, 27) == 127 = prf { evl; };

thm add_bytes_breaks: .brk(add_bytes(100, 28)) = prf { evl; };

thm byte_range(a: u8): a <= 255 = prf { lia; };

A chr compares by its code point, which .chr_to_int reads, and .len of a str counts its UTF-8 bytes, as the compiled program does. A block that several branches reach outside every loop is reflected once and shared, so a reflected routine grows with its code, not with its paths.

fun[exp] tally(word: str): int = {
    if (word == "") {
        return 0;
    } else {
    };
    return .len(word);
};

thm tally_two: tally("ab") == 2 = prf { evl; };

Lawful standards

A standard may state laws: thm members about its required routines and the conforming type, which a law calls self, the way the required routines have an implicit receiver. Every type that claims the standard takes on each law as a proof obligation. It proves the law with a receiver theorem, thm (T)law, whose statement must be the law with self and the standard’s parameters instantiated at T; a law may also carry a default proof, which is checked at each type that writes none.

std ordered(T): pro = {
    fun le(other: T): bol;
    thm refl: self.le(self) = prf {
        unf le;
        lia;
    };
    thm total(b: T): self.le(b) or b.le(self);
};

typ Money()(ordered[Money]): rec = {
    var cents: int;
};

fun (Money)le(other: Money): bol = {
    return self.cents <= other.cents;
};

thm (Money)total(b: Money): self.le(b) or b.le(self) = prf {
    unf le;
    lia;
};

Each obligation ends as the kernel theorem Money::ordered::total, whose type is the law at Money and whose value is the proof, so the kernel itself checks that the proof states the law. Inside thm (Money)..., and in a default proof, the names of Money’s receiver routines resolve directly, which is why unf le works. A law that is false for the type fails its proof with the goal, like any theorem.

A law with neither a receiver theorem nor a default proof is tried automatically: first smp over the type’s routines the law names, then lia with those routines unfolded. When neither closes it, the claim is V1008, and the message names the tactics that were tried; a proof of a different statement is V1008 as well.

std tallied: pro = {
    fun tally(): int;
    thm capped: self.tally() <= 9;
};

typ Vote()(tallied): rec = {
    var yes: int;
};

fun (Vote)tally(): int = {
    return 2;
};

A required routine may come with a default body in the standard. A type that writes no routine of its own takes the default, and the prover reflects the default body as that type’s routine, T::m, with the type’s value as its first parameter, so laws and theorems read x.m() the same way for either.

When two standards a type claims state laws of the same name, thm (T)law would be ambiguous, so each is proved by its qualified name thm (T)S::law. The qualified name is accepted without a clash too.

std short: pro = {
    fun width(): int;
    thm fits: self.width() <= 10;
};

std rounded: pro = {
    fun twice(): int;
    thm fits: self.twice() % 2 == 0;
};

typ Label()(short, rounded): rec = {
    var text: str;
};

fun (Label)width(): int = {
    return 4;
};

fun (Label)twice(): int = {
    return 8;
};

thm (Label)short::fits: self.width() <= 10 = prf {
    unf width;
    lia;
};

thm (Label)rounded::fits: self.twice() % 2 == 0 = prf {
    unf twice;
    evl;
};

A law may take generics of its own, thm order(U: ord)(a, b: U): ..., and the receiver theorem that proves it declares the same generics.

A lawful standard bounds a theorem’s generic parameter like ord does. T: S brings S’s required routines and laws into the theorem: x.m(..) on a value of T is S’s routine, and the law S::law is a hypothesis about T. A type whose every law is certified gets an instance of S, so the theorem applies to it. A standard whose parameter is the conforming type itself, as ordered(T) is when Money claims ordered[Money], bounds as X: ordered[X].

thm le_self(X: ordered[X])(a: X): a.le(a) = prf {
    qed ordered::refl(a);
};

thm money_le_self(m: Money): m.le(m) = prf {
    qed le_self(m);
};

The built-in ord and eq are lawful. A T: ord bound carries the proofs that <= is reflexive (ord::refl), antisymmetric (ord::antisymm), transitive (ord::trans), and total (ord::total); a T: eq bound carries the proofs that its boolean equality eqs::beq is reflexive, symmetric, and transitive (eqs::refl, eqs::symm, eqs::trans). The laws are proven once, for nat, big, every integer width, bol, chr, and str, and <= on bol (false below true), chr (by code point), and str (lexicographic by code point) uses them.

thm le_both(T: ord)(a, b: T): a <= b -> b <= a -> a == b = prf {
    fix h1, h2;
    qed ord::antisymm(a, b, h1, h2);
};

thm chr_total(a, b: chr): a <= b or b <= a = prf {
    qed ord::total(a, b);
};

thm str_trans(a, b, c: str): a <= b -> b <= c -> a <= c = prf {
    fix h1, h2;
    qed ord::trans(a, b, c, h1, h2);
};

thm u16_total(a, b: u16): a <= b or b <= a = prf {
    qed ord::total(a, b);
};

Generic types

A generic record is one kernel structure over its generics: typ Shelf(T) is ns::Shelf, and Shelf[int] in a proposition is that structure at int. A generic receiver routine, fun (Shelf[T])room(T)(), is reflected once for every T at ns::Shelf::room, with the generics as its leading arguments, so s.room() on a Shelf[int] is Shelf::room at int and unf Shelf::room opens it. Each instance the program monomorphizes is also reflected from the code the binary runs, at ns::Shelf[int]::room, its type arguments spelled as FOL types (Pair[int, str], Shelf[vec[int]]). The kernel checks that the instance is the generic routine at those arguments, so a reflected caller of the instance reads as the generic routine and the same unf proves facts about it.

A generic type that claims a lawful standard, typ Shelf(T)(S), proves each law once for every T: with a receiver theorem over the generic receiver, thm (Shelf[T])law(T)(..), which declares the type’s generics before the law’s own (thm (Shelf[T])order(T; U: ord)(a, b: U)), by the law’s default proof, or automatically. The certificate Shelf::S::law is the law at Shelf[T] for every T, and Shelf::S::inst is an instance of S at every Shelf[T], so a theorem bounded by X: S applies at any instance. Each instance the program uses, Shelf[int], also gets its certificates Shelf[int]::S::law and its instance Shelf[int]::S::inst, built from the instance’s own routines. A law that is false for the generic type fails its receiver theorem with the goal.

std roomy: pro = {
    fun room(): int;
    thm spare: self.room() >= 0;
};

typ Shelf(T)(roomy): rec = {
    var top: T;
    var slots: int;
};

fun (Shelf[T])room(T)(): int = {
    if (self.slots < 0) {
        return 0;
    } else {
    };
    return self.slots;
};

thm (Shelf[T])spare(T)(): self.room() >= 0 = prf {
    unf room;
    lia;
};

thm room_spare(X: roomy)(s: X): s.room() >= 0 = prf {
    qed roomy::spare(s);
};

thm shelf_room(s: Shelf[str]): s.room() >= 0 = prf {
    qed room_spare(s);
};

fun shelf_slots(s: Shelf[int]): int = {
    return s.room();
};

thm shelf_slots_exact(s: Shelf[int]): s.slots >= 0 -> shelf_slots(s) == s.slots = prf {
    fix h;
    unf shelf_slots, Shelf::room;
    lia;
};

A generic receiver routine is reflected for every T only when its body never needs an operation of its generic type: a routine that calls a bound’s routine on a value of that type is reflected per instance only, and a proposition that calls it is V1003. A generic parameter that no field mentions does not tell two instances apart in the compiled program, so they share one reflected instance.

Checking

fol code check and fol code build run the prover after lowering. Verdicts are cached per declaration in .fol/build/proof/, keyed by a fingerprint of the declaration and everything it mentions, including the reflected routines and, transitively, the routines they call, so a changed callee proves its callers’ theorems again. Cache replay elaborates the source statement, matches its declaration kind, universe parameters and kernel type, then kernel-checks the cached proof. Malformed or mismatched entries fall back to the source proof. Entries with auxiliary declarations also re-run the proof instead of importing names that are not bound to a source declaration. --recheck ignores the cache.

CodeMeaning
V1001exec code names a ghost or proof declaration
V1002goals are left when the proof ends; they are printed in FOL syntax
V1003a named exec routine cannot be reflected, or a named exec logical has no rule program the prover can read
V1004a tactic failed; the goal before it is printed
V1005fuel ran out; raise one theorem’s limit with thm[lim = N]
V1006a ghost inductive is not strictly positive, or its universes do not fit
V1007a statement or definition is ill-formed
V1008a type claims a standard but does not prove one of its laws
V9001the kernel refused an elaborated term, which is a prover bug

Each has a fol code explain entry with a failing and a fixed example. Limits are step counts, never time, so the verdict is the same on every machine.

fol tool proof axioms <theorem> lists every axiom a theorem rests on, fol tool proof show <routine> prints a routine’s reflected definition, and fol tool proof goals <file>:<line>:<col> prints the goals in front of the tactic at a position. The language server answers the same question through the fol/goals request.

Logicals in proofs

fol code check mounts the checked rule program of every package in the prover, dependencies first, so a theorem names a log or a con relation by its path, an imported package’s included. A rule that reads a dependency’s relation names the dependency’s own predicate, and evl takes that relation’s tuples and closed world from the dependency’s program. A con relation is decidable membership in its tuples. An executable log is an inductive predicate: each clause is a constructor, named by its label or, when it has none, c0, c1, … in order; the alternatives of a labelled clause that or splits are <label>_1, <label>_2, … in source order. Its exi variables and one proof per conjunct are the constructor’s arguments. Integer columns are big in the prover, str columns are strings, and bol and chr columns are booleans and characters.

evl decides a ground query in both directions. The logicals engine answers it, and the answer becomes a term the kernel checks: a derivation becomes constructor applications, and an absent tuple is refuted by a case split over the finite closed world. The engine is never trusted, so a wrong answer can make evl fail but cannot prove a false query.

con parent: rel[str, str] = { { "albert", "bob" }, { "bob", "carl" } };

log grandparent(g, c: str) = {
    via => exi p: str, parent(g, p) and parent(p, c);
};

thm carl: grandparent("albert", "carl") = prf { evl; };

thm not_reverse: not grandparent("carl", "albert") = prf { evl; };

A relation parameter is a parameter of the predicate, so a theorem over it holds for every fact base. cas takes a derivation apart clause by clause, and ind is induction over the derivations of a recursive log:

log dating(likes: rel[str, str]; a, b: str) = {
    duo => likes(a, b) and likes(b, a);
};

thm dating_sym(likes: rel[str, str]; a, b: str):
    dating(likes, a, b) -> dating(likes, b, a) = prf {
    fix h;
    cas h { is duo(ab, ba) -> { ctr; qed ba; qed ab; }; };
};

log reach(edges: rel[int, int]; a, b: int) = {
    base => edges(a, b);
    step => exi m: int, edges(a, m) and reach(edges, m, b);
};

thm reach_trans(edges: rel[int, int]; a, b, c: big):
    reach(edges, a, b) -> reach(edges, b, c) -> reach(edges, a, c) = prf {
    fix h1, h2;
    ind h1 {
        is base(x, y, e) -> { qed reach::step(x, c, y, e, h2); };
        is step(x, y, m, e, r, ih) -> { qed reach::step(x, c, m, e, ih(h2)); };
    };
};

con edge: rel[int, int] = { { 1, 2 }, { 2, 3 }, { 3, 4 } };

thm one_four: reach(edge, 1, 4) = prf { evl; };

thm not_four_one: not reach(edge, 4, 1) = prf { evl; };

In the ind arms each constructor’s fields come first, then the induction hypothesis for each recursive premise.

A labelled clause that or splits is one constructor per alternative, and cas names each:

con road: rel[str, str] = { { "ur", "kish" } };
con ferry: rel[str, str] = { { "kish", "lagash" } };

log link(a, b: str) = {
    way => road(a, b) or ferry(a, b);
};

thm link_is_a_way(a, b: str): link(a, b) -> road(a, b) or ferry(a, b) = prf {
    fix h;
    cas h {
        is way_1(r) -> { lft; qed r; };
        is way_2(f) -> { rgt; qed f; };
    };
};

A relation literal can stand for a relation argument. It is an anonymous fact table, built as a con relation is, so evl decides queries over it in both directions. Its tuples are constants; a tuple that names a variable is V1007.

thm lit_reach: reach({ { 1, 2 }, { 2, 3 } }, 1, 3) = prf { evl; };

thm lit_not_reach: not reach({ { 1, 2 } }, 2, 1) = prf { evl; };

Rule sets that name each other form one mutual block. cas takes a member apart clause by clause, as it does any log. ind on a member also proves a property of every member the induction reaches, so it takes a motive for each of them by name, a predicate over that member’s columns, and has an arm for every clause of each. A bare constructor name is the major premise’s own; another member’s constructor is named by its path. A member the motives leave out is V1004, with the block and the motive it needs.

con rung: rel[int, int] = { { 0, 1 }, { 1, 2 }, { 2, 3 } };
con ground: rel[int] = { 0 };

log climb(n: int) = {
    base => ground(n);
    up => exi m: int, rung(m, n) and climb(m);
};

log even_rung(n: int) = {
    base => ground(n);
    up => exi m: int, rung(m, n) and odd_rung(m);
};

log odd_rung(n: int) = {
    up => exi m: int, rung(m, n) and even_rung(m);
};

thm odd_steps(n: big): odd_rung(n) -> exi m: big, rung(m, n) = prf {
    fix h;
    cas h { is up(k, m, r, e) -> { wit m; }; };
};

thm even_climbs(n: big): even_rung(n) -> climb(n) = prf {
    fix h;
    ind h, odd_rung = fun(k: big): prp => climb(k) {
        is base(k, g) -> { qed climb::base(k, g); };
        is up(k, m, r, o, ih) -> { qed climb::up(k, m, r, ih); };
        is odd_rung::up(k, m, r, e, ih) -> { qed climb::up(k, m, r, ih); };
    };
};

A clause may call an exec fun. The prover reflects it from the lowered code, as for any theorem that names it, and models the call as the value it returns where it returns; where it breaks, the comparison is false. The compiled query reads the call the same way, in every build profile, so a theorem about the relation holds of every run. The engine evaluates the same reflected definition, and the kernel re-checks every answer:

fun[exp] triple(n: int): int = {
    return n * 3;
};

con seeds: rel[int] = { 1, 2 };

log tripled(n, m: int) = {
    seeds(n) and m == triple(n);
};

thm two_six: tripled(2, 6) = prf { evl; };

thm not_two_five: not tripled(2, 5) = prf { evl; };

A fun that returns opt[T] is modelled at T: the value where it returns one, and a false comparison where it returns nil, as in the compiled query.

fun[exp] third_of(n: int): opt[int] = {
    if (n % 3 == 0) {
        return n / 3;
    };
    return nil;
};

con counts: rel[int] = { 3, 4 };

log thirds(n, m: int) = {
    counts(n) and m == third_of(n);
};

thm three_one: thirds(3, 1) = prf { evl; };

thm four_none: not thirds(4, 1) and not thirds(4, 0) = prf { evl; };

What the bridge does not cover:

  • a clause cannot call a fun that is not reflectable; it is V1003 with the reason;
  • ind on a member of a mutual block does not infer the motives of the members it reaches, and each is given by name;
  • the engine reads a relation literal at the column types of the parameter it is passed to, so a value outside them makes evl fail.

The showcase test/apps/showcases/proven_logic proves ground queries over a family tree, a negated rule, reachability with transitivity for every edge relation, and a clause that calls exec code.

What is trusted

Only the kernel, and the one translator that reflects lowered exec code into the logic, which a differential harness checks against the compiled program: on the same inputs, the outcome and the value returned or reported must be equal. The elaborator, the tactics, and the automation can fail to find a proof but can never admit a false one, because every theorem ends as a term the kernel checks. There is no way to leave a hole: the only skip is thm[axm], which is always reported.