leanfran | TypeScript quick start
Source paths below are relative to langs/TypeScript/.
pnpm add leanfran
nix profile install 'github:conao3/lean-leanfran/v<version>#leanfran'<version> is the release of the npm package. Run leanfran --lang typescript with the compiler executable on PATH.
Generation needs lean and lake of Lean 4.35.0 on PATH. Generated modules run in Node 22.18 or later, Bun and browsers with the npm package.
// src/arith.ts
import { lean } from "leanfran"
import * as arith from "./_lean/arith.ts"
export const arithBlock = lean(
"arith",
String.raw`
def double (n : Nat) : Nat := n + n
theorem double_eq (n : Nat) : double n = 2 * n := by
unfold double; omega
`,
)
arith.double(21n) // 42n$ leanfran --lang typescript sync
leanfran: 1 blocks checked and generatedsync also prints the progress of Lake.
samples/ holds packages with Lean blocks
and verified TypeScript functions. make check-samples syncs each one, runs it, compares the output with
its expected.txt, checks the proofs of the verified ones with leanfran --lang typescript check --require proved,
and fails when a committed generated module is out of date.
| sample | shows |
|---|---|
| word-count | strings and lists, a proof by induction |
| roman-numerals | a lake project compiled with leanfran generate, a round-trip theorem checked for every number below 1000 |
| todo-cli | an invariant over a list kept by every operation, JSON storage, tampered JSON rejected |
| generic-search | polymorphic functions proved for every type, called through monomorphic definitions |
| pricing-api | Hono with a zod model and a Lean inductive type as request body, 400 for invalid input, OpenAPI |
| verified-typescript | a for (let i ...) loop proved equal to a recursive spec, which it then replaces; an insertion that keeps an array sorted |
| sorted-search | refines under requires (a scan of a sorted array) |
| inventory | a block's structure and enum in the signatures of verified functions |
samples/steps/ introduces one
feature at a time, from functions on Nat (01) to types shared between blocks with uses (09)
and the verification of TypeScript functions (10 to 14).
leanfran --lang typescript syncruns thescancommand of the project's npm packageleanfran(node node_modules/leanfran/dist/cli.js), which reads thelean(...)calls of the.tsfiles insrc/(or thepathsof[embed.typescript]) with oxc-parser (the name is a string literal, the source a template literal orString.raw, the optionsimports,uses,modelsandoutputan object literal). The compiler writes each block to.leanfran/typescript/workspace/LeanTsEmbed/<module>/<name>.lean, builds it with Lake, generates_lean/<module>__<name>.tsnext to the module (and_lean/<module>.tswhen the module has one block) and records the blocks and their files in thetypescriptsection ofleanfran.manifest.jsonat the project root, then printsleanfran: <N> blocks checked and generatedon standard error. It removes the files of removed blocks, and those that an earliersyncwrote in the_lean/directories. Other files stay. A Lean error is reported at the line and UTF-16 column of the TypeScript file (src/arith.ts:11:18: error: (lean block src/arith.ts:arith, Lean 5:17) ...) with exit code 254..leanfran/lockkeeps two runs from writing at once, and a failed install restores the previous files.uses: ["./geometry.ts:geometry"]imports and opens another block of the package; the generated module imports the types and schemas of that block's module.models: { LineItem }takes the user's Standard JSON Schema values (zod, valibot, arktype):syncimports the module, reads~standard.jsonSchema.output({ target: "draft-2020-12" })and writes a Lean structureLeanTsModels.<module>.LineItem(opened in the block).integerisNatwhen its minimum is at least 0 andIntotherwise,numberFloat,arrayList, a property that is not required anx? : Option αfield, a stringenuman inductive type inLeanTsEnums.<module>, an object equal to another model that model;minimum,maximum, the exclusive bounds,minLength,maxLength,minItemsandmaxItemsbecome proof fields (qty_ge : 1 ≤ qty) the Lean proofs can assume, andpattern,format,multipleOfare listed in the structure's docstring as not assumed. A property of anumberthat is a constantchas the proof field(x == c) = true, the===ofnumber. The length of a string is the number of its characters (code points) as in JSON Schema, also with a validator that counts UTF-16 code units (valibot, arktype): the generated functions,checkModeland the schema inmodelsof the value oflean(...)judgeminLengthandmaxLengthby the characters (block.models.LineItem["~standard"].validate(value)). Theparseof the library itself counts UTF-16 code units, so validate the arguments of a verified function with the schema of the block. With such a validator,maxLengthnext topatternorformat, or in a schema with a check or a transformation, stopssyncwith 254: use a validator that counts characters (zod), or leave outmaxLength. An integer that is not safe reaches Lean as it is, and a function that returns an integer that nonumberholds throws aRangeError. Other JSON Schema, a property that takes bothnullandundefined, and a validator that returnsnullorundefinedfor a place that the JSON Schema does not have it at stopsyncwith 254 and the model and property. A model must be an exported variable, a named import or a property of a namespace import: the functions take and returnStandardSchemaV1.InferOutput<typeof LineItem>(a type-only import), run the model's~standard.validateon the arguments and return plain objects.output: { tagKey, option }of a block replaces thetag-keyandoptionof[embed.typescript]; a block and the blocks it uses must have the same settings.- A generated module registers its block when imported.
lean(...)throwsLeanBlockStalewhen no registered module was generated from the same name, source, options and model JSON Schemas:leanfran: the Lean block src/arith.ts:arith is out of date; run 'leanfran --lang typescript sync'. WithLEANFRAN_AUTO_SYNC=1it runsleanfran --lang typescript syncinstead, and the regenerated module is used from the next start. When the generated module of the block exists and its module does not import it, the error names the module to import.lean(...)does not readleanfran.toml: after a change of[embed.typescript],leanfran --lang typescript statusprintsstale.
| Lean | TypeScript |
|---|---|
Nat, Int |
bigint (arguments also take a safe-integer number) |
UInt8..UInt32, Int8..Int32 |
number |
UInt64, USize, Int64, ISize |
bigint |
Bool |
boolean |
Char |
string of one code point |
String |
string |
Float, Float32 |
number |
Unit |
void / undefined |
Option α |
α | null, or α | undefined with --option undefined |
List α, Array α |
readonly α[] (arguments), α[] (results) |
α × β |
readonly [α, β] |
Except ε α |
{ ok: true; value: α } | { ok: false; error: ε } |
IO α |
α; an IO.Error is thrown as LeanIOError (code is the constructor name) |
Fin n |
number (bigint when n > 2^32) |
| structures | plain objects ({ readonly lo: bigint; readonly hi: bigint }) |
| enumerations | string literal unions ("red" | "green") |
| other inductive types | unions on the --tag-key ({ ctor: "percent"; p: bigint } | ...) |
{x : α // p x} |
α, checked by p |
Arguments are checked while they are converted: a value that does not fit throws
LeanValidationError, whose issues ({ message, path }) name every place that
does not fit. A definition without arguments becomes a function evaluated on the
first call. Names are the Lean names under --namespace (default: the module) in
lowerCamelCase (? → Q, ! → Bang, ' → Prime); a name with more components
is a member of a namespace object (Calc.add is export const Calc = { add }).
structure Range where
lo : Nat
hi : Nat
ok : lo ≤ hi
inductive Discount where
| none
| percent (p : Nat) (h : p ≤ 100)
| fixed (amount : Nat)export type Range = { readonly lo: bigint; readonly hi: bigint }
export type RangeInput = {
readonly lo: bigint | number | string
readonly hi: bigint | number | string
}
export const Range: L.LeanSchema<RangeInput, Range> = L.schema<RangeInput, Range>($tRange)
Range["~standard"].validate({ lo: 3, hi: 1 }) // { issues: [{ message: "Range.ok: lo ≤ hi", path: [] }] }
Discount["~standard"].validate({ percent: { p: 10 } }) // { value: { ctor: "percent", p: 10n } }-
Every type is a
LeanSchema<Input, Output>: aStandardSchemaV1andStandardJSONSchemaV1(@standard-schema/spec1.1.0, vendorleanfran) with the descriptor indesc. Hono'ssValidator("json", Range), tRPC, TanStack Form and zod'sz.customtake it as it is.Inputis the JSON of Lean'sderiving ToJson: a structure is an object (the fields of a parent flat, anx?field omitted whennone), a constructor without arguments is"none", named arguments are{ "percent": { "p": 10 } }, one unnamed argument{ "tag": v }, several{ "pair": [a, b] },UInt64/USizeare decimal strings without leading zeros within the range of the type and of its conditions (thepatternof the JSON Schema), andparsereads1.0and1e2as integers.validatetakes the JSON and the TypeScript form and returns the TypeScript form; it is synchronous. -
A proof field (
ok : lo ≤ hi) or the property of a subtype is checked by the decision procedure Lean compiles from the proposition (LeanTsGen.Range.mk.ok_decide), both invalidateand in the arguments of the public functions, so the values that reach Lean satisfy the propositions. A comparison with a constant is also in the JSON Schema (maximum,exclusiveMinimum,maxLength,maxItems, ...). -
jsonSchema.inputand.outputtakedraft-2020-12,draft-07andopenapi-3.0; recursive types use$defs/definitions. -
leanfran/schemahas the scalar schemas (Nat,Int,UInt8..,String,Float, ...),toJSON(safe integers as numbers, the others as strings),fromJSON,stringify(bigintas JSON numbers) andparse(integer literals read without loss through theJSON.parsereviver's source text). -
A structure with type parameters is a type per instance (
Pair Nat BoolisPairNatBool). A namespace of functions named as a type is merged into its schema (Point.sumis a member of the schemaPoint). -
The generation settings change the TypeScript form only:
setting values default effect tagKeya JavaScript identifier "ctor"the discriminant of the inductive types ( { kind: "percent"; p: bigint })option"null"or"undefined""null"Option αisα | null, orα | undefinedand an optional fieldx?: α
sync writes _lean/<module>__<name>.ts next to the module with the block, and _lean/<module>.ts when the
module has one block. leanfran.manifest.json at the project root lists the blocks and their files.
- Commit
_lean/andleanfran.manifest.json;syncwrites.leanfran/.gitignore, which ignores.leanfran/typescript/and.leanfran/lock. The package then runs without Lean.
A generated module starts with the line of leanfran. This is the output of module generate for a module with
def double (n : Nat) : Nat := n + n:
// Code generated by leanfran --lang typescript (generator 11) from LeanTsTest.Public. DO NOT EDIT.
import * as L from "leanfran/runtime"
import type { Obj } from "leanfran/runtime"
function l_LeanTsTest_Public_double(x_1: Obj): Obj {
const x_2: Obj = L.lean_nat_add(x_1, x_1)
return x_2
}
const $d0: L.TypeDesc<bigint> = L.natDesc
/** Lean `LeanTsTest.Public.double : Nat → Nat`. */
export function double(n: bigint | number): bigint {
return L.toTs($d0, l_LeanTsTest_Public_double(L.toLean($d0, n, "n")))
}
L.leanName(double, "LeanTsTest.Public.double")make bench (Node.js 26, x86_64; the native column is the C backend):
| workload | n | TypeScript (s) | native C (s) |
|---|---|---|---|
Array.push, set!, sum |
10⁴ | 0.008 | 0.005 |
Array.push, set!, sum |
10⁵ | 0.046 | 0.006 |
Array.push, set!, sum |
10⁶ | 0.438 | 0.016 |
fib (loop) |
10⁵ | 0.055 | 0.072 |
naiveFib |
25 | 0.016 | 0.005 |
String.push |
10⁴ | 0.004 | 0.005 |
String.push |
10⁵ | 0.018 | 0.006 |
Array.qsort |
10⁵ | 0.425 | 0.020 |
Passing 10⁴ structures to a Lean function takes 0.024 s (zod's
z.array(z.object(...)).parse validates 10⁴ objects in 0.011 s).
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 typescript sync [--dir <dir>] [--verbose]
leanfran --lang typescript check [--dir <dir>] [--verbose] [--require proved]
leanfran --lang typescript status [--dir <dir>] [--require proved]
The compiler runs sync, check and status: it writes the Lake workspace .leanfran/typescript/workspace, runs the Lake builds and the generation, installs the files and writes leanfran.manifest.json and leanfran.lock. The npm package leanfran provides the runtime of the generated modules and the two commands the compiler runs with Node.js, scan and translate of the project's node_modules/leanfran/dist/cli.js, which read the TypeScript sources and print JSON. The compiler looks up the npm package in node_modules of the project root and exits with 255 and an installation hint when it is missing. When the version of node_modules/leanfran/package.json is another release, the compiler exits with 255 and npm install leanfran@<version> for its own release before it runs the package. The npm package exits with 255 and names the compiler release to install when an older compiler passes it sync, check, status or generate. The npm package checks that the compiler's release, generator and Lean versions are its own and exits with 255 otherwise, so install the compiler and the npm package from the same release. status needs sha256sum (shasum on macOS) on PATH and exits with 255 without it.
leanfran --lang typescript statuscompares the keys (which also cover the module path and the settings of[embed.typescript]) withleanfran.manifest.jsonand the generated files without Lean or Lake. It prints<module>:<name>: stalefor a changed block,<module>:<name>: missing <path>for a deleted generated file and<path>: removedfor a filesyncwould remove (src/arith.ts:arith: stale,src/_lean/extra.ts: removed), prints nothing for a current block and exits with 1 when it prints a block line. It hashes the files withsha256sum(shasum -a 256on macOS), so that command must be on PATH; without itsync,checkandstatusexit with 255.
Run leanfran generate from the directory with leanfran.toml to build Lake modules and generate TypeScript. Set lang = "typescript" in a [[generate]] table to share types across its modules. See the generation guide for the table keys, output paths, and bindings.
The compiler also provides these lower-level commands:
leanfran --lang typescript module generate --module-name Foo.Bar [--roots <Name> ...] [--main <Name>]
[--namespace <Name>] [--import <Name> ...] [--search-path <dir> ...] [--output-file <path>]
[--runtime-path <specifier>] [--type-module <Name>=<specifier> ...] [--model-module <Name>=<key> ...]
[--tag-key <key>] [--option null|undefined] [--ts-root <specifier>] [--batch <file>]
[--internal-only] [--output json|text]
leanfran --lang typescript obligations check --modules <Name> ... --obligations <file> [--search-path <dir> ...]
leanfran --lang typescript --help | --version | --generator-version
--help (or -h) after a command prints its options. --version prints
leanfran <version> (Lean <version>). --import adds modules; of their @[csimp] lemmas, those that
name a ts: extern apply.
The roots default to the module's public definitions with IR. Each root becomes a
public function that takes and returns TypeScript values; the internal functions it
calls are not exported. --internal-only exports the internal functions instead
(the diff-test calls them with runtime values). --main also emits the module's
@[init] chain and a call running the given function as main. A root whose type
cannot cross the boundary (type parameters, instance or proof arguments, function
values, nested Option, types without a Lean form such as a proposition without
Decidable) is listed in the summary's skipped with the reason. The structures and
inductive types of the module (and those the public functions use) are exported as
types and schemas. --output json prints an array with one summary per job: module,
files, functions ({"lean", "name"} of every generated function), externs (the
runtime functions the module calls), skipped, error of a failed job and data, whose
public and types are {"lean", "name"} arrays of the public functions and types.
--batch runs a JSON
array of jobs against one environment (leanfran --lang typescript sync and
leanfran generate use it) and exits with the largest exit code of the jobs.
sync, check and status: 0 success, 1 a stale, missing <path> or removed line of status, an
unextracted or failed obligation of check or status or an unmet --require proved, 252 an argument the
command cannot read, 254 an error in the project (the sources, leanfran.toml, a Lean diagnostic, a file in the way
that leanfran did not generate), 255 an error of the environment (the npm package, lake, lean, sha256sum, a
version that does not match).
module generate and obligations check: 0 success, 252 invalid parameters (also an invalid --tag-key or
--option and a --batch file with an unknown key or a value of another type), 254 input that cannot be converted
(an extern the runtime does not provide, a name without IR, a constructor field named as the --tag-key, a module
without .olean), 255 other errors.
The project file leanfran.toml is optional. The
settings of sync, check and status describe
the project root, [check], [[require]] and projects with several languages.
[embed.typescript]
paths = ["src"]
tag-key = "kind"
option = "undefined"| Key | Default | Meaning |
|---|---|---|
paths |
["src"] |
The directories to scan, relative to the project root |
tag-key |
"ctor" |
The discriminant of the inductive types |
option |
"null" |
"null" or "undefined", the value of none |
A "leanfran" field of package.json, in the project root or in a directory from one of paths up to it, is an
error with exit code 254 that names the [embed.typescript] table. The compiler starts the npm package from
node_modules in the project root, so install it there when package.json is in another directory.
| Variable | Effect |
|---|---|
LEANFRAN_AUTO_SYNC=1 |
A stale lean(...) runs leanfran --lang typescript sync --dir <root> instead of throwing LeanBlockStale. |
LEANFRAN_RUNS, LEANFRAN_SEED |
The number of inputs and the seed of the random tests. |
model(...) binds a TypeScript function to specifications in a Lean block. The function stays ordinary TypeScript.
leanfran --lang typescript check translates it to Lean and checks your proofs, and checkModel runs the same
specifications as a random test.
// src/calc.ts
import { lean } from "leanfran"
import { model } from "leanfran/verify"
import * as spec from "./_lean/calc.ts"
export const specBlock = lean(
"spec",
String.raw`
def clampSpec (x lo hi : Int) : Int := max lo (min hi x)
def ordered (_x lo hi : Int) : Bool := lo ≤ hi
def inRange (_x lo hi : Int) (r : Int) : Bool := lo ≤ r && r ≤ hi
`,
)
export function clamp(x: number, lo: number, hi: number): number {
if (x < lo) return lo
if (x > hi) return hi
return x
}
model(clamp, {
refines: spec.clampSpec,
requires: spec.ordered,
ensures: { in_range: spec.inRange },
})-
model(fn, { refines?, requires?, ensures? })(leanfran/verify) returns the function and records it; the specifications are public functions oflean(...)blocks (each generated function carries its Lean name as__leanName). -
The labels of
ensuresmatch[a-z][a-z0-9_]*;refinesandreturns_natare reserved. -
The subset: parameters and results annotated with
number,bigint,boolean,string,T[],readonly T[],[A, B],T | null,T | undefined,NatandIntofleanfran/schema, the structures, inductive types and enums generated from a block andz.infer<typeof X>(infer,outputandInferOutputof any schema library, andtypeof X.infer) of a modelXof a block;const/letand reassignment, compound assignment,++,if,switchon a string, an enum or the tag of an inductive value, earlyreturn,for ... of,for (let i = a; i < b; i++),while,break,continue,throw new Error(...)(and the built-in errors),pushto an array that the function created and nothing else refers to, destructuring of tuples and structures;+ - * %,Math.floor(a / b),Math.trunc(a / b), bigint/, comparisons,===,!==,&&,||,!,??,?:,xs[i],xs[i]!,.length, tuple indices, properties, object and array literals,map,filter,reduce,some,every,includes,startsWith,endsWith, template literals,Math.max/min/abs,BigInt,Number,Stringand calls of the module's model functions. Ax === nulltest on a parameter narrows it as in TypeScript. -
Values:
===,!==andincludesof arrays, tuples, structures and inductive values compare references, socheckprintsunextracted; of numbers, bigints, booleans, strings, enums (deriving DecidableEq) and these ornullthey compare values. The type of a value is that of its place:nullandundefined,numberandbigintdo not stand for each other, the tuples of the parameters and the result have two elements, and a function withT | undefinedreplaces its specification and has random tests only under theoptionsetting"undefined". -
Numbers: a
numberis anIntof the model. Where the result of+,-,*,++,--orNumbercan be no safe integer, the model stops withTs.Exc.unsafeInteger(Ts.safe), and the obligations assume that the numbers in the arguments are safe integers (Ts.Safe x). The operation of a returned value has the mathematical result, and anensuresassumes that it is a safe integer. Abiginthas no such condition, so use it for sums of any length. -
Errors: the model stops where JavaScript goes on with a value that the model does not have,
xs[i]!andx!without a value (Ts.Exc.undefinedValue),%and/of numbers by 0 (Ts.Exc.zeroDivision), an unsafe integer, and a negativebigintfor aNat(Ts.Exc.negativeNat).refinesandensureshold only if no argument leads there.throwand/and%of bigints by 0 throw in JavaScript (Ts.Exc.error). -
Strings:
.lengthis the number of the UTF-16 code units (Ts.strLength), and<,<=,>and>=compare them (Ts.strLt;Ts.utf16_of_ltstates that they are the characters when none is above U+FFFF), where Lean'ss.lengthands < tare about characters. A literal with a lone surrogate is no LeanString, socheckprintsunextracted. -
Loops:
for (const x of xs)isfor x in xsover the list, whichsimpturns intoList.foldlwhen the body only updates variables; a body with an earlyreturnor apushunderifis proved by induction on the list (theforInequations ofList.cons).for (let i = a; i < b; i++)iteratesTs.range a b, andTs.range_succsplits off the last index for an induction on the bound (sumToinsamples/verified-typescript). Awhileloop is Lean's partialLoopand cannot be unfolded in a proof; the model of a function with one is inTs.M, so arefinesneeds a proof that the loop ends.
-- lean/Proofs/Calc.lean (at the project root)
import LeanTsModel.calc
namespace LeanTsModel.calc
theorem clamp.proof.refines : clamp.obligation.refines := by
intro x lo hi h
simp only [LeanTsEmbed.calc.spec.ordered, decide_eq_true_eq] at h
simp only [clamp, LeanTsEmbed.calc.spec.clampSpec]
split <;> (try split) <;> simp_all <;> omegaleanfran --lang typescript checksyncs the package, reads themodel(...)calls with oxc-parser, translates each function (afunctiondeclaration or aconstarrow function) intoLeanTsModel.<module>.<function>in Leandonotation overLeanTsLib.Ts(src/lean/LeanTsLib/Ts.lean), states<function>.obligation.refines(∀ x, requires x = true → f x = s x,= Except.ok (s x)for a function that may throw),.obligation.<label>for eachensures(partial correctness for a function that may throw,Ts.Holdsfor one whose model may stop with another error) and.obligation.returns_natfor a function returningNat, builds the proofs oflean/Proofs/at the project root one file at a time and prints each obligation asproved,sorry,axioms(an axiom outsidepropext,Quot.sound,Classical.choice),failed(its proof has an error),missingormismatch(the theorem's type is not the obligation). It writes thetypescriptsection ofleanfran.lockat the project root, which records the obligations with a hash of each function's AST without positions and of the keys of its specification blocks, and prints one line per obligation on standard output,<module>:<function> [<label>]: <status>(src/calc.ts:clamp [refines]: proved). A construct outside the subset makes that functionunextractedand prints<file>:<line>:<column>: error: unextracted <module>:<function>: <message>on standard error, and the other functions are still checked (Functions that a tool rejects).checkexits with 1 when a function isunextractedorfailed, and--require provedexits with 1 unless every obligation is proved. Commitleanfran.lockwith_lean/andleanfran.manifest.json;statusand the replaced specifications read it.leanfran --lang typescript statusalso prints the obligations of the lock in the same form, without Lean, and printsstalefor a function whose hash differs from the lock or that the lock does not have (src/calc.ts:clamp [refines]: stale) and<module>:<function>: removedfor a function of the lock that the sources do not have. It exits with 1 when it printsstale,removed,unextractedorfailed, and with--require provedalso when an obligation is notproved.
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.
The generated module imports the host function; its <module>__<name>.block.ts registers
the block first. It uses the original Lean body for integer arguments or results that are
unsafe as JavaScript number values. The generated module also keeps that body for
checkModel to call. Host exceptions reach the caller.
Types mixing number and bigint in a parameter are not eligible, nor are functions
that their module does not export under their own name.
- The proofs hold for the translation of the function and assume that the arguments have their
annotated types (
tsc --strict,validateat the boundary) and that nothing replaces the built-in objects.checkModel,test/verify/values.mjsandtest/verify/ts-model.test.tscompare the translation andLeanTsLib.Tswith TypeScript.
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>.
-
checkModel(fn, { numRuns?, seed?, range? })runs the specifications as a fast-check random test (fast-check is an optional peer dependency): it reads the parameter types from the source of themodel(...)call, discards arguments that failrequiresand results that are integers but not safe ones, and throwsPropertyFailurewith the smallest failing arguments it found: integers near 0, short arrays and strings, each field of an object.LEANFRAN_RUNS(1 to 2147483647, 200 by default) is the number of the other arguments andLEANFRAN_SEED(0 to 9223372036854775807, 1 by default) the seed.checkModule(m)runs it for every model function of a module and reports failures together.arbitrary(schema, fc)ofleanfran/schemagenerates the values of a descriptor.A specification runs the Lean definitions of its block, also when the generated code calls a proved TypeScript function in their place.
checkModelthrowsLeanBlockStalewhen the block of a specification is out of date. Await it in a test or in a module of its own:checkModelloads the generated modules of the function, and at the top level of a module that they import it throws aTypeErrorafter 10 seconds.runis the number (from 0, of the arguments that satisfyrequires) of the arguments that failed first, andinputis what they shrank to with the same label, in up to 1000 calls of the function:src/calc.ts:clamp [refines]: mismatch (seed 1, run 0) input: x=1, lo=0, hi=0 expected: 0n, got: -1An
ensuresspecification shows<name in the block> does not holdin place ofmismatchandresult: <value>in place of the last line. A function that throws showsfailed: <error>as its value, and a specification that throws showsthe spec failedanderror: <error>.checkModelfails when it discards more than 100 arguments per run.
-
Tail calls through closures: the native C backend does not TCO tail calls that cross a closure application (CPS/continuation loops), so programs like
cpsCount/cpsSumabort withStack overflow detectedaround N≈1e5. leanfran lowers tail.apto an apply-thunk and runs them in constant JS stack. The diff-tests therefore check value equality at a native-safe N, and the no-overflow property at N=1e6 on the node side only. -
Float32transcendentals use double-precisionMath.*narrowed viaMath.fround, whose rounding path differs from single-precision libm (sinf), so they can differ by more than 1 ULP at f32; the%f6-digittoStringcomparison absorbs this but direct bit comparison is not claimed.Float.scalebuses aMath.pow(2,e)approximation untested at extreme exponents. -
The 32-bit
USizeprofile is covered by a literal-comparison test only (a 64-bit host cannot produce a native 32-bit reference); the default 64-bit profile is native-verified.
Generation stops with 254 at an extern that the runtime does not provide, and the error names the C symbols.
These cannot be matched byte-for-byte against the native oracle, so mapping them would replace an error with a silent divergence:
- Task /
IO.asTask/IO.Promiseconcurrency (lean_task_*,lean_io_*_task,lean_io_promise_*): native runs a real OS thread pool with genuine parallelism and scheduler-dependent interleaving/waitAny/cancellation timing; Node is single-threaded, so any emulation observes a different ordering wherever ordering is observable. - Filesystem metadata / enumeration (
lean_io_metadata,lean_io_symlink_metadata,lean_io_read_dir,lean_io_realpath):accessed/modifiedtimestamps,numLinks, directory order and symlink canonicalization are host/OS state, not program state, so they vary between runs and machines. IO.getRandomBytes(lean_io_get_random_bytes): by definition nondeterministic CSPRNG output; can never equal a fixed oracle run (used as the negative-test sentinel).- Raw-mode interactive TTY (
lean_io_prim_handle_is_ttyand termios raw mode): depends on a live terminal device and real-time keystrokes; there is no reproducible input stream to diff. (Pipe/redirect/file stdin is supported and tested.) - Unsafe pointer identity (
ptrAddrUnsafe/isExclusiveUnsafe/ptrEqused to distinguish defeq values): real addresses are nondeterministic. The safe wrappers (withPtrAddr/withPtrEq/withPtrEqDecEq) are proven address-independent and are pure Lean (they do not even reach the extern), so they are faithful; the rawlean_ptr_addr/lean_is_exclusive_objare mapped to address-independent constants (0n/ non-exclusive) for the safe surface only.