Skip to content

Latest commit

 

History

History
594 lines (494 loc) · 38.1 KB

typescript-guide.md

File metadata and controls

594 lines (494 loc) · 38.1 KB

TypeScript guide

leanfran | TypeScript quick start

Source paths below are relative to langs/TypeScript/.

Install

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.

Quick start

// 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 generated

sync also prints the progress of Lake.

Samples

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).

Lean blocks

  • leanfran --lang typescript sync runs the scan command of the project's npm package leanfran (node node_modules/leanfran/dist/cli.js), which reads the lean(...) calls of the .ts files in src/ (or the paths of [embed.typescript]) with oxc-parser (the name is a string literal, the source a template literal or String.raw, the options imports, uses, models and output an object literal). The compiler writes each block to .leanfran/typescript/workspace/LeanTsEmbed/<module>/<name>.lean, builds it with Lake, generates _lean/<module>__<name>.ts next to the module (and _lean/<module>.ts when the module has one block) and records the blocks and their files in the typescript section of leanfran.manifest.json at the project root, then prints leanfran: <N> blocks checked and generated on standard error. It removes the files of removed blocks, and those that an earlier sync wrote 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/lock keeps 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): sync imports the module, reads ~standard.jsonSchema.output({ target: "draft-2020-12" }) and writes a Lean structure LeanTsModels.<module>.LineItem (opened in the block). integer is Nat when its minimum is at least 0 and Int otherwise, number Float, array List, a property that is not required an x? : Option α field, a string enum an inductive type in LeanTsEnums.<module>, an object equal to another model that model; minimum, maximum, the exclusive bounds, minLength, maxLength, minItems and maxItems become proof fields (qty_ge : 1 ≤ qty) the Lean proofs can assume, and pattern, format, multipleOf are listed in the structure's docstring as not assumed. A property of a number that is a constant c has the proof field (x == c) = true, the === of number. 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, checkModel and the schema in models of the value of lean(...) judge minLength and maxLength by the characters (block.models.LineItem["~standard"].validate(value)). The parse of 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, maxLength next to pattern or format, or in a schema with a check or a transformation, stops sync with 254: use a validator that counts characters (zod), or leave out maxLength. An integer that is not safe reaches Lean as it is, and a function that returns an integer that no number holds throws a RangeError. Other JSON Schema, a property that takes both null and undefined, and a validator that returns null or undefined for a place that the JSON Schema does not have it at stop sync with 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 return StandardSchemaV1.InferOutput<typeof LineItem> (a type-only import), run the model's ~standard.validate on the arguments and return plain objects.
  • output: { tagKey, option } of a block replaces the tag-key and option of [embed.typescript]; a block and the blocks it uses must have the same settings.
  • A generated module registers its block when imported. lean(...) throws LeanBlockStale when 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'. With LEANFRAN_AUTO_SYNC=1 it runs leanfran --lang typescript sync instead, 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 read leanfran.toml: after a change of [embed.typescript], leanfran --lang typescript status prints stale.

Types

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 }).

Structures, inductive types and Standard Schema

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>: a StandardSchemaV1 and StandardJSONSchemaV1 (@standard-schema/spec 1.1.0, vendor leanfran) with the descriptor in desc. Hono's sValidator("json", Range), tRPC, TanStack Form and zod's z.custom take it as it is. Input is the JSON of Lean's deriving ToJson: a structure is an object (the fields of a parent flat, an x? field omitted when none), a constructor without arguments is "none", named arguments are { "percent": { "p": 10 } }, one unnamed argument { "tag": v }, several { "pair": [a, b] }, UInt64/USize are decimal strings without leading zeros within the range of the type and of its conditions (the pattern of the JSON Schema), and parse reads 1.0 and 1e2 as integers. validate takes 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 in validate and 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.input and .output take draft-2020-12, draft-07 and openapi-3.0; recursive types use $defs/definitions.

  • leanfran/schema has the scalar schemas (Nat, Int, UInt8.., String, Float, ...), toJSON (safe integers as numbers, the others as strings), fromJSON, stringify (bigint as JSON numbers) and parse (integer literals read without loss through the JSON.parse reviver's source text).

  • A structure with type parameters is a type per instance (Pair Nat Bool is PairNatBool). A namespace of functions named as a type is merged into its schema (Point.sum is a member of the schema Point).

  • The generation settings change the TypeScript form only:

    setting values default effect
    tagKey a JavaScript identifier "ctor" the discriminant of the inductive types ({ kind: "percent"; p: bigint })
    option "null" or "undefined" "null" Option α is α | null, or α | undefined and an optional field x?: α

Generated code

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/ and leanfran.manifest.json; sync writes .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")

Performance

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).

Commands

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 status compares the keys (which also cover the module path and the settings of [embed.typescript]) with leanfran.manifest.json and the generated files without Lean or Lake. It prints <module>:<name>: stale for a changed block, <module>:<name>: missing <path> for a deleted generated file and <path>: removed for a file sync would 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 with sha256sum (shasum -a 256 on macOS), so that command must be on PATH; without it sync, check and status exit with 255.

module generate

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.

Exit codes

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.

Configuration

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.

Verifying functions

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.

Marking a function

// 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 of lean(...) blocks (each generated function carries its Lean name as __leanName).

  • The labels of ensures match [a-z][a-z0-9_]*; refines and returns_nat are reserved.

  • The subset: parameters and results annotated with number, bigint, boolean, string, T[], readonly T[], [A, B], T | null, T | undefined, Nat and Int of leanfran/schema, the structures, inductive types and enums generated from a block and z.infer<typeof X> (infer, output and InferOutput of any schema library, and typeof X.infer) of a model X of a block; const/let and reassignment, compound assignment, ++, if, switch on a string, an enum or the tag of an inductive value, early return, for ... of, for (let i = a; i < b; i++), while, break, continue, throw new Error(...) (and the built-in errors), push to 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, String and calls of the module's model functions. A x === null test on a parameter narrows it as in TypeScript.

  • Values: ===, !== and includes of arrays, tuples, structures and inductive values compare references, so check prints unextracted; of numbers, bigints, booleans, strings, enums (deriving DecidableEq) and these or null they compare values. The type of a value is that of its place: null and undefined, number and bigint do not stand for each other, the tuples of the parameters and the result have two elements, and a function with T | undefined replaces its specification and has random tests only under the option setting "undefined".

  • Numbers: a number is an Int of the model. Where the result of +, -, *, ++, -- or Number can be no safe integer, the model stops with Ts.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 an ensures assumes that it is a safe integer. A bigint has 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]! and x! without a value (Ts.Exc.undefinedValue), % and / of numbers by 0 (Ts.Exc.zeroDivision), an unsafe integer, and a negative bigint for a Nat (Ts.Exc.negativeNat). refines and ensures hold only if no argument leads there. throw and / and % of bigints by 0 throw in JavaScript (Ts.Exc.error).

  • Strings: .length is the number of the UTF-16 code units (Ts.strLength), and <, <=, > and >= compare them (Ts.strLt; Ts.utf16_of_lt states that they are the characters when none is above U+FFFF), where Lean's s.length and s < t are about characters. A literal with a lone surrogate is no Lean String, so check prints unextracted.

  • Loops: for (const x of xs) is for x in xs over the list, which simp turns into List.foldl when the body only updates variables; a body with an early return or a push under if is proved by induction on the list (the forIn equations of List.cons). for (let i = a; i < b; i++) iterates Ts.range a b, and Ts.range_succ splits off the last index for an induction on the bound (sumTo in samples/verified-typescript). A while loop is Lean's partial Loop and cannot be unfolded in a proof; the model of a function with one is in Ts.M, so a refines needs a proof that the loop ends.

Obligations and proof status

-- 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 <;> omega
  • leanfran --lang typescript check syncs the package, reads the model(...) calls with oxc-parser, translates each function (a function declaration or a const arrow function) into LeanTsModel.<module>.<function> in Lean do notation over LeanTsLib.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 each ensures (partial correctness for a function that may throw, Ts.Holds for one whose model may stop with another error) and .obligation.returns_nat for a function returning Nat, builds the proofs of lean/Proofs/ at the project root one file at a time and prints each obligation as proved, sorry, axioms (an axiom outside propext, Quot.sound, Classical.choice), failed (its proof has an error), missing or mismatch (the theorem's type is not the obligation). It writes the typescript section of leanfran.lock at 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 function unextracted and prints <file>:<line>:<column>: error: unextracted <module>:<function>: <message> on standard error, and the other functions are still checked (Functions that a tool rejects). check exits with 1 when a function is unextracted or failed, and --require proved exits with 1 unless every obligation is proved. Commit leanfran.lock with _lean/ and leanfran.manifest.json; status and the replaced specifications read it.
  • leanfran --lang typescript status also prints the obligations of the lock in the same form, without Lean, and prints stale for a function whose hash differs from the lock or that the lock does not have (src/calc.ts:clamp [refines]: stale) and <module>:<function>: removed for a function of the lock that the sources do not have. It exits with 1 when it prints stale, removed, unextracted or failed, and with --require proved also when an obligation is not proved.

Replacing a proved specification

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, validate at the boundary) and that nothing replaces the built-in objects. checkModel, test/verify/values.mjs and test/verify/ts-model.test.ts compare the translation and LeanTsLib.Ts with TypeScript.

Random tests

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 the model(...) call, discards arguments that fail requires and results that are integers but not safe ones, and throws PropertyFailure with 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 and LEANFRAN_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) of leanfran/schema generates 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. checkModel throws LeanBlockStale when the block of a specification is out of date. Await it in a test or in a module of its own: checkModel loads the generated modules of the function, and at the top level of a module that they import it throws a TypeError after 10 seconds.

    run is the number (from 0, of the arguments that satisfy requires) of the arguments that failed first, and input is 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: -1
    

    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: <error> as its value, and a specification that throws shows the spec failed and error: <error>. checkModel fails when it discards more than 100 arguments per run.

Limits

Differences from the C backend

  • 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/cpsSum abort with Stack overflow detected around N≈1e5. leanfran lowers tail .ap to 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.

  • Float32 transcendentals use double-precision Math.* narrowed via Math.fround, whose rounding path differs from single-precision libm (sinf), so they can differ by more than 1 ULP at f32; the %f 6-digit toString comparison absorbs this but direct bit comparison is not claimed. Float.scaleb uses a Math.pow(2,e) approximation untested at extreme exponents.

  • The 32-bit USize profile 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.

Externs that the runtime does not provide

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.Promise concurrency (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/modified timestamps, 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_tty and 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/ptrEq used 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 raw lean_ptr_addr/ lean_is_exclusive_obj are mapped to address-independent constants (0n / non-exclusive) for the safe surface only.