How-to Guides

Writing proofs with Session

For a first introduction to formal proofs, follow the tutorial sequence. This guide is the broader tour to return to when you want to find a particular proof operation.

Session provides the implemented higher-level proof API. Import it from judgment; the existing judgment_shell imports and kernel-facing library interfaces remain available. This surface constructs typed symbolic expressions and checks explicit proofs. Global mathematical assumptions require an explicit axiom declaration or labeled admit; there is no automatic simplifier.

Quick start

Follow these three complete programs in order. Each includes its command and expected output. Run pixi run build once from the repository root to prepare the library and its pinned dependencies, then use the commands beneath the examples.

1. State a goal and supply its proof

Declare the statement with theorem, introduce its premise with intro, and compose the facts needed by exact:

Mojo

quick_start_goal.mojo Download
"""Complete a goal-first proof by composing checked facts directly."""

from judgment import Session, implies


def main() raises:
    var s = Session()
    var P = s.prop("P")
    var Q = s.prop("Q")

    var proof = s.theorem("swap", implies(P & Q, Q & P))
    var h = proof.intro("h")
    proof.exact(proof.conjoin(proof.right(h), proof.left(h)))
    var theorem = proof.finish()
    print(theorem)

Run from the repository root pixi run core-run docs/examples/library/quick_start_goal.mojo

Output

⊢ P ∧ Q → Q ∧ P

Python

quick_start_goal.py Download
"""Complete a goal-first proof by composing checked facts directly."""

from judgment import Session, implies


def main():
    s = Session()
    P = s.prop("P")
    Q = s.prop("Q")

    proof = s.theorem("swap", implies(P & Q, Q & P))
    h = proof.intro("h")
    proof.exact(proof.conjoin(proof.right(h), proof.left(h)))
    theorem = proof.finish()
    print(theorem)


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/quick_start_goal.py

Output

⊢ P ∧ Q → Q ∧ P

right(h) proves Q, left(h) proves P, and conjoin proves Q & P. finish() checks the declared statement and registers swap, available later as s.fact("swap"). The symbols P and Q are proposition constants; declaring them asserts neither proposition. For arbitrary parameters, use a theorem header, as in the calculation below.

Direct composition keeps this derivation in one exact call. When branches need several steps of their own, use split and named selection.

2. Rewrite only the part that changes

== constructs symbolic equality. Select a side with lhs() or rhs(), then use at to identify a subexpression. Here the premise P == Q justifies changing the second P beneath a negation:

Mojo

targeted_rewrite.mojo Download
"""Rewrite one occurrence in a nested expression using explicit evidence."""

from std.testing import assert_true
from judgment import Session, implies


def main() raises:
    var s = Session()
    var P = s.prop("P")
    var Q = s.prop("Q")
    var R = s.prop("R")
    var before = (~P & R) | (~P & R)
    var after = (~P & R) | (~Q & R)
    var target = implies(P == Q, before == after)
    var proof = s.theorem("rewrite_second", target)
    var h = proof.intro("h")

    _ = proof.lhs().at(P, occurrence=2).to(Q, using=h)
    proof.rfl()
    var theorem = proof.finish()
    assert_true(theorem.statement().same_as(target))
    print(theorem)

Run from the repository root pixi run core-run docs/examples/library/targeted_rewrite.mojo

Output

⊢ P = Q → (¬P ∧ R ∨ ¬P ∧ R) = (¬P ∧ R ∨ ¬Q ∧ R)

Python

targeted_rewrite.py Download
"""Rewrite one occurrence in a nested expression using explicit evidence."""

from judgment import Session, implies


def main():
    s = Session()
    P = s.prop("P")
    Q = s.prop("Q")
    R = s.prop("R")
    before = (~P & R) | (~P & R)
    after = (~P & R) | (~Q & R)
    target = implies(P == Q, before == after)
    proof = s.theorem("rewrite_second", target)
    h = proof.intro("h")

    _ = proof.lhs().at(P, occurrence=2).to(Q, using=h)
    proof.rfl()
    theorem = proof.finish()
    assert theorem.statement().same_as(target)
    print(theorem)


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/targeted_rewrite.py

Output

⊢ P = Q → (¬P ∧ R ∨ ¬P ∧ R) = (¬P ∧ R ∨ ¬Q ∧ R)

occurrence=2 counts matching occurrences from one within the selected side. Only that occurrence changes; the rewrite step needs no copy of the surrounding formula. to(Q, using=h) states both the replacement and its reason. The shorter rw(h) at the same focus takes the replacement from the equality fact. rfl() closes the resulting equality of identical sides, and finish() returns a proof of the original statement.

Use change for a definitionally equal presentation and unfold to expand a chosen definition. Algebraic laws need explicit evidence with to or rw; see the rewrite guide for selection details. For exploratory steps, save a checkpoint and retry when a chosen occurrence does not lead to the proof you want.

3. Write a calculation with a reason for each step

A header declares arbitrary parameters and premises before goal fixes the conclusion. Here A is an arbitrary type; the equality proof needs no arithmetic structure or global axiom:

Mojo

quick_start_calculation.mojo Download
"""Prove an equality by stating each intermediate expression and its reason."""

from judgment import Session


def main() raises:
    var s = Session()
    var proof = s.theorem("transitivity")
    var A = proof.type_var("A")
    var values = proof.vars("a b c", A)
    var a, b, c = values[0], values[1], values[2]
    var ab = proof.given("ab", a == b)
    var bc = proof.given("bc", b == c)
    proof.goal(a == c)

    var chain = proof.calc(a)
    chain.eq(b, using=ab, label="ab")
    chain.eq(c, using=bc, label="bc")
    print(chain.format())
    proof.exact(chain.finish())
    print(proof.finish())

Run from the repository root pixi run core-run docs/examples/library/quick_start_calculation.mojo

Output

a
= b [ab: checked]
= c [bc: checked]
[A] ⊢ ∀a:A. ∀b:A. ∀c:A. a = b → b = c → a = c

Python

quick_start_calculation.py Download
"""Prove an equality by stating each intermediate expression and its reason."""

from judgment import Session


def main():
    s = Session()
    proof = s.theorem("transitivity")
    A = proof.type_var("A")
    values = proof.vars("a b c", A)
    a, b, c = values[0], values[1], values[2]
    ab = proof.given("ab", a == b)
    bc = proof.given("bc", b == c)
    proof.goal(a == c)

    chain = proof.calc(a)
    chain.eq(b, using=ab, label="ab")
    chain.eq(c, using=bc, label="bc")
    print(chain.format())
    proof.exact(chain.finish())
    print(proof.finish())


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/quick_start_calculation.py

Output

a
= b [ab: checked]
= c [bc: checked]
[A] ⊢ ∀a:A. ∀b:A. ∀c:A. a = b → b = c → a = c

Each eq gives the next expression and checked equality evidence. Keep the intermediate expressions you want a reader to see; label supplies optional text for the trace, while using supplies the actual reason. A calculation returns evidence with chain.finish(). Pass that evidence to proof.exact, then finish the enclosing theorem. Completion universally quantifies a, b, and c and discharges the two written premises.

For a definitional step, use chain.change(next, label="reason"). The longer algebra example expands a square this way; its distribution and collection steps still cite explicit laws.

Continue with algebra and its explicit law assumptions, or calculation steps proved later. An unfinished step, including one marked sorry, still blocks completion.

State the goal first

A named theorem records its expected conclusion before proof construction. intro introduces an implication or negation premise, split returns the two conjuncts or equivalence directions, and exact supplies evidence. finish checks every subgoal, reconstructs the original statement, and only then registers the theorem's name. lemma has the same semantics as theorem.

The second proof in this example uses the compact forward style: assume a proposition, derive a fact, and finish with that fact. Forward completion exports the actual dependency closure; goal-first completion preserves the exact declared statement, including unused premises.

Mojo

first_proof.mojo Download
"""Prove conjunction commutativity with a small session-owned API."""

from std.testing import assert_true
from judgment import Session, implies


def main() raises:
    var s = Session()
    var P = s.prop("P")
    var Q = s.prop("Q")
    var target = implies(P & Q, Q & P)

    var proof = s.theorem("and_swap", target)
    var h = proof.intro("h")
    _ = proof.split()
    var left = proof.select("left")
    left.exact(proof.right(h))
    var right = proof.select("right")
    right.exact(proof.left(h))
    var theorem = proof.finish()
    assert_true(theorem.statement().same_as(target))
    assert_true(s.fact("and_swap").statement().same_as(target))
    print(theorem)

    var forward = s.proof()
    var premise = forward.assume(P & Q)
    var swapped = forward.conjoin(forward.right(premise), forward.left(premise))
    var result = forward.finish(swapped)
    assert_true(result.statement().same_as(target))
    print(result)

Run from the repository root pixi run core-run docs/examples/library/first_proof.mojo

Output

⊢ P ∧ Q → Q ∧ P
⊢ P ∧ Q → Q ∧ P

Python

first_proof.py Download
"""Prove conjunction commutativity with a small session-owned API."""

from judgment import Session, implies


def main():
    s = Session()
    P = s.prop("P")
    Q = s.prop("Q")
    target = implies(P & Q, Q & P)

    proof = s.theorem("and_swap", target)
    h = proof.intro("h")
    _ = proof.split()
    left = proof.select("left")
    left.exact(proof.right(h))
    right = proof.select("right")
    right.exact(proof.left(h))
    theorem = proof.finish()
    assert theorem.statement().same_as(target)
    assert s.fact("and_swap").statement().same_as(target)
    print(theorem)

    forward = s.proof()
    premise = forward.assume(P & Q)
    swapped = forward.conjoin(forward.right(premise), forward.left(premise))
    result = forward.finish(swapped)
    assert result.statement().same_as(target)
    print(result)


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/first_proof.py

Output

⊢ P ∧ Q → Q ∧ P
⊢ P ∧ Q → Q ∧ P

After split, select the conjuncts by their structural names, "left" and "right", and keep a local handle for each branch you are proving. Selection returns a handle to an existing obligation. Complete the theorem with the original root's finish().

s.prop("P") declares a proposition symbol; it does not assert P. A theorem about these symbols concerns those declared constants. Use proof parameters for statements about arbitrary propositions or values.

s.true_() and s.false_() construct logical propositions, distinct from Mojo Booleans. proof.truth() supplies checked evidence of True; use proof.exact(proof.truth()) after introducing the premise of P → True. The unused premise remains in the declared theorem. false_elim(fact, target) derives a specified proposition only from visible checked evidence of False.

Negation and equivalence

On a goal ~P, intro("hp") supplies a scoped fact proving P and leaves False to prove. contradiction(negative, positive) constructs checked False evidence from matching facts for ~P and P. It performs no search for either fact. use(negative, using=[positive]) also eliminates the negation; applying a negative fact backward to a False goal exposes P as an explicit obligation.

On a goal iff(P, Q), split() returns P → Q and Q → P in that order. Select those directions by name with proof.select("forward") and proof.select("backward"). For an equivalence fact, left(fact) returns its forward implication and right(fact) its reverse implication. Both directions remain required, including a deferred one. Completion retains the original negation and equivalence syntax and checks the corresponding constructive derived rules. The intro and split tactic constructors support these connectives too.

Mojo

logical_proofs.mojo Download
"""Prove contraposition and equivalence symmetry with explicit logical steps."""

from std.testing import assert_equal, assert_true
from judgment import Session, iff, implies


def main() raises:
    var s = Session()
    var P = s.prop("P")
    var Q = s.prop("Q")
    var target = implies(implies(P, Q), implies(~Q, ~P))
    var proof = s.theorem("contraposition", target)
    var pq = proof.intro("pq")
    var nq = proof.intro("nq")
    var hp = proof.intro("hp")
    proof.exact(proof.contradiction(nq, proof.use(pq, using=[hp])))
    var theorem = proof.finish()
    assert_true(theorem.statement().same_as(target))
    assert_equal(len(theorem.axioms()), 0)
    print(theorem)

    var symmetry = s.theorem("iff_symmetry", implies(iff(P, Q), iff(Q, P)))
    var equivalence = symmetry.intro("equivalence")
    _ = symmetry.split()
    var forward = symmetry.select("forward")
    var backward = symmetry.select("backward")
    forward.exact(symmetry.right(equivalence))
    backward.sorry()
    print("Deferred directions:", len(symmetry.obligations()))
    backward = symmetry.select("backward")
    backward.resume()
    backward.exact(symmetry.left(equivalence))
    theorem = symmetry.finish()
    assert_equal(len(theorem.axioms()), 0)
    print(theorem)

Run from the repository root pixi run core-run docs/examples/library/logical_proofs.mojo

Output

⊢ (P → Q) → ¬Q → ¬P
Deferred directions: 1
⊢ (P ↔ Q) → (Q ↔ P)

Python

logical_proofs.py Download
"""Prove contraposition and equivalence symmetry with explicit logical steps."""

from judgment import Session, iff, implies


def main():
    s = Session()
    P = s.prop("P")
    Q = s.prop("Q")
    target = implies(implies(P, Q), implies(~Q, ~P))
    proof = s.theorem("contraposition", target)
    pq = proof.intro("pq")
    nq = proof.intro("nq")
    hp = proof.intro("hp")
    proof.exact(proof.contradiction(nq, proof.use(pq, using=[hp])))
    theorem = proof.finish()
    assert theorem.statement().same_as(target)
    assert len(theorem.axioms()) == 0
    print(theorem)

    symmetry = s.theorem("iff_symmetry", implies(iff(P, Q), iff(Q, P)))
    equivalence = symmetry.intro("equivalence")
    _ = symmetry.split()
    forward = symmetry.select("forward")
    backward = symmetry.select("backward")
    forward.exact(symmetry.right(equivalence))
    backward.sorry()
    print("Deferred directions:", len(symmetry.obligations()))
    backward = symmetry.select("backward")
    backward.resume()
    backward.exact(symmetry.left(equivalence))
    theorem = symmetry.finish()
    assert len(theorem.axioms()) == 0
    print(theorem)


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/logical_proofs.py

Output

⊢ (P → Q) → ¬Q → ¬P
Deferred directions: 1
⊢ (P ↔ Q) → (Q ↔ P)

These operations unfold only the logical definition required by the chosen rule. They do not add classical axioms, prove an arbitrary contradiction, or eliminate double negation automatically.

Types and theorem parameters

s.declare_type("Point") declares a particular opaque type. By contrast, proof.type_var("A") introduces an arbitrary, rigid type parameter for that proof. Two proofs declaring a parameter named A receive different identities. The built-in proposition type is s.prop_type(), and arrow(A, B) constructs a function type. These functions return TypeExpr values.

s.symbol(name, kind) declares a constant of a global type. proof.var(name, kind) introduces an arbitrary term parameter; it can use the proof's type parameters. proof.prop(name) is the corresponding shorthand for a proposition parameter. proof.vars("a b", kind) and proof.props("P Q") return ordered Lists, accessed by index in Mojo. Function expressions support calls such as f(a) and f(a, b); the kernel checks argument types.

Mojo can bind several names from a tuple expression. Use that syntax to keep batch declarations compact:

var values = proof.vars("a b", kind)
var a, b = values[0], values[1]

The batch still introduces both parameters atomically, in the written order. The second line binds Mojo names to the returned expressions; it introduces no additional proof parameters. The same pattern works with props, definition headers, and axiom headers. Subsequent assignments omit var when those Mojo names already exist.

Direct var a, b = proof.vars("a b", kind) is unsupported: Mojo cannot unpack a List, even when its runtime length is two. Separate proof.var calls also work, but each is a separate declaration; a later failure does not undo an earlier successful one. The batch API preserves ordered parameters and atomic validation.

Start a header with s.theorem(name) or s.lemma(name), add parameters and given premises, then fix the body with goal. This example proves function congruence using a selected argument rewrite:

Mojo

typed_proof.mojo Download
"""State a generic theorem with typed parameters and rewrite an argument."""

from std.testing import assert_true
from judgment import Session, arrow


def main() raises:
    var s = Session()
    var proof = s.theorem("congruence")
    var A = proof.type_var("A")
    var a = proof.var("a", A)
    var b = proof.var("b", A)
    var f = proof.var("f", arrow(A, A))
    var h = proof.given("h", a == b)
    proof.goal(f(a) == f(b))

    _ = proof.lhs().at(a).rw(h)
    proof.rfl()
    var theorem = proof.finish()
    assert_true(theorem.type_params()[0].same_as(A))
    assert_true(theorem.statement().format() == "∀a:A. ∀b:A. ∀f:(A → A). a = b → f(a) = f(b)")
    print(theorem)

Run from the repository root pixi run core-run docs/examples/library/typed_proof.mojo

Output

[A] ⊢ ∀a:A. ∀b:A. ∀f:(A → A). a = b → f(a) = f(b)

Python

typed_proof.py Download
"""State a generic theorem with typed parameters and rewrite an argument."""

from judgment import Session, arrow


def main():
    s = Session()
    proof = s.theorem("congruence")
    A = proof.type_var("A")
    a = proof.var("a", A)
    b = proof.var("b", A)
    f = proof.var("f", arrow(A, A))
    h = proof.given("h", a == b)
    proof.goal(f(a) == f(b))

    _ = proof.lhs().at(a).rw(h)
    proof.rfl()
    theorem = proof.finish()
    assert theorem.type_params()[0].same_as(A)
    assert theorem.statement().format() == "∀a:A. ∀b:A. ∀f:(A → A). a = b → f(a) = f(b)"
    print(theorem)


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/typed_proof.py

Output

[A] ⊢ ∀a:A. ∀b:A. ∀f:(A → A). a = b → f(a) = f(b)

goal freezes the header. Proof steps then operate on that body. finish universally quantifies each term parameter and discharges each header premise, in declaration order, retaining even unused parameters and premises. The exact closed statement is fixed when goal succeeds and checked on completion. Interleaving variables and premises preserves their nesting order.

Fact.type_params() retains the declared type parameter order, including unused types. Printing a generic theorem prefixes its statement with [A, ...]. s.fact(name) retains this metadata. Specialize a generic theorem with use before supplying it to exact. apply and focused rw can infer unambiguous arguments from the selected goal or occurrence and explicitly supplied premises.

Header names must be unique and cannot shadow visible session declarations. Prop is reserved for the built-in type. A proof starts in the session theory that exists at creation time; declare global types and constants before creating proofs that use them. A failed header operation leaves it retryable.

Forward proofs also accept type_var, var, and prop; they use assume for premises. Their completion generalizes the actual used term and hypothesis dependencies, plus parameters still present in the authored statement even when canonical computation erases them (such as the base of a zeroth power). Use a named theorem header and given when unused parameters or premises must remain in the stated theorem.

Quantified goals and witnesses

Use proof.bound_var(name, kind) for a variable that belongs to explicit quantified syntax, then forall(variable, body) or exists(variable, body). These constructors return propositions. They add no theorem parameters, assumptions, or evidence. In contrast, proof.var adds a header parameter that completion universally quantifies automatically.

Create syntax variables after the header parameters they reference. Variables created in the same selected context share a private construction context, so nested formulas can mention several of them. Their creation order does not fix their binding order. Every free syntax variable must be bound before a formula can be used as a goal, premise, or evidence, including occurrences erased by canonical computation. A template created before a later header variable or introduction does not become part of that later proof context; create a new template there when it needs to refer to the new local.

Mojo

quantified_proof.mojo Download
"""State quantified goals, introduce arbitrary variables, and supply witnesses."""

from judgment import Session, exists, forall


def main() raises:
    var s = Session()
    var proof = s.theorem("self_witness")
    var A = proof.type_var("A")
    var x = proof.bound_var("x", A)
    var y = proof.bound_var("y", A)
    proof.goal(forall(x, exists(y, y == x)))

    var a = proof.intro_var("a")
    proof.witness(a)
    print("Remaining goal:", proof.target().format())
    proof.rfl()
    var theorem = proof.finish()
    print(theorem)
    print("Axiom dependencies:", len(theorem.axioms()))

    var Point = s.declare_type("Point")
    var origin = s.symbol("origin", Point)
    var concrete = s.proof()
    print(concrete.finish(concrete.use(theorem, type_args=[Point], terms=[origin])))

Run from the repository root pixi run core-run docs/examples/library/quantified_proof.mojo

Output

Remaining goal: a = a
[A] ⊢ ∀x:A. ∃y:A. y = x
Axiom dependencies: 0
⊢ ∃y:Point. y = origin

Python

quantified_proof.py Download
"""State quantified goals, introduce arbitrary variables, and supply witnesses."""

from judgment import Session, exists, forall


def main():
    s = Session()
    proof = s.theorem("self_witness")
    A = proof.type_var("A")
    x = proof.bound_var("x", A)
    y = proof.bound_var("y", A)
    proof.goal(forall(x, exists(y, y == x)))

    a = proof.intro_var("a")
    proof.witness(a)
    print("Remaining goal:", proof.target().format())
    proof.rfl()
    theorem = proof.finish()
    print(theorem)
    print("Axiom dependencies:", len(theorem.axioms()))

    Point = s.declare_type("Point")
    origin = s.symbol("origin", Point)
    concrete = s.proof()
    print(concrete.finish(concrete.use(theorem, type_args=[Point], terms=[origin])))


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/quantified_proof.py

Output

Remaining goal: a = a
[A] ⊢ ∀x:A. ∃y:A. y = x
Axiom dependencies: 0
⊢ ∃y:Point. y = origin

intro_var(name) opens a universal goal and returns an arbitrary Expr fixed over the goal's frame. The selected target becomes the instantiated body. intro(name) continues to open an implication and return a Fact; separate methods keep both return types explicit in Mojo. Introduction never changes the original theorem statement. Completion retains explicit universal binders even when their variables are unused in the proof.

When a leading universal quantifier only introduces an arbitrary parameter, declare it once with proof.var in the header. This version of the same theorem omits the explicit forall and its separate intro_var step:

Mojo

compact_quantified_proof.mojo Download
"""Use a theorem parameter for a leading universal quantifier."""

from judgment import Session, exists


def main() raises:
    var s = Session()
    var proof = s.theorem("self_witness")
    var A = proof.type_var("A")
    var x = proof.var("x", A)
    var y = proof.bound_var("y", A)
    proof.goal(exists(y, y == x))

    proof.witness(x)
    proof.rfl()
    var theorem = proof.finish()
    print(theorem)
    print("Axiom dependencies:", len(theorem.axioms()))

Run from the repository root pixi run core-run docs/examples/library/compact_quantified_proof.mojo

Output

[A] ⊢ ∀x:A. ∃y:A. y = x
Axiom dependencies: 0

Python

compact_quantified_proof.py Download
"""Use a theorem parameter for a leading universal quantifier."""

from judgment import Session, exists


def main():
    s = Session()
    proof = s.theorem("self_witness")
    A = proof.type_var("A")
    x = proof.var("x", A)
    y = proof.bound_var("y", A)
    proof.goal(exists(y, y == x))

    proof.witness(x)
    proof.rfl()
    theorem = proof.finish()
    print(theorem)
    print("Axiom dependencies:", len(theorem.axioms()))


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/compact_quantified_proof.py

Output

[A] ⊢ ∀x:A. ∃y:A. y = x
Axiom dependencies: 0

finish() supplies the leading ∀x:A from the header. The existential still needs a syntax variable, a chosen witness, and evidence of its property. Keep the explicit quantified form when opening a goal supplied by another theorem, when the binder occurs inside another connective, or when teaching that proof step. Both versions here conclude [A] ⊢ ∀x:A. ∃y:A. y = x without global axioms.

witness(value) opens an existential goal by selecting a correctly typed value from the current context. It leaves the predicate at that value as a new proof obligation. Supplying a witness does not prove that predicate. A syntax template, a sibling branch's variable, or a later theory declaration cannot be used as a witness. Even unused witnesses are checked for type and scope.

These steps compose with intro, split, use, rw, change, and unfold. sorry still defers a goal and blocks completion; resume reactivates it. Each introduction and witness step validates its instantiated body against a kernel application before committing the new goal. finish reconstructs the original statement using universal introduction and the existing constructive existential derivation. Failed operations leave the selected goal, proof names, and publication state unchanged; consumed work is not refunded.

An introduced variable may reuse its template's name. Remaining binders are freshened when necessary to avoid capture, while the completed theorem retains its original requested display. Sibling branches may independently use the same name. Template names cannot shadow active parameters or session declarations; quantifier construction rechecks the current namespace and free displayed atoms so later declarations cannot make distinct expressions look identical.

use specializes outer universal quantifiers and implications; it preserves existential conclusions. Occurrence selection can select a whole quantifier, but its body remains opaque; open a universal goal before rewriting its body.

Use an existential fact

proof.obtain(existence, name="w") opens checked existential evidence and returns a pair: the fresh witness Expr and a Fact proving its property. The existing goal remains the conclusion to prove. property="hw" also names the property's assumption, so that fact("hw") finds it later, as a tactic needs. Use the witness and property in that goal or its descendants, including targeted rewrites, theorem application, and further obtain steps. For example, a witness of both predicates is also a witness of the first:

Mojo

obtaining_witnesses.mojo Download
"""Use an existential fact through its scoped witness and checked property."""

from judgment import Session, arrow, exists, implies


def main() raises:
    var s = Session()
    var proof = s.theorem("project_exists")
    var A = proof.type_var("A")
    var P = proof.var("P", arrow(A, s.prop_type()))
    var Q = proof.var("Q", arrow(A, s.prop_type()))
    var x = proof.bound_var("x", A)
    proof.goal(implies(exists(x, P(x) & Q(x)), exists(x, P(x))))

    var h = proof.intro()
    var (w, hw) = proof.obtain(h, "w")
    print("Witness:", w.format())
    print("Its property:", hw.statement().format())
    proof.witness(w)
    proof.exact(proof.left(hw))

    var theorem = proof.finish()
    print(theorem)
    print("Axiom dependencies:", len(theorem.axioms()))

Run from the repository root pixi run core-run docs/examples/library/obtaining_witnesses.mojo

Output

Witness: w
Its property: P(w) ∧ Q(w)
[A] ⊢ ∀P:(A → Prop). ∀Q:(A → Prop). (∃x:A. P(x) ∧ Q(x)) → (∃x:A. P(x))
Axiom dependencies: 0

Python

obtaining_witnesses.py Download
"""Use an existential fact through its scoped witness and checked property."""

from judgment import Session, arrow, exists, implies


def main():
    s = Session()
    proof = s.theorem("project_exists")
    A = proof.type_var("A")
    P = proof.var("P", arrow(A, s.prop_type()))
    Q = proof.var("Q", arrow(A, s.prop_type()))
    x = proof.bound_var("x", A)
    proof.goal(implies(exists(x, P(x) & Q(x)), exists(x, P(x))))

    h = proof.intro()
    w, hw = proof.obtain(h, "w")
    print("Witness:", w.format())
    print("Its property:", hw.statement().format())
    proof.witness(w)
    proof.exact(proof.left(hw))

    theorem = proof.finish()
    print(theorem)
    print("Axiom dependencies:", len(theorem.axioms()))


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/obtaining_witnesses.py

Output

Witness: w
Its property: P(w) ∧ Q(w)
[A] ⊢ ∀P:(A → Prop). ∀Q:(A → Prop). (∃x:A. P(x) ∧ Q(x)) → (∃x:A. P(x))
Axiom dependencies: 0

finish discharges the property assumption and the witness through constructive existential elimination. The final theorem states the original goal and adds no axiom. The witness and its evidence cannot escape into an unrelated proof or a sibling branch, even if computation erases a displayed occurrence. Nested obtains close from the innermost scope outward.

Supply an existential Fact visible in the selected context. Specialize a generic fact first with use; obtain does not infer its type arguments or premises. Witness names must be fresh among active locals and visible declarations. Remaining binders in the property and goal are renamed when necessary to avoid capture; sibling branches may independently use the same witness name.

This operation requires an active declared goal. Forward proofs need a separate continuation design to fix the conclusion before introducing the witness. sorry and resume work inside an obtained scope; an open or deferred branch still blocks completion. Failure preserves the selected goal and does not reserve the witness name, while already consumed work remains spent.

Named intermediate claims

var step = proof.have("name", proposition) creates a separate claim subgoal and advances proof to a continuation with the same target. The returned step is a Proof handle supporting the usual operations: exact, intro, intro_var, split, witness, obtain, rewrites, and further have steps.

step.fact() supplies the claim as a local premise in the continuation and its descendants. You can use it immediately in exact, use, a targeted rewrite, or another claim, then return to prove the claim later. Its printed text includes the name and [claim] [local]. This is kernel evidence under an additional local hypothesis; it is not a closed proof of the claim and adds no global axiom.

Mojo

intermediate_claims.mojo Download
"""Develop a named intermediate claim independently of its continuation."""

from judgment import Session, implies


def main() raises:
    var s = Session()
    var P = s.prop("P")
    var Q = s.prop("Q")
    var proof = s.theorem("swap_with_claim", implies(P & Q, Q & P))
    var h = proof.intro()

    var step = proof.have("first_component", Q)
    step.sorry()
    proof.exact(proof.conjoin(step.fact(), proof.left(h)))

    # The continuation is solved, but the intermediate claim still needs proof.
    step.resume()
    step.exact(step.right(h))
    var theorem = proof.finish()
    print(theorem)
    print("Axiom dependencies:", len(theorem.axioms()))

Run from the repository root pixi run core-run docs/examples/library/intermediate_claims.mojo

Output

⊢ P ∧ Q → Q ∧ P
Axiom dependencies: 0

Python

intermediate_claims.py Download
"""Develop a named intermediate claim independently of its continuation."""

from judgment import Session, implies


def main():
    s = Session()
    P = s.prop("P")
    Q = s.prop("Q")
    proof = s.theorem("swap_with_claim", implies(P & Q, Q & P))
    h = proof.intro()

    step = proof.have("first_component", Q)
    step.sorry()
    proof.exact(proof.conjoin(step.fact(), proof.left(h)))

    # The continuation is solved, but the intermediate claim still needs proof.
    step.resume()
    step.exact(step.right(h))
    theorem = proof.finish()
    print(theorem)
    print("Axiom dependencies:", len(theorem.axioms()))


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/intermediate_claims.py

Output

⊢ P ∧ Q → Q ∧ P
Axiom dependencies: 0

The claim's own proof stays in the context from before its hypothesis was added. It cannot cite itself or a later claim depending on it. Earlier claims may support later ones, and the obligations may be solved in either order. Sibling branches cannot use each other's claim premises, with one exception: one proposition assumed twice in the same context is one hypothesis, so siblings in one context that claim the same proposition share its premise. Each claim remains an obligation of its own, and each name is found only in its own branch. Names are fresh among active proof names and visible declarations; independent siblings may reuse a name.

fact() always refers to the original claimed proposition, even after step introduces binders, splits, or creates another claim. The handle returned by have or rewrite retains this reference; subgoal handles returned by split do not. Handles returned by cases retain their own branch assumptions through the same accessor. A solved claim's reference remains a local premise. Call finish() on the original root to reconstruct the whole theorem, discharging each claim hypothesis with its checked proof. Claim names are not registered in Session.fact.

Every created claim must be proved before completion, including an unused claim or one whose continuation is already solved. sorry defers a claim without admitting it; resume reopens it. The example develops the continuation while its claim is deferred and supplies the missing proof before finishing. Dropping the claim handle does not remove its obligation.

have requires an active declared goal. Invalid names, scopes, types, or owners, and exhausted work leave the goal tree and name reservations unchanged. Claims use the proof's original theory snapshot, just like other tactics.

Reuse a theorem

proof.use(theorem, type_args=[...], terms=[...], using=[...]) returns a checked fact in the selected proof context. It does not change or close the goal. Use the result with exact, with a targeted rw, or in another use call. It is also available while building a header, like refl and conjunction operations.

Mojo

reusing_theorems.mojo Download
"""Prove a generic theorem once, then use it for a targeted rewrite."""

from std.testing import assert_true
from judgment import Session, arrow


def main() raises:
    var s = Session()
    var point = s.declare_type("Point")
    var map_ = s.symbol("map", arrow(point, point))

    var source = s.theorem("congruence")
    var A = source.type_var("A")
    var a = source.var("a", A)
    var b = source.var("b", A)
    var f = source.var("f", arrow(A, A))
    var h = source.given("h", a == b)
    source.goal(f(a) == f(b))
    _ = source.lhs().at(a).rw(h)
    source.rfl()
    _ = source.finish()

    var proof = s.theorem("map_twice")
    var x = proof.var("x", point)
    var y = proof.var("y", point)
    var equal = proof.given("equal", x == y)
    proof.goal(map_(map_(x)) == map_(map_(y)))

    _ = proof.lhs().at(map_(x)).rw(s.fact("congruence"), using=[equal])
    proof.rfl()
    var theorem = proof.finish()
    assert_true(theorem.statement().format() == "∀x:Point. ∀y:Point. x = y → map(map(x)) = map(map(y))")
    print(theorem)

Run from the repository root pixi run core-run docs/examples/library/reusing_theorems.mojo

Output

⊢ ∀x:Point. ∀y:Point. x = y → map(map(x)) = map(map(y))

Python

reusing_theorems.py Download
"""Prove a generic theorem once, then use it for a targeted rewrite."""

from judgment import Session, arrow


def main():
    s = Session()
    point = s.declare_type("Point")
    map_ = s.symbol("map", arrow(point, point))

    source = s.theorem("congruence")
    A = source.type_var("A")
    a = source.var("a", A)
    b = source.var("b", A)
    f = source.var("f", arrow(A, A))
    h = source.given("h", a == b)
    source.goal(f(a) == f(b))
    _ = source.lhs().at(a).rw(h)
    source.rfl()
    _ = source.finish()

    proof = s.theorem("map_twice")
    x = proof.var("x", point)
    y = proof.var("y", point)
    equal = proof.given("equal", x == y)
    proof.goal(map_(map_(x)) == map_(map_(y)))

    _ = proof.lhs().at(map_(x)).rw(s.fact("congruence"), using=[equal])
    proof.rfl()
    theorem = proof.finish()
    assert theorem.statement().format() == "∀x:Point. ∀y:Point. x = y → map(map(x)) = map(map(y))"
    print(theorem)


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/reusing_theorems.py

Output

⊢ ∀x:Point. ∀y:Point. x = y → map(map(x)) = map(map(y))

The example supplies the equality premise explicitly to rw. Its selected occurrence and that premise determine the theorem's type, function, and term arguments. The separate use form remains available when an instantiated fact will be reused across several steps.

Explicit type arguments follow declaration order, including unused parameters. When omitted, unambiguous type arguments are inferred from supplied terms and premises; unused or ambiguous parameters still require explicit arguments. Declared types remain concrete, and a destination proof's type parameters remain rigid. Every argument must belong to the session and be usable in the destination context, even when the theorem does not use it.

terms supplies universal arguments and using supplies evidence for implication premises. The two lists consume a contiguous outer prefix of the statement, in its existing order. An intervening premise must be justified before a later universal argument can be supplied. A missing earlier argument needed to reach a supplied argument, or an excess argument, fails explicitly.

Partial application leaves the remaining statement visible. For example, specializing the example's congruence theorem with only type_args=[point] returns its universal statement over Point. Supplying all three term arguments leaves (x = y) → (map(x) = map(y)); a later use(..., using=[equal]) discharges that premise. Type arguments are empty on subsequent uses of an already specialized fact. Remaining binders are rebuilt with specialized types, and names are freshened when needed to avoid capturing caller names in the printed statement.

Generic completion publishes a private kernel Proven declaration after checking the theorem. It advances the active session theory without adding an axiom. Create a consuming proof after completion: existing proofs keep their earlier theory snapshots and cannot specialize through a declaration they cannot see. The fact retains its original checked judgment and ordered type parameters.

Failed uses leave goals, contexts, and theory publication unchanged. Failed completion publishes neither a name nor its private declaration. Work already spent is not refunded. No premises are assumed, solved, or simplified by use.

Work backward from a theorem

proof.apply(theorem, type_args=[...], terms=[...], using=[...]) checks that a theorem can establish the selected goal and returns a List[Proof] for its unproved premises. This complements use, which returns a checked fact and requires evidence for every premise it consumes.

Mojo

applying_theorems.mojo Download
"""Use a theorem backward, proving its premises as independent subgoals."""

from judgment import Session, implies


def main() raises:
    var s = Session()
    var join = s.theorem("join")
    var Left = join.prop("Left")
    var Right = join.prop("Right")
    var left = join.given("left", Left)
    var right = join.given("right", Right)
    join.goal(Left & Right)
    join.exact(join.conjoin(left, right))
    var conjunction = join.finish()

    var P = s.prop("P")
    var Q = s.prop("Q")
    var proof = s.theorem("swap_by_apply", implies(P & Q, Q & P))
    var h = proof.intro("pair")
    _ = proof.apply(conjunction)
    var first = proof.select("premise_1")
    var second = proof.select("premise_2")
    print("First premise:", first.target().format())
    print("Second premise:", second.target().format())

    # These can be proved in either order, deferred, or selected later.
    second.exact(second.left(h))
    first.exact(first.right(h))
    var theorem = proof.finish()
    print(theorem)
    print("Axiom dependencies:", len(theorem.axioms()))

Run from the repository root pixi run core-run docs/examples/library/applying_theorems.mojo

Output

First premise: Q
Second premise: P
⊢ P ∧ Q → Q ∧ P
Axiom dependencies: 0

Python

applying_theorems.py Download
"""Use a theorem backward, proving its premises as independent subgoals."""

from judgment import Session, implies


def main():
    s = Session()
    join = s.theorem("join")
    Left = join.prop("Left")
    Right = join.prop("Right")
    left = join.given("left", Left)
    right = join.given("right", Right)
    join.goal(Left & Right)
    join.exact(join.conjoin(left, right))
    conjunction = join.finish()

    P = s.prop("P")
    Q = s.prop("Q")
    proof = s.theorem("swap_by_apply", implies(P & Q, Q & P))
    h = proof.intro("pair")
    _ = proof.apply(conjunction)
    first = proof.select("premise_1")
    second = proof.select("premise_2")
    print("First premise:", first.target().format())
    print("Second premise:", second.target().format())

    # These can be proved in either order, deferred, or selected later.
    second.exact(second.left(h))
    first.exact(first.right(h))
    theorem = proof.finish()
    print(theorem)
    print("Axiom dependencies:", len(theorem.axioms()))


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/applying_theorems.py

Output

First premise: Q
Second premise: P
⊢ P ∧ Q → Q ∧ P
Axiom dependencies: 0

Here the goal Q & P determines the conjunction theorem's two proposition arguments. apply(conjunction) leaves only the two premise goals; it does not search for their proofs. Use terms=[Q, P] when explicit specialization is useful.

Type arguments include every declared parameter, including unused ones. Term arguments instantiate successive outer universal quantifiers. Unlike use, apply can cross an unproved implication premise to reach a later universal argument: for ∀x. P(x) → ∀y. Q(y) → R(x, y), applying to R(a, b) with terms=[a, b] produces P(a) and Q(b). With omitted argument lists, unambiguous parameters can instead be inferred from the goal. using supplies evidence for a prefix of encountered implication premises; all subsequent premises become obligations in theorem order. Their names are premise_1, premise_2, and so on, counting the implication premises in the applied fact, including those supplied to this apply call. Providing the first premise therefore leaves premise_2 as the next name.

Application stops at the first remaining statement that matches the target after all supplied arguments have been consumed. The target can itself be an implication or a quantified statement. Extra arguments are rejected. A different conclusion raises NO_MATCH; a parameter that cannot be inferred from the target requires an explicit argument. Matching uses the checked canonical proposition in the proof's existing theory. It performs no search, automatic simplification, or automatic premise solving.

The returned subgoals share the original context. They do not acquire assumptions from one another, and repeated identical premises remain separate obligations. Prove them in any order, defer them with sorry(), or recover them through obligations() and select(). As with split, the receiving goal is consumed; continue with the returned handles. Its old focus and goal snapshot cannot select a child implicitly. Application inside a named claim retains its original fact() reference and passes the claim name to its children.

If no premises remain, apply returns an empty list and solves the goal directly. Only the original root can finish(). Every generated premise must be solved, including premises unused by the source theorem's proof. Completion replays checked universal and implication elimination with the actual child proofs and restores any earlier rewrite transport. Failure creates no public subgoals or context entries, leaves existing selections usable, and does not refund work.

Read application inference errors

For a chosen law ∀x. D(x) → ∀y. E(y) → f(x) = y and the goal f(a) == b, incorrect supplied facts can produce:

apply premise 1: expected D(a); supplied D(b)
apply premise 2: expected E(b); supplied E(a)

Positions follow implication order, including conditions already supplied. The explanation uses the selected goal and explicit arguments to determine the expected condition. It checks only the supplied prefix: omitted conditions remain ordinary premise_N subgoals, even when suitable facts are visible in the context. A conjunction remains one premise. Excess evidence reports the maximum number of facts the theorem can consume.

An undetermined argument instead produces a message such as apply: unresolved term parameter x. If x occurs only in an unproved condition, provide an explicit argument or a checked premise fact that determines it. The application can then expose any remaining conditions as subgoals. Type parameters that are unused still need explicit type_args.

These explanations apply to failures during argument inference. Fully explicit applications and later kernel checking retain their existing errors, including kernel messages and kinds. Optional diagnostic work preserves the original short refusal if its budget runs out. Reporting changes no goals, contexts, or saved selections; a corrected call can reuse the same proof handle.

Correct, defer, and recover an application

Return to the conjunction-swap proof. The goal Q & P determines that the conjunction theorem needs Q first and P second. Supplying P first produces apply premise 1: expected Q; supplied P; the same proof handle remains usable.

Mojo

application_troubleshooting.mojo Download
"""Correct a supplied premise, then defer and recover the remaining goal."""

from std.testing import assert_equal, assert_true
from judgment_shell import LibErrorKind, Session, implies


def main() raises:
    var s = Session()
    var join = s.theorem("join")
    var Left = join.prop("Left")
    var Right = join.prop("Right")
    var left = join.given("left", Left)
    var right = join.given("right", Right)
    join.goal(Left & Right)
    join.exact(join.conjoin(left, right))
    var conjunction = join.finish()

    var P = s.prop("P")
    var Q = s.prop("Q")
    var target = implies(P & Q, Q & P)
    var proof = s.theorem("recover_application", target)
    var pair = proof.intro("pair")
    var p = proof.left(pair)
    var q = proof.right(pair)

    # Q & P needs Q first. Supplying P leaves the original goal intact.
    var before = proof.format()
    try:
        _ = proof.apply(conjunction, using=[p])
    except error:
        assert_equal(error.kind, LibErrorKind.NO_MATCH)
        print(error.message)
    assert_equal(proof.format(), before)

    # Correct the first premise; P remains an explicit obligation.
    _ = proof.apply(conjunction, using=[q])
    var second = proof.select("premise_2")
    second.sorry()
    var remaining = proof.obligations()
    assert_equal(len(remaining), 1)
    assert_true(remaining[0].target().same_as(P))
    assert_equal(remaining[0].status(), "deferred")
    print("Deferred premise:", remaining[0].path()[0], "requires", remaining[0].target().format())

    # Sorry saves unfinished work; it does not supply evidence.
    var blocked = False
    try:
        _ = proof.finish()
    except error:
        assert_equal(error.kind, LibErrorKind.SHAPE)
        blocked = True
    assert_true(blocked)
    print("Finish blocked:", blocked)

    # Recover by name, resume, and supply the checked fact explicitly.
    second = proof.select("premise_2")
    second.resume()
    second.exact(p)
    var theorem = proof.finish()
    assert_true(theorem.statement().same_as(target))
    assert_equal(len(theorem.axioms()), 0)
    assert_equal(len(theorem.admissions()), 0)
    print(theorem)

Run from the repository root pixi run mojo run -I src docs/examples/library/application_troubleshooting.mojo

Output

apply premise 1: expected Q; supplied P
Deferred premise: premise_2 requires P
Finish blocked: True
⊢ P ∧ Q → Q ∧ P

Python

application_troubleshooting.py Download
"""Correct a supplied premise, then defer and recover the remaining goal."""

from judgment import LibErrorKind, Session, implies, JudgmentError


def main():
    s = Session()
    join = s.theorem("join")
    Left = join.prop("Left")
    Right = join.prop("Right")
    left = join.given("left", Left)
    right = join.given("right", Right)
    join.goal(Left & Right)
    join.exact(join.conjoin(left, right))
    conjunction = join.finish()

    P = s.prop("P")
    Q = s.prop("Q")
    target = implies(P & Q, Q & P)
    proof = s.theorem("recover_application", target)
    pair = proof.intro("pair")
    p = proof.left(pair)
    q = proof.right(pair)

    # Q & P needs Q first. Supplying P leaves the original goal intact.
    before = proof.format()
    try:
        _ = proof.apply(conjunction, using=[p])
    except JudgmentError as error:
        assert error.kind == LibErrorKind.NO_MATCH
        print(error.message)
    assert proof.format() == before

    # Correct the first premise; P remains an explicit obligation.
    _ = proof.apply(conjunction, using=[q])
    second = proof.select("premise_2")
    second.sorry()
    remaining = proof.obligations()
    assert len(remaining) == 1
    assert remaining[0].target().same_as(P)
    assert remaining[0].status() == "deferred"
    print("Deferred premise:", remaining[0].path()[0], "requires", remaining[0].target().format())

    # Sorry saves unfinished work; it does not supply evidence.
    blocked = False
    try:
        _ = proof.finish()
    except JudgmentError as error:
        assert error.kind == LibErrorKind.SHAPE
        blocked = True
    assert blocked
    print("Finish blocked:", blocked)

    # Recover by name, resume, and supply the checked fact explicitly.
    second = proof.select("premise_2")
    second.resume()
    second.exact(p)
    theorem = proof.finish()
    assert theorem.statement().same_as(target)
    assert len(theorem.axioms()) == 0
    assert len(theorem.admissions()) == 0
    print(theorem)


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/application_troubleshooting.py

Output

apply premise 1: expected Q; supplied P
Deferred premise: premise_2 requires P
Finish blocked: True
⊢ P ∧ Q → Q ∧ P

The corrected call supplies Q with using=[q]. Its remaining goal is named premise_2, because the first premise is already proved. Even though p is available, application leaves that second premise for an explicit proof.

sorry() marks it deferred, and finish() still refuses to produce a theorem. Later, select("premise_2") retrieves it, resume() reopens it, and exact(p) solves it. Completion checks the original statement without adding an axiom or an admission. The example catches errors to demonstrate recovery; an ordinary proof can proceed directly with the corrected application.

Prove by cases

proof.cases(disjunction, left_name="left", right_name="right") uses visible evidence of P | Q to return two Proof handles. Each branch must prove the current target: the first assumes P, the second assumes Q. Select those obligations by "left" and "right", then retrieve each local assumption by its supplied name, such as p_case.fact("hp"):

Mojo

proof_by_cases.mojo Download
"""Prove a common consequence in two independently scoped cases."""

from judgment import Session, implies


def main() raises:
    var s = Session()
    var P = s.prop("P")
    var Q = s.prop("Q")
    var R = s.prop("R")
    var proof = s.theorem("common_consequence")
    var either = proof.given("either", P | Q)
    var from_p = proof.given("from_p", implies(P, R))
    var from_q = proof.given("from_q", implies(Q, R))
    proof.goal(R)

    _ = proof.cases(either, left_name="hp", right_name="hq")
    var p_case = proof.select("left")
    _ = p_case.apply(from_p, using=[p_case.fact("hp")])
    var q_case = proof.select("right")
    _ = q_case.apply(from_q, using=[q_case.fact("hq")])

    var theorem = proof.finish()
    print(theorem)
    print("Axiom dependencies:", len(theorem.axioms()))

Run from the repository root pixi run core-run docs/examples/library/proof_by_cases.mojo

Output

⊢ P ∨ Q → (P → R) → (Q → R) → R
Axiom dependencies: 0

Python

proof_by_cases.py Download
"""Prove a common consequence in two independently scoped cases."""

from judgment import Session, implies


def main():
    s = Session()
    P = s.prop("P")
    Q = s.prop("Q")
    R = s.prop("R")
    proof = s.theorem("common_consequence")
    either = proof.given("either", P | Q)
    from_p = proof.given("from_p", implies(P, R))
    from_q = proof.given("from_q", implies(Q, R))
    proof.goal(R)

    _ = proof.cases(either, left_name="hp", right_name="hq")
    p_case = proof.select("left")
    _ = p_case.apply(from_p, using=[p_case.fact("hp")])
    q_case = proof.select("right")
    _ = q_case.apply(from_q, using=[q_case.fact("hq")])

    theorem = proof.finish()
    print(theorem)
    print("Axiom dependencies:", len(theorem.axioms()))


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/proof_by_cases.py

Output

⊢ P ∨ Q → (P → R) → (Q → R) → R
Axiom dependencies: 0

When the supplied theorem concludes exactly the case's target, apply with all its premise evidence closes that case directly. This avoids nesting use inside exact. The explicit using facts still justify every premise; no assumption is searched for automatically. Keep use when its result will be combined with other facts before reaching the goal. The two local handles retain the readable structural names left and right, and each retrieves only its own case premise.

The parent becomes inactive, as with split and apply. Both branches remain obligations, even if their assumptions are unused or their propositions coincide. Solve them in either order, nest further tactics, or defer one with sorry. finish() requires both checked proofs and discharges their assumptions through disjunction elimination. Any rewrites made before the split are restored when reconstructing the original theorem.

Each branch sees the original context and its own assumption. Sibling assumptions of different propositions cannot be exchanged. When both branches assume the same proposition, as for P | P, they share one hypothesis: one proposition assumed twice in the same context is one assumption, so either branch's fact is evidence in the other, while each case name is found only in its own branch. Names follow the same reservation rules as have: they cannot conflict with header names, syntax binders, active scoped declarations, or visible global declarations. Case names are reserved only within their branch and descendants; independent siblings may use the same name. Goal labels retain the enclosing theorem or claim name, with case names shown on their assumptions. The structural branch names are always left and right, independently of assumption names.

On a handle returned directly by cases, branch.fact() retains its original premise through introductions, splits, claims, and nested cases, including after completion. It remains local evidence. If the receiving handle came from have, rewrite, or an earlier cases, its own reference is unchanged. Handles returned by split, apply, or select have no retained reference; visible case assumptions can be read by name with branch.fact("hp") or inspected through Goal.assumptions(). Dropping a branch handle does not remove its obligation.

Specialize generic evidence with use before passing it to cases, as with obtain. This tactic requires an active declared goal. Invalid evidence, names, or exhausted work publish neither branch and preserve existing selections and context metadata. Proofs keep their original theory snapshot.

Choose a side of a disjunction

For a goal P | Q, call proof.choose_left() to prove P, or proof.choose_right() to prove Q. The same handle advances to the chosen proposition in the same context. Only that proposition becomes an obligation; choosing a side supplies no assumption or evidence.

Mojo

choosing_disjuncts.mojo Download
"""Swap a disjunction by explicitly choosing what each case proves."""

from judgment import Session, implies


def main() raises:
    var s = Session()
    var P = s.prop("P")
    var Q = s.prop("Q")
    var proof = s.theorem("swap_disjunction", implies(P | Q, Q | P))
    var either = proof.intro("either")
    _ = proof.cases(either, left_name="hp", right_name="hq")

    # In the P case, prove the right side of Q | P.
    var p_case = proof.select("left")
    p_case.choose_right()
    p_case.exact(p_case.fact("hp"))

    # In the Q case, prove the left side of Q | P.
    var q_case = proof.select("right")
    q_case.choose_left()
    q_case.exact(q_case.fact("hq"))

    var theorem = proof.finish()
    print(theorem)
    print("Axiom dependencies:", len(theorem.axioms()))

Run from the repository root pixi run core-run docs/examples/library/choosing_disjuncts.mojo

Output

⊢ P ∨ Q → Q ∨ P
Axiom dependencies: 0

Python

choosing_disjuncts.py Download
"""Swap a disjunction by explicitly choosing what each case proves."""

from judgment import Session, implies


def main():
    s = Session()
    P = s.prop("P")
    Q = s.prop("Q")
    proof = s.theorem("swap_disjunction", implies(P | Q, Q | P))
    either = proof.intro("either")
    _ = proof.cases(either, left_name="hp", right_name="hq")

    # In the P case, prove the right side of Q | P.
    p_case = proof.select("left")
    p_case.choose_right()
    p_case.exact(p_case.fact("hp"))

    # In the Q case, prove the left side of Q | P.
    q_case = proof.select("right")
    q_case.choose_left()
    q_case.exact(q_case.fact("hq"))

    theorem = proof.finish()
    print(theorem)
    print("Axiom dependencies:", len(theorem.axioms()))


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/choosing_disjuncts.py

Output

⊢ P ∨ Q → Q ∨ P
Axiom dependencies: 0

The example combines elimination and introduction: each selected cases branch chooses the appropriate side of the reversed disjunction, then retrieves its own assumption by name. The left case assumes P, but chooses the right side of the goal Q | P; case selection and disjunct selection refer to different formulas. The handles originally returned by cases retain their no-argument fact() reference through a choice. A handle from have likewise retains its original claim reference. left(fact) and right(fact) still extract conjuncts from existing evidence; choose_left() and choose_right() operate on the goal.

The chosen goal supports the usual tactics, including nested choices, variable introduction, split, apply, have, and targeted equality rewrites. sorry defers it without proving it. Root finish() requires its checked proof, applies the kernel's disjunction introduction rule, and restores the originally stated goal, including any earlier unfolding or conversion.

Goal inspection exposes the chosen child with its enclosing theorem or claim label and unchanged context. The replaced parent cannot be selected through an old snapshot. Invalid shape, scope, or exhausted work leaves the proof unchanged; both sides are validated even though only one will be proved. This tactic requires an active declared disjunction and retains the proof's original theory.

Inspect and select outstanding goals

proof.obligations() returns an owned List[Goal] of every open or deferred obligation in the entire proof, in creation order. This includes unused claims and claims whose continuations have already been solved. The same list is visible from the root or any subgoal handle. A dropped handle can therefore be recovered:

Mojo

inspecting_proofs.mojo Download
"""Inspect a deferred claim and recover it by name or exact goal identity."""

from judgment import Session, implies


def main() raises:
    var s = Session()
    var P = s.prop("P")
    var Q = s.prop("Q")
    var proof = s.theorem("swap", implies(P & Q, Q & P))
    var h = proof.intro("h")
    var step = proof.have("first_component", Q)
    step.sorry()
    proof.exact(proof.conjoin(step.fact(), proof.left(h)))
    print(proof.format())

    var goals = proof.obligations()
    var missing = proof.select("first_component")
    missing.resume()
    missing = proof.select(goals[0])
    missing.exact(missing.right(missing.fact("h")))
    print(proof.format())
    print(proof.finish())
    print(proof.format())

Run from the repository root pixi run core-run docs/examples/library/inspecting_proofs.mojo

Output

swap: 1 obligation

goal 2 [deferred] first_component [claim / first_component]
  h: [local] ⊢ P ∧ Q
  ⊢ Q
swap: ready to finish
⊢ P ∧ Q → Q ∧ P
swap: finished

Python

inspecting_proofs.py Download
"""Inspect a deferred claim and recover it by name or exact goal identity."""

from judgment import Session, implies


def main():
    s = Session()
    P = s.prop("P")
    Q = s.prop("Q")
    proof = s.theorem("swap", implies(P & Q, Q & P))
    h = proof.intro("h")
    step = proof.have("first_component", Q)
    step.sorry()
    proof.exact(proof.conjoin(step.fact(), proof.left(h)))
    print(proof.format())

    goals = proof.obligations()
    missing = proof.select("first_component")
    missing.resume()
    missing = proof.select(goals[0])
    missing.exact(missing.right(missing.fact("h")))
    print(proof.format())
    print(proof.finish())
    print(proof.format())


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/inspecting_proofs.py

Output

swap: 1 obligation

goal 2 [deferred] first_component [claim / first_component]
  h: [local] ⊢ P ∧ Q
  ⊢ Q
swap: ready to finish
⊢ P ∧ Q → Q ∧ P
swap: finished

The example recovers the deferred claim by name and then by its saved identity. It retrieves h by name from that claim's current context, so completing the proof does not depend on the order of the assumption list.

Each Goal captures id(), name(), path(), status(), target(), type_params(), variables(), and assumptions(). Status is "open" or "deferred". Names identify the enclosing theorem or intermediate claim; sibling goals can share a name. IDs are stable within one proof. Variables and premises follow their actual kernel context in outermost-first order; syntax-only binder templates are excluded. Type parameters retain header order, including unused parameters. Premises are checked Fact values with their original scopes, names, and local/claim markers. Reading them does not prove or discharge a claim.

proof.select(goal) returns a handle to that same outstanding goal without changing the receiving handle. It requires a snapshot from the exact same proof, not an integer ID. A deferred goal still needs resume(). Selection works after immediate rewrites or resumption of the same goal, and reads its current target. If a tactic replaced the goal with children, or the goal was solved, selection refuses the old identity; call obligations() to find the remaining work. Only the original root can finish the proof. A selected handle has no retained fact() reference; visible claim and case premises remain available through assumptions() or selected.fact("premise_name").

Use selected.current_goal() to inspect only that selected goal and its context. It returns the same immutable Goal snapshot type as obligations(). It accepts open and deferred goals; it refuses a solved goal or a parent replaced by a split, so select a remaining branch first. Whole-proof format() and obligations() retain their meaning regardless of which handle receives the call.

selected.fact(name) retrieves a unique visible local premise named by given, intro, cases, have, or rewrite. Names are literal, including punctuation. An absent name raises NO_MATCH; duplicate visible names raise SHAPE rather than choosing one. Keep distinct intro hints when using named retrieval. A claim can be retrieved only in its continuation, and sibling premises remain private. The no-argument fact() keeps its retained-reference behavior. Global facts are still retrieved with s.fact(name).

selected.variable(name) likewise retrieves a unique visible variable named by var, intro_var, obtain, or define, with the same NO_MATCH and SHAPE refusals. Both lookups find what a tactic introduced as well as what a direct step did.

Use proof.select("forward") to select the unique outstanding goal whose final path component is forward. A short name that matches several goals raises SHAPE; it never silently chooses one. proof.select(["forward", "left"]) instead uses a complete path relative to the theorem root, regardless of which handle receives the call. An absent name or path raises NO_MATCH.

Use named selection for readable branch-oriented proofs, and retain the selected handle while working within that branch. In a nested proof, use the complete path when a short name would be ambiguous. select performs a fresh, budgeted lookup; it does not rename goals or retain a case assumption through no-argument fact().

Step Path components added
Conjunction split or disjunction cases left, right
Equivalence split forward, backward
Backward apply premise_1, premise_2, … in implication order
have or deferred rewrite claim claim, followed by the claim name
refine hole hole, followed by the hole name

Introductions, witnesses, local definitions, disjunct selection, and the main continuation after a claim retain their path. Solving or deferring a sibling never changes a remaining path. The main theorem continuation has an empty path and can be selected with List[String]() or its theorem name. Path components are literal strings: dots, slashes, or spaces inside a claim name are not parsed. Inspection displays the path alongside the enclosing theorem or claim name.

Mojo

named_goals.mojo Download
"""Select nested branches by stable names and literal path components."""

from std.testing import assert_equal, assert_true
from judgment_shell import LibErrorKind, Session, implies


def main() raises:
    var s = Session()
    var P = s.prop("P")
    var Q = s.prop("Q")
    var target = implies(P & Q, (Q & P) & (P & Q))
    var proof = s.theorem("nested_pairs", target)
    var pair = proof.intro("pair")
    _ = proof.split()
    var left = proof.select("left")
    var right = proof.select("right")
    _ = left.split()
    _ = right.split()

    # Both halves now contain a left goal. An ambiguous short name is refused.
    var ambiguous = False
    try:
        _ = proof.select("left")
    except error:
        ambiguous = error.kind == LibErrorKind.SHAPE
    assert_true(ambiguous)
    print("Ambiguous short name refused:", ambiguous)

    var last = proof.select(["right", "right"])
    last.sorry()
    var part = proof.select(["left", "left"])
    part.exact(part.right(pair))
    part = proof.select(["left", "right"])
    part.exact(part.left(pair))
    part = proof.select(["right", "left"])
    part.exact(part.left(pair))

    var remaining = proof.obligations()[0]
    var path = remaining.path()
    print("Remaining branch:", path[0], "/", path[1])
    last = proof.select(remaining.path())
    last.resume()
    last.exact(last.right(pair))
    var theorem = proof.finish()
    assert_true(theorem.statement().same_as(target))
    assert_equal(len(theorem.axioms()), 0)
    print(theorem)

Run from the repository root pixi run mojo run -I src docs/examples/library/named_goals.mojo

Output

Ambiguous short name refused: True
Remaining branch: right / right
⊢ P ∧ Q → Q ∧ P ∧ (P ∧ Q)

Python

named_goals.py Download
"""Select nested branches by stable names and literal path components."""

from judgment import LibErrorKind, Session, implies, JudgmentError


def main():
    s = Session()
    P = s.prop("P")
    Q = s.prop("Q")
    target = implies(P & Q, (Q & P) & (P & Q))
    proof = s.theorem("nested_pairs", target)
    pair = proof.intro("pair")
    _ = proof.split()
    left = proof.select("left")
    right = proof.select("right")
    _ = left.split()
    _ = right.split()

    # Both halves now contain a left goal. An ambiguous short name is refused.
    ambiguous = False
    try:
        _ = proof.select("left")
    except JudgmentError as error:
        ambiguous = error.kind == LibErrorKind.SHAPE
    assert ambiguous
    print("Ambiguous short name refused:", ambiguous)

    last = proof.select(["right", "right"])
    last.sorry()
    part = proof.select(["left", "left"])
    part.exact(part.right(pair))
    part = proof.select(["left", "right"])
    part.exact(part.left(pair))
    part = proof.select(["right", "left"])
    part.exact(part.left(pair))

    remaining = proof.obligations()[0]
    path = remaining.path()
    print("Remaining branch:", path[0], "/", path[1])
    last = proof.select(remaining.path())
    last.resume()
    last.exact(last.right(pair))
    theorem = proof.finish()
    assert theorem.statement().same_as(target)
    assert len(theorem.axioms()) == 0
    print(theorem)


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/named_goals.py

Output

Ambiguous short name refused: True
Remaining branch: right / right
⊢ P ∧ Q → Q ∧ P ∧ (P ∧ Q)

Selecting a name or a path is a fresh lookup in the current proof tree. It can follow introductions within a branch, and a restored proof can reuse a path for a newly created goal. Select the Goal snapshot itself when exact identity is required: old snapshots and handles still refuse discarded or replaced goals. Named selection shares the existing selection contract: deferred work requires resume, only the root may finish, and selected handles have no retained fact() reference. The returned context grants no access to sibling assumptions.

Snapshots retain their captured text and expressions after later tactics and even after the original wrappers are destroyed. Lists returned by their accessors are independent copies. print(goal) displays the captured goal and context; print(proof.format()) inspects the current proof. An empty obligation list before completion means ready to finish, not a published theorem. After finish(), the list remains empty and the display says finished. Forward proofs and headers without a declared target reject goal inspection. Inspection and copying consume bounded work; failure changes no goals, names, or context metadata.

Rewrite a selected occurrence

== constructs a symbolic equality. The lowercase helper eq(a, b) means the same thing. same_as returns a Boolean comparing canonical identity and ownership; symbolic expressions cannot be used as Boolean conditions.

Choose the operation according to the justification you already have:

Intent Operation
Show a definitionally equal expression, such as x**2 as x * x focus.change(replacement)
Apply a chosen equality law at the selected occurrence focus.rw(law, using=[premise_facts]); omit using when there are no premises
State the replacement explicitly and choose its equality theorem focus.to(replacement, using=law, premises=[condition]); omit premises for an unconditional law
Introduce or expand a local abbreviation focus.fold(symbol) or focus.unfold(symbol)
Change one occurrence now and prove its equality later proof.rewrite(name, at=focus, to=replacement)
Write a sequence of equalities with independently proved steps proof.calc(start), then chain.eq(...) or chain.step(...)

Use proof.lhs().at(expression) or proof.rhs().at(expression) to keep the surrounding formula out of each rewrite. A rewrite claim belongs to the parent proof and is recovered with proof.select; a calculation's steps belong to the chain and are recovered with chain.select. Finish a calculation with proof.exact(chain.finish()), then finish the enclosing theorem.

to infers arguments from the selected expression, the explicit replacement, and any supplied premise facts. This includes arguments that occur only on the right of the chosen equality theorem or only in a condition. For a conditional law, supply every condition explicitly with premises=[condition], in declaration order; a conjunction needs one fact proving the conjunction. It does not find or prove premises. Already specialized facts remain supported. Explicit use also handles unused arguments and matches outside the structural matcher. Conflicts or missing arguments leave the goal and selection unchanged. Calculation.eq infers the same arguments from its current and next expressions and the supplied premises.

~P constructs logical negation and has exactly the same meaning as not_(P). It composes with P & Q and P | Q; write ~(P & Q) to negate the whole conjunction, since ~P & Q means (~P) & Q. Both negation spellings require a proposition and perform no automatic simplification, including double-negation elimination. Mojo's not P requests Boolean truth testing and is unavailable for symbolic expressions; !P is not Mojo syntax. The quick-start rewrite changes just the second occurrence of P, beneath its negation.

lhs() and rhs() select a side of the active equality goal. at(expr) requires one matching occurrence. If an expression occurs more than once, pass a one-based occurrence counted in left-to-right authored preorder in the current scope. For function applications, the function precedes its arguments. Nested at calls restrict the search to the previous selection. Quantified and lambda expressions can be selected as a whole, but their bodies are opaque: they do not hide accessible siblings or contribute occurrences inside their binders. A search needing binder traversal raises UNSUPPORTED. Use under(name) to open an explicit binder scope.

to(replacement, using=fact) requires evidence of precisely the selected old expression's equality to the replacement. rw(fact) infers the replacement from that equality's right side; rw(fact, reverse=True) uses its converse. Evidence must be visible in the goal's context. The library lifts the supplied equality through the surrounding expression with kernel congruence, then composes the resulting proof with earlier steps.

For a quantified or polymorphic equality theorem, focused rw infers its arguments from the selected endpoint and explicitly supplied using=[...] premises. Reversing the rule matches its right endpoint. Supply type_args for all type parameters when inference is ambiguous, and terms for an explicit prefix of universal arguments; remaining term arguments must be inferable. Every premise needs checked evidence. Missing or mismatched evidence leaves the goal and focus unchanged; it is never silently assumed or deferred. Inference uses structural matching, without binder or ACU unification. For a match outside that subset, specialize the theorem with use first and pass its equality to rw. The primitive Tactics.rw also takes a specialized equality.

inferred_rewrites.mojo Download
"""Infer arguments for explicitly chosen function and algebra rewrites."""

from std.testing import assert_equal
from judgment import Session, arrow, forall
from arithmetic_setup import arithmetic_setup


def main() raises:
    var s = Session()
    var proof = s.theorem("left_inverse_implies_injective")
    var A = proof.type_var("A")
    var B = proof.type_var("B")
    var f = proof.var("f", arrow(A, B))
    var g = proof.var("g", arrow(B, A))
    var t = proof.bound_var("t", A)
    var left_inverse = proof.given("left_inverse", forall(t, g(f(t)) == t))
    var x = proof.var("x", A)
    var y = proof.var("y", A)
    var same_image = proof.given("same_image", f(x) == f(y))
    proof.goal(x == y)

    _ = proof.lhs().rw(left_inverse, reverse=True)
    _ = proof.lhs().at(f(x)).rw(same_image)
    _ = proof.lhs().rw(left_inverse)
    proof.rfl()
    var theorem = proof.finish()
    assert_equal(len(theorem.axioms()), 0)
    print(theorem)

    var algebra = arithmetic_setup(s)
    var commute = s.fact("mul_comm")
    var distribute = s.fact("left_distrib")
    var right = s.theorem("right_distrib_inferred")
    var a = right.var("a", algebra.kind)
    var b = right.var("b", algebra.kind)
    var c = right.var("c", algebra.kind)
    right.goal((a + b) * c == a * c + b * c)

    _ = right.lhs().rw(commute)
    _ = right.lhs().rw(distribute)
    _ = right.lhs().at(c * a).rw(commute)
    _ = right.lhs().at(c * b).rw(commute)
    right.rfl()
    theorem = right.finish()
    assert_equal(len(theorem.axioms()), 2)
    print(theorem)

Run from the repository root pixi run core-run docs/examples/library/inferred_rewrites.mojo --include docs/examples/library

Output

[A, B] ⊢ ∀f:(A → B). ∀g:(B → A). (∀t:A. g(f(t)) = t) → (∀x:A. ∀y:A. f(x) = f(y) → x = y)
[assuming 2 axioms] ⊢ ∀a:S. ∀b:S. ∀c:S. (a + b) * c = a * c + b * c
  axioms: mul_comm, left_distrib

The first proof needs no axioms. The algebra proof uses the example's explicitly assumed multiplication commutativity and distributivity laws. Each line chooses its rule and occurrence; inference supplies arguments without searching for another rule, rewriting other occurrences, or simplifying the expression.

Both methods return the selection at the replacement, so calls can be chained. When retaining a selection in a variable, assign that return value to it. Every successful edit invalidates previous selections of the goal; they never silently select a different occurrence. Original expressions remain immutable, even when two occurrences share the same canonical node.

rfl() closes a reflexive goal. refl(expr) only constructs a fact. change replaces the whole goal using definitional equality; it cannot assert distributivity or another algebraic law. Failed evidence, missing/ambiguous occurrences, and failed conversion leave the logical goal unchanged. Work already spent is not refunded, and harmless intermediate kernel and syntax nodes can remain allocated.

Conditional rewrites across nested branches

A partial inverse gives a useful longer example. Suppose g(f(t)) = t when D(t) holds, and h(f(t)) = t when E(t) holds. The theorem proves f(x) = f(y) ↔ x = y for inputs both in D, and separately for inputs both in E. The domain conditions remain explicit; this does not assert injectivity for an arbitrary pair with one input in each domain.

Mojo

conditional_rewrites.mojo Download
"""Use partial inverses in nested branches with a shared deferred claim."""

from std.testing import assert_equal
from judgment_shell import Expr, LibError, Proof, Session, arrow, forall, iff, implies


def cancel_on_domain(mut proof: Proof, inverse_name: String, domain_name: String, image: Expr) raises LibError:
    """Prove the forward implication using both explicit domain conditions."""
    var same_image = proof.intro("same_image")
    var inverse = proof.fact(inverse_name)
    var domain = proof.fact(domain_name)
    var in_domain_x = proof.left(domain)
    var in_domain_y = proof.right(domain)

    _ = proof.lhs().rw(inverse, reverse=True, using=[in_domain_x])
    _ = proof.lhs().at(image).rw(same_image)
    _ = proof.lhs().rw(inverse, using=[in_domain_y])
    proof.rfl()


def main() raises:
    var s = Session()
    var proof = s.theorem("partial_inverses")
    var A = proof.type_var("A")
    var B = proof.type_var("B")
    var f = proof.var("f", arrow(A, B))
    var g = proof.var("g", arrow(B, A))
    var h = proof.var("h", arrow(B, A))
    var D = proof.var("D", arrow(A, s.prop_type()))
    var E = proof.var("E", arrow(A, s.prop_type()))
    var t = proof.bound_var("t", A)
    _ = proof.given("inverse_on_D", forall(t, implies(D(t), g(f(t)) == t)))
    _ = proof.given("inverse_on_E", forall(t, implies(E(t), h(f(t)) == t)))
    var x = proof.var("x", A)
    var y = proof.var("y", A)
    var equivalent = iff(f(x) == f(y), x == y)
    proof.goal(implies(D(x) & D(y), equivalent) & implies(E(x) & E(y), equivalent))

    # Both backward directions will use this claim. It remains an obligation.
    var reverse = proof.have("same_inputs_same_image", implies(x == y, f(x) == f(y)))
    reverse.sorry()

    _ = proof.split()
    var on_d = proof.select("left")
    var on_e = proof.select("right")
    _ = on_d.intro("in_D")
    _ = on_e.intro("in_E")
    _ = on_d.split()
    _ = on_e.split()
    assert_equal(len(proof.obligations()), 5)
    for goal in proof.obligations():
        print(goal.path(), goal.status(), ":", goal.target().format())

    # Complete the right domain first; the left paths remain unchanged.
    var forward = proof.select(["right", "forward"])
    cancel_on_domain(forward, "inverse_on_E", "in_E", f(x))
    var backward = proof.select(["right", "backward"])
    backward.exact(backward.fact("same_inputs_same_image"))

    forward = proof.select(["left", "forward"])
    var selected = forward.current_goal()
    assert_equal(selected.target().same_as(implies(f(x) == f(y), x == y)), True)
    cancel_on_domain(forward, "inverse_on_D", "in_D", f(x))
    backward = proof.select(["left", "backward"])
    backward.exact(backward.fact("same_inputs_same_image"))

    var remaining = proof.obligations()
    assert_equal(len(remaining), 1)
    assert_equal(remaining[0].status(), "deferred")
    print("Remaining:", remaining[0].name(), "[", remaining[0].status(), "]")
    var recovered = proof.select("same_inputs_same_image")
    assert_equal(recovered.current_goal().status(), "deferred")
    recovered.resume()
    var equal_inputs = recovered.intro("equal_inputs")
    _ = recovered.lhs().at(x).rw(equal_inputs)
    recovered.rfl()

    var theorem = proof.finish()
    assert_equal(len(theorem.axioms()), 0)
    assert_equal(len(theorem.admissions()), 0)
    print(theorem)

Run from the repository root pixi run mojo run -I src docs/examples/library/conditional_rewrites.mojo

Output

[claim, same_inputs_same_image] deferred : x = y → f(x) = f(y)
[left, forward] open : f(x) = f(y) → x = y
[left, backward] open : x = y → f(x) = f(y)
[right, forward] open : f(x) = f(y) → x = y
[right, backward] open : x = y → f(x) = f(y)
Remaining: same_inputs_same_image [ deferred ]
[A, B] ⊢ ∀f:(A → B). ∀g:(B → A). ∀h:(B → A). ∀D:(A → Prop). ∀E:(A → Prop). (∀t:A. D(t) → g(f(t)) = t) → (∀t:A. E(t) → h(f(t)) = t) → (∀x:A. ∀y:A. (D(x) ∧ D(y) → (f(x) = f(y) ↔ x = y)) ∧ (E(x) ∧ E(y) → (f(x) = f(y) ↔ x = y)))

Python

conditional_rewrites.py Download
"""Use partial inverses in nested branches with a shared deferred claim."""

from judgment import Expr, JudgmentError, Proof, Session, arrow, forall, iff, implies


def cancel_on_domain(proof, inverse_name, domain_name, image):
    """Prove the forward implication using both explicit domain conditions."""
    same_image = proof.intro("same_image")
    inverse = proof.fact(inverse_name)
    domain = proof.fact(domain_name)
    in_domain_x = proof.left(domain)
    in_domain_y = proof.right(domain)

    _ = proof.lhs().rw(inverse, reverse=True, using=[in_domain_x])
    _ = proof.lhs().at(image).rw(same_image)
    _ = proof.lhs().rw(inverse, using=[in_domain_y])
    proof.rfl()


def main():
    s = Session()
    proof = s.theorem("partial_inverses")
    A = proof.type_var("A")
    B = proof.type_var("B")
    f = proof.var("f", arrow(A, B))
    g = proof.var("g", arrow(B, A))
    h = proof.var("h", arrow(B, A))
    D = proof.var("D", arrow(A, s.prop_type()))
    E = proof.var("E", arrow(A, s.prop_type()))
    t = proof.bound_var("t", A)
    _ = proof.given("inverse_on_D", forall(t, implies(D(t), g(f(t)) == t)))
    _ = proof.given("inverse_on_E", forall(t, implies(E(t), h(f(t)) == t)))
    x = proof.var("x", A)
    y = proof.var("y", A)
    equivalent = iff(f(x) == f(y), x == y)
    proof.goal(implies(D(x) & D(y), equivalent) & implies(E(x) & E(y), equivalent))

    # Both backward directions will use this claim. It remains an obligation.
    reverse = proof.have("same_inputs_same_image", implies(x == y, f(x) == f(y)))
    reverse.sorry()

    _ = proof.split()
    on_d = proof.select("left")
    on_e = proof.select("right")
    _ = on_d.intro("in_D")
    _ = on_e.intro("in_E")
    _ = on_d.split()
    _ = on_e.split()
    assert len(proof.obligations()) == 5
    for goal in proof.obligations():
        print("[" + ", ".join(goal.path()) + "]", goal.status(), ":", goal.target().format())

    # Complete the right domain first; the left paths remain unchanged.
    forward = proof.select(["right", "forward"])
    cancel_on_domain(forward, "inverse_on_E", "in_E", f(x))
    backward = proof.select(["right", "backward"])
    backward.exact(backward.fact("same_inputs_same_image"))

    forward = proof.select(["left", "forward"])
    selected = forward.current_goal()
    assert selected.target().same_as(implies(f(x) == f(y), x == y)) == True
    cancel_on_domain(forward, "inverse_on_D", "in_D", f(x))
    backward = proof.select(["left", "backward"])
    backward.exact(backward.fact("same_inputs_same_image"))

    remaining = proof.obligations()
    assert len(remaining) == 1
    assert remaining[0].status() == "deferred"
    print("Remaining:", remaining[0].name(), "[", remaining[0].status(), "]")
    recovered = proof.select("same_inputs_same_image")
    assert recovered.current_goal().status() == "deferred"
    recovered.resume()
    equal_inputs = recovered.intro("equal_inputs")
    _ = recovered.lhs().at(x).rw(equal_inputs)
    recovered.rfl()

    theorem = proof.finish()
    assert len(theorem.axioms()) == 0
    assert len(theorem.admissions()) == 0
    print(theorem)


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/conditional_rewrites.py

Output

[claim, same_inputs_same_image] deferred : x = y → f(x) = f(y)
[left, forward] open : f(x) = f(y) → x = y
[left, backward] open : x = y → f(x) = f(y)
[right, forward] open : f(x) = f(y) → x = y
[right, backward] open : x = y → f(x) = f(y)
Remaining: same_inputs_same_image [ deferred ]
[A, B] ⊢ ∀f:(A → B). ∀g:(B → A). ∀h:(B → A). ∀D:(A → Prop). ∀E:(A → Prop). (∀t:A. D(t) → g(f(t)) = t) → (∀t:A. E(t) → h(f(t)) = t) → (∀x:A. ∀y:A. (D(x) ∧ D(y) → (f(x) = f(y) ↔ x = y)) ∧ (E(x) ∧ E(y) → (f(x) = f(y) ↔ x = y)))

The ordinary Mojo helper cancel_on_domain proves either forward direction with three selected rewrites. In the D branch, the goal develops as follows:

Current equality Justification for the next step
x = y Reverse the chosen inverse law using evidence of D(x).
g(f(x)) = y Rewrite the occurrence f(x) using the introduced image equality.
g(f(y)) = y Use the same inverse law with evidence of D(y).
y = y Close by reflexivity.

The same proof function works for the E branch. Conditional premises are supplied explicitly through using; the selected occurrence determines the universal argument. No simplifier or premise search is needed.

Both backward directions use the local claim same_inputs_same_image. Its sorry() leaves a real obligation even after the four branches are closed. The example recovers that obligation by name, resumes it, and proves it before calling finish(). The final theorem has zero global axioms and zero admissions; the two inverse laws are retained as explicit local premises in its statement.

The initial domain split is selected as on_d and on_e by its left and right paths. After the equivalence splits, the full paths distinguish each domain's forward and backward directions. These are local Mojo variable names for selected handles; the displayed goal paths stay unchanged.

The example recovers local evidence with proof.fact(name), so the helper needs only the chosen premise names and rewrite occurrence. The backward branches retrieve the shared claim from their own contexts. forward.current_goal() captures just that branch; the overview loop still prints each outstanding Goal's path, status, and target.

Omitting the condition when reversing at x reports rw premise 1: expected D(x); missing evidence. Supplying D(y) instead reports rw premise 1: expected D(x); supplied D(y). These keep the original SHAPE and NO_MATCH kinds. An unresolved parameter is named explicitly; if the remaining work budget cannot support the detailed explanation, the shorter original message remains. Every failed rewrite preserves the goal and focus for retry.

Write a calculation before proving its steps

proof.rewrite(name, at=focus, to=replacement) requests a targeted rewrite and returns a Proof for its equality. The original handle advances to the rewritten continuation, so you can write several calculation steps and then prove them:

deferred_rewrites.mojo Download
"""Write an algebra calculation first, then prove each requested equality."""

from judgment import Session
from arithmetic_setup import arithmetic_setup


def main() raises:
    var s = Session()
    var algebra = arithmetic_setup(s)
    var proof = s.theorem("sum_squared_deferred")
    var ab = proof.vars("a b", algebra.kind)
    var a, b = ab[0], ab[1]
    proof.goal((a + b)**2 == a**2 + 2 * a * b + b**2)

    var square = proof.rewrite("square", at=proof.lhs(), to=(a + b) * (a + b))
    var expand = proof.rewrite("expand", at=proof.lhs(), to=a**2 + a * b + b * a + b**2)
    var collect = proof.rewrite("collect", at=proof.lhs(), to=a**2 + 2 * a * b + b**2)
    proof.rfl()

    # The calculation is complete, but its three equality claims remain.
    print("Equality obligations:", len(proof.obligations()))
    _ = collect.apply(algebra.collect)
    _ = expand.apply(algebra.expand)
    square.rfl()

    var theorem = proof.finish()
    print(theorem)

Run from the repository root pixi run core-run docs/examples/library/deferred_rewrites.mojo --include docs/examples/library

Output

Equality obligations: 3
[assuming 4 axioms] ⊢ ∀a:S. ∀b:S. (a + b)**2 = a**2 + 2 * a * b + b**2
  axioms: add_assoc, mul_comm, mul_one, left_distrib

The example closes the rewritten continuation before discharging its three equality claims. square.rfl() checks the power expansion by kernel computation; the other steps cite the same explicitly proved algebra lemmas as the earlier square example. collect.apply(algebra.collect) and expand.apply(algebra.expand) infer the lemma arguments from each claim's stated equality. There is no need to repeat [a, b] in an intermediate use call just to pass the result to exact. The result still reports the four mathematical assumptions.

For a long expression, select only the part you want to replace. For example, pass at=proof.lhs().at(a, occurrence=2) and to=b to replace the second a.

The claim target is exactly a == b. The continuation changes only that authored occurrence, using checked congruence through its surrounding expression. Selectors on either side of the goal, function positions, and displayed power bases follow the same rules as immediate rewrites. Binder bodies require an explicit under scope, as described below. The focus must belong to this exact proof, selected goal, and current revision.

A rewrite step is a named intermediate claim, with the same rules as have. Its fact() is a local equality premise available to the continuation and later claims, while the step's own proof stays in the original context. It cannot use its own premise or a later dependent claim. The receiving handle retains any earlier claim or case reference. Names follow the existing scoped claim policy.

You may prove the claims out of order, defer them with sorry, or recover dropped handles through obligations() and select(). Every claim must close before finish(), even if the continuation is already solved or the replacement was reflexive. No equality is admitted automatically. Inspection shows both the named claim and the enclosing theorem/claim's rewritten continuation.

Successful deferred rewrites replace the selected goal with these two obligations, so old foci and parent snapshots cannot select the continuation. Obtain new foci from the receiving proof handle. Invalid replacements, names, selections, or exhausted work publish neither obligation and preserve the previous focus and context. Validation and reconstruction retain the proof's original theory.

Use rw or to(..., using=...) when the equality evidence is already available. Use rewrite when you want to provide it later. change keeps its existing meaning of definitional equality.

Definitions and explicit unfolding

s.define(name, body, transparent=True) defines a closed expression and infers its type. For a parameterized function, start s.definition(name), declare its parameters with type_var, var/vars, or prop/props, and call finish(body). Definition headers follow the same parameter-scope rules as theorem headers. They accept no assumed premises. Term parameters become lambda binders, including unused parameters. All type parameters appearing in the body must occur in the inferred function type; the kernel enforces this generalization condition.

Mojo

definitions.mojo Download
"""Define typed functions and unfold exactly the selected occurrence."""

from judgment import Session, arrow


def main() raises:
    var s = Session()
    var point = s.declare_type("Point")
    var map_ = s.symbol("map", arrow(point, point))

    var definition = s.definition("identity", transparent=False)
    var A = definition.type_var("A")
    var value = definition.var("value", A)
    var identity = definition.finish(value)
    var id = identity.symbol(type_args=[point])

    var proof = s.theorem("nested_identity")
    var x = proof.var("x", point)
    proof.goal(map_(id(id(x))) == map_(x))
    _ = proof.lhs().at(id(id(x))).unfold(identity).unfold(identity)
    proof.rfl()
    print(proof.finish())

    # Opaque definitions still provide checked defining equations.
    print(identity.equation())

    var P = s.prop("P")
    var alias = s.define("Alias", P)
    var conversion = s.theorem("alias", alias.symbol() == P)
    conversion.change(P == P, unfold=[alias])
    conversion.rfl()
    print(conversion.finish())

Run from the repository root pixi run core-run docs/examples/library/definitions.mojo

Output

⊢ ∀x:Point. map(identity(identity(x))) = map(x)
[A] ⊢ identity = (λvalue:A. value)
⊢ Alias = P

Python

definitions.py Download
"""Define typed functions and unfold exactly the selected occurrence."""

from judgment import Session, arrow


def main():
    s = Session()
    point = s.declare_type("Point")
    map_ = s.symbol("map", arrow(point, point))

    definition = s.definition("identity", transparent=False)
    A = definition.type_var("A")
    value = definition.var("value", A)
    identity = definition.finish(value)
    id = identity.symbol(type_args=[point])

    proof = s.theorem("nested_identity")
    x = proof.var("x", point)
    proof.goal(map_(id(id(x))) == map_(x))
    _ = proof.lhs().at(id(id(x))).unfold(identity).unfold(identity)
    proof.rfl()
    print(proof.finish())

    # Opaque definitions still provide checked defining equations.
    print(identity.equation())

    P = s.prop("P")
    alias = s.define("Alias", P)
    conversion = s.theorem("alias", alias.symbol() == P)
    conversion.change(P == P, unfold=[alias])
    conversion.rfl()
    print(conversion.finish())


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/definitions.py

Output

⊢ ∀x:Point. map(identity(identity(x))) = map(x)
[A] ⊢ identity = (λvalue:A. value)
⊢ Alias = P

Completion returns a Definition. symbol() returns its symbolic constant; monomorphic functions also support direct calls such as duplicate(P). For a generic definition, supply every declared type argument to symbol(type_args=[...]), in header order, then call the resulting expression. Unused declared type parameters still require explicit arguments. Creating or applying a symbol does not unfold it.

equation() returns a checked Fact stating that the symbol equals its body. For functions, the body is displayed as a lambda. Generic equations retain their declared type parameters and can be specialized with proof.use. They are function equalities, so terms does not supply lambda arguments as though they were universal quantifiers. Use unfold to expand a selected function application.

proof.lhs().at(expression).unfold(definition) expands exactly that occurrence, using the checked defining equation and congruence. Its refreshed focus supports chaining. proof.unfold(definition) instead expands a definition at the root of the whole target. Each call expands one definition application; nested calls remain explicit. Ordinary, curried, partial, and overapplied functions are supported. Partial expansion leaves a lambda, with bound names freshened to avoid capture. Lambdas, like quantifiers, are opaque to occurrence searches inside their bodies; use under(name) to transform a body explicitly.

Transparency controls conversion, not equation availability. Both transparent and opaque definitions can be explicitly unfolded with their equations. change(target, unfold=[definition]) permits conversion through the supplied transparent definitions; opaque entries are rejected by the kernel. Plain change(target) retains an empty unfolding set. No automatic simplification or recursive definition expansion is enabled.

Definition headers and proofs retain their creation-time theory snapshots. Create a consumer after completing the definitions it needs. Successful completion advances the active session theory; failed completion publishes no declaration, leaves the header editable, and does not refund work. Failed unfolding preserves the goal and its selection version. These are global, nonrecursive definitions. Proof-local abbreviations use proof.define, described below; recursive definition packages remain outside this API.

Arithmetic and readable algebra

Bind notation with s.arithmetic(kind, zero=..., one=..., add=..., mul=..., neg=...). The carrier is a concrete global type, the constants have that type, add and mul have type kind → kind → kind, and optional neg has type kind → kind. Binding checks these types and scopes. It adds no axioms, canonical operator registrations, or automatic simplifications. Each carrier has one profile per session; rebinding is refused.

Expressions of the carrier support +, *, and natural powers **. With negation bound, they also support unary - and subtraction, defined as addition of the negative. Integer operands on either side use that carrier; expr == 0 constructs symbolic equality. profile.number(n) constructs a standalone numeral. Zero and one denote the supplied constants, larger numerals are left-associated additions of one, and negative numerals apply negation. These initial bindings use symbolic numerals. Large numerals and powers consume work proportional to their expansion. Exact profiles below make numeric literals compact; natural powers still use the explicit product definition.

x**0 denotes one, x**1 denotes x, and higher powers are left-associated products. Negative powers require inverse semantics and are currently refused. Authored powers retain their compact display and one displayed base. A rewrite of that base lifts through the entire power by kernel congruence. Selection uses canonical matching: for x**1, both the whole power and its base match x, so at(x, occurrence=2) selects the base. Numerals are opaque authored atoms; rewriting inside their hidden addition expansion is not an occurrence operation.

The following example proves the square-of-sum identity in three explicit steps:

sum_squared.mojo Download
"""Prove a square-of-sum identity through three readable, checked steps."""

from judgment import Session
from arithmetic_setup import arithmetic_setup


def main() raises:
    var s = Session()
    var algebra = arithmetic_setup(s)
    var proof = s.theorem("sum_squared")
    var ab = proof.vars("a b", algebra.kind)
    var a, b = ab[0], ab[1]
    proof.goal((a + b)**2 == a**2 + 2 * a * b + b**2)

    _ = (
        proof.lhs()
        .change((a + b) * (a + b))
        .to(a**2 + a * b + b * a + b**2, using=algebra.expand)
        .to(a**2 + 2 * a * b + b**2, using=algebra.collect)
    )
    proof.rfl()
    var theorem = proof.finish()
    print(theorem)

Run from the repository root pixi run core-run docs/examples/library/sum_squared.mojo --include docs/examples/library

Output

[assuming 4 axioms] ⊢ ∀a:S. ∀b:S. (a + b)**2 = a**2 + 2 * a * b + b**2
  axioms: add_assoc, mul_comm, mul_one, left_distrib

The first step uses change: natural powers already have their product meaning. Distribution and collection pass their checked lemmas directly to to(..., using=...). Both endpoints determine a and b, so the source keeps each intermediate expression without repeating proof.use(..., terms=[a, b]). These are algebraic equalities, so change alone cannot justify them.

The example declares an abstract carrier S with addition, multiplication, zero, and one. It explicitly assumes four laws: add_assoc, mul_comm, mul_one, and left_distrib. Thus ∀a:S. ∀b:S. quantifies over this fixed carrier in a theory containing those assumptions; it does not assert the identity for every type or every interpretation of + and *. These four laws are only the subset used by this proof, not a declaration of a complete semiring structure.

In particular, mul_comm justifies replacing b * a with a * b before collecting the cross terms. For general square matrices the expansion retains both terms: (A + B)² = A² + AB + BA + B². Replacing them with 2AB requires AB = BA. The theorem prints [assuming 4 axioms] on the statement line and lists their names below it. To read the actual laws, use print(theorem.format(details=True)):

[assuming 4 axioms] ⊢ ∀a:S. ∀b:S. (a + b)**2 = a**2 + 2 * a * b + b**2
Global axioms (4):
  add_assoc: ∀a:S. ∀b:S. ∀c:S. a + b + c = a + (b + c)
  mul_comm: ∀a:S. ∀b:S. a * b = b * a
  mul_one: ∀x:S. S.one * x = x
  left_distrib: ∀a:S. ∀b:S. ∀c:S. a * (b + c) = a * b + a * c

The short display previews at most four names and reports how many remain. Expanded formatting includes all laws, with their original type headers when generic. A law keeps its original statement even after switching to a branch that reuses its name. These lists describe the checked derivation's dependencies; they do not claim every law is mathematically necessary for the result.

The setup does not construct the real numbers. It supplies its four laws to an ordinary Mojo module that proves the expansion and collection lemmas, then passes their checked facts to the final proof. The defaults preserve the original S and unqualified law names. Supplying a distinct carrier_name and fact prefix lets another setup coexist in the same session:

arithmetic_setup.mojo Download
"""Explicit assumptions and checked helper lemmas for the algebra example."""

from judgment import Arithmetic, Fact, Session, TypeExpr, arrow
from algebra_lemmas import right_distributivity, square_lemmas


@fieldwise_init
struct Algebra(Copyable):
    """Notation and proved steps over an abstract arithmetic carrier."""

    var kind: TypeExpr
    var numbers: Arithmetic
    var expand: Fact
    var collect: Fact


def arithmetic_setup(
    mut s: Session, carrier_name: String = "S", prefix: String = "",
) raises -> Algebra:
    """Bind notation and derive helpers from four named semiring assumptions.

    This example assumes only the laws it uses. It does not construct the real
    numbers or claim that binding arithmetic notation proves any algebraic law.
    A distinct carrier_name and fact prefix let independent setups coexist.
    """
    var names = prefix
    if names.byte_length() != 0:
        names += "."
    var S = s.declare_type(carrier_name)
    var zero = s.symbol(carrier_name + ".zero", S)
    var one = s.symbol(carrier_name + ".one", S)
    var binary = arrow(S, arrow(S, S))
    var add = s.symbol(carrier_name + ".add", binary)
    var mul = s.symbol(carrier_name + ".mul", binary)
    var numbers = s.arithmetic(S, zero=zero, one=one, add=add, mul=mul)

    var law = s.axiom(names + "add_assoc")
    var abc = law.vars("a b c", S)
    var a, b, c = abc[0], abc[1], abc[2]
    var add_assoc = law.finish((a + b) + c == a + (b + c))

    var comm = s.axiom(names + "mul_comm")
    var ab = comm.vars("a b", S)
    var mul_comm = comm.finish(ab[0] * ab[1] == ab[1] * ab[0])

    var unit = s.axiom(names + "mul_one")
    var x = unit.var("x", S)
    var mul_one = unit.finish(one * x == x)

    var distrib = s.axiom(names + "left_distrib")
    abc = distrib.vars("a b c", S)
    a, b, c = abc[0], abc[1], abc[2]
    var left_distrib = distrib.finish(a * (b + c) == a * b + a * c)

    var right_distrib = right_distributivity(
        s, S, mul_comm, left_distrib, name=names + "right_distrib",
    )
    var lemmas = square_lemmas(
        s, S, one,
        add_assoc=add_assoc, mul_one=mul_one,
        left_distrib=left_distrib, right_distrib=right_distrib,
        prefix=prefix,
    )

    var collect = s.theorem(names + "collect_cross_terms")
    ab = collect.vars("a b", S)
    a, b = ab[0], ab[1]
    collect.goal(a**2 + a * b + b * a + b**2 == a**2 + 2 * a * b + b**2)
    var commute = collect.use(mul_comm, terms=[a, b])
    _ = collect.apply(lemmas.collect_of_commute, using=[commute])
    return Algebra(S, numbers, lemmas.expand, collect.finish())

Use s.axiom(name, proposition) to explicitly assume a closed proposition, or start s.axiom(name), declare typed parameters, and call finish(proposition). An axiom header accepts the same type and term parameter operations as theorem headers. Its parameters are universally closed; declared unused type parameters remain available for explicit specialization. Axioms print with [axiom] and are available through s.fact(name). This operation admits an assumption; it performs no proof search and is separate from sorry. Labels classify such an axiom UNCLASSIFIED. A profile builder declares its axioms with s.profile_axiom(name, proposition) instead: the same operation, classified PROFILE_AXIOM, and kept so by snapshots and seals.

fact.axioms() lists the names of the global axioms on which the checked evidence actually depends, including transitive theorem and canonical-signature law dependencies. Merely visible unused axioms are excluded. Local hypotheses are premises, not global axioms, and are not included in this list. The four names printed by the example are therefore the assumptions of its proof.

Axiom publication is staged: failure publishes no name or active theory change, and the header can be retried. Consumers retain their creation-time theory snapshots, so create a proof after the axioms and generic theorems it needs.

Reuse algebra proofs across carriers

The shared module takes a carrier with symbolic arithmetic notation, its unit, and four explicit law facts. right_distributivity separately derives one of those laws when global multiplication commutativity is available. The square proofs accept the resulting theorem just as they accept an axiom; their dependencies remain visible. Neither function declares an axiom.

SquareLemmas holds three proved facts: expansion with both cross terms, doubling a product, and collection under the local premise a*b == b*a. The latter can be used when two particular elements commute, even if other elements of the carrier do not. These are ordinary example helpers, not a new library API or a validator for a complete semiring law set.

algebra_lemmas.mojo Download
"""Reusable square proofs from supplied operations and law evidence."""

from judgment import Expr, Fact, Session, TypeExpr


@fieldwise_init
struct SquareLemmas(Copyable):
    """Checked facts; collecting cross terms still requires commutation."""

    var expand: Fact
    var double_product: Fact
    var collect_of_commute: Fact


def right_distributivity(
    mut s: Session,
    kind: TypeExpr,
    mul_comm: Fact,
    left_distrib: Fact,
    name: String = "right_distrib",
) raises -> Fact:
    """Derive right distributivity when multiplication is commutative."""
    var proof = s.theorem(name)
    var abc = proof.vars("a b c", kind)
    var a, b, c = abc[0], abc[1], abc[2]
    proof.goal((a + b) * c == a * c + b * c)
    _ = proof.lhs().rw(mul_comm)
    _ = proof.lhs().rw(left_distrib)
    _ = proof.lhs().at(c * a).rw(mul_comm)
    _ = proof.lhs().at(c * b).rw(mul_comm)
    proof.rfl()
    return proof.finish()


def square_lemmas(
    mut s: Session,
    kind: TypeExpr,
    one: Expr,
    add_assoc: Fact,
    mul_one: Fact,
    left_distrib: Fact,
    right_distrib: Fact,
    prefix: String = "",
) raises -> SquareLemmas:
    """Prove square steps using the carrier's already-bound arithmetic notation.

    The supplied facts may be axioms or proved lemmas. Their actual dependencies
    flow through each kernel-checked rewrite. No law is assumed by this module.
    """
    var names = prefix
    if names.byte_length() != 0:
        names += "."

    var expand = s.theorem(names + "expand_square_product")
    var ab = expand.vars("a b", kind)
    var a, b = ab[0], ab[1]
    expand.goal((a + b) * (a + b) == a**2 + a * b + b * a + b**2)
    _ = expand.lhs().rw(right_distrib)
    _ = expand.lhs().at(a * (a + b)).rw(left_distrib)
    _ = expand.lhs().at(b * (a + b)).rw(left_distrib)
    _ = expand.lhs().rw(add_assoc, reverse=True)
    expand.rfl()
    var expanded = expand.finish()

    var double = s.theorem(names + "double_product")
    ab = double.vars("a b", kind)
    a, b = ab[0], ab[1]
    double.goal(a * b + a * b == 2 * a * b)
    # Inference does not split the numeral 2 into its defining sum of ones.
    _ = double.rhs().at(2 * a).rw(double.use(right_distrib, terms=[one, one, a]))
    _ = double.rhs().at(one * a, occurrence=1).rw(mul_one)
    _ = double.rhs().at(one * a).rw(mul_one)
    _ = double.rhs().rw(right_distrib)
    double.rfl()
    var doubled = double.finish()

    var collect = s.theorem(names + "collect_cross_terms_of_commute")
    ab = collect.vars("a b", kind)
    a, b = ab[0], ab[1]
    var commute = collect.given("commute", a * b == b * a)
    collect.goal(a**2 + a * b + b * a + b**2 == a**2 + 2 * a * b + b**2)
    _ = collect.lhs().at(b * a).rw(commute, reverse=True)
    _ = collect.lhs().at(a**2 + a * b + a * b).rw(add_assoc)
    _ = collect.lhs().at(a * b + a * b).rw(doubled)
    collect.rfl()
    return SquareLemmas(expanded, doubled, collect.finish())

rw(law) infers arguments from the chosen occurrence; the rule and occurrence remain explicit. The doubling proof keeps one use(..., terms=[one, one, a]) because inference does not split the authored numeral 2 into one + one. That specialization supplies the checked equality for rewriting 2 * a.

The following executable client uses the shared proofs twice in one session. C assumes multiplication commutativity and derives right-distributivity. M supplies both distributive laws and makes no commutativity assumption. They have distinct types, operations, and fact prefixes. Neither is a construction of the reals or matrices.

reusable_algebra.mojo Download
"""Reuse the same square proofs with and without global commutativity."""

from std.testing import assert_equal, assert_true
from judgment_shell import LibErrorKind, Session, arrow
from algebra_lemmas import square_lemmas
from arithmetic_setup import arithmetic_setup


def main() raises:
    var s = Session()
    var C = arithmetic_setup(s, carrier_name="C", prefix="C")
    var commutative = s.theorem("C.sum_squared")
    var ab = commutative.vars("a b", C.kind)
    var a, b = ab[0], ab[1]
    commutative.goal((a + b)**2 == a**2 + 2 * a * b + b**2)
    _ = commutative.lhs().change((a + b) * (a + b)).rw(C.expand).rw(C.collect)
    commutative.rfl()
    var result = commutative.finish()
    assert_equal(len(result.axioms()), 4)
    assert_equal(len(result.admissions()), 0)
    print(result)

    # M has distinct operations and four explicit laws. Multiplication need not
    # commute. This is an abstract example, not a construction of matrices.
    var M = s.declare_type("M")
    var zero = s.symbol("M.zero", M)
    var one = s.symbol("M.one", M)
    var binary = arrow(M, arrow(M, M))
    var add = s.symbol("M.add", binary)
    var mul = s.symbol("M.mul", binary)
    _ = s.arithmetic(M, zero=zero, one=one, add=add, mul=mul)

    var assoc = s.axiom("M.add_assoc")
    var abc = assoc.vars("a b c", M)
    a, b = abc[0], abc[1]
    var c = abc[2]
    var add_assoc = assoc.finish((a + b) + c == a + (b + c))

    var unit = s.axiom("M.mul_one")
    var x = unit.var("x", M)
    var mul_one = unit.finish(one * x == x)

    var left = s.axiom("M.left_distrib")
    abc = left.vars("a b c", M)
    a, b, c = abc[0], abc[1], abc[2]
    var left_distrib = left.finish(a * (b + c) == a * b + a * c)

    var right = s.axiom("M.right_distrib")
    abc = right.vars("a b c", M)
    a, b, c = abc[0], abc[1], abc[2]
    var right_distrib = right.finish((a + b) * c == a * c + b * c)

    # The same module also accepts proved laws: C's setup derives its
    # right-distributivity law before calling this function.
    var squares = square_lemmas(
        s, M, one,
        add_assoc=add_assoc, mul_one=mul_one,
        left_distrib=left_distrib, right_distrib=right_distrib,
        prefix="M",
    )

    var expansion = s.theorem("M.expand_square")
    ab = expansion.vars("a b", M)
    a, b = ab[0], ab[1]
    expansion.goal((a + b)**2 == a**2 + a * b + b * a + b**2)
    _ = expansion.lhs().change((a + b) * (a + b)).rw(squares.expand)
    expansion.rfl()
    var expanded = expansion.finish()
    assert_equal(len(expanded.axioms()), 3)
    assert_equal(len(expanded.admissions()), 0)
    print(expanded)

    var conditional = s.theorem("M.sum_squared_of_commute")
    ab = conditional.vars("a b", M)
    a, b = ab[0], ab[1]
    var commute = conditional.given("commute", a * b == b * a)
    conditional.goal((a + b)**2 == a**2 + 2 * a * b + b**2)
    _ = conditional.lhs().rw(expanded).rw(squares.collect_of_commute, using=[commute])
    conditional.rfl()
    result = conditional.finish()
    assert_equal(len(result.axioms()), 4)
    assert_equal(len(result.admissions()), 0)
    for name in result.axioms():
        assert_true(name.startswith("M."))
    print(result)

    # Namespaces and types isolate the two independent setups.
    assert_true(not M.same_as(C.kind))
    assert_equal(len(s.find("C.", limit=100)), 10)
    assert_equal(len(s.find("M.", limit=100)), 9)
    var consumer = s.theorem("M.commutation_is_still_required")
    ab = consumer.vars("a b", M)
    a, b = ab[0], ab[1]
    consumer.goal(a * b == b * a)
    var original = consumer.target()
    var refused = False
    try:
        _ = consumer.apply(s.fact("C.mul_comm"))
    except error:
        refused = error.kind == LibErrorKind.NO_MATCH
    assert_true(refused)
    assert_true(consumer.target().same_as(original))
    assert_equal(len(consumer.obligations()), 1)
    print("Cross-carrier law refused; commutation goal remains open")

Run from the repository root pixi run mojo run -I src docs/examples/library/reusable_algebra.mojo

Output

[assuming 4 axioms] ⊢ ∀a:C. ∀b:C. (a + b)**2 = a**2 + 2 * a * b + b**2
  axioms: C.add_assoc, C.mul_comm, C.mul_one, C.left_distrib
[assuming 3 axioms] ⊢ ∀a:M. ∀b:M. (a + b)**2 = a**2 + a * b + b * a + b**2
  axioms: M.add_assoc, M.left_distrib, M.right_distrib
[assuming 4 axioms] ⊢ ∀a:M. ∀b:M. a * b = b * a → (a + b)**2 = a**2 + 2 * a * b + b**2
  axioms: M.add_assoc, M.mul_one, M.left_distrib, M.right_distrib
Cross-carrier law refused; commutation goal remains open

The first M result retains a*b + b*a; the second retains the explicit commutation premise. Neither depends on any C axiom. Applying C.mul_comm to an M goal fails with NO_MATCH and leaves that goal open.

The saving comes from writing the lemma proofs once and passing their facts to later clients. The existing short square example keeps its four assumptions and its printed result; the new carrier needs only its own operation bindings and law evidence, followed by the same helper call. A prefix qualifies names rather than providing a separate namespace object. Helpers publish proofs in sequence, so a later failure can leave earlier completed lemmas; callers choose fresh names and use existing transactions if they need allocation rollback.

Compact exact integers and rationals

The notation-only profile remains available. To explicitly enable exact literals, call profile.integers(name, lt, le, laws) or profile.rationals(name, lt, le, inv, laws). These calls require a concrete carrier with plain constant operations and checked, closed, monomorphic law facts. They assume no laws themselves. The kernel validates all required statements, registers addition and multiplication as associative and commutative with their respective units, and registers its built-in exact literal implementation.

This is an explicit canonicalization choice: association, commutativity, units, and literal arithmetic become kernel computation. Symbolic distributivity still requires theorem evidence. There is no automatic simplifier or proof search. Each carrier can be upgraded once; integer profiles cannot silently become rational profiles, and operations cannot be rebound.

ArithmeticLaws holds named facts in any input order. Required slots are:

Laws Slots
Addition add_assoc, add_comm, add_zero
Multiplication mul_assoc, mul_comm, mul_one
Ring operations add_inverse, left_distrib
Strict order lt_irrefl, lt_trans, lt_total, lt_add, lt_mul, zero_lt_one
Nonstrict order le_iff
Rational inverse only mul_inverse

add_zero and mul_one state the left-unit laws. left_distrib states x*(y+z) = x*y+x*z; mul_inverse states x != 0 → x*inv(x) = 1. not_(p) and iff(p, q) construct the kernel's logical negation and equivalence for these law statements. The source modules below give every exact quantified formula. A law can be proved or explicitly assumed; a local hypothesis or an unspecialized generic fact is not sufficient. Registration stages all citations, ACU declarations, and the literal kind before publishing anything.

Mojo

exact_arithmetic.mojo Download
"""Use compact exact literals with an explicitly registered arithmetic profile."""

from judgment import Session
from exact_arithmetic_setup import numeric_setup


def main() raises:
    var s = Session()
    var setup = numeric_setup(s, "Q", rational=True)
    var q = setup.register_rationals("rational_literals")
    var half = q.rational(1, 2)
    var third = q.rational(1, 3)
    var proof = s.theorem("fraction_sum", half + third == q.rational(5, 6))
    proof.rfl()
    var theorem = proof.finish()
    print(theorem)

    # Retrieve the same profile by carrier; its large numeral remains one node.
    var again = s.arithmetic(setup.kind)
    var large = again.number("123456789012345678901234567890")
    var arithmetic = s.theorem("large_sum", large + 1 == q.number("123456789012345678901234567891"))
    arithmetic.rfl()
    print(arithmetic.finish())
    print("Reduced fraction:", q.rational(-10, -12).format())
    print("Inverse of zero:", q.inverse(q.number(0)).format())

Run from the repository root pixi run mojo run -I src docs/examples/library/exact_arithmetic.mojo

Output

[assuming 16 axioms] ⊢ 1/2 + 1/3 = 5/6
  axioms: Q.add_assoc, Q.add_comm, Q.add_zero, Q.mul_assoc, … (+12 more)
[assuming 16 axioms] ⊢ 123456789012345678901234567890 + 1 = 123456789012345678901234567891
  axioms: Q.add_assoc, Q.add_comm, Q.add_zero, Q.mul_assoc, … (+12 more)
Reduced fraction: 5/6
Inverse of zero: Q.inv(0)

Python

exact_arithmetic.py Download
"""Use compact exact literals with an explicitly registered arithmetic profile."""

from judgment import Session
from exact_arithmetic_setup import numeric_setup


def main():
    s = Session()
    setup = numeric_setup(s, "Q", rational=True)
    q = setup.register_rationals("rational_literals")
    half = q.rational(1, 2)
    third = q.rational(1, 3)
    proof = s.theorem("fraction_sum", half + third == q.rational(5, 6))
    proof.rfl()
    theorem = proof.finish()
    print(theorem)

    # Retrieve the same profile by carrier; its large numeral remains one node.
    again = s.arithmetic(setup.kind)
    large = again.number("123456789012345678901234567890")
    arithmetic = s.theorem("large_sum", large + 1 == q.number("123456789012345678901234567891"))
    arithmetic.rfl()
    print(arithmetic.finish())
    print("Reduced fraction:", q.rational(-10, -12).format())
    print("Inverse of zero:", q.inverse(q.number(0)).format())


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/exact_arithmetic.py

Output

[assuming 16 axioms] ⊢ 1/2 + 1/3 = 5/6
  axioms: Q.add_assoc, Q.add_comm, Q.add_zero, Q.mul_assoc, … (+12 more)
[assuming 16 axioms] ⊢ 123456789012345678901234567890 + 1 = 123456789012345678901234567891
  axioms: Q.add_assoc, Q.add_comm, Q.add_zero, Q.mul_assoc, … (+12 more)
Reduced fraction: 5/6
Inverse of zero: Q.inv(0)

The provider's setup.register_rationals("rational_literals") forwards its operations and law evidence to Arithmetic.rationals. Its name makes the canonicalization change explicit while avoiding a repeated field list. The registration name remains supplied by the client.

After registration, number(Int), number(Integer), and number(decimal_text) produce compact exact literals. The Integer overload accepts arbitrary precision from apn_mojo; decimal text permits a sign and rejects whitespace or malformed digits. rational(numerator, denominator) accepts machine integers or APN integers, reduces the fraction, and requires a nonzero denominator. No floating-point conversion occurs. Literal construction and formatting consume bounded work based on input size, rather than the magnitude of a repeated-addition expansion.

profile.inverse(expr) applies the rational inverse operation. The inverse of zero remains an ordinary symbolic expression; a rational literal with denominator zero is rejected. There is no inverse operation on exact integer profiles. Fractions and negative numerals are parenthesized when used as power bases, so (2/3)**2 and (-2)**2 cannot be confused with different expressions.

Retrieve a profile with s.arithmetic(kind). Every profile handle for the carrier sees its current registration, including a handle retained before the upgrade. Handles preserve session ownership; they are not historical theory snapshots. Expressions and proofs do retain their authored construction signatures. A proof created before registration cannot use later canonical rules through a numeral, selector query, or argument erased by computation. It can still finish under its original theory. Rebuild expressions after registration when their old canonical nodes changed; stale nested expressions are rejected as well as stale roots.

proof.use(old_fact) explicitly rebuilds the fact's authored syntax in the consuming proof's theory, including hidden numeric atoms and remaining binders. It preserves the original equation display even if the kernel represents a literal equality as True. Saved facts retain their original evidence and syntax. Their reuse and numeric computation report supporting signature laws through axioms(). Existing definition/axiom headers validate their input in their original scope, then rebuild the closed statement when publishing into a newer active signature.

Shared ring assumptions

The exact-arithmetic and polynomial fixtures share the eight ring-law declarations through assume_commutative_ring_laws. Its name marks the assumption boundary: each returned fact comes from an explicitly named s.axiom, including mul_comm. The helper uses the supplied carrier, zero, and one with its already-bound addition, multiplication, and negation. It preserves the law names and formulas and returns entries for the existing ArithmeticLaws constructor.

Mojo

ring_assumptions.mojo Download
"""Shared, explicitly assumed commutative ring laws for arithmetic examples."""

from judgment_shell import Expr, Fact, LibError, Session, TypeExpr


def assume_commutative_ring_laws(
    mut s: Session, kind: TypeExpr, zero: Expr, one: Expr, prefix: String,
) raises LibError -> List[Tuple[String, Fact]]:
    """Declare eight named axioms using the carrier's bound arithmetic notation.

    Addition, multiplication, and negation must already be bound. Each axiom is
    published as prefix.slot. The returned entries can be extended with order
    or coefficient laws before constructing ArithmeticLaws. This assumes laws;
    it does not prove them or register exact arithmetic.
    """
    var names: List[String] = ["add_assoc", "add_comm", "add_zero", "mul_assoc", "mul_comm", "mul_one", "add_inverse", "left_distrib"]
    var arities: List[Int] = [3, 2, 1, 3, 2, 1, 1, 3]
    var entries = List[Tuple[String, Fact]]()
    for i in range(len(names)):
        var law = s.axiom(prefix + "." + names[i])
        var x = law.var("x", kind)
        var y = zero
        var z = zero
        if arities[i] > 1:
            y = law.var("y", kind)
        if arities[i] > 2:
            z = law.var("z", kind)
        var statement: Expr
        if i == 0:
            statement = (x + y) + z == x + (y + z)
        elif i == 1:
            statement = x + y == y + x
        elif i == 2:
            statement = zero + x == x
        elif i == 3:
            statement = (x * y) * z == x * (y * z)
        elif i == 4:
            statement = x * y == y * x
        elif i == 5:
            statement = one * x == x
        elif i == 6:
            statement = x + (-x) == zero
        else:
            statement = x * (y + z) == x * y + x * z
        entries.append((names[i], law.finish(statement)))
    return entries^

Python

ring_assumptions.py Download
"""Shared, explicitly assumed commutative ring laws for arithmetic examples."""

from judgment import Expr, Fact, JudgmentError, Session, TypeExpr


def assume_commutative_ring_laws(s, kind, zero, one, prefix):
    """Declare eight named axioms using the carrier's bound arithmetic notation.

    Addition, multiplication, and negation must already be bound. Each axiom is
    published as prefix.slot. The returned entries can be extended with order
    or coefficient laws before constructing ArithmeticLaws. This assumes laws;
    it does not prove them or register exact arithmetic.
    """
    names = ["add_assoc", "add_comm", "add_zero", "mul_assoc", "mul_comm", "mul_one", "add_inverse", "left_distrib"]
    arities = [3, 2, 1, 3, 2, 1, 1, 3]
    entries = []
    for i in range(len(names)):
        law = s.axiom(prefix + "." + names[i])
        x = law.var("x", kind)
        y = zero
        z = zero
        if arities[i] > 1:
            y = law.var("y", kind)
        if arities[i] > 2:
            z = law.var("z", kind)
        statement = None
        if i == 0:
            statement = (x + y) + z == x + (y + z)
        elif i == 1:
            statement = x + y == y + x
        elif i == 2:
            statement = zero + x == x
        elif i == 3:
            statement = (x * y) * z == x * (y * z)
        elif i == 4:
            statement = x * y == y * x
        elif i == 5:
            statement = one * x == x
        elif i == 6:
            statement = x + (-x) == zero
        else:
            statement = x * (y + z) == x * y + x * z
        entries.append((names[i], law.finish(statement)))
    return entries

The numeric setup appends seven order laws and, for rationals, one inverse law. That gives the same fifteen or sixteen named assumptions. The polynomial setup appends four coefficient laws to its own eight ring laws. Exact registration is still a separate explicit operation that validates the completed law set. The helper itself assumes laws without enabling canonicalization, and publishes its axioms in sequence rather than as an atomic installation.

The numeric fixture remains an abstract teaching setup; it does not construct the mathematical integers, rationals, or reals:

Mojo

exact_arithmetic_setup.mojo Download
"""Explicit teaching assumptions for reusable exact arithmetic profiles.

These are assumed ordered-ring/field laws over an abstract carrier, not a
construction of the mathematical integers or rationals.
"""

from judgment_shell import Arithmetic, ArithmeticLaws, Expr, LibError, LibErrorKind, Session, TypeExpr, arrow, iff, implies, not_
from ring_assumptions import assume_commutative_ring_laws


@fieldwise_init
struct NumericSetup(Copyable):
    """Typed operations and the complete explicit law bundle."""

    var kind: TypeExpr
    var numbers: Arithmetic
    var lt: Expr
    var le: Expr
    var inv: Optional[Expr]
    var laws: ArithmeticLaws

    def register_integers(self, name: String) raises LibError -> Arithmetic:
        """Explicitly enable exact integers using this provider's operations and laws.

        Args:
            name: The client's fresh literal-kind name and private law-name prefix.

        Returns:
            The checked Arithmetic profile with canonical integer arithmetic enabled.

        Raises:
            LibError: For invalid operations, evidence, names, or exhausted work.
                Failure publishes no theory or profile change.
        """
        return self.numbers.integers(name, self.lt, self.le, self.laws)

    def register_rationals(self, name: String) raises LibError -> Arithmetic:
        """Explicitly enable exact rationals using this provider's operations and laws.

        Args:
            name: The client's fresh literal-kind name and private law-name prefix.

        Returns:
            The checked Arithmetic profile with canonical rational arithmetic enabled.

        Raises:
            LibError: UNSUPPORTED if this setup has no inverse; otherwise the
                registration's errors for invalid operations, evidence, names,
                or exhausted work. Failure publishes no theory or profile change.
        """
        if not self.inv:
            raise LibError(LibErrorKind.UNSUPPORTED, "rational registration requires a setup with an inverse")
        return self.numbers.rationals(name, self.lt, self.le, self.inv.value(), self.laws)


def numeric_setup(mut s: Session, prefix: String, rational: Bool) raises -> NumericSetup:
    """Declare operations and assume each law explicitly, before exact registration."""
    var T = s.declare_type(prefix + ".T")
    var zero = s.symbol(prefix + ".zero", T)
    var one = s.symbol(prefix + ".one", T)
    var binary = arrow(T, arrow(T, T))
    var add = s.symbol(prefix + ".add", binary)
    var mul = s.symbol(prefix + ".mul", binary)
    var neg = s.symbol(prefix + ".neg", arrow(T, T))
    var relation = arrow(T, arrow(T, s.prop_type()))
    var lt = s.symbol(prefix + ".lt", relation)
    var le = s.symbol(prefix + ".le", relation)
    var inv: Optional[Expr] = None
    if rational:
        inv = s.symbol(prefix + ".inv", arrow(T, T))
    var numbers = s.arithmetic(T, zero, one, add, mul, neg)
    var entries = assume_commutative_ring_laws(s, T, zero, one, prefix)
    var names: List[String] = ["lt_irrefl", "lt_trans", "lt_total", "lt_add", "lt_mul", "zero_lt_one", "le_iff"]
    var arities: List[Int] = [1, 3, 2, 3, 2, 0, 2]
    if rational:
        names.append("mul_inverse")
        arities.append(1)
    for i in range(len(names)):
        var law = s.axiom(prefix + "." + names[i])
        var x = zero
        var y = zero
        var z = zero
        if arities[i] > 0:
            x = law.var("x", T)
        if arities[i] > 1:
            y = law.var("y", T)
        if arities[i] > 2:
            z = law.var("z", T)
        var statement: Expr
        if i == 0:
            statement = not_(lt(x, x))
        elif i == 1:
            statement = implies(lt(x, y), implies(lt(y, z), lt(x, z)))
        elif i == 2:
            statement = lt(x, y) | ((x == y) | lt(y, x))
        elif i == 3:
            statement = implies(lt(x, y), lt(x + z, y + z))
        elif i == 4:
            statement = implies(lt(zero, x), implies(lt(zero, y), lt(zero, x * y)))
        elif i == 5:
            statement = lt(zero, one)
        elif i == 6:
            statement = iff(le(x, y), lt(x, y) | (x == y))
        else:
            statement = implies(not_(x == zero), x * inv.value()(x) == one)
        entries.append((names[i], law.finish(statement)))
    return NumericSetup(T, numbers, lt, le, inv, ArithmeticLaws(entries^))

Python

exact_arithmetic_setup.py Download
"""Explicit teaching assumptions for reusable exact arithmetic profiles.

These are assumed ordered-ring/field laws over an abstract carrier, not a
construction of the mathematical integers or rationals.
"""

from __future__ import annotations

from dataclasses import dataclass

from judgment import Arithmetic, ArithmeticLaws, Expr, JudgmentError, LibErrorKind, Session, TypeExpr, arrow, iff, implies, not_
from ring_assumptions import assume_commutative_ring_laws


@dataclass
class NumericSetup:
    """Typed operations and the complete explicit law bundle."""

    kind: TypeExpr
    numbers: Arithmetic
    lt: Expr
    le: Expr
    inv: Optional[Expr]
    laws: ArithmeticLaws

    def register_integers(self, name):
        """Explicitly enable exact integers using this provider's operations and laws.

        Args:
            name: The client's fresh literal-kind name and private law-name prefix.

        Returns:
            The checked Arithmetic profile with canonical integer arithmetic enabled.

        Raises:
            LibError: For invalid operations, evidence, names, or exhausted work.
                Failure publishes no theory or profile change.
        """
        return self.numbers.integers(name, self.lt, self.le, self.laws)

    def register_rationals(self, name):
        """Explicitly enable exact rationals using this provider's operations and laws.

        Args:
            name: The client's fresh literal-kind name and private law-name prefix.

        Returns:
            The checked Arithmetic profile with canonical rational arithmetic enabled.

        Raises:
            LibError: UNSUPPORTED if this setup has no inverse; otherwise the
                registration's errors for invalid operations, evidence, names,
                or exhausted work. Failure publishes no theory or profile change.
        """
        if self.inv is None:
            raise LibError(LibErrorKind.UNSUPPORTED, "rational registration requires a setup with an inverse")
        return self.numbers.rationals(name, self.lt, self.le, self.inv, self.laws)


def numeric_setup(s, prefix, rational):
    """Declare operations and assume each law explicitly, before exact registration."""
    T = s.declare_type(prefix + ".T")
    zero = s.symbol(prefix + ".zero", T)
    one = s.symbol(prefix + ".one", T)
    binary = arrow(T, arrow(T, T))
    add = s.symbol(prefix + ".add", binary)
    mul = s.symbol(prefix + ".mul", binary)
    neg = s.symbol(prefix + ".neg", arrow(T, T))
    relation = arrow(T, arrow(T, s.prop_type()))
    lt = s.symbol(prefix + ".lt", relation)
    le = s.symbol(prefix + ".le", relation)
    inv = None
    if rational:
        inv = s.symbol(prefix + ".inv", arrow(T, T))
    numbers = s.arithmetic(T, zero, one, add, mul, neg)
    entries = assume_commutative_ring_laws(s, T, zero, one, prefix)
    names = ["lt_irrefl", "lt_trans", "lt_total", "lt_add", "lt_mul", "zero_lt_one", "le_iff"]
    arities = [1, 3, 2, 3, 2, 0, 2]
    if rational:
        names.append("mul_inverse")
        arities.append(1)
    for i in range(len(names)):
        law = s.axiom(prefix + "." + names[i])
        x = zero
        y = zero
        z = zero
        if arities[i] > 0:
            x = law.var("x", T)
        if arities[i] > 1:
            y = law.var("y", T)
        if arities[i] > 2:
            z = law.var("z", T)
        statement = None
        if i == 0:
            statement = not_(lt(x, x))
        elif i == 1:
            statement = implies(lt(x, y), implies(lt(y, z), lt(x, z)))
        elif i == 2:
            statement = lt(x, y) | ((x == y) | lt(y, x))
        elif i == 3:
            statement = implies(lt(x, y), lt(x + z, y + z))
        elif i == 4:
            statement = implies(lt(zero, x), implies(lt(zero, y), lt(zero, x * y)))
        elif i == 5:
            statement = lt(zero, one)
        elif i == 6:
            statement = iff(le(x, y), lt(x, y) | (x == y))
        else:
            statement = implies(not_(x == zero), x * inv(x) == one)
        entries.append((names[i], law.finish(statement)))
    return NumericSetup(T, numbers, lt, le, inv, ArithmeticLaws(entries))

The setup record offers register_integers(name) and register_rationals(name); both return the existing Arithmetic view. These methods validate the supplied laws through the library's registration API and declare no additional assumptions. An integer-only setup has no inverse, so register_rationals reports LibErrorKind.UNSUPPORTED. Use register_integers for that setup.

Registration failures retain the existing typed errors and publish no theory or profile change. This guarantee applies to registration, not the preceding sequence of setup declarations. The underlying numbers.integers(...) and numbers.rationals(...) methods remain available for explicitly supplied inputs.

Incomplete proofs

sorry() defers the selected goal without producing evidence. finish() rejects the proof while any open or deferred goal remains, including a child of split, apply, or cases, or an intermediate claim created by have or rewrite. Solving a continuation does not discharge the claims it uses. Call resume() on the same handle to reactivate a deferred goal. After resumption, admit(name, reason) can explicitly assume that obligation; this is a distinct, labeled operation described below. Neither sorry nor finish admits anything.

Names are unavailable through s.fact(name) until successful completion. A proof cannot cite itself, repeated completion fails, and concurrent attempts to complete the same name cannot overwrite a registered theorem.

Ownership and limits

Expressions, facts, proofs, and selections retain their session storage through reference counting. Moving or destroying the original Session wrapper does not invalidate surviving objects. Sessions are synchronous and are not thread-safe. Expression, type, and fact handles support cheap implicit copies, so argument lists such as terms=[x, y] and using=[h] need no manual copy markers. Fact text and type-parameter metadata use shared storage that is immutable after return. Owning storage does not grant logical scope: a local assumption still cannot be used in an unrelated proof or sibling context, unless that context assumes the same proposition over the same frame, which makes it the same hypothesis.

Session(work=...) bounds authoring traversals, construction, and formatting. work_remaining() reads the authoring allowance and add_work(amount) explicitly grants more; neither changes the storage limits or refunds earlier work. set_memory_limit(bytes) changes the current workspace's tracked-storage cap; set_spill_directory(directory) and spill() control the shared snapshot bank's verified pages. See memory and spill storage for their scope, live reconfiguration rules and seal/open sequence. Failures use LibError; kernel refusals preserve their original error kind. Facts print a bounded snapshot of the checked statement, with [local] for evidence in a non-root context. Expr.format() renders authored grouping using the remaining work allowance.

Display uses ordinary mathematical precedence. The square-of-a-sum example prints ∀a:S. ∀b:S. (a + b)**2 = a**2 + 2 * a * b + b**2. Parentheses still distinguish a + (b + c) from a + b + c, and (P → Q) → R from P → Q → R. Nested equalities stay explicit, as in (a = b) = P. Quantifiers used inside an operator are delimited too: (∀x:A. P(x)) → Q.

These are display conventions, not simplification steps. Formatting never changes the authored tree or which occurrence a focused rewrite selects. Negative numbers, fractions, and polynomial literals keep the grouping needed when used as power bases or inside other operations. Function types print as A → B → C, with (A → B) → C for a function argument. See the display contract for the complete precedence rules; printed mathematical text is not Mojo source.

Local definitions

proof.define(name, body) introduces a local symbol with the body's inferred type. proof.defining_eq(symbol) supplies its scoped equality. Use that equality in reverse to fold a long expression, or use focus.fold(symbol) directly. focus.unfold(symbol) expands it. proof.focus() selects an entire proposition, including goals that are not equalities.

Mojo

local_definitions.mojo Download
"""Name an expression inside a proof, then fold and unfold it explicitly."""

from judgment import Session, arrow


def main() raises:
    var s = Session()
    var A = s.declare_type("A")
    var f = s.symbol("f", arrow(A, A))
    var proof = s.theorem("named_expression")
    var x = proof.var("x", A)
    proof.goal(f(f(x)) == f(f(x)))

    var t = proof.define("t", f(x))
    _ = proof.lhs().at(f(x)).fold(t)
    print(proof.target().format())
    _ = proof.lhs().at(t).unfold(t)
    proof.rfl()
    print(proof.finish())

Run from the repository root pixi run core-run docs/examples/library/local_definitions.mojo

Output

f(t) = f(f(x))
⊢ ∀x:A. f(f(x)) = f(f(x))

Python

local_definitions.py Download
"""Name an expression inside a proof, then fold and unfold it explicitly."""

from judgment import Session, arrow


def main():
    s = Session()
    A = s.declare_type("A")
    f = s.symbol("f", arrow(A, A))
    proof = s.theorem("named_expression")
    x = proof.var("x", A)
    proof.goal(f(f(x)) == f(f(x)))

    t = proof.define("t", f(x))
    _ = proof.lhs().at(f(x)).fold(t)
    print(proof.target().format())
    _ = proof.lhs().at(t).unfold(t)
    proof.rfl()
    print(proof.finish())


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/local_definitions.py

Output

f(t) = f(f(x))
⊢ ∀x:A. f(f(x)) = f(f(x))

Definitions extend only the selected branch. Their symbols and equations cannot escape to siblings. Completion eliminates the fresh variable and its equation with universal and implication rules, instantiated at the original body. This adds no global declaration or axiom and preserves the declared theorem exactly.

focus.fold(symbol) requires the selected expression itself to match the definition's body. For example, proof.lhs().at(long_expression).fold(u) folds just that occurrence. To fold all eligible occurrences within a selected scope, use proof.lhs().fold(u, all=True) or proof.focus().fold(u, all=True) for the whole goal. The result is a refreshed focus at that same subtree, so folds chain:

_ = proof.focus().fold(u, all=True).fold(v, all=True)

Matching follows canonical equality and authored occurrence order. An outer match takes precedence over its descendants; replacements are never searched again. Lambda and quantifier bodies remain opaque until opened with under, although an entire matching binder may be folded as one expression. The operation uses only the selected local definition's checked equation. No match in the selected scope raises NO_MATCH; stale selections, unavailable definitions, and exhaustion also refuse the operation. An all=True call commits every replacement together, so failure preserves the entire goal and its existing foci. Separate calls in a fluent chain remain separate commits.

Independent equality chains

proof.calc(start) creates a calculation in the selected context. Each chain.eq(next, using=reason, label="optional reason", premises=[]) checks both equality endpoints and infers the chosen theorem's arguments from them and any supplied condition evidence. Omit premises for an unconditional theorem. chain.change(next, unfold=[], label="optional reason") checks a definitional conversion immediately, with only the listed transparent definitions permitted to unfold. It needs no separate step handle or rfl() call. chain.step(name, to=next) returns an independent equality obligation; it can be proved later or deferred with sorry. chain.finish() checks every step and returns a local fact. It neither registers a theorem nor changes the enclosing target.

The chain keeps the context where it was started. Later parent introductions, sibling hypotheses, or a parent theory refresh do not make new evidence available to it. Conditional laws require explicit evidence for every premise; a pre-specialized fact from use is also accepted. Failed inference leaves the chain, labels, and existing obligations unchanged.

Mojo

calculation_chains.mojo Download
"""Prove a readable chain and discharge a step after writing the calculation."""

from judgment import Session


def main() raises:
    var s = Session()
    var A = s.declare_type("A")
    var proof = s.theorem("equality_chain")
    var values = proof.vars("a b c", A)
    var a, b, c = values[0], values[1], values[2]
    var ab = proof.given("ab", a == b)
    var bc = proof.given("bc", b == c)
    proof.goal(a == c)

    var chain = proof.calc(a)
    chain.eq(b, using=ab, label="ab")
    var last = chain.step("last_step", to=c)
    last.sorry()
    print(chain.format())
    var outstanding = chain.obligations()
    last = chain.select(outstanding[0])
    last.resume()
    last.exact(bc)
    print(chain.format())
    proof.exact(chain.finish())
    print(proof.finish())

Run from the repository root pixi run core-run docs/examples/library/calculation_chains.mojo

Output

a
= b [ab: checked]
= c [last_step: deferred]
a
= b [ab: checked]
= c [last_step: solved]
⊢ ∀a:A. ∀b:A. ∀c:A. a = b → b = c → a = c

Python

calculation_chains.py Download
"""Prove a readable chain and discharge a step after writing the calculation."""

from judgment import Session


def main():
    s = Session()
    A = s.declare_type("A")
    proof = s.theorem("equality_chain")
    values = proof.vars("a b c", A)
    a, b, c = values[0], values[1], values[2]
    ab = proof.given("ab", a == b)
    bc = proof.given("bc", b == c)
    proof.goal(a == c)

    chain = proof.calc(a)
    chain.eq(b, using=ab, label="ab")
    last = chain.step("last_step", to=c)
    last.sorry()
    print(chain.format())
    outstanding = chain.obligations()
    last = chain.select(outstanding[0])
    last.resume()
    last.exact(bc)
    print(chain.format())
    proof.exact(chain.finish())
    print(proof.finish())


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/calculation_chains.py

Output

a
= b [ab: checked]
= c [last_step: deferred]
a
= b [ab: checked]
= c [last_step: solved]
⊢ ∀a:A. ∀b:A. ∀c:A. a = b → b = c → a = c

The trace displays [ab: checked] for the supplied equality. Its label is authored display text, so choose a reason that explains your proof; omitting it shows [checked]. Labels never select a theorem or replace the required evidence. The named step changes from [last_step: deferred] to [last_step: solved] only after it is explicitly resumed and proved.

An unfinished named step shows open or deferred. Branched steps show counts when needed, such as [distribute: 1 open, 1 deferred]; a solved continuation does not hide an unfinished claim. solved means there are no outstanding leaves, and finish() still reconstructs the proof. Neither checked nor solved means axiom-free; the final theorem reports its actual dependencies. Formatting is read-only, and saved trace strings keep their captured text.

Steps have distinct proof identities while sharing the enclosing rigid parameters. They cannot justify themselves or each other provisionally. Chain completion requires all steps even when the endpoints happen to coincide. Mixed mathematical relations require explicit composition laws; chains use equality only.

chain.obligations() inspects every open or deferred leaf, in step order and then creation order within each step. Each returned Goal includes its target, status, local context, and structural path. Checked and solved steps disappear from this list; inspection does not prove anything or resume deferred work.

Recover work with chain.select("collect"), a full path such as chain.select(["distribute", "claim", "aux", "left"]), or an exact snapshot from chain.obligations(). Short names must identify a unique outstanding leaf; ambiguous names require the full path. Step names identify their main continuations, so a step that has branched may require a longer path. Path components are literal strings, including names containing punctuation.

Selecting a snapshot keeps the exact owning step and goal identity; a goal's numeric id is only local to its step. Solved, replaced, or restored-away snapshots are refused. Selecting a name or path performs a fresh lookup in the current tree. Snapshots obtained directly from a step handle are also accepted by chain.select(snapshot), although their paths are relative to that step. The recovered handle's own inspection uses ordinary proof-relative paths. Recovery retains the original step's restrictions: it cannot publish a theorem, invent a retained claim reference, or use another step's provisional assumptions.

Conditional calculation steps

Suppose f(t) = t whenever D(t) holds. To calculate from f(f(x)) to x using this law twice at the outermost occurrence, supply both D(f(x)) and D(x). Neither condition follows from the stated law alone.

Mojo

conditional_calculations.mojo Download
"""Keep conditional calculation steps and their required evidence explicit."""

from std.testing import assert_equal
from judgment import Session, arrow, forall, implies


def main() raises:
    var s = Session()
    var proof = s.theorem("cancel_twice")
    var A = proof.type_var("A")
    var f = proof.var("f", arrow(A, A))
    var D = proof.var("D", arrow(A, s.prop_type()))
    var t = proof.bound_var("t", A)
    var law = proof.given("fix_on_D", forall(t, implies(D(t), f(t) == t)))
    var x = proof.var("x", A)
    var inside = proof.given("inside", D(f(x)))
    var at_x = proof.given("at_x", D(x))
    proof.goal(f(f(x)) == x)

    var chain = proof.calc(f(f(x)))
    # The endpoints and supplied condition determine the rule's arguments.
    chain.eq(
        f(x),
        using=law,
        premises=[inside],
        label="fix at f(x)",
    )

    # Apply infers x from the equality and exposes D(x) as a separate goal.
    var cancel = chain.step("cancel", to=x)
    var premises = cancel.apply(law)
    assert_equal(len(premises), 1)
    assert_equal(premises[0].target().same_as(D(x)), True)
    premises[0].sorry()
    print(chain.format())
    var remaining = chain.obligations()
    assert_equal(len(remaining), 1)
    print("Required premise:", remaining[0].target().format())

    # Having D(x) in the context does not discharge it automatically.
    var domain = chain.select(remaining[0])
    domain.resume()
    domain.exact(at_x)
    assert_equal(len(chain.obligations()), 0)
    proof.exact(chain.finish())
    var theorem = proof.finish()
    assert_equal(len(theorem.axioms()), 0)
    assert_equal(len(theorem.admissions()), 0)
    print(theorem)

Run from the repository root pixi run core-run docs/examples/library/conditional_calculations.mojo

Output

f(f(x))
= f(x) [fix at f(x): checked]
= x [cancel: deferred]
Required premise: D(x)
[A] ⊢ ∀f:(A → A). ∀D:(A → Prop). (∀t:A. D(t) → f(t) = t) → (∀x:A. D(f(x)) → D(x) → f(f(x)) = x)

Python

conditional_calculations.py Download
"""Keep conditional calculation steps and their required evidence explicit."""

from judgment import Session, arrow, forall, implies


def main():
    s = Session()
    proof = s.theorem("cancel_twice")
    A = proof.type_var("A")
    f = proof.var("f", arrow(A, A))
    D = proof.var("D", arrow(A, s.prop_type()))
    t = proof.bound_var("t", A)
    law = proof.given("fix_on_D", forall(t, implies(D(t), f(t) == t)))
    x = proof.var("x", A)
    inside = proof.given("inside", D(f(x)))
    at_x = proof.given("at_x", D(x))
    proof.goal(f(f(x)) == x)

    chain = proof.calc(f(f(x)))
    # The endpoints and supplied condition determine the rule's arguments.
    chain.eq(
        f(x),
        using=law,
        premises=[inside],
        label="fix at f(x)",
    )

    # Apply infers x from the equality and exposes D(x) as a separate goal.
    cancel = chain.step("cancel", to=x)
    premises = cancel.apply(law)
    assert len(premises) == 1
    assert premises[0].target().same_as(D(x)) == True
    premises[0].sorry()
    print(chain.format())
    remaining = chain.obligations()
    assert len(remaining) == 1
    print("Required premise:", remaining[0].target().format())

    # Having D(x) in the context does not discharge it automatically.
    domain = chain.select(remaining[0])
    domain.resume()
    domain.exact(at_x)
    assert len(chain.obligations()) == 0
    proof.exact(chain.finish())
    theorem = proof.finish()
    assert len(theorem.axioms()) == 0
    assert len(theorem.admissions()) == 0
    print(theorem)


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/conditional_calculations.py

Output

f(f(x))
= f(x) [fix at f(x): checked]
= x [cancel: deferred]
Required premise: D(x)
[A] ⊢ ∀f:(A → A). ∀D:(A → Prop). (∀t:A. D(t) → f(t) = t) → (∀x:A. D(f(x)) → D(x) → f(f(x)) = x)

The immediate first step uses chain.eq(f(x), using=law, premises=[inside]). The written endpoints and supplied condition determine the theorem's arguments, so neither a nested proof.use call nor a repeated terms=[f(x)] list is needed. Its label describes the step; the checked inside fact supplies the domain condition. Every condition is required for an immediate step, in declaration order.

The second step uses the existing step and apply operations. The stated equality f(x) == x determines the universal argument. cancel.apply(law) returns a proof of the missing condition D(x). The example deliberately marks that condition sorry, recovers it through chain.obligations(), and supplies at_x explicitly. Even though at_x is already in the context, apply does not search for it. The enclosing theorem retains both domain premises and has no global axioms or admissions.

When the evidence is ready, _ = cancel.apply(law, using=[at_x]) closes the named step immediately. For a law with several implication premises, using discharges a supplied prefix in declaration order; the remaining premises become separate goals. A conjunction premise still requires one fact proving that conjunction. These operations already support incremental proofs without an additional calculation tactic.

For a selected subexpression, focus.to(x, using=law, premises=[at_x]) accepts the same explicit condition evidence while retaining the written replacement. Both endpoints and conditions contribute to inference. Missing or conflicting evidence leaves the calculation or selected goal unchanged. rw(law, using=[at_x]) remains the form that takes the replacement from the chosen rule.

Reading conditional-step errors

eq and to explain which condition needs attention, using the same reporting as rw. For the conditional law above, an omitted or mismatched domain fact can produce:

eq premise 1: expected D(f(x)); missing evidence
to premise 1: expected D(x); supplied D(y)

Premise positions start at one and follow implication order. Both written endpoints contribute to the expected expression, including parameters determined only by the replacement. A conjunction still requires one conjunction fact. When all conditions match but extra facts were supplied, the message gives the required and supplied counts.

If an argument is not determined, the error names the unresolved parameter instead of showing a guessed instance. If the endpoints and supplied facts cannot determine an argument, specialize the law with use first. Diagnostics do not look up facts or add obligations. The original error kind remains unchanged, and a short error is retained when there is insufficient work budget for a fuller explanation. The failed operation leaves the proof, calculation, and existing selections usable.

Longer algebra with named subexpressions

The next example squares a sum whose two summands are themselves products of sums. Mojo variables first and second avoid repeating their construction; proof-local definitions u and v also shorten the displayed mathematics. The calculation then operates on (u + v)**2 and proves distribution and collection through targeted rewrites:

long_algebra.mojo Download
"""Keep a long square expansion readable with local names and explicit laws."""

from std.testing import assert_equal
from judgment import Session
from arithmetic_setup import arithmetic_setup


def main() raises:
    var s = Session()
    var algebra = arithmetic_setup(s)
    var proof = s.theorem("long_sum_squared")
    var values = proof.vars("a b c d e f g h", algebra.kind)
    var a, b, c, d = values[0], values[1], values[2], values[3]
    var e, f, g, h = values[4], values[5], values[6], values[7]
    var first = (a + b) * (c + d)
    var second = (e + f) * (g + h)
    var target = (first + second)**2 == first**2 + 2 * first * second + second**2
    proof.goal(target)

    # These are proof-local names with checked defining equations.
    var u = proof.define("u", first)
    var v = proof.define("v", second)
    _ = proof.focus().fold(u, all=True).fold(v, all=True)
    print("Let", proof.defining_eq(u).statement().format())
    print("Let", proof.defining_eq(v).statement().format())
    print("Abbreviated goal:", proof.current_goal().target().format())

    # Record the calculation, then prove its substantive steps explicitly.
    var chain = proof.calc((u + v)**2)
    chain.change((u + v) * (u + v), label="square")
    chain.eq(
        u * (u + v) + v * (u + v),
        using=s.fact("right_distrib"),
        label="right_distrib",
    )
    _ = chain.step("distribute", to=u**2 + u * v + v * u + v**2)
    _ = chain.step("collect", to=u**2 + 2 * u * v + v**2)
    assert_equal(len(chain.obligations()), 2)
    print(chain.format())

    # Check the later equality first. Every rewrite names its mathematical law.
    var collect = chain.select("collect")
    _ = collect.lhs().at(v * u).rw(s.fact("mul_comm"))
    _ = collect.lhs().at(u**2 + u * v + u * v).rw(s.fact("add_assoc"))
    _ = collect.lhs().at(u * v + u * v).rw(s.fact("double_product"))
    collect.rfl()

    var expand = chain.select("distribute")
    _ = expand.lhs().at(u * (u + v)).rw(s.fact("left_distrib"))
    _ = expand.lhs().at(v * (u + v)).rw(s.fact("left_distrib"))
    _ = expand.lhs().rw(s.fact("add_assoc"), reverse=True)
    expand.rfl()

    proof.exact(chain.finish())
    var theorem = proof.finish()
    assert_equal(len(theorem.axioms()), 4)
    assert_equal(theorem.axioms()[1], "mul_comm")
    assert_equal(len(theorem.admissions()), 0)
    print(theorem)

Run from the repository root pixi run core-run docs/examples/library/long_algebra.mojo --include docs/examples/library

Output

Let u = (a + b) * (c + d)
Let v = (e + f) * (g + h)
Abbreviated goal: (u + v)**2 = u**2 + 2 * u * v + v**2
(u + v)**2
= (u + v) * (u + v) [square: checked]
= u * (u + v) + v * (u + v) [right_distrib: checked]
= u**2 + u * v + v * u + v**2 [distribute: open]
= u**2 + 2 * u * v + v**2 [collect: open]
[assuming 4 axioms] ⊢ ∀a:S. ∀b:S. ∀c:S. ∀d:S. ∀e:S. ∀f:S. ∀g:S. ∀h:S. ((a + b) * (c + d) + (e + f) * (g + h))**2 = ((a + b) * (c + d))**2 + 2 * ((a + b) * (c + d)) * ((e + f) * (g + h)) + ((e + f) * (g + h))**2
  axioms: add_assoc, mul_comm, mul_one, left_distrib

The same arithmetic setup supplies four explicit laws: additive associativity, multiplicative commutativity, a left multiplicative unit, and left distributivity. right_distrib and double_product are proved helpers. The mul_comm rewrite is the step that allows the two cross terms to combine. The carrier S is the fixed type in that theory; the theorem does not apply to arbitrary noncommuting matrices.

The two explicit fold(..., all=True) calls use the checked defining equations to abbreviate each long expression throughout the goal. The right side contains each expression twice; the single pass handles those occurrences together. No selected rewrite expands unrelated parts of the goal. The later calculation equality is proved before the earlier one; chain.finish() checks both before producing evidence. proof.exact(...) then supplies that evidence to the enclosing goal. Final theorem reconstruction eliminates u, v, and their defining equations, preserving the original expanded statement and its four axiom dependencies.

The example checks the definitional square equality in one call: chain.change((u + v) * (u + v), label="square"). The next expression stays visible without a temporary proof handle. Power expansion follows the registered notation's definition; distribution and commutativity still require evidence. It then declares the substantive distribute and collect equalities and recovers them by name in reverse order. chain.obligations() reports those two remaining equalities. Calculation goals stay in their independent step proofs, so inspect and select them through the chain instead of the enclosing theorem.

The trace shows the checked square conversion, the checked equality labeled right_distrib, and the open distribute and collect steps. Use chain.obligations() for the exact remaining goals and contexts. Folding keeps the expressions short; named recovery and trace statuses identify unfinished work.

The checked right_distrib step passes s.fact("right_distrib") directly to chain.eq. Its two written endpoints determine u, v, and u + v, so no proof.use(..., terms=[u, v, u + v]) wrapper is needed. The label remains display text, while the selected theorem supplies the checked mathematical reason.

Partial proof recipes

recipe(fact) embeds checked evidence. hole(name, proposition) describes a missing proof. Recipes provide conjunction introduction/projection, implication application, equality symmetry, and equality transitivity without exposing rule encodings. proof.refine(plan) checks the whole recipe against the selected target and returns named obligations.

Mojo

partial_recipes.mojo Download
"""Mix direct evidence with named proof holes."""

from judgment import Session, hole, implies, recipe


def main() raises:
    var s = Session()
    var proof = s.theorem("and_swap")
    var parameters = proof.props("P Q")
    var P, Q = parameters[0], parameters[1]
    proof.goal(implies(P & Q, Q & P))
    var h = proof.intro()

    var holes = proof.refine(recipe(proof.right(h)).conjoin(hole("prove_P", P)))
    var missing = holes["prove_P"]
    missing.exact(proof.left(h))
    print(proof.finish())

Run from the repository root pixi run core-run docs/examples/library/partial_recipes.mojo

Output

⊢ ∀P:Prop. ∀Q:Prop. P ∧ Q → Q ∧ P

Python

partial_recipes.py Download
"""Mix direct evidence with named proof holes."""

from judgment import Session, hole, implies, recipe


def main():
    s = Session()
    proof = s.theorem("and_swap")
    parameters = proof.props("P Q")
    P, Q = parameters[0], parameters[1]
    proof.goal(implies(P & Q, Q & P))
    h = proof.intro()

    holes = proof.refine(recipe(proof.right(h)).conjoin(hole("prove_P", P)))
    missing = holes["prove_P"]
    missing.exact(proof.left(h))
    print(proof.finish())


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/partial_recipes.py

Output

⊢ ∀P:Prop. ∀Q:Prop. P ∧ Q → Q ∧ P

Repeated hole names share one obligation only when their expected propositions agree. Holes remain in the original context; neither the recipe nor its temporary checking assumptions gives them evidence. Wrong rules, conclusions, scopes, and names fail before publishing goals. A complete recipe closes its goal directly. assumption() closes a goal with an exactly matching visible premise.

Checkpoints and explicit tactic composition

Retry a targeted rewrite

Save a checkpoint before trying a sequence of direct proof steps. In this example, rewriting the first occurrence succeeds, but leaves a goal that reflexivity cannot close. Restoring the checkpoint lets the author try the second occurrence.

Mojo

checkpoint_retry.mojo Download
"""Restore an exploratory rewrite and retry at a different occurrence."""

from std.testing import assert_true
from judgment import Session, implies


def main() raises:
    var s = Session()
    var P = s.prop("P")
    var Q = s.prop("Q")
    var R = s.prop("R")
    var start = (P & R) | (P & R)
    var wanted = (P & R) | (Q & R)
    var statement = implies(P == Q, start == wanted)
    var proof = s.theorem("retry_rewrite", statement)
    var equal = proof.intro("equal")
    var saved = proof.checkpoint()
    var t = proof.tactics()

    # This checked rewrite succeeds, but reflexivity cannot finish this route.
    _ = proof.lhs().at(P, occurrence=1).rw(equal)
    var trial = proof.by(t.rfl())
    assert_true(trial.status() == "no_match" and not trial.changed())
    assert_true(proof.target().same_as(((Q & R) | (P & R)) == wanted))
    print("First occurrence:", trial.status())

    # Undo the earlier direct rewrite; by only stages its own tactic program.
    proof.restore(saved)
    assert_true(proof.target().same_as(start == wanted))
    print("Restored original goal:", proof.target().same_as(start == wanted))

    # Restoration invalidates old foci, so select the occurrence afresh.
    _ = proof.lhs().at(P, occurrence=2).rw(equal)
    proof.rfl()
    var theorem = proof.finish()
    assert_true(theorem.statement().same_as(statement))
    assert_true(len(theorem.axioms()) == 0 and len(theorem.admissions()) == 0)
    print(theorem)
    print("Axiom dependencies:", len(theorem.axioms()))

Run from the repository root pixi run core-run docs/examples/library/checkpoint_retry.mojo

Output

First occurrence: no_match
Restored original goal: True
⊢ P = Q → (P ∧ R ∨ P ∧ R) = (P ∧ R ∨ Q ∧ R)
Axiom dependencies: 0

Python

checkpoint_retry.py Download
"""Restore an exploratory rewrite and retry at a different occurrence."""

from judgment import Session, implies


def main():
    s = Session()
    P = s.prop("P")
    Q = s.prop("Q")
    R = s.prop("R")
    start = (P & R) | (P & R)
    wanted = (P & R) | (Q & R)
    statement = implies(P == Q, start == wanted)
    proof = s.theorem("retry_rewrite", statement)
    equal = proof.intro("equal")
    saved = proof.checkpoint()
    t = proof.tactics()

    # This checked rewrite succeeds, but reflexivity cannot finish this route.
    _ = proof.lhs().at(P, occurrence=1).rw(equal)
    trial = proof.by(t.rfl())
    assert trial.status() == "no_match" and not trial.changed()
    assert proof.target().same_as(((Q & R) | (P & R)) == wanted)
    print("First occurrence:", trial.status())

    # Undo the earlier direct rewrite; by only stages its own tactic program.
    proof.restore(saved)
    assert proof.target().same_as(start == wanted)
    print("Restored original goal:", proof.target().same_as(start == wanted))

    # Restoration invalidates old foci, so select the occurrence afresh.
    _ = proof.lhs().at(P, occurrence=2).rw(equal)
    proof.rfl()
    theorem = proof.finish()
    assert theorem.statement().same_as(statement)
    assert len(theorem.axioms()) == 0 and len(theorem.admissions()) == 0
    print(theorem)
    print("Axiom dependencies:", len(theorem.axioms()))


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/checkpoint_retry.py

Output

First occurrence: no_match
Restored original goal: True
⊢ P = Q → (P ∧ R ∨ P ∧ R) = (P ∧ R ∨ Q ∧ R)
Axiom dependencies: 0

The no_match report belongs to by(t.rfl()): that attempt changes nothing, so the earlier direct rw remains in the draft until restore(saved) undoes it. After restoration, select a fresh focus with lhs().at(...). The equality fact introduced before the checkpoint remains available for the retry.

proof.checkpoint() captures the logical draft and selected goal. proof.restore(checkpoint) restores those choices without refunding work or undoing global declarations. All old foci become stale. Goals created afterward are discarded and their IDs are never reused; their scoped facts cannot escape. Finished theorem publication cannot be rolled back with a draft checkpoint.

Take a checkpoint before entering a transaction when you want to restore the draft after discarding temporary work. Checkpoints created inside a transaction expire when it closes.

Compose an atomic attempt

proof.tactics() supplies explicit tactic values. then applies its second program to each resulting active subgoal. or_else restores logical state before a fallback and handles only no_match; invalid evidence and resource stops stay visible. repeat(max_steps) requires a bound and stops when no progress occurs. all_goals applies a program independently to each active obligation. require_closed checks the entire draft, including deferred claims.

Mojo

composed_tactics.mojo Download
"""Compose explicit tactics and inspect their outcome."""

from judgment import Session, implies


def main() raises:
    var s = Session()
    var proof = s.theorem("duplicate")
    var P = proof.prop("P")
    proof.goal(implies(P, P & P))
    var t = proof.tactics()
    var report = proof.by(t.intro().then(t.split()).then(t.assumption()).require_closed())
    print(report.status())
    print(proof.finish())

Run from the repository root pixi run core-run docs/examples/library/composed_tactics.mojo

Output

solved
⊢ ∀P:Prop. P → P ∧ P

Python

composed_tactics.py Download
"""Compose explicit tactics and inspect their outcome."""

from judgment import Session, implies


def main():
    s = Session()
    proof = s.theorem("duplicate")
    P = proof.prop("P")
    proof.goal(implies(P, P & P))
    t = proof.tactics()
    report = proof.by(t.intro().then(t.split()).then(t.assumption()).require_closed())
    print(report.status())
    print(proof.finish())


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/composed_tactics.py

Output

solved
⊢ ∀P:Prop. P → P ∧ P

by stages the whole attempt before committing it. Its report distinguishes solved, progress, no_change, no_match, and resource_exhausted; it is not a proof certificate. Invalid explicit evidence raises a typed error. finish still checks reconstruction and publishes the theorem. These combinators do not select rewrite rules or perform automatic simplification.

Every goal step as a tactic

Each goal step of a declared proof is also a tactic value: intro_var, witness, cases, obtain, have, define, change, unfold, refine, and sorry, besides the connective, closing, and application steps above. A tactic often needs a premise or variable that an earlier step of the same tactic introduces, before any Fact exists for it, so exact, apply, rw, cases, and obtain also accept a premise name, and witness a variable name, looked up in each goal's context when the step runs:

Mojo

quantifier_tactics.mojo Download
"""Open quantifiers and cases with one tactic, then finish each branch directly; name nested binders freshly."""

from judgment import Session, arrow, exists, forall, implies


def main() raises:
    var s = Session()
    var proof = s.theorem("exists_or_split")
    var A = proof.type_var("A")
    var F = proof.var("F", arrow(A, s.prop_type()))
    var G = proof.var("G", arrow(A, s.prop_type()))
    var x = proof.bound_var("x", A)
    proof.goal(implies(exists(x, F(x) | G(x)), exists(x, F(x)) | exists(x, G(x))))
    var t = proof.tactics()
    # Each step uses the names the earlier steps gave.
    var opening = t.intro("h").then(t.obtain("h", "w", "hw")).then(t.cases("hw", "hf", "hg"))
    print(proof.by(opening).status())
    # The handle selects the left branch; direct steps find the witness and premises by name.
    proof.choose_left()
    proof.witness(proof.variable("w"))
    proof.exact(proof.fact("hf"))
    var right = proof.select("right")
    print(right.by(t.choose_right().then(t.witness("w")).then(t.exact("hg"))).status())
    print(proof.finish())

    # fresh=True picks x, x_1, x_2, ... so one repeated step opens nested universals.
    var nested = s.theorem("nested_fresh")
    var B = nested.type_var("B")
    var R = nested.var("R", arrow(B, s.prop_type()))
    var a = nested.bound_var("a", B)
    var b = nested.bound_var("b", B)
    nested.goal(forall(a, forall(b, implies(R(a), R(a) | R(b)))))
    t = nested.tactics()
    print(nested.by(t.intro_var("x", fresh=True).repeat().then(t.intro("h"))).status())
    print(nested.target().format())
    nested.choose_left()
    nested.exact(nested.fact("h"))
    print(nested.finish())

Run from the repository root pixi run core-run docs/examples/library/quantifier_tactics.mojo

Output

progress
solved
[A] ⊢ ∀F:(A → Prop). ∀G:(A → Prop). (∃x:A. F(x) ∨ G(x)) → (∃x:A. F(x)) ∨ (∃x:A. G(x))
progress
R(x) ∨ R(x_1)
[B] ⊢ ∀R:(B → Prop). ∀a:B. ∀b:B. R(a) → R(a) ∨ R(b)

Python

quantifier_tactics.py Download
"""Open quantifiers and cases with one tactic, then finish each branch directly; name nested binders freshly."""

from judgment import Session, arrow, exists, forall, implies


def main():
    s = Session()
    proof = s.theorem("exists_or_split")
    A = proof.type_var("A")
    F = proof.var("F", arrow(A, s.prop_type()))
    G = proof.var("G", arrow(A, s.prop_type()))
    x = proof.bound_var("x", A)
    proof.goal(implies(exists(x, F(x) | G(x)), exists(x, F(x)) | exists(x, G(x))))
    t = proof.tactics()
    # Each step uses the names the earlier steps gave.
    opening = t.intro("h").then(t.obtain("h", "w", "hw")).then(t.cases("hw", "hf", "hg"))
    print(proof.by(opening).status())
    # The handle selects the left branch; direct steps find the witness and premises by name.
    proof.choose_left()
    proof.witness(proof.variable("w"))
    proof.exact(proof.fact("hf"))
    right = proof.select("right")
    print(right.by(t.choose_right().then(t.witness("w")).then(t.exact("hg"))).status())
    print(proof.finish())

    # fresh=True picks x, x_1, x_2, ... so one repeated step opens nested universals.
    nested = s.theorem("nested_fresh")
    B = nested.type_var("B")
    R = nested.var("R", arrow(B, s.prop_type()))
    a = nested.bound_var("a", B)
    b = nested.bound_var("b", B)
    nested.goal(forall(a, forall(b, implies(R(a), R(a) | R(b)))))
    t = nested.tactics()
    print(nested.by(t.intro_var("x", fresh=True).repeat().then(t.intro("h"))).status())
    print(nested.target().format())
    nested.choose_left()
    nested.exact(nested.fact("h"))
    print(nested.finish())


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/quantifier_tactics.py

Output

progress
solved
[A] ⊢ ∀F:(A → Prop). ∀G:(A → Prop). (∃x:A. F(x) ∨ G(x)) → (∃x:A. F(x)) ∨ (∃x:A. G(x))
progress
R(x) ∨ R(x_1)
[B] ⊢ ∀R:(B → Prop). ∀a:B. ∀b:B. R(a) → R(a) ∨ R(b)

The names intro, obtain, and cases give are the names later steps use. When no premise or variable has a given name the step reports no_match, so or_else can try another, as obtain("l", ...).or_else(obtain("r", ...)) does across two case branches. Otherwise the step behaves exactly as with the Fact itself: two visible premises with the name, or evidence that is unavailable, of the wrong shape, or does not prove the goal, is an error, never an alternative, so give distinct names and use assumption to try premises.

A repeated intro_var or obtain cannot reuse its name, and a repeated intro("h") makes fact("h") ambiguous, so intro, intro_var, and obtain take fresh=True: the step then uses the first of x, x_1, x_2, … that no visible name uses, as the second half of the example does for two nested universals. The choice depends only on the names visible in the goal, so the same draft always gets the same names, and the names are found by variable and fact like any other. Recipe holes only label their goals, so one recipe can refine several goals of a context, such as both halves of a split; select those holes by full path, for example ["left", "hole", "h"], because their short name is shared.

After by, the handle selects the first goal the tactic left active. Direct steps continue from there and find what the tactic introduced with fact(name) and variable(name), and its other goals with select; a tactic, in turn, takes facts and expressions that direct steps produced, and branch handles run tactics like any other. admit stays a direct step, because its global declaration could not be rolled back with a failed attempt; focused rewrites and calculations address one goal's positions and stay direct too. See the step table for what each tactic leaves active and when it does not match.

Tactic programs as data

A program that a search or another process produces is data: TacticData with ExprData and TypeData, holding names rather than session values. A producer reads Goal.data(), proposes Candidates for the goal's path and revision, and the proof tries and commits them:

Mojo

tactic_data.mojo Download
"""Describe a goal as data, propose two candidate programs, try both, and commit the one that solves."""

from judgment import Candidate, ExprData, Session, TacticData, TypeData, arrow, exists, implies


def main() raises:
    var s = Session()
    var T = s.declare_type("T")
    var R = s.symbol("R", arrow(T, s.prop_type()))
    var proof = s.theorem("witnessed")
    var a = proof.var("a", T)
    _ = proof.given("ra", R(a))
    var y = proof.bound_var("y", T)
    proof.goal(exists(y, R(y)))

    # A producer sees only data: the goal's path, revision, target, and context.
    var goal = proof.current_goal().data()
    print(goal.target().format(), goal.variables()[0], goal.premises()[0])

    # Two candidate programs, built without any session reference.
    var first = TacticData.split().then(TacticData.assumption())
    var second = TacticData.witness(ExprData.name("a")).then(TacticData.exact("ra"))
    var candidates = [Candidate(goal.path(), goal.revision(), first), Candidate(goal.path(), goal.revision(), second)]

    # Trials report without changing the draft; the first that solves is committed.
    for candidate in candidates:
        var report = proof.trial(proof.compile(candidate.tactic()))
        print(report.status())
        if report.status() == "solved":
            print(proof.by(candidate).status())
            break
    print(proof.finish())

Run from the repository root pixi run core-run docs/examples/library/tactic_data.mojo

Output

∃y:T. R(y) a ra
no_match
solved
solved
⊢ ∀a:T. R(a) → (∃y:T. R(y))

Python

tactic_data.py Download
"""Describe a goal as data, propose two candidate programs, try both, and commit the one that solves."""

from judgment import Candidate, ExprData, Session, TacticData, TypeData, arrow, exists, implies


def main():
    s = Session()
    T = s.declare_type("T")
    R = s.symbol("R", arrow(T, s.prop_type()))
    proof = s.theorem("witnessed")
    a = proof.var("a", T)
    _ = proof.given("ra", R(a))
    y = proof.bound_var("y", T)
    proof.goal(exists(y, R(y)))

    # A producer sees only data: the goal's path, revision, target, and context.
    goal = proof.current_goal().data()
    print(goal.target().format(), goal.variables()[0], goal.premises()[0])

    # Two candidate programs, built without any session reference.
    first = TacticData.split().then(TacticData.assumption())
    second = TacticData.witness(ExprData.name("a")).then(TacticData.exact("ra"))
    candidates = [Candidate(goal.path(), goal.revision(), first), Candidate(goal.path(), goal.revision(), second)]

    # Trials report without changing the draft; the first that solves is committed.
    for candidate in candidates:
        report = proof.trial(proof.compile(candidate.tactic()))
        print(report.status())
        if report.status() == "solved":
            print(proof.by(candidate).status())
            break
    print(proof.finish())


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/tactic_data.py

Output

∃y:T. R(y) a ra
no_match
solved
solved
⊢ ∀a:T. R(a) → (∃y:T. R(y))

trial reports without committing, and by(candidate) refuses a candidate made for an earlier revision of its goal. Names are resolved in each goal when a step runs, so an absent name does not match, and by(tactic, work=…) caps a single attempt. See the data contract.

Composable theorem application

Use t.apply(theorem).then(t.assumption()) when each generated premise should be proved from the visible assumptions. The theorem and the premise-solving tactic are both explicit choices. The composed attempt rolls back if any premise fails.

Mojo

composable_application.mojo Download
"""Replace a premise loop with one atomic, explicitly chosen tactic sequence."""

from judgment import Session, implies


def main() raises:
    var s = Session()
    var source = s.theorem("join")
    var Left = source.prop("Left")
    var Right = source.prop("Right")
    var left = source.given("left", Left)
    var right = source.given("right", Right)
    source.goal(Left & Right)
    source.exact(source.conjoin(left, right))
    var join = source.finish()

    var P = s.prop("P")
    var Q = s.prop("Q")
    var goal = implies(P, implies(Q, P & Q))

    # Direct application returns premises for an explicit loop.
    var direct = s.theorem("direct", goal)
    _ = direct.intro("p")
    _ = direct.intro("q")
    var premises = direct.apply(join)
    for i in range(len(premises)):
        premises[i].assumption()
    print(direct.finish())

    # Composition makes application and every premise proof one atomic attempt.
    var proof = s.theorem("composed", goal)
    _ = proof.intro("p")
    _ = proof.intro("q")
    var t = proof.tactics()
    var solve = t.apply(join).then(t.assumption()).require_closed()
    print("Composed:", proof.by(solve).status())
    print(proof.finish())

    # The same program cannot prove Q without evidence; even its first premise
    # solution rolls back, so the caller retains the complete original goal.
    var partial = s.theorem("partial", implies(P, P & Q))
    _ = partial.intro("p")
    var before = partial.format()
    print("Missing premise:", partial.by(solve).status())
    print("Draft unchanged:", partial.format() == before)

Run from the repository root pixi run core-run docs/examples/library/composable_application.mojo

Output

⊢ P → Q → P ∧ Q
Composed: solved
⊢ P → Q → P ∧ Q
Missing premise: no_match
Draft unchanged: True

Python

composable_application.py Download
"""Replace a premise loop with one atomic, explicitly chosen tactic sequence."""

from judgment import Session, implies


def main():
    s = Session()
    source = s.theorem("join")
    Left = source.prop("Left")
    Right = source.prop("Right")
    left = source.given("left", Left)
    right = source.given("right", Right)
    source.goal(Left & Right)
    source.exact(source.conjoin(left, right))
    join = source.finish()

    P = s.prop("P")
    Q = s.prop("Q")
    goal = implies(P, implies(Q, P & Q))

    # Direct application returns premises for an explicit loop.
    direct = s.theorem("direct", goal)
    _ = direct.intro("p")
    _ = direct.intro("q")
    premises = direct.apply(join)
    for i in range(len(premises)):
        premises[i].assumption()
    print(direct.finish())

    # Composition makes application and every premise proof one atomic attempt.
    proof = s.theorem("composed", goal)
    _ = proof.intro("p")
    _ = proof.intro("q")
    t = proof.tactics()
    solve = t.apply(join).then(t.assumption()).require_closed()
    print("Composed:", proof.by(solve).status())
    print(proof.finish())

    # The same program cannot prove Q without evidence; even its first premise
    # solution rolls back, so the caller retains the complete original goal.
    partial = s.theorem("partial", implies(P, P & Q))
    _ = partial.intro("p")
    before = partial.format()
    print("Missing premise:", partial.by(solve).status())
    print("Draft unchanged:", partial.format() == before)


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/composable_application.py

Output

⊢ P → Q → P ∧ Q
Composed: solved
⊢ P → Q → P ∧ Q
Missing premise: no_match
Draft unchanged: True

type_args, terms, and using have the same meanings as on Proof.apply. A supplied using prefix leaves only the later premises for then; when no premises remain, then has nothing to run. Saved programs own copies of those Lists and infer afresh in each execution's context.

A checked incompatible conclusion reports no_match and can select or_else. Wrong supplied evidence, inaccessible facts, and ambiguous inference raise typed errors, even when their error kind is NO_MATCH. Supplying D(b) when the goal requires the instance at a is an error. A fully explicit valid instance at b can instead be a recoverable mismatch. See the application contract for the precise boundary. Automatic premise solving is not part of apply.

Inference and theorem discovery

use(theorem, terms=[...]) infers unambiguous type arguments from the supplied terms and premise statements. apply(theorem) can also infer term arguments from the selected conclusion. Inference assigns only the theorem's source parameters; the receiving proof's parameters remain rigid. Unused and ambiguous arguments require explicit values. Every inferred instance is rebuilt and kernel checked. Matching under binders and matching modulo alternative authored ACU groupings remain conservative; supply explicit arguments when a structural match fails.

session.find(prefix) lists registered facts in publication order, including explicitly declared axioms. Their evidence labels and dependencies remain visible. proof.suggest(prefix) returns checked candidates with their inferred type/term arguments and remaining premises, without changing the draft. Select a candidate with proof.apply(candidate). Goal changes invalidate saved suggestions, and application checks the evidence again.

Mojo

theorem_discovery.mojo Download
"""Inspect a theorem application before selecting it."""

from judgment import Session


def main() raises:
    var s = Session()
    var identity = s.theorem("identity_refl")
    var A = identity.type_var("A")
    var x = identity.var("x", A)
    identity.goal(x == x)
    identity.rfl()
    _ = identity.finish()

    var P = s.prop("P")
    var proof = s.theorem("discovered", P == P)
    var candidates = proof.suggest("identity")
    print("Candidate:", candidates[0].name())
    print("Remaining premises:", len(candidates[0].premises()))
    _ = proof.apply(candidates[0])
    print(proof.finish())

Run from the repository root pixi run core-run docs/examples/library/theorem_discovery.mojo

Output

Candidate: identity_refl
Remaining premises: 0
⊢ P = P

Python

theorem_discovery.py Download
"""Inspect a theorem application before selecting it."""

from judgment import Session


def main():
    s = Session()
    identity = s.theorem("identity_refl")
    A = identity.type_var("A")
    x = identity.var("x", A)
    identity.goal(x == x)
    identity.rfl()
    _ = identity.finish()

    P = s.prop("P")
    proof = s.theorem("discovered", P == P)
    candidates = proof.suggest("identity")
    print("Candidate:", candidates[0].name())
    print("Remaining premises:", len(candidates[0].premises()))
    _ = proof.apply(candidates[0])
    print(proof.finish())


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/theorem_discovery.py

Output

Candidate: identity_refl
Remaining premises: 0
⊢ P = P

Certified transformations and binder bodies

proof.transform(expression) creates an independent transformation in the selected context. session.transform(expression) uses the current global context. Both retain their input, expose output(), and produce checked input == output evidence through evidence(). Their focus() and at() methods use the same explicit rw, unfold, to, and change operations as a goal. When the input is a proposition, apply(fact) transports its evidence to the output proposition without modifying the original fact. Conditional equalities require the actual premise evidence: pass using=[...] to the selected focus's rw, or premises=[...] to its to. Explicit specialization through transformation.use(..., using=[...]) remains available when arguments cannot be inferred. A transformation does not create missing-condition goals; use a proof or named calculation step when those conditions will be proved later.

focus.change(replacement, unfold=[...]) performs targeted definitional conversion. It cannot use a merely provable equality in place of conversion; use rw for that. lambda_(variable, body) builds typed lambda syntax with the same binding hygiene as forall and exists.

A selected lambda or quantifier can be opened with under(name). The returned BinderFocus exposes a fresh variable() and a separate body transformation. body().use(theorem, terms=[variable]) specializes evidence inside that scope. finish() abstracts the local through kernel congruence and commits the outer rewrite. A stale outer focus fails, and the variable cannot escape the body.

Mojo

binder_rewrites.mojo Download
"""Rewrite beneath a quantifier through an explicit fresh-variable scope."""

from judgment import Session, forall


def main() raises:
    var s = Session()
    var A = s.declare_type("A")
    var proof = s.theorem("replace_under_forall")
    var values = proof.vars("a b", A)
    var a, b = values[0], values[1]
    var equality = proof.given("equality", a == b)
    var x = proof.bound_var("x", A)
    proof.goal(forall(x, x == a) == forall(x, x == b))

    var opened = proof.lhs().under("z")
    _ = opened.body().at(a).rw(equality)
    _ = opened.finish()
    proof.rfl()
    print(proof.finish())

Run from the repository root pixi run core-run docs/examples/library/binder_rewrites.mojo

Output

⊢ ∀a:A. ∀b:A. a = b → (∀x:A. x = a) = (∀x:A. x = b)

Python

binder_rewrites.py Download
"""Rewrite beneath a quantifier through an explicit fresh-variable scope."""

from judgment import Session, forall


def main():
    s = Session()
    A = s.declare_type("A")
    proof = s.theorem("replace_under_forall")
    values = proof.vars("a b", A)
    a, b = values[0], values[1]
    equality = proof.given("equality", a == b)
    x = proof.bound_var("x", A)
    proof.goal(forall(x, x == a) == forall(x, x == b))

    opened = proof.lhs().under("z")
    _ = opened.body().at(a).rw(equality)
    _ = opened.finish()
    proof.rfl()
    print(proof.finish())


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/binder_rewrites.py

Output

⊢ ∀a:A. ∀b:A. a = b → (∀x:A. x = a) = (∀x:A. x = b)

Explicit admission and provenance

proof.admit(name, reason) assumes precisely the active obligation, with every local parameter and premise closed in its original order. Both the separate name and explanation are required. It adds a global assumption and closes the selected goal. Facts depending on it print [admitted]; admissions() returns the names and reasons of their actual transitive dependencies. Unrelated theorems remain unmarked. Ordinary declared axioms have their own count and preview; evidence using both kinds shows both qualifications. format(details=True) expands each admission into its original closed statement and reason, as below. axioms() continues to include admission declarations because they are kernel axioms.

Mojo

explicit_admission.mojo Download
"""Separate deferred work from an explicitly labeled mathematical assumption."""

from judgment import Session, implies


def main() raises:
    var s = Session()
    var P = s.prop("P")
    var Q = s.prop("Q")
    var proof = s.theorem("conditional", implies(P, Q))
    _ = proof.intro("h")
    proof.sorry()
    print("Deferred obligations:", len(proof.obligations()))
    proof.resume()
    proof.admit("missing_lemma", "Awaiting the mathematical proof")
    var theorem = proof.finish()
    print(theorem.format(details=True))

Run from the repository root pixi run core-run docs/examples/library/explicit_admission.mojo

Output

Deferred obligations: 1
[admitted] ⊢ P → Q
Admissions (1):
  missing_lemma: P → Q
    reason: Awaiting the mathematical proof

Python

explicit_admission.py Download
"""Separate deferred work from an explicitly labeled mathematical assumption."""

from judgment import Session, implies


def main():
    s = Session()
    P = s.prop("P")
    Q = s.prop("Q")
    proof = s.theorem("conditional", implies(P, Q))
    _ = proof.intro("h")
    proof.sorry()
    print("Deferred obligations:", len(proof.obligations()))
    proof.resume()
    proof.admit("missing_lemma", "Awaiting the mathematical proof")
    theorem = proof.finish()
    print(theorem.format(details=True))


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/explicit_admission.py

Output

Deferred obligations: 1
[admitted] ⊢ P → Q
Admissions (1):
  missing_lemma: P → Q
    reason: Awaiting the mathematical proof

proof.refresh() explicitly adopts later declarations when the canonical signature has not changed. For example, an enclosing proof can refresh after an independent calculation step creates an admission. Refresh invalidates saved foci and suggestions; it never silently installs an arithmetic canonicalization change in an older proof.

Specifications and overloaded constants

A specification introduces constants that satisfy a proved property, with no defining equation; an overloaded constant gets one opaque equation per instance:

Mojo

specifications.mojo Download
"""Specify constants by a theorem, and define an overloaded constant at two types."""

from judgment import Session, forall, implies


def main() raises:
    var s = Session()
    var T = s.declare_type("T")
    var z = s.symbol("z", T)

    # A witness of the form ∀v. v = t → φ specifies a constant satisfying φ, with no equation.
    var witness = s.theorem("witness")
    var v = witness.bound_var("v", T)
    witness.goal(forall(v, implies(v == z, v == z)))
    var t = witness.tactics()
    _ = witness.by(t.intro_var("a").then(t.intro("h")).then(t.assumption()))
    var spec = s.specification(["c"], witness.finish())
    print(spec.law())

    # An overloaded constant has one opaque equation per instance.
    var header = s.overloaded("default")
    var A = header.type_var("A")
    var default = header.finish(A)
    var at_t = s.instance_definition(default, [T], z)
    print(at_t)
    print(s.instance_definition(default, [s.prop_type()], s.true_()))
    var proof = s.theorem("default_is_z", default.symbol([T]) == z)
    proof.exact(at_t)
    print(proof.finish())

Run from the repository root pixi run core-run docs/examples/library/specifications.mojo

Output

⊢ c = z
⊢ default = z
⊢ default = True
⊢ default = z

Python

specifications.py Download
"""Specify constants by a theorem, and define an overloaded constant at two types."""

from judgment import Session, forall, implies


def main():
    s = Session()
    T = s.declare_type("T")
    z = s.symbol("z", T)

    # A witness of the form ∀v. v = t → φ specifies a constant satisfying φ, with no equation.
    witness = s.theorem("witness")
    v = witness.bound_var("v", T)
    witness.goal(forall(v, implies(v == z, v == z)))
    t = witness.tactics()
    _ = witness.by(t.intro_var("a").then(t.intro("h")).then(t.assumption()))
    spec = s.specification(["c"], witness.finish())
    print(spec.law())

    # An overloaded constant has one opaque equation per instance.
    header = s.overloaded("default")
    A = header.type_var("A")
    default = header.finish(A)
    at_t = s.instance_definition(default, [T], z)
    print(at_t)
    print(s.instance_definition(default, [s.prop_type()], s.true_()))
    proof = s.theorem("default_is_z", default.symbol([T]) == z)
    proof.exact(at_t)
    print(proof.finish())


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/specifications.py

Output

⊢ c = z
⊢ default = z
⊢ default = True
⊢ default = z

The witness is a completed theorem ∀v. v = t → φ; the law is φ with the new constant for v. Instance definitions at concrete types take the types directly; instance_definition(constant) is a header for one with type parameters. The kernel refuses a second instance at an overlapping type or a definition that refers to itself. A generic witness specifies generic constants. Generic constants use symbol(name) with type_var the same way.

Type classes and instances

A class names a property of types: one type variable, overloaded parameters over it, superclasses, and an axiom. membership(τ) states that τ belongs to the class; an instance declares it for a type constructor from a proof:

Mojo

classes.mojo Download
"""Declare a semigroup class, instances at a type and at list(α) by an instance definition, and use a theorem over a sorted parameter."""

from judgment import Class, Session, arrow, forall


def main() raises:
    var s = Session()
    var N = s.declare_type("N")
    var list_ = s.type_constructor("list", 1)

    # A class: one type variable, an overloaded parameter, and an axiom.
    var builder = s.class_("semigroup")
    var a = builder.type_var("a")
    var times = builder.parameter("times", arrow(a, arrow(a, a)))
    var x = builder.bound_var("x", a)
    var y = builder.bound_var("y", a)
    var z = builder.bound_var("z", a)
    var t = times.symbol([a])
    var semigroup = builder.finish(forall(x, forall(y, forall(z, t(t(x, y), z) == t(x, t(y, z))))))
    print(semigroup.intro())

    # N is a semigroup: prove membership by the class's definition.
    var tn = times.symbol([N])
    var law = s.axiom("times_N_assoc")
    var ns = law.vars("x y z", N)
    var assoc = law.finish(tn(tn(ns[0], ns[1]), ns[2]) == tn(ns[0], tn(ns[1], ns[2])))
    var witness = s.theorem("N_semigroup", semigroup.membership(N))
    var goals = witness.apply(semigroup.intro())
    goals[0].exact(assoc)
    s.instance(N, semigroup, witness.finish())

    # list(g) is a semigroup by a generic instance definition, times[list(g)] = append[g].
    var header = s.symbol("append")
    var b = header.type_var("b")
    var append = header.finish(arrow(list_(b), arrow(list_(b), list_(b))))
    var append_law = s.axiom("append_assoc")
    var e = append_law.type_var("e")
    var xs = append_law.vars("x y z", list_(e))
    var ap = append.symbol([e])
    var append_assoc = append_law.finish(ap(ap(xs[0], xs[1]), xs[2]) == ap(xs[0], ap(xs[1], xs[2])))
    var definition = s.instance_definition(times)
    var g = definition.type_var("g")
    var times_list = definition.finish([list_(g)], append.symbol([g]))
    print(times_list)
    var list_witness = s.theorem("list_semigroup")
    var f = list_witness.type_var("f")
    list_witness.goal(semigroup.membership(list_(f)))
    var list_goals = list_witness.apply(semigroup.intro())
    var x0 = list_goals[0].intro_var("x")
    var y0 = list_goals[0].intro_var("y")
    var z0 = list_goals[0].intro_var("z")
    var unfold = list_goals[0].use(times_list, [f])
    for _ in range(4):
        _ = list_goals[0].focus().at(times.symbol([list_(f)]), 1).rw(unfold)
    list_goals[0].exact(list_goals[0].use(append_assoc, [f], [x0, y0, z0]))
    var sorts = List[List[Class]]()
    sorts.append(List[Class]())
    s.instance(list_, sorts, semigroup, list_witness.finish())
    print(s.of_class(list_(list_(N)), semigroup))

    # A theorem over a sorted parameter, from the class axiom.
    var proof = s.theorem("reassociate")
    var m = proof.type_var("m", [semigroup])
    var p = proof.var("p", m)
    var tm = times.symbol([m])
    proof.goal(tm(tm(p, p), p) == tm(p, tm(p, p)))
    var axiom = proof.use(semigroup.elim(), [m], using=[s.of_class(m, semigroup)])
    proof.exact(proof.use(axiom, terms=[p, p, p]))
    var reassociate = proof.finish()
    print(reassociate)

    # Used at list(N), which the instances make a semigroup; an arrow is refused.
    var ln = list_(N)
    var use = s.theorem("at_lists")
    var q = use.var("q", ln)
    var tq = times.symbol([ln])
    use.goal(tq(tq(q, q), q) == tq(q, tq(q, q)))
    use.exact(use.use(reassociate, [ln], terms=[q]))
    print(use.finish())
    try:
        _ = s.theorem("at_arrows").use(reassociate, [arrow(N, N)])
    except error:
        print(error.kind)

Run from the repository root pixi run core-run docs/examples/library/classes.mojo

Output

[?0] ⊢ (∀x·2:a. ∀x·3:a. ∀x·4:a. times(times(x·2, x·3), x·4) = times(x·2, times(x·3, x·4))) → class.semigroup(TYPE[a])
[g] ⊢ times = append
[assuming 1 axiom] ⊢ class.semigroup(TYPE[list(list(N))])
  axioms: append_assoc
[m] ⊢ ∀p:m. times(times(p, p), p) = times(p, times(p, p))
[assuming 1 axiom] ⊢ ∀q:list(N). times(times(q, q), q) = times(q, times(q, q))
  axioms: append_assoc
KERNEL

Python

classes.py Download
"""Declare a semigroup class, instances at a type and at list(α) by an instance definition, and use a theorem over a sorted parameter."""

from judgment import Class, Session, arrow, forall, JudgmentError


def main():
    s = Session()
    N = s.declare_type("N")
    list_ = s.type_constructor("list", 1)

    # A class: one type variable, an overloaded parameter, and an axiom.
    builder = s.class_("semigroup")
    a = builder.type_var("a")
    times = builder.parameter("times", arrow(a, arrow(a, a)))
    x = builder.bound_var("x", a)
    y = builder.bound_var("y", a)
    z = builder.bound_var("z", a)
    t = times.symbol([a])
    semigroup = builder.finish(forall(x, forall(y, forall(z, t(t(x, y), z) == t(x, t(y, z))))))
    print(semigroup.intro())

    # N is a semigroup: prove membership by the class's definition.
    tn = times.symbol([N])
    law = s.axiom("times_N_assoc")
    ns = law.vars("x y z", N)
    assoc = law.finish(tn(tn(ns[0], ns[1]), ns[2]) == tn(ns[0], tn(ns[1], ns[2])))
    witness = s.theorem("N_semigroup", semigroup.membership(N))
    goals = witness.apply(semigroup.intro())
    goals[0].exact(assoc)
    s.instance(N, semigroup, witness.finish())

    # list(g) is a semigroup by a generic instance definition, times[list(g)] = append[g].
    header = s.symbol("append")
    b = header.type_var("b")
    append = header.finish(arrow(list_(b), arrow(list_(b), list_(b))))
    append_law = s.axiom("append_assoc")
    e = append_law.type_var("e")
    xs = append_law.vars("x y z", list_(e))
    ap = append.symbol([e])
    append_assoc = append_law.finish(ap(ap(xs[0], xs[1]), xs[2]) == ap(xs[0], ap(xs[1], xs[2])))
    definition = s.instance_definition(times)
    g = definition.type_var("g")
    times_list = definition.finish([list_(g)], append.symbol([g]))
    print(times_list)
    list_witness = s.theorem("list_semigroup")
    f = list_witness.type_var("f")
    list_witness.goal(semigroup.membership(list_(f)))
    list_goals = list_witness.apply(semigroup.intro())
    x0 = list_goals[0].intro_var("x")
    y0 = list_goals[0].intro_var("y")
    z0 = list_goals[0].intro_var("z")
    unfold = list_goals[0].use(times_list, [f])
    for _ in range(4):
        _ = list_goals[0].focus().at(times.symbol([list_(f)]), 1).rw(unfold)
    list_goals[0].exact(list_goals[0].use(append_assoc, [f], [x0, y0, z0]))
    sorts = []
    sorts.append([])
    s.instance(list_, sorts, semigroup, list_witness.finish())
    print(s.of_class(list_(list_(N)), semigroup))

    # A theorem over a sorted parameter, from the class axiom.
    proof = s.theorem("reassociate")
    m = proof.type_var("m", [semigroup])
    p = proof.var("p", m)
    tm = times.symbol([m])
    proof.goal(tm(tm(p, p), p) == tm(p, tm(p, p)))
    axiom = proof.use(semigroup.elim(), [m], using=[s.of_class(m, semigroup)])
    proof.exact(proof.use(axiom, terms=[p, p, p]))
    reassociate = proof.finish()
    print(reassociate)

    # Used at list(N), which the instances make a semigroup; an arrow is refused.
    ln = list_(N)
    use = s.theorem("at_lists")
    q = use.var("q", ln)
    tq = times.symbol([ln])
    use.goal(tq(tq(q, q), q) == tq(q, tq(q, q)))
    use.exact(use.use(reassociate, [ln], terms=[q]))
    print(use.finish())
    try:
        _ = s.theorem("at_arrows").use(reassociate, [arrow(N, N)])
    except JudgmentError as error:
        print(error.kind)


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/classes.py

Output

[?0] ⊢ (∀x·2:a. ∀x·3:a. ∀x·4:a. times(times(x·2, x·3), x·4) = times(x·2, times(x·3, x·4))) → class.semigroup(TYPE[a])
[g] ⊢ times = append
[assuming 1 axiom] ⊢ class.semigroup(TYPE[list(list(N))])
  axioms: append_assoc
[m] ⊢ ∀p:m. times(times(p, p), p) = times(p, times(p, p))
[assuming 1 axiom] ⊢ ∀q:list(N). times(times(q, q), q) = times(q, times(q, q))
  axioms: append_assoc
KERNEL

type_constructor(name, arity) declares κ; applying it gives κ(τ̄). A header's type_var(name, sort) takes a list of classes, shown as f{semigroup} in the header. Sorts are given, never inferred: use at a type outside a parameter's sort is the kernel's SIDE_CONDITION. The class predicate is opaque, so a witness applies class_.intro(), which turns the goal into the superclass memberships and the axiom; split separates them and Session.of_class proves each superclass from the declared instances. Over a sorted parameter, class_.elim() with of_class gives the axiom. A witness must state exactly class.c(TYPE[κ(α₁, …, αₖ)]) at parameters of the argument sorts; another statement, an arity that adds nothing, and arities with no weakest domain (coregularity) are the kernel's DECLARATION. class_relation(sub, super, witness) adds a later superclass edge from a generic proof of class.sub(TYPE[α]) → class.super(TYPE[α]). A theorem whose proof uses a sorted parameter that its statement does not mention keeps a sort hypothesis; finish refuses it, naming the sort, unless an instance witnesses the sort.

The list instance is proved from a generic instance definition: instance_definition(times) is a header whose finish([list(g)], append[g]) states times[list(g)] = append[g] over g. The witness rewrites each occurrence of times at list(f) with that equation at f, then uses append's law. subset(name) and specification take generic witnesses the same way, and import_class(name) reads a class declared before the session.

Subset types

session.subset(name, predicate, inhabited) requires a closed, monomorphic predicate and checked evidence of its nonemptiness. The result exposes kind(), abstract(value), represent(value), and the exact generated abs_rep() and rep_abs() laws. The reverse law retains its membership condition. Construction introduces no additional axiom beyond the witness's existing dependencies.

Mojo

subset_types.mojo Download
"""Construct a subset type from a proved nonemptiness witness."""

from judgment import Session, exists, lambda_


def main() raises:
    var s = Session()
    var A = s.declare_type("A")
    var a = s.symbol("a", A)
    var witness = s.theorem("nonempty")
    var x = witness.bound_var("x", A)
    var predicate = lambda_(x, x == a)
    witness.goal(exists(x, x == a))
    witness.witness(a)
    witness.rfl()
    var singleton = s.subset("Singleton", predicate, witness.finish())

    var proof = s.theorem("round_trip")
    var value = proof.var("value", singleton.kind())
    proof.goal(singleton.abstract(singleton.represent(value)) == value)
    _ = proof.apply(singleton.abs_rep())
    print(proof.finish())

Run from the repository root pixi run core-run docs/examples/library/subset_types.mojo

Output

⊢ ∀value:Singleton. Singleton_abs(Singleton_rep(value)) = value

Python

subset_types.py Download
"""Construct a subset type from a proved nonemptiness witness."""

from judgment import Session, exists, lambda_


def main():
    s = Session()
    A = s.declare_type("A")
    a = s.symbol("a", A)
    witness = s.theorem("nonempty")
    x = witness.bound_var("x", A)
    predicate = lambda_(x, x == a)
    witness.goal(exists(x, x == a))
    witness.witness(a)
    witness.rfl()
    singleton = s.subset("Singleton", predicate, witness.finish())

    proof = s.theorem("round_trip")
    value = proof.var("value", singleton.kind())
    proof.goal(singleton.abstract(singleton.represent(value)) == value)
    _ = proof.apply(singleton.abs_rep())
    print(proof.finish())


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/subset_types.py

Output

⊢ ∀value:Singleton. Singleton_abs(Singleton_rep(value)) = value

The round-trip goal fixes the argument to singleton.abs_rep(), so proof.apply(singleton.abs_rep()) checks that theorem directly against the goal. Explicit use remains useful when the specialized fact is needed inside another proof operation or its arguments cannot be determined from the goal.

Exact polynomial literals

arithmetic.polynomials(name, base, coeff, indet, laws) registers a polynomial carrier over an explicitly registered rational profile. Its twelve named laws are the eight ring laws and coeff_zero, coeff_one, coeff_add, and coeff_mul. Every law is checked against the selected operations before publication.

indeterminate(index) constructs literal data, and polynomial(coefficients, variable=0) accepts rational coefficients in ascending degree order. Empty coefficients mean zero. Multiple indeterminates compose multivariate literals using ordinary arithmetic. A symbolic theorem parameter still needs a theorem for distribution.

Mojo

polynomial_arithmetic.mojo Download
"""Compute literal polynomials while retaining their declared mathematical laws."""

from apn_mojo import Rational
from judgment import Session
from polynomial_setup import polynomial_setup


def main() raises:
    var s = Session()
    var setup = polynomial_setup(s)
    var p = setup.register_polynomials("polynomials")
    var x = p.indeterminate()
    var expected = p.polynomial([Rational(-1), Rational(0), Rational(1)])
    var proof = s.theorem("difference_of_squares", (x + 1) * (x - 1) == expected)
    proof.rfl()
    var theorem = proof.finish()
    print(theorem)

Run from the repository root pixi run mojo run -I src docs/examples/library/polynomial_arithmetic.mojo

Output

[assuming 28 axioms] ⊢ (1*X[0] + 1) * (1*X[0] - 1) = -1 + 1*X[0]^2
  axioms: Q.add_assoc, Q.add_comm, Q.add_zero, Q.mul_assoc, … (+24 more)

Python

polynomial_arithmetic.py Download
"""Compute literal polynomials while retaining their declared mathematical laws."""

from judgment import Session
from polynomial_setup import polynomial_setup


def main():
    s = Session()
    setup = polynomial_setup(s)
    p = setup.register_polynomials("polynomials")
    x = p.indeterminate()
    expected = p.polynomial([-1, 0, 1])
    proof = s.theorem("difference_of_squares", (x + 1) * (x - 1) == expected)
    proof.rfl()
    theorem = proof.finish()
    print(theorem)


main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/polynomial_arithmetic.py

Output

[assuming 28 axioms] ⊢ (1*X[0] + 1) * (1*X[0] - 1) = -1 + 1*X[0]^2
  axioms: Q.add_assoc, Q.add_comm, Q.add_zero, Q.mul_assoc, … (+24 more)

setup.register_polynomials("polynomials") supplies the record's base, coefficient embedding, indeterminate operation, and law bundle to Arithmetic.polynomials. It requires the client's chosen registration name and enables the same checked canonical arithmetic as the full call.

The teaching setup reuses the shared ring assumptions for both its rational base and its polynomial carrier, then adds the respective order/inverse and coefficient laws. Its result retains all 28 axiom dependencies: sixteen from the base and twelve from the polynomial structure. It does not construct the standard rationals or a mathematical polynomial model. The example's expected coefficients are supplied independently of the multiplication being checked.

Mojo

polynomial_setup.mojo Download
"""Explicit teaching axioms for formal polynomials over an exact rational base."""

from judgment_shell import Arithmetic, ArithmeticLaws, Expr, LibError, Session, TypeExpr, arrow
from exact_arithmetic_setup import numeric_setup
from ring_assumptions import assume_commutative_ring_laws


@fieldwise_init
struct PolynomialSetup(Copyable):
    """The polynomial carrier, exact base, and checked registration inputs."""

    var kind: TypeExpr
    var numbers: Arithmetic
    var base: Arithmetic
    var coeff: Expr
    var indet: Expr
    var laws: ArithmeticLaws

    def register_polynomials(self, name: String) raises LibError -> Arithmetic:
        """Explicitly enable polynomial literals using this provider's base and laws.

        Args:
            name: The client's fresh literal-kind name and private law-name prefix.

        Returns:
            The checked Arithmetic profile with canonical polynomial arithmetic enabled.

        Raises:
            LibError: For invalid owners, operations, evidence, names, or exhausted
                work. Failure publishes no theory or profile change.
        """
        return self.numbers.polynomials(name, self.base, self.coeff, self.indet, self.laws)


def polynomial_setup(
    mut s: Session, base_kind: TypeExpr,
    carrier_name: String = "Polynomial", prefix: String = "P",
) raises LibError -> PolynomialSetup:
    """Assume polynomial laws over an existing exact rational base.

    The base must belong to this session and already support exact rationals.
    Check it before publishing the polynomial carrier or its assumptions.
    The caller chooses fresh names and explicitly registers polynomial literals.
    """
    var base = s.arithmetic(base_kind)
    _ = base.rational(0, 1)
    var P = s.declare_type(carrier_name)
    var zero = s.symbol(prefix + ".zero", P)
    var one = s.symbol(prefix + ".one", P)
    var binary = arrow(P, arrow(P, P))
    var add = s.symbol(prefix + ".add", binary)
    var mul = s.symbol(prefix + ".mul", binary)
    var neg = s.symbol(prefix + ".neg", arrow(P, P))
    var coeff = s.symbol(prefix + ".coeff", arrow(base_kind, P))
    var indet = s.symbol(prefix + ".indet", arrow(base_kind, P))
    var numbers = s.arithmetic(P, zero, one, add, mul, neg)
    var entries = assume_commutative_ring_laws(s, P, zero, one, prefix)
    var names: List[String] = ["coeff_zero", "coeff_one", "coeff_add", "coeff_mul"]
    var arities: List[Int] = [0, 0, 2, 2]
    for i in range(len(names)):
        var law = s.axiom(prefix + "." + names[i])
        var x = zero
        var y = zero
        if arities[i] > 0:
            x = law.var("x", base_kind)
        if arities[i] > 1:
            y = law.var("y", base_kind)
        var statement: Expr
        if i == 0:
            statement = coeff(base.number(0)) == zero
        elif i == 1:
            statement = coeff(base.number(1)) == one
        elif i == 2:
            statement = coeff(x + y) == coeff(x) + coeff(y)
        else:
            statement = coeff(x * y) == coeff(x) * coeff(y)
        entries.append((names[i], law.finish(statement)))
    return PolynomialSetup(P, numbers, base, coeff, indet, ArithmeticLaws(entries^))


def polynomial_setup(mut s: Session) raises -> PolynomialSetup:
    """Create the original Q base and Polynomial fixture with explicit axioms."""
    var q = numeric_setup(s, "Q", rational=True)
    _ = q.register_rationals("rationals")
    return polynomial_setup(s, base_kind=q.kind)

Python

polynomial_setup.py Download
"""Explicit teaching axioms for formal polynomials over an exact rational base."""

from dataclasses import dataclass

from judgment import Arithmetic, ArithmeticLaws, Expr, Session, TypeExpr, arrow
from exact_arithmetic_setup import numeric_setup
from ring_assumptions import assume_commutative_ring_laws


@dataclass
class PolynomialSetup:
    """The polynomial carrier, exact base, and checked registration inputs."""

    kind: TypeExpr
    numbers: Arithmetic
    base: Arithmetic
    coeff: Expr
    indet: Expr
    laws: ArithmeticLaws

    def register_polynomials(self, name):
        """Explicitly enable polynomial literals using this provider's base and laws.

        Args:
            name: The client's fresh literal-kind name and private law-name prefix.

        Returns:
            The checked Arithmetic profile with canonical polynomial arithmetic enabled.

        Raises:
            JudgmentError: For invalid owners, operations, evidence, names, or exhausted
                work. Failure publishes no theory or profile change.
        """
        return self.numbers.polynomials(name, self.base, self.coeff, self.indet, self.laws)


def polynomial_setup(s, base_kind=None, carrier_name="Polynomial", prefix="P"):
    """Assume polynomial laws over an existing exact rational base.

    The base must belong to this session and already support exact rationals.
    Check it before publishing the polynomial carrier or its assumptions.
    The caller chooses fresh names and explicitly registers polynomial literals.
    Without `base_kind`, it first creates the original Q base with explicit axioms.
    """
    if base_kind is None:
        q = numeric_setup(s, "Q", rational=True)
        q.register_rationals("rationals")
        base_kind = q.kind
    base = s.arithmetic(base_kind)
    base.rational(0, 1)
    P = s.declare_type(carrier_name)
    zero = s.symbol(prefix + ".zero", P)
    one = s.symbol(prefix + ".one", P)
    binary = arrow(P, arrow(P, P))
    add = s.symbol(prefix + ".add", binary)
    mul = s.symbol(prefix + ".mul", binary)
    neg = s.symbol(prefix + ".neg", arrow(P, P))
    coeff = s.symbol(prefix + ".coeff", arrow(base_kind, P))
    indet = s.symbol(prefix + ".indet", arrow(base_kind, P))
    numbers = s.arithmetic(P, zero, one, add, mul, neg)
    entries = assume_commutative_ring_laws(s, P, zero, one, prefix)
    names = ["coeff_zero", "coeff_one", "coeff_add", "coeff_mul"]
    arities = [0, 0, 2, 2]
    for i in range(len(names)):
        law = s.axiom(prefix + "." + names[i])
        x = law.var("x", base_kind) if arities[i] > 0 else zero
        y = law.var("y", base_kind) if arities[i] > 1 else zero
        if i == 0:
            statement = coeff(base.number(0)) == zero
        elif i == 1:
            statement = coeff(base.number(1)) == one
        elif i == 2:
            statement = coeff(x + y) == coeff(x) + coeff(y)
        else:
            statement = coeff(x * y) == coeff(x) * coeff(y)
        entries.append((names[i], law.finish(statement)))
    return PolynomialSetup(P, numbers, base, coeff, indet, ArithmeticLaws(entries))

Share an exact rational base

The polynomial_setup(s) convenience call creates the original Q base and Polynomial carrier. Its second overload accepts base_kind, carrier_name, and prefix. Pass the carrier of a rational profile already registered in the session; the helper retrieves that profile through s.arithmetic(base_kind). It checks rational-literal support before declaring the new polynomial carrier or its twelve assumptions. It creates no further base laws or registration.

The carrier name identifies the new type; the prefix qualifies its operations and axioms. Each caller then explicitly registers polynomial literals under a fresh name. Two carriers can therefore share their coefficient base:

Mojo

shared_polynomial_base.mojo Download
"""Two polynomial carriers share one explicitly assumed rational base."""

from apn_mojo import Rational
from std.testing import assert_equal, assert_true
from judgment_shell import LibErrorKind, Session
from exact_arithmetic_setup import numeric_setup
from polynomial_setup import polynomial_setup


def main() raises:
    var s = Session()
    var q = numeric_setup(s, "Q", rational=True)
    _ = q.register_rationals("rationals")

    var first = polynomial_setup(s, base_kind=q.kind, carrier_name="First", prefix="A")
    var a = first.register_polynomials("A.literals")
    var x = a.indeterminate()
    var first_proof = s.theorem("A.difference_of_squares",
        (x + 1) * (x - 1) == a.polynomial([Rational(-1), Rational(0), Rational(1)]))
    first_proof.rfl()
    var first_fact = first_proof.finish()
    assert_equal(len(first_fact.axioms()), 28)
    assert_equal(len(first_fact.admissions()), 0)
    print("First carrier:")
    print(first_fact)

    var second = polynomial_setup(s, base_kind=q.kind, carrier_name="Second", prefix="B")
    var b = second.register_polynomials("B.literals")
    var y = b.indeterminate()
    var second_proof = s.theorem("B.difference_of_squares",
        (y + 1) * (y - 1) == b.polynomial([Rational(-1), Rational(0), Rational(1)]))
    second_proof.rfl()
    var second_fact = second_proof.finish()
    # Its later canonical signature includes both polynomial registrations.
    assert_equal(len(second_fact.axioms()), 40)
    assert_equal(len(second_fact.admissions()), 0)
    print("Second carrier:")
    print(second_fact)

    # The base is reused; each polynomial carrier has its own twelve axioms.
    assert_equal(len(s.find("Q.", limit=100)), 16)
    assert_equal(len(s.find("A.", limit=100)), 13)
    assert_equal(len(s.find("B.", limit=100)), 13)
    assert_true(first.base.rational(1, 2).same_as(second.base.rational(1, 2)))
    assert_true(not first.kind.same_as(second.kind))
    assert_equal(len(first_fact.axioms()), 28)
    print("Shared base: 16 axioms; original theorem still has 28 dependencies")

    # Sharing coefficients does not make the two polynomial types interchangeable.
    x = a.indeterminate()
    var refused = False
    try:
        _ = x + y
    except error:
        refused = error.kind == LibErrorKind.KERNEL
    assert_true(refused)
    print("Mixed polynomial carriers refused")

Run from the repository root pixi run mojo run -I src docs/examples/library/shared_polynomial_base.mojo

Output

First carrier:
[assuming 28 axioms] ⊢ (1*X[0] + 1) * (1*X[0] - 1) = -1 + 1*X[0]^2
  axioms: Q.add_assoc, Q.add_comm, Q.add_zero, Q.mul_assoc, … (+24 more)
Second carrier:
[assuming 40 axioms] ⊢ (1*X[0] + 1) * (1*X[0] - 1) = -1 + 1*X[0]^2
  axioms: Q.add_assoc, Q.add_comm, Q.add_zero, Q.mul_assoc, … (+36 more)
Shared base: 16 axioms; original theorem still has 28 dependencies
Mixed polynomial carriers refused

Python

shared_polynomial_base.py Download
"""Two polynomial carriers share one explicitly assumed rational base."""

from judgment import JudgmentError, LibErrorKind, Session
from exact_arithmetic_setup import numeric_setup
from polynomial_setup import polynomial_setup


def main():
    s = Session()
    q = numeric_setup(s, "Q", rational=True)
    q.register_rationals("rationals")

    first = polynomial_setup(s, base_kind=q.kind, carrier_name="First", prefix="A")
    a = first.register_polynomials("A.literals")
    x = a.indeterminate()
    first_proof = s.theorem("A.difference_of_squares", (x + 1) * (x - 1) == a.polynomial([-1, 0, 1]))
    first_proof.rfl()
    first_fact = first_proof.finish()
    assert len(first_fact.axioms()) == 28
    assert len(first_fact.admissions()) == 0
    print("First carrier:")
    print(first_fact)

    second = polynomial_setup(s, base_kind=q.kind, carrier_name="Second", prefix="B")
    b = second.register_polynomials("B.literals")
    y = b.indeterminate()
    second_proof = s.theorem("B.difference_of_squares", (y + 1) * (y - 1) == b.polynomial([-1, 0, 1]))
    second_proof.rfl()
    second_fact = second_proof.finish()
    # Its later canonical signature includes both polynomial registrations.
    assert len(second_fact.axioms()) == 40
    assert len(second_fact.admissions()) == 0
    print("Second carrier:")
    print(second_fact)

    # The base is reused; each polynomial carrier has its own twelve axioms.
    assert len(s.find("Q.", limit=100)) == 16
    assert len(s.find("A.", limit=100)) == 13
    assert len(s.find("B.", limit=100)) == 13
    assert first.base.rational(1, 2).same_as(second.base.rational(1, 2))
    assert not first.kind.same_as(second.kind)
    assert len(first_fact.axioms()) == 28
    print("Shared base: 16 axioms; original theorem still has 28 dependencies")

    # Sharing coefficients does not make the two polynomial types interchangeable.
    x = a.indeterminate()
    refused = False
    try:
        x + y
    except JudgmentError as error:
        refused = error.kind == LibErrorKind.KERNEL
    assert refused
    print("Mixed polynomial carriers refused")


main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/shared_polynomial_base.py

Output

First carrier:
[assuming 28 axioms] ⊢ (1*X[0] + 1) * (1*X[0] - 1) = -1 + 1*X[0]^2
  axioms: Q.add_assoc, Q.add_comm, Q.add_zero, Q.mul_assoc, … (+24 more)
Second carrier:
[assuming 40 axioms] ⊢ (1*X[0] + 1) * (1*X[0] - 1) = -1 + 1*X[0]^2
  axioms: Q.add_assoc, Q.add_comm, Q.add_zero, Q.mul_assoc, … (+36 more)
Shared base: 16 axioms; original theorem still has 28 dependencies
Mixed polynomial carriers refused

The session has one set of sixteen Q assumptions and twelve assumptions for each polynomial carrier. The two carriers remain distinct: sharing a coefficient base does not provide an implicit conversion between their polynomial values.

The first result has 28 dependencies. After the second polynomial registration, the active canonical signature includes both registrations, so the second result reports 40 dependencies. The saved first result retains its original 28. These are the checked derivation's signature dependencies, not a claim that all forty laws are mathematically necessary for that polynomial identity.

The supplied-base overload preserves LibError: an unbound base reports NO_MATCH, symbolic-only and integer profiles report UNSUPPORTED, and a foreign carrier reports WRONG_KERNEL. These checks precede polynomial declarations. Setup remains an ordinary sequence of declarations: a later name collision or budget failure can leave earlier declarations. Existing transactions provide allocation rollback when needed.

Theory snapshots and transactions

session.snapshot() captures the session's theory, completed-theorem namespace, and arithmetic bindings as a TheorySnapshot; it needs every transaction closed. checkout(snapshot) returns the session to it, charging the rollback work; rollback(snapshot) does the same without charging. Handles made after the snapshot are then stale. A snapshot supports historical fact(name) and theorem(name, target) access.

theory_branches.mojo Download
"""Return to an earlier theory while keeping historical theorem visibility."""

from judgment import Session


def main() raises:
    var s = Session()
    var P = s.prop("P")
    var left = s.theorem("left", P == P)
    left.rfl()
    _ = left.finish()
    var branch = s.snapshot()

    var right = s.theorem("right", (P & P) == (P & P))
    right.rfl()
    _ = right.finish()
    s.checkout(branch)
    for name in s.find():
        print(name)
    print(branch.fact("left"))

Run from the repository root pixi run core-run docs/examples/library/theory_branches.mojo

Output

left
⊢ P = P

session.transaction() opens a nested transaction. Close transactions in reverse creation order. discard() restores the session to its state when the transaction opened, and every handle made inside is stale. commit(expressions, facts, types, definitions, subsets, steps, declarations) keeps the session's work and returns a Retained object with replacement lists in request order; proof rows are always kept.

Mojo

transactions.mojo Download
"""Retain replacement results and discard temporary work explicitly."""

from judgment import Session


def main() raises:
    var s = Session()
    var scope = s.transaction()
    var P = s.prop("P")
    var proof = s.theorem("reflexivity", P == P)
    proof.rfl()
    var kept = scope.commit(expressions=[P], facts=[proof.finish()])

    var live_P = kept.expressions()[0]
    var reused = s.theorem("reused", live_P == live_P)
    reused.exact(kept.facts()[0])
    print(reused.finish())

    var temporary = s.transaction()
    _ = s.prop("temporary")
    temporary.discard()
    print("Registered theorems:", len(s.find()))

Run from the repository root pixi run core-run docs/examples/library/transactions.mojo

Output

⊢ P = P
Registered theorems: 2

Python

transactions.py Download
"""Retain replacement results and discard temporary work explicitly."""

from judgment import Session


def main():
    s = Session()
    scope = s.transaction()
    P = s.prop("P")
    proof = s.theorem("reflexivity", P == P)
    proof.rfl()
    kept = scope.commit(expressions=[P], facts=[proof.finish()])

    live_P = kept.expressions()[0]
    reused = s.theorem("reused", live_P == live_P)
    reused.exact(kept.facts()[0])
    print(reused.finish())

    temporary = s.transaction()
    _ = s.prop("temporary")
    temporary.discard()
    print("Registered theorems:", len(s.find()))


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/transactions.py

Output

⊢ P = P
Registered theorems: 2

Use replacements after commit: every other handle made inside the transaction is stale. Drafts are not retention results; a proof modified with objects made inside a transaction must be discarded or restored to an earlier live checkpoint. The theorem namespace, profiles, generic parameters, generated subset laws, and admission provenance survive the commit with their evidence. Retrieve a retained arithmetic profile with session.arithmetic(retained_type). Logical finish() and commit() are separate operations; unfinished drafts are not retainable. Transactions require explicit closure rather than implicit destructor rollback.

session.fork(work) makes an independent session over a child of the session's workspace; a session can fork any number of times. session.merge(fork) commits the fork's work back when the parent has declared nothing and made no variable since the fork. It is also refused when a variable the fork made is one the parent made after the fork, at the same binding site (SHAPE), or when the two sessions registered different claims of one decider on one frame (FORMAT). A refused merge leaves the parent as it was; the forks contract says which refusals also close the fork.

Work over a sealed snapshot

A theory built elsewhere, by another session, a Scalar profile, or Store, becomes a session's starting point as a checked Snapshot: session.seal() closes a session and returns its snapshot, and Session.open(snapshot, work) opens a new session over it. Read the declarations you need with import_type, import_symbol, and import_fact, and take library theorems with import_theorem:

Mojo

imported_theory.mojo Download
"""Seal a base theory snapshot, then open a new Session over it and import its declarations."""

from judgment import Session, arrow, forall


def main() raises:
    # Build a base theory in one session and seal it into an immutable Snapshot.
    var base = Session()
    var nat = base.declare_type("nat")
    var zero = base.symbol("zero", nat)
    var succ = base.symbol("succ", arrow(nat, nat))
    var n = base.bound_var("n", nat)
    _ = base.axiom("succ_ne_zero", forall(n, ~(succ(n) == zero)))
    var snapshot = base.seal()

    # Open a new session over the snapshot and import the declarations it needs.
    var s = Session.open(snapshot)
    var N = s.import_type("nat")
    var z = s.import_symbol("zero")
    var S = s.import_symbol("succ")
    var axiom = s.import_fact("succ_ne_zero")
    print(axiom)
    var proof = s.theorem("one_ne_zero", ~(S(z) == z))
    proof.exact(proof.use(axiom, terms=[z]))
    var result = proof.finish()
    print(result)
    print(result.axioms()[0], N.format())
    var exported = result.step()
    print(len(exported.hypotheses()) == 0)

Run from the repository root pixi run core-run docs/examples/library/imported_theory.mojo

Output

[axiom] ⊢ ∀x·1:nat. ¬(succ(x·1) = zero)
  axioms: succ_ne_zero
[assuming 1 axiom] ⊢ ¬(succ(zero) = zero)
  axioms: succ_ne_zero
succ_ne_zero nat
True

Python

imported_theory.py Download
"""Seal a base theory snapshot, then open a new Session over it and import its declarations."""

from judgment import Session, arrow, forall


def main():
    # Build a base theory in one session and seal it into an immutable Snapshot.
    base = Session()
    nat = base.declare_type("nat")
    zero = base.symbol("zero", nat)
    succ = base.symbol("succ", arrow(nat, nat))
    n = base.bound_var("n", nat)
    _ = base.axiom("succ_ne_zero", forall(n, ~(succ(n) == zero)))
    snapshot = base.seal()

    # Open a new session over the snapshot and import the declarations it needs.
    s = Session.open(snapshot)
    N = s.import_type("nat")
    z = s.import_symbol("zero")
    S = s.import_symbol("succ")
    axiom = s.import_fact("succ_ne_zero")
    print(axiom)
    proof = s.theorem("one_ne_zero", ~(S(z) == z))
    proof.exact(proof.use(axiom, terms=[z]))
    result = proof.finish()
    print(result)
    print(result.axioms()[0], N.format())
    exported = result.step()
    print(len(exported.hypotheses()) == 0)


if __name__ == "__main__":
    main()

Run from the repository root PYTHONPATH=bindings/python:docs/examples/python/library pixi run python docs/examples/python/library/imported_theory.py

Output

[axiom] ⊢ ∀x·1:nat. ¬(succ(x·1) = zero)
  axioms: succ_ne_zero
[assuming 1 axiom] ⊢ ¬(succ(zero) = zero)
  axioms: succ_ne_zero
succ_ne_zero nat
True

Imported facts behave like registered theorems: use, apply, and exact take them, Session.fact(name) finds them, and axioms() names the imported axioms a proof rests on. Bound variables get fresh display names, because the stored statement keeps no binder names. Fact.step() exposes the checked step for inspection, and Session.export(theorem, name) gives a theorem with its checked proof for library publication. See the import contract for the forms it does not support.

Scope and limits

The proof-authoring specification records the API, its failure and lifetime rules, and the example acceptance mapping. All transformations are explicit. Equality calculations and typed recipe holes are supported; shared unresolved inference metavariables, mixed-relation chains, and serialization of unfinished drafts are not. Checkpoints are in-process logical snapshots, not durable storage.

The lower-level judgment_shell interfaces remain available alongside Session, for example for the import forms a session does not support and for the conversion and engine protocols. Class-level ACU notation, locales, a constructed real-number theory, implicit ACU subset selection, recursive definitions, and automatic simplification are outside the API; the specification's deferred extensions list them. See the API reference for exact signatures.

judgment v1.0.0 for Mojo 1.2 · Apache License 2.0 with LLVM Exceptions · Source on GitHub