leanfran | Clojure quick start
Source paths below are relative to langs/Clojure/.
Add the dependency to deps.edn (see the Clojure quick start) and install
the compiler with nix profile install 'github:conao3/lean-leanfran/v<version>#leanfran', where <version> is
the release of the library. Clojure 1.12 and JDK 21 or later are required, and sync needs lean and lake of
Lean 4.35.0 on PATH. The generated code runs without Lean and without the compiler.
(ns demo.core
(:refer-clojure :exclude [double])
(:require [leanfran.core :refer [deflean]]))
(deflean arith
(def double [n Nat] Nat
(+ n n))
(theorem double_eq [n Nat] (= (double n) (* 2 n))
(by (unfold double) omega))
(structure Account [owner String balance Nat])
(def deposit [a Account n Nat] Account
(with a {:balance (+ (.balance a) n)})))
(double 21) ;=> 42
(deposit {:owner "ann" :balance 10} 5) ;=> {:owner "ann", :balance 15}Generate the code of the block, and load the namespace:
leanfran --lang clojure sync
clojure -M -m demo.coreIf a proof in the block fails, sync stops and prints Lean's error messages at the positions in the Clojure file.
samples/ holds small programs built with leanfran. Each one is a
Clojure project with its own README and a make test.
| Use | Samples |
|---|---|
Write functions in Lean and call them from Clojure (deflean) |
todo-cli, word-count |
| Compile a Lean project to a Clojure namespace (the CLI) | roman-numerals |
Write functions in Clojure and verify them in Lean (leanfran.typed) |
verified-clojure, sorted-search, inventory, generic-search, typed-schemas |
samples/README.md describes what each sample shows and
where to start.
(deflean <block> [{:imports ["Std.Data.HashMap"], :uses [other-block], :opens ["Std"]}] <command> ...)Each command is an S-expression of leanfran.dsl or a string of Lean source.
leanfran.dsl/render shows the Lean source of a sequence of commands.
| S-expression | Lean |
|---|---|
(def f [x T y U] R body) |
def f (x : T) (y : U) : R := body |
(theorem t [x T] P proof) |
theorem t (x : T) : P := proof |
(structure S [f T g U] (deriving Repr)) |
structure S where f : T ... |
(inductive I a (b [x T])) |
inductive I where | a | b (x : T) |
(instance C body), (mutual ...), (namespace N ...), (open N) |
the same commands |
(f a b), (+ a b c), (- a), (not p) |
(f a b), (a + b + c), (-a), (¬p) |
(if c t e), (if h c t e), (let [x v] e), (fn [x] e) |
if, if h : c then, let, fun |
(match x p1 e1 p2 e2), (match [x y] [p q] e), (match-eq h x ...) |
match x with | p1 => e1 ..., match h : x with |
(.field x), (.method x a) |
x.field, (x.method a) |
{:x 1}, (with s {:x 1}), (<> a b) |
{ x := 1 }, { s with x := 1 }, ⟨a, b⟩ |
[a b], (array a b) |
[a, b], #[a, b] |
(the T e), (-> A B), (forall [x T] P), (exists [x T] P) |
(e : T), A → B, ∀, ∃ |
(by (simp [a b]) omega) |
(by simp [a, b]; omega) |
(lean "...") |
Lean source as is |
Names:
- A
-in a symbol becomes lowerCamelCase in Lean (is-prime→isPrime), and the public Clojure name converts back (is-prime). leanfran keeps_, so you write Lean lemma names as they are (Nat.add_comm). - Binder vectors take
(implicit α Type)and(inst (BEq α)). Metadata on a name adds modifiers (^:partial,^:private,^{:attrs [simp]}), and:termination-byand:decreasing-byon adefaddtermination_byanddecreasing_by. - Inside
by, a-in a tactic name becomes_(all-goals→all_goals).(on-all t1 t2)ist1 <;> t2, and(case tag [x] t ...)iscase tag x => ....
Binary operators: + - * / % pow ++ = == != not= < <= > >= and or iff && || band bor land lor xor <<< >>> in not-in cons |> <| >>= <$> comp.
The block becomes the Lean module LeanCljEmbed.<Namespace>.<Block> (for demo.core and arith:
LeanCljEmbed.Demo.Core.Arith) in the Lake workspace .leanfran/clojure/workspace/.
-
:importsare Lean modules to import, and:opensLean namespaces to open. -
{:uses [other-block demo.types/types]}imports and opens other blocks, of the same namespace or of another one, so that a block uses their structures and functions. Another key of the map is an error. -
(export f {:at {α Int} :as name})adds a monomorphic definition that calls the polymorphic definitionfof the block. Clojure calls it asname(by defaultf-int). A definition that cannot be a Clojure function (one with instance arguments, say) is reported on standard error bysync, asleanfran: skipped <name>: <reason>. -
Each Clojure function that a block defines carries
:lean/nameand:lean/modulemetadata. -
An error from Lean is reported as
<file>:<line>:<column>: error: (lean block <ns>/<block>, Lean <line>:<column>) <message>. The first position is that in a string of Lean source, or the start of the S-expression that the error came from; the second is in the Lean source of the block. -
A block with
sorryis generated, andsyncreports it as<file>:<line>:<column>: warning: (lean block <ns>/<block>, Lean <line>:<column>) declaration uses `sorry`on standard error. -
syncreads the top-leveldefleanforms of the files, without loading their namespaces. Adefleanthat a macro orevalmakes has no code.
clj-kondo picks up the names a block defines through the hook exported in
resources/clj-kondo.exports/io.github.conao3/leanfran.
Public functions convert arguments and results between Clojure and Lean values according to the Lean signature:
| Lean | Clojure |
|---|---|
Nat, Int, UInt8..UInt64, Fin n, Float |
numbers (BigInt beyond Long) |
Unit |
nil |
Bool |
true / false |
Char |
Character, or a string for a character above U+FFFF |
String |
string |
List α / Array α |
list / vector |
Option α |
the value or nil |
α × β |
two-element vector |
| structures | maps with keyword keys (a one-field structure too) |
| enumerations | keywords (Suit.hearts → :hearts) |
other inductives (Except too) |
maps with a :tag ({:tag :circle :r 1}, {:tag :ok :value 3}) |
Clj.Map κ ν / Clj.Set α |
map / set |
IO α |
the value of running the action, or an exception |
Other types pass through in the runtime representation (Ctor objects, and
Closure objects that also implement IFn).
Inside generated code, Nat and Int are Long/BigInt, fixed-width
integers and Bool are Long, UInt64 holds the 64-bit pattern in a Long,
String positions are UTF-8 byte offsets as in Lean, and Array is a
persistent vector.
At run time, only the JVM runs. Lean runs in leanfran --lang clojure sync and
when the CLI compiles a module, and leanfran.runtime replaces Lean's C
runtime, so no Lean process, FFI, or second heap takes part. The values that
cross between Clojure and generated code are immutable, and Lean's mutable
state runs on Clojure's own: IO.Ref and ST.Ref are atoms, Task is a
future, Thunk is a delay, a constant is a delay computed once per namespace,
and the standard streams are *out*, *err*, and *in*, so binding
redirects them.
leanfran.types derives from a Lean type, written as in signatures:
| Function | Result |
|---|---|
gen |
a test.check generator of the Clojure values of the type |
valid? |
whether a value has the type, telling lists from vectors |
malli-schema, fn-schema |
a malli schema as data, and the function schema of a lt/defn var ([:function ...] for several arities) |
kondo-type, kondo-config, write-kondo-config! |
clj-kondo :type-mismatch types of lt/defn functions, written to .clj-kondo/leanfran/types/config.edn |
It knows Nat, Int, Bool, String, Char, Float, UInt8..UInt64,
Unit, (Fin n), List, Array, Option, Prod, (Map K V), (Set α),
and the structures, enumerations, and sum types (as {:tag :circle :r 1})
of deflean blocks and generated namespaces, by full Lean name or by a short
name that one of them has. leanfran.malli/instrument! registers the malli
function schemas of the lt/defn functions of namespaces and instruments them
(malli is your dependency).
leanfran --lang clojure sync writes the code of the block my-block of the namespace demo.core to
demo/core/_lean/my_block.clj, next to the namespace. Commit it, with leanfran.manifest.json and, after check,
leanfran.lock. deflean expands to this file, which it finds on the classpath as a resource, and starts neither Lean
nor the compiler. Do not commit the Lake workspace at .leanfran/clojure/workspace/. The second line of the file holds a hash of the block. When the file is missing or the hash is that
of another block, compilation stops with
leanfran: the Lean block demo.core/my-block is out of date; run 'leanfran --lang clojure sync'
With LEANFRAN_AUTO_SYNC=1 it runs leanfran --lang clojure sync in the directory of the source file instead, for
the blocks that need no Clojure functions. A block with (clojure f ...), and one that uses such a block, still stops:
its models come from namespaces that load, and this one is loading.
Comments and blank lines are not a part of the hash. Commit .leanfran/.gitignore to exclude workspace files.
_lean/leanfran.typed.clj holds the models of the functions of a namespace that
leanfran.typed/check-translation runs; deflean does not read it.
The files of sync and the namespaces of module generate start with
;; Code generated by leanfran --lang clojure (generator 2) from Roman. DO NOT EDIT.Public functions take the Lean name relative to the module (or
--namespace) in kebab-case: Point.add → point-add, isEven? →
is-even?. An IO action runs when called and returns its value, or throws
for an error; its output goes to *out* and *err*.
The backend works on Lean's compiler IR. A hand-written runtime
(leanfran.runtime) provides the C symbols of Lean's @[extern]
declarations, including Float32, ByteArray, FloatArray, Thunk, Task,
and the standard streams and references of IO. A generated namespace checks
at load time that the runtime has the symbols it uses.
Run the commands in the project, or with --dir <dir>:
| Command | Effect |
|---|---|
leanfran --lang clojure sync |
Checks the blocks with Lean and writes their code and leanfran.manifest.json. |
leanfran --lang clojure check |
sync, then checks the models of the functions and the proofs in lean/Proofs/, and writes leanfran.lock. |
leanfran --lang clojure status |
Prints a line for each block and function that is out of date, without Lean. --output json prints JSON. |
The commands run clojure -M -m leanfran.cli with the deps.edn of the project root. sync and check load the
namespaces that have blocks with (clojure f ...), since a function may use macros of the project. They add the
directories of paths to the classpath, but not the :extra-deps of aliases. A block whose code is missing stops the
load of its namespace, and sync repeats the load after it generated the block.
sync and check accept --verbose for Lake output. check and status accept
--require proved; this gate does not apply to Clojure compilation.
Set LEANFRAN_CLI to select the compiler executable used by host tools (default: leanfran on
PATH). Set LAKE to select the Lake executable used by the compiler (default: lake on PATH).
leanfran --lang clojure --help | --version | --generator-version
leanfran --lang clojure module generate (--module-name <Name> --clojure-namespace <ns> | --batch <file>)
[--roots <Name> ...] [--namespace <Name>] [--import <Name> ...]
[--search-path <dir> ...] [--output-file <path>] [--forms-only]
[--output json|text]
module generate generates the Clojure namespace of one module, or with
--batch the namespaces of the jobs of a JSON array. A job has the keys
module, output_file, path (the Clojure namespace), roots, namespace,
and type_group. Without --roots, the public definitions of the module that
have a supported signature are generated, and the others are listed in the
summary as skipped. --search-path adds directories of .olean files (in a
lake package, .lake/build/lib/lean), and --import adds modules whose
@[csimp] lemmas apply to the roots; a lemma whose other side is an
@[extern "clj:<ns>/<name>"] definition applies to every call.
leanfran --lang clojure module generate --help prints the options.
leanfran --lang clojure theorems check --modules <Name> ... [--output text|json] [--search-path <dir> ...]
theorems check exits with 1 and prints <file>:<line>:<column>: error: <name>: <status> for each declaration of the
modules with a theorem or a proof that is not proved, or a JSON array of them with --output json.
The summary is a JSON array with the module, files, functions, externs,
skipped, data (the namespace and the public functions), and for a
failed job the error of each job; --output text prints a line per job. It
goes to standard output, or to standard error when the code goes to standard
output.
To generate namespaces from several Lake packages and modules with one command,
list them in leanfran.toml with lang = "clojure" and run
leanfran generate. See the generation guide for the
table keys and the names and files of the namespaces.
0 success, 1 out-of-date output or unmet obligations (status, check) or unproved theorems (theorems check), 252 invalid parameters, 254 input that cannot be
converted (a missing module, an unsupported definition, a mistake in leanfran.toml), 255 other errors.
The project root is the nearest directory with a leanfran.toml, or else with a deps.edn. It must have a deps.edn.
The shared settings and the table of Clojure:
[check]
require = "proved"
[[require]]
name = "mathlib"
scope = "leanprover-community"
[embed.clojure]
paths = ["src"]paths are the directories of the classpath to scan (default: ["src"]). [[require]] adds Lake packages to the
workspace; a block imports their modules with :imports, and so do the models of the functions that the block names.
| Variable | Effect |
|---|---|
LEANFRAN_AUTO_SYNC=1 |
A stale deflean without (clojure f ...) runs leanfran --lang clojure sync instead of stopping the compilation. |
LEANFRAN_RUNS, LEANFRAN_SEED |
The number of inputs and the seed of the random tests. |
leanfran.typed/defn defines an ordinary Clojure function with a Lean
signature, and binds it to specifications written in a deflean block.
leanfran --lang clojure check translates the function to Lean, its model, and
checks your proofs, and leanfran.typed/check runs the same specifications as
a random test:
(require '[leanfran.core :refer [deflean]]
'[leanfran.typed :as lt])
(deflean spec
(def clamp-spec [x Int lo Int hi Int] Int (max lo (min hi x)))
(def ordered [_x Int lo Int hi Int] Bool (<= lo hi))
(def in-range [_x Int lo Int hi Int r Int] Bool (&& (<= lo r) (<= r hi))))
(lt/defn clamp
{:refines clamp-spec, :requires ordered, :ensures {in_range in-range}}
[x Int lo Int hi Int] Int
(max lo (min hi x)))To verify a function without changing its ordinary defn, add lt/verify
after it in the same namespace and source file:
(defn clamp [x lo hi]
(max lo (min hi x)))
(lt/verify clamp
{:sig [[Int Int Int] Int]
:refines clamp-spec
:requires ordered
:ensures {in_range in-range}})Declare verify once per function. It does not wrap or replace the function.
The signature has one type per argument, including destructuring arguments,
and a return type. The definition must have one fixed arity and one body form;
it cannot use pre/post conditions, primitive hints, unchecked math, or inline
metadata. If you register a Malli schema yourself, leanfran.malli/register!
leaves it in place.
(clojure f ...) in a deflean block gives the block the models of functions, to state and prove theorems about:
(lt/defn insert-sorted [x Int xs (List Int)] (List Int)
(if-let [y (first xs)]
(if (<= x y) (cons x xs) (cons y (insert-sorted x (rest xs))))
(list x)))
(deflean sorting
(clojure insert-sorted)
(theorem insert-sorted-length [x Int xs (List Int)]
(= (.length (insert-sorted x xs)) (+ (.length xs) 1))
(by (on-all (fun-induction insert-sorted x xs) simp-all grind)))):refines s:f x = s x;:requires p:p x = true →before each obligation;:ensures {label q}:q x (f x) = true. The attribute map after the documentation, or the metadata of the name, holds them.- A specification is the name of a Clojure function that a
defleanblock defines (clamp-spec, orspec/clamp-specwith an alias of its namespace). The block may be before or after the function, and may name the function in(clojure f ...).:requiresand:ensurestake functions that returnBool. - The labels of
:ensuresmatch[a-z][a-z0-9_]*;refinesis reserved. A map of more than eight entries has no order in Clojure; a vector[label q label q ...]has. - A function with marks has one arity and no type parameters.
[x T y U] R, as indeflean. Parameters may be destructuring forms ([[a b] (Prod Int String) {:keys [owner]} Account]), and& xs (List T)takes the rest arguments.(lt/defn f ([x Int] Int ...) ([x Int y Int] Int ...))has several arities; their models aref.arity1andf.arity2.(implicit α Type)and(inst (BEq α))make a polymorphic function. Its model takes[Clj.Truthy α], so that a test of anαvalue means what it means at the type the caller uses,[Clj.NonNil α], sincenilis not a value ofα, and[Clj.Same α]for[BEq α], which is Clojure's=; theorems about it state(inst (Clj.Truthy α)),(inst (Clj.NonNil α))and(inst (Clj.Same α)), or(inst (LawfulBEq α)), among their binders.- Types are Lean types, and
(Map K V)and(Set α)are the models of Clojure maps and sets. :termination-by(a Lean term) and:decreasing-bymetadata on the name give Lean the termination argument; Lean finds it itself for recursion on(rest xs)under(if-let [y (first xs)] ...).:atmetadata on the name lists the types, besidesInt, at whichcheck-translationruns a polymorphic function:^{:at [{α String}]}.
The model of f of the namespace demo.core is the Lean definition LeanCljModel.Demo.Core.f, in a module of its
own, which the block imports. In the block, it has the name f. The model sees the types of the blocks and packages
that the block imports, and not those that the block defines itself. import LeanCljModel.Demo.Core imports the models
of the namespace.
| Clojure | Lean model |
|---|---|
if, when, when-not, if-not, cond, case on keywords and literals |
if h : truthy c = true, match; a local tested by if stands for its non-nil value in the branch |
if-let, when-let, if-some, when-some |
match h : v with | some x => ... |
and, or |
&&, || in conditions; the first falsy or truthy value elsewhere ((or x 0)) |
let, fn, destructuring |
let, fun, projections (Clj.elem i of a vector: a pair's component, or an Option element) |
lt/loop ([i Nat 0 ...]) and recur, lt/letfn |
a local let rec |
calls of lt/defn functions and of functions from deflean |
calls of their models and Lean definitions; mutual recursion becomes mutual |
keywords: (:k m), (get m :k), (map :k xs), assoc, update |
structure fields |
{k v} with other keys, #{...}, get, assoc, update, dissoc, merge, frequencies, group-by, clojure.set |
Clj.Map, Clj.Set |
'(1 2), [a b], macros that expand to these (->, ->>, cond->) |
list and vector literals; a two-element vector is a pair or a vector |
do with several forms, atoms, Java interop, try, keys and vals of a hash
map (whose order is the hash order), and keyword-keyed maps other than
structures stop the translation with the reason. So do forms whose value in Clojure is not the one that their model would
have:
| Clojure | Why it has no model |
|---|---|
primitive type hints (^long, ^double), also those that macros write; a namespace with *unchecked-math* |
numbers are converted, and Long arithmetic wraps |
| a map or set literal of variables | equal keys throw; hash-map and hash-set take them |
| keywords with a namespace, and keys that are not in kebab-case | they are no fields of the generated maps |
:strs and :syms in destructuring |
the maps of structures have keyword keys |
a body of several forms in when-let, when-some, lt/loop, lt/letfn |
all but the last are discarded |
| functions with several arities, with rest parameters or without parameters as values, functions that return functions, and calls of what a call returns | Clojure functions are not curried |
| a function from Lean with fewer arguments than parameters | Lean fills in default values |
^:dynamic and :inline functions, functions whose var holds another function (alter-var-root), symbols that name another var since the function was defined |
other code runs |
macros that read &env |
the translation expands them without the locals of the compiler |
Lean checks the types of the rest, and clj_body, which the body of each model starts with, checks what Lean made of it.
These give no model either:
| Clojure | Why it has no model |
|---|---|
a call that can throw: (quot a b), (nth xs i), (subvec v a b), (reduce max xs) |
Lean cannot prove that it returns; see below |
=, distinct, set, map keys and others that compare doubles, or structures that hold them |
two ##NaN are equal when they are one object |
= of a type whose BEq instance is not equality |
Clojure compares the values |
an integer literal as a double, (reduce + doubles) |
0 is a Long; next to a double, as in (+ x 1) and (< 0 x), it has a model |
max, min, quot, rem, mod, even? of doubles; / by anything but a double literal that is not zero |
the sign of zero and the exceptions depend on whether a number is primitive |
first, get, destructuring and others that return an element or nil, where the elements can be nil |
the two are one value |
| rest arguments as a value: tested, returned, or passed to a function | they are nil when there are none; first, map, reduce, count and the like read them |
count of a list that comes from range, concat, mapcat, interleave or interpose, also through functions |
count of a seq is an int, which wraps at 2^31; count a vector ((count (vec xs))) |
case on doubles |
whether 0.0 is -0.0 depends on the constants |
| a field that is no field of the structure, a structure without all its fields, a keyword that is no constructor of an enumeration | Lean has other names there, and default values |
| coercions, instances and literals that a block defines | Clojure does not know them |
an integer literal that UInt8 or (Fin n) does not hold |
Lean wraps it |
types without Clojure values, (Option (Option T)), a constructor with a field tag |
their values are not told apart |
The model of a monomorphic function is @[extern] to the Clojure var, so
compiled Lean code that calls it runs the Clojure function. The generated code
finds the var when it calls it, and loads its namespace when it is not loaded.
A function that takes or returns a Clj.Map, a Clj.Set or a Char runs as its model: a hash map has an order of its
own, and a Char above U+FFFF is no Clojure character.
Leanfran replaces a specification only when status reports a proved refines without
requires, the generated code can call the implementation, and its values can round-trip.
The model must not use a specification that is a candidate for replacement. If several
functions qualify for one specification, the first by function id wins.
The obligation must cover all of the specification's arguments in the same order, and the model
and specification types must match after unfolding reducible definitions such as abbrev.
The sole result exception is an Int model result for a Nat specification; that proof
guarantees a nonnegative result. Arguments coerced or supplied by elaboration do not qualify.
check writes the lock and applies the replacement. The next sync drops it if the function,
its dependencies, the proofs, or other inputs changed so that status no longer reports it as
proved. Until that sync, generated calls may still reach the changed implementation.
Random tests always compare the host function against the Lean body with no replacements.
Generated code resolves the implementation's var on demand. If it cannot load the
namespace or the var is not bound yet, it uses the original lean-spec--<name> function.
It also uses that function for a Char argument above U+FFFF. The property test uses the
original function through the public function's :lean/spec metadata.
Raw types (such as recursive inductives, nested options and function values), Clj.Map,
Clj.Set, and IO are not eligible. Default or variadic parameters are not eligible.
from-clj rejects a negative value at a Nat boundary, both when a public Lean function
takes a Nat and when a replacement for a Nat specification returns an Int.
leanfran --lang clojure check runs sync, writes the model of each function with marks and one obligation per label
to .leanfran/clojure/workspace/LeanCljModel/, and judges the theorems <function>.proof.<label> of
lean/Proofs/*.lean at the project root. The function sort-ints has the Lean name sortInts. A proof of the
namespace demo.core:
import LeanCljModel.Demo.Core
open LeanCljEmbed.Demo.Core.Spec
namespace LeanCljModel.Demo.Core
theorem clamp.proof.refines : clamp.obligation.refines := by
intro x lo hi _
simp only [clamp, clampSpec, clj_simp]The proof sees the specifications through LeanCljEmbed.<Ns>.<Block>, and a block that only holds lemmas with an
import LeanCljEmbed.<Ns>.<Block>. It prints a row <namespace>/<function> [<label>]: <state> per obligation:
demo.core/clamp [in_range]: missing
demo.core/clamp [refines]: proved
The states:
| state | meaning |
|---|---|
proved |
the theorem holds |
sorry |
the proof uses sorry |
axioms |
the proof uses non-standard axioms |
failed |
the proof has an error, or the kernel rejects it |
missing |
no theorem for the obligation |
mismatch |
the theorem states something else |
unextracted |
the function has no obligation to prove (reasons) |
A function that cannot be translated, and one with marks that state no obligations (which has the label model when it
has no other), also prints <file>:<line>:<column>: error: unextracted <id>: <message> on stderr. It does not stop
sync. check exits 1 when an obligation is unextracted or failed, and with --require proved when an obligation is
not proved. It writes leanfran.lock at the project root. In CI, run leanfran --lang clojure check --require proved, then use git diff --exit-code to compare the lock, manifest and generated files.
status prints stale for a function when one of these changes: its form, the functions, the macros and the other
definitions that it reaches, the blocks of its specifications and of the types and the functions that it names with the
blocks that they use, the blocks that name it in (clojure f ...), the files of lean/Proofs/, and the settings.
It also prints stale for the blocks with (clojure f ...) that the function is a part of, for <namespace>/leanfran.typed
of the namespaces of the function and of those that call it, and for the blocks that use a specification that the
function replaces.
The theorems about models in a deflean block are theorems of the block: sync stops when a proof fails, and check
and status print <namespace>/<block> [<theorem>]: <state> for those that are not proved.
The Lean library Clj
(resources/leanfran/lean/Clj.lean) models
the arithmetic of Nat, Int, and Float; truthiness and nil; the sequence
functions (map, filter, reduce, some, every?, mapcat, keep,
partition, distinct, sort, sort-by, take-while, interpose, and
more); maps and sets; str and clojure.string. Where Clojure's meaning
depends on the type, a model has instances only for the types on which Lean can
state it: - and dec take Int and Float (Clojure's (- 3 5) is -2), and first,
next, seq, and get return Option. simp only [clj_simp] rewrites the
models to Lean's own operations. Each model is compared with clojure.core on
generated inputs in test/leanfran/core_model_test.clj.
The models of functions that throw for some arguments take a proof that the call returns, which Lean looks for in the conditions around the call:
| Clojure | What Lean proves |
|---|---|
(quot a b) |
b is not 0, and not -1 when a is Long/MIN_VALUE (the Long result is Long/MIN_VALUE, and the BigInt one 2^63) |
(rem a b), (mod a b) |
b is not 0 |
(nth xs i) |
i is below the length, and for a list also below 2^31 |
(nth xs i default) |
i is below 2^31 |
(assoc v i x), (update v i f) of a vector |
i is at most the length, or below it |
(subvec v a b) |
a is at most b, and b at most the length |
(drop n xs), (split-at n xs), (nthrest xs n), (nthnext xs n) |
n is below 2^31, or at most the length of a vector; not 0 for nthrest of a vector |
(partition n xs), (partition-all n xs) |
n is not 0, and for partition-all below 2^31 |
(reduce f xs), (apply max xs), (apply min xs) |
xs is not empty |
(quot n 2), (if (< i (count v)) (nth v i) 0) and (if (seq xs) (reduce max xs) 0) have models. Tests by if, cond
and the like are conditions, and so are the hypotheses of a lt/loop; :requires is none.
+, -, *, inc and dec throw on a Long overflow, and their models return the integer: a theorem holds for the
Clojure function where no arithmetic overflows. +', -', *', inc' and dec' have the same models, and do not throw.
A Clojure string is a sequence of UTF-16 code units, in which a character above U+FFFF is two, and a Lean String is one
of characters. count is the number of the code units (Clj.count_string_of_lt states that it is the number of
characters when none is above U+FFFF), and sort, sort-by, max-key and min-key order strings by them
(Clj.utf16_of_lt). A function has no model, so that check prints unextracted, when its result depends on the
locale or on dynamic vars, or can hold a half of a character, which is no Lean Char:
| Clojure | Why it has no model |
|---|---|
first, nth, seq, map, reduce, vec, sort and the other sequence functions on a string, destructuring of a string, subs, clojure.string/reverse |
code units |
clojure.string/replace with a match that is not a string literal or is empty, clojure.string/split on an empty regular expression |
code units |
| a string literal with a half of a character | no Lean String |
clojure.string/upper-case, lower-case, capitalize |
the default locale ("i" is "İ" under tr) |
str of a collection |
*print-length*, *print-level*, *print-readably* |
Each accepted input calls the implementation once. The test checks refines first, then
ensures in the written order, and reports the first failure for that function. run is the
zero-based index of the original failure among accepted inputs; input shows the counterexample
after shrinking. If the host call fails, the value is failed: <reason>. If a specification
fails, the report says the spec failed and shows error: <reason>.
(lt/check #'f opts) generates arguments from the signature with test.check, skips those that do not satisfy
:requires, and compares the results with :refines and then with :ensures, in the order that they are written in. It
runs the Lean code of the specifications that sync generated, also of those that a Clojure function
replaces. The options:
:num-tests, the number of arguments that satisfy :requires (LEANFRAN_RUNS, or 200, from 1 to 2147483647), :seed
(LEANFRAN_SEED, or 1, from 0 to 9223372036854775807), :gens (generators by parameter name), :max-size, and
:big-ints? (integers on the bounds of Long and beyond). (lt/defcheck name f opts) defines a clojure.test test that runs it. The
result has :pass?, and a failure has a :message, which defcheck reports, with the seed, the number (from 0, of the
arguments that satisfy :requires) of the run that failed first, and the arguments that were shrunk. A function that is wrong for
x > 100, with a :requires that accepts even numbers:
demo.core/succ [refines]: mismatch (seed 1, run 54)
input: x=102
expected: 103, got: 102
The input is the simplest one found with the same label: integers nearer to 0, shorter collections and strings, false,
earlier constructors, and structures with such fields. The generators of :gens shrink with test.check. Shrinking ends
after 1,000 calls of the function.
An :ensures specification shows <name in the block> does not hold in place of mismatch and result: <value> in
place of the last line. A function that throws shows failed: <exception> as its value, and a specification that throws
shows the spec failed and error: <exception>; a Lean panic in a specification shows error: panic: <message>. A result that is not a value of the
return type fails. check fails when it discards more than 100 arguments per run because they do not satisfy :requires.
Functions that cannot be translated are tested like the others.
(lt/check-translation #'f opts) compares each arity of f with its model instead, and also takes :at, the types of
the type variables of a polymorphic function, which the :at metadata of the function lists. It finds mistakes of the translation, and works on
functions without specifications: those with marks, those that a block names in (clojure f ...), and those that they
call. A call where Long arithmetic overflows is outside what the model describes and passes; another exception fails.
It runs the model that sync generated, and stops when that is the model of another version of the function.
The generators make values on the bounds of the types too: ##NaN, ##Inf, -0.0 and the bounds of doubles, those of
UInt8 to UInt64 and (Fin n), strings with characters above U+FFFF, lists with equal elements, and arguments equal to
the one before. Nat and Int are small, as functions recurse on them; with :big-ints? they are on the bounds of
Long, 2^31, 2^32 and 2^53 too, and beyond.
Results are compared as Lean values: ##NaN is itself, and 0.0 is not -0.0.
For a short Bool postcondition, put one list expression in :ensures. It
sees the function's arguments (including destructured locals) and its result as %.
(defn echo-flag [flag] flag)
(lt/verify echo-flag
{:sig [[Bool] Bool]
:ensures {same (= flag %)}})The same :ensures works on a single-arity lt/defn. Write (= flag true)
to use a Bool argument as a condition; a standalone symbol still names a
deflean specification. lt/check runs the JVM predicate, while
lt/check-translation compares it with the translated Lean predicate.
(require '[leanfran.repl :as lr])
(lr/sync!)
(lr/status #'clamp)
(lt/check #'clamp)
(lr/check! #'clamp {:require-proved? true})
(lr/proof-stub #'clamp)
(lr/show-lean #'clamp)Save the source before running a proof check. sync!, status, and
check! call the Clojure backend of leanfran (or LEANFRAN_CLI) and never
reload a namespace. Pass {:dir root} to select another project. The proof
results describe the saved files, not the REPL's current function. Use
lt/check for a quick random test of that function; check! runs it
separately only with :random? true.
check! returns label results only when the CLI succeeds and writes a new
lock. status shows :stale after edits and omits old proof locations.
proof-stub gives Lean text for missing obligations without writing a proof
file. show-lean reads the generated model and obligation files.
clojure -X leanfran.tools/sync
clojure -X leanfran.tools/check :require-proved true
clojure -X leanfran.tools/statusThese commands print Clojure data and preserve the compiler's exit status.
Pass :dir '"path/to/project"' to select another saved project.
For clojure -T, add the dependency explicitly because tool aliases do
not use the project's dependencies. Replace <version> with the same
leanfran release used by the project:
{:aliases
{:leanfran
{:extra-deps {io.github.conao3/leanfran {:mvn/version "<version>"}}
:ns-default leanfran.tools}}}clojure -T:leanfran check :require-proved truesync and check compare a verified function's same-file
(m/=> f [:=> [:cat ...] R]) declaration with the loaded Malli registration
and the Lean signature. They do not replace the registration.
| Malli | Lean | Result |
|---|---|---|
:boolean / boolean?, :double / double?, :nil / nil? |
Bool, Float, Unit |
Match |
[:vector T], [:set T], [:map-of K V] |
Array, Set, Map |
Match if elements match |
[:tuple A B], [:maybe T] |
Prod, Option |
Match if elements match; nested :maybe is unsupported |
:int / nat-int?, :string |
Int / Nat, String |
Warning: arbitrary-precision integers or lone UTF-16 surrogates |
[:sequential T] |
List |
Error: Malli accepts vectors and Lean's Clojure representation does not |
Dynamic registries, references (including references from dependency JARs), schema properties, multiple arities, and guards are not supported.
- A block with
(clojure f ...)cannot define a type thatfuses; another block defines it. statusreads no library: a change of a macro outside the project leaves the blocks that use it as they are until the nextsync.- A definition whose signature has no Clojure form is skipped and reported, such as one with instance arguments.
- The translation of
leanfran.typedfunctions takes the forms above, and theorems say nothing about calls whereLongarithmetic overflows, the stack or the memory ends, or a var ofclojure.coreis redefined.