Liking cljdoc? Tell your friends :D

TypeScript development

Paths in this guide are relative to langs/TypeScript/. See the backend README for usage.

Layout

  • LeanTs/EmitTs.lean: the emitter: IR walk, transitive decl collection, extern mapping, trampoline TCO, typed TypeScript output.
  • LeanTs/Marshal.lean: the TypeScript types and descriptors of the Lean types at the boundary (structures, inductive types and subtypes with their constructor layouts and the deciders compiled from their proof fields) and the signatures of the public functions; LeanTs/Generate.lean: the type aliases, descriptors and schemas, the public functions, namespace objects and the skipped roots.
  • LeanTs/RuntimeExterns.lean: the runtime functions the generated code may call (generated from src/runtime by make gen-externs).
  • LeanTs/Cli.lean: the CLI leanfran --lang typescript (the options of module generate, its jobs and the policy of obligations check, on the modules of Leanfran/); LeanTs/Embed.lean: the TypeScript Backend that sync, check and status of Leanfran/Embed/ run (the launch of dist/cli.js, the workspace's lakefile.toml and LeanTsLib). The emitter takes the replacements of @[csimp] lemmas whose target is a ts: extern, and the copies that keep the Lean bodies, from Leanfran/Csimp.lean.
  • src/verify/: leanfran/verify (model, checkModel, checkModule), the translation of TypeScript functions to Lean (translate.ts) the model(...) functions of scan and the translate command (check.ts) and the shrinking of failing arguments (shrink.ts; fast-check takes an argument that requires discards for one that passes, and stops there); src/lean/LeanTsLib/Ts.lean: the meaning of the TypeScript operations; src/schema/arbitrary.ts: fast-check arbitraries of the descriptors.
  • src/index.ts, src/embed.ts: lean(...), LeanBlockStale and the block keys; src/scan.ts, src/project.ts, src/cli.ts: the commands scan and translate that the compiler runs (dist/cli.js); src/runtime/block.ts: the registry the generated modules register in; src/models.ts: the Lean structures of the user's models (lean(..., { models })); src/judged.ts: the Standard Schema of a model, which judges the length of a string by its characters.
  • src/schema/: leanfran/schema: LeanSchema (Standard Schema and Standard JSON Schema), the scalar schemas, toJSON, fromJSON, stringify, parse and the JSON Schema of a descriptor (desc.ts).
  • src/runtime/: the runtime (npm package leanfran, export ./runtime): object.ts (the Obj type, constructors, closures, lean_apply, lean_trampoline), nat.ts/int.ts/uint.ts/float.ts (numeric tower), string.ts, array.ts (Array, ByteArray, FloatArray), io.ts (IO.Error, streams, panic, init chain, main), marshal.ts (the boundary: TypeDesc, toLean, toTs, the validation of validate, LeanValidationError, LeanIOError), node.ts (the Node platform), index.ts (re-exports; installs the Node platform when process.getBuiltinModule exists, otherwise OS operations return IO.Error.unsupportedOperation).
  • LeanTsTest/: the diff-test programs (Vectors, HigherOrder, Io, Init, Stress..Stress4, Verify, Fuzz) and their native oracles (*Main.lean, executables oracle-*), Public (called through the public functions) and Json (values with deriving ToJson, FromJson; oracle-json prints their JSON).
  • test/difftest/: node harnesses for the function-level diff, fuzz, deep TCO and the 32-bit profile; test/*.test.ts: Vitest tests of the runtime and of the public functions and schemas with both generation settings (test/public.test.ts), the JSON against Lean's ToJson (test/json.test.ts), Standard Schema with Hono and zod (test/standard.test.ts); test/embed.test.ts: leanfran --lang typescript sync, status and leanfran generate on the fixtures test/embed/app/ (with its committed src/_lean/ and leanfran.manifest.json) and test/project/.
  • samples/: the samples (pnpm workspace packages that link leanfran), samples/run.sh and samples/Makefile (test, verify, status).

How the emitter works

  1. Target functions are defined in library modules so their IR is persisted in the .olean and visible to Lean.IR.findEnvDecl.
  2. From the roots, LeanTs.collectTransitive does a worklist DFS over findEnvDecl, walking fap/pap callees; .fdecl are emitted as TS functions, .extern map to runtime functions by their C symbol, none (e.g. Nat.rec) is the boundary. Functions nothing references are not emitted.
  3. The emitter walks FnBody / Expr, mirroring EmitC's match arms. Parameters and consts are typed from the IR types (object/tobject/erased → Obj, uint8..uint32/float/float32 → number, uint64/usize → bigint), and only bindings the code reads are emitted.

Reference counting

Constructors, arrays, ByteArrays and FloatArrays carry a reference count rc, and the IR's reference-counting nodes run on it as in EmitC, so an exclusive array or constructor is updated in place:

  • FnBody.inc / dec -> L.lean_inc / L.lean_dec (a dec to 0 releases the children); del -> nothing
  • Expr.reset -> L.lean_reset (the cell when exclusive, else null); Expr.reuse -> L.lean_reuse (writes into the cell, or allocates for null)
  • Expr.isShared -> L.lean_is_shared (rc !== 1)
  • Expr.box -> identity; Expr.unbox -> L.lean_unbox (a checked narrowing)

A value whose rc is not a positive integer counts as shared: a persistent value (initialize globals, cached constants of the public functions) and a value made outside the runtime are copied before they are updated. The runtime keeps rc at least the number of references: the externs that return a part of their argument (Array.get, IO.Ref.get, Thunk.get) inc it, a copy incs the elements, and lean_apply incs the arguments a closure holds.

Object and value model

  • Nat / Int / UInt64 / USize / Int64 / ISize -> bigint; UInt8/UInt16/UInt32/Int8/Int16/Int32/Float/Float32/Char -> JS number (the signed ones hold the unsigned bit pattern, as lean.h does).
  • ctor with fields -> L.lean_ctor(cidx, size, usize, ssize, ...objs) producing { tag, fields, sdata }: object pointers and USize slots are word-indexed in fields (proj/uproj/set/uset), packed scalars live in a byte-addressed DataView sdata (sproj/sset), mirroring lean_alloc_ctor's three regions. Nullary ctor / enum -> cidx. lean_tag(x) recovers the tag for both forms.
  • Bool -> scalar 0/1; extern decEq/decLt/decLe return 0/1 so the emitted switch matches.
  • String -> JS string; String.Pos is a UTF-8 byte offset (get/next/prev/ extract/atEnd index bytes, utf8ByteSize counts bytes, length counts code points).
  • Array -> JS array with an rc property; setters (set/uset/push/pop/ swap) update an exclusive array in place and copy a shared one. ByteArray -> Uint8Array and FloatArray -> Float64Array, whose push grows a view over a buffer with spare capacity.
  • case on scalar -> switch (x); on object -> switch (L.lean_tag(x)).
  • self-tail-recursion -> for (;;) loop with staged param rebind + continue (join points are inlined at each jump, so continue stays lexically inside the loop).

Conventions

  • Update LeanTs/Cli.lean's generatorVersion and src/embed.ts's GENERATOR_VERSION together when changing generated code.
  • make gen-externs updates LeanTs/RuntimeExterns.lean from src/runtime/.
  • ../../maint/cli-expect/typescript.txt holds the expected command lines of leanfran --lang typescript (../../maint/test-cli.sh) and of dist/cli.js (make check-cli).
  • Format Markdown with vp fmt inside the development environment.

Any extern the runtime does not provide is a hard generation error (exit 254, no output written), never a silent wrong answer or a dangling runtime call. The error names the exact missing C symbols so they can be implemented and retried. The CLI checks the symbols against LeanTs/RuntimeExterns.lean, which make gen-externs generates from the runtime's exports. ../../maint/TypeScript/test-diff.sh asserts an unmapped extern (lean_io_get_random_bytes) is rejected while a mapped root generates.

Testing

Build the compiler with lake --dir ../.. build leanfran and invoke it with ../../.lake/build/bin/leanfran --lang typescript. Run make pack to build the npm distribution.

nix develop ../..#typescript -c make check

make check runs treefmt --ci, ../../maint/TypeScript/test-diff.sh (generates the LeanTsTest modules into test-out/ and diffs them against the native oracles), ../../maint/TypeScript/test-public.sh (generates test-out/public.ts with the default settings, test-out/public-alt.ts with --tag-key _tag --option undefined and test-out/json.ts, and runs test/public.test.ts and test/json.test.ts against oracle-json), ../../maint/TypeScript/fuzz.sh, the type check of every generated module (vp lint test-out/**/*.ts), leanfran --lang typescript status of the embedding and verification fixtures, test/verify/test.sh (copies test/verify/app/ to test-out/verify/<scene>/ and checks the states proved, sorry, axioms, missing, mismatch, failed and stale, --require proved, the TypeScript functions called through their specifications, an untranslatable function and a wrong implementation that checkModel rejects with a counterexample; test/verify/values.mjs writes a function for each operation, evaluates its model and runs it on the same boundary values, and lists the functions that have no model, and test/verify/schemas.mjs compares the conditions of the models of zod, valibot and arktype with their validators), make check-samples (leanfran --lang typescript status on every synced sample, which must exit with 0 and leave git status clean, leanfran --lang typescript check --require proved on the verified samples, samples/run.sh on every sample, and no difference in the committed generated modules), and vp run check (vp check && vp test, which includes test/embed.test.ts). ../../maint/TypeScript/test-diff.sh covers: 136 function-level value assertions (numeric tower, UTF-8 String and its order, Array/List, packed ctors, a TodoList sequence, closures); deep TCO (incl. closure-boundary tail .ap) at N=1e6; a 32-bit USize profile; the fail-loud extern link check; runnable IO / stdin / error / panic / module-init programs; four stress programs (parser/sort/HashMap/TreeMap/numeric/monadic; ByteArray+UTF-8 + derived Repr + a[i]!; HashMap/HashSet order; FloatArray + dbgTrace); and a verifier-authored verify program (JSON printer, RLE, matrix multiply exercising borrowed a[i]! indexing, HashMap Dijkstra). Every program must match the native binary in stdout, stderr and exit code.

Comparison with the C backend

The oracle for every diff-test is the native C-compiled Lean binary (each test program built through lake build → leanc), not lean --run (the interpreter shares the same naive stack behaviour as JS and would mask divergences). Every claim below is enforced by ../../maint/TypeScript/test-diff.sh diffing node output against that native binary.

Covered and native-verified

  • Object / value model: constructor three-region layout (pointer/USize words + packed-scalar DataView), nullary-ctor/enum lowering, case/switch tagging.
  • Numeric tower: Nat/Int bignum (bigint, Euclidean div/mod), UInt8/16/32/64, USize, Float/Float32 (IEEE add/sub/mul/div/sqrt/cmp bit-exact; transcendentals within ≤1 ULP, compared via the C %f 6-digit toString), signed fixed-width Int8..Int64/ISize (unsigned storage + asIntN recovery, as in EmitC).
  • String: UTF-8 byte-positioned String.Pos, get/next/prev/extract/atEnd/posOf, length (code points) vs utf8ByteSize (bytes), String.hash (MurmurHash64A, seed 11, bit-identical so Std.HashMap String _ iteration order matches native).
  • Collections: Array/List operations (setters update an exclusive array in place and copy a shared one), ByteArray (Uint8Array), FloatArray (Float64Array: push/get!/set!/get/uget/fold/toList with native OOB conventions: get! gives 0.0, set! leaves the array unchanged), Std.HashMap/ HashSet with native-matching bucket-order iteration.
  • Owned/borrowed externs: Lean 4.35.0 emits four borrowed @[extern] variants: three for array element access (lean_array_get_borrowed, lean_array_fget_borrowed, lean_array_uget_borrowed) and lean_panic_fn_borrowed (panicCore, borrowed default). Each returns the element without the inc its owned twin does. So a[i]! and borrowed indexing/projection work uniformly (verified by the matrix-multiply inner loop in the verify diff-test, which lowers to lean_array_get_borrowed).
  • Control flow: self- and mutual-recursion plus non-cyclic tail chains are loop-ified through a unified trampoline (__tc cores returning tc thunks); join points are inlined so continue stays lexically valid.
  • IO: stdout/stderr/stdin (real fd, sync read), IO.Error formatting + entry-point uncaught exception: reporting, @[init]/initialize module-init chain, panic! semantics (print to stderr, return the Inhabited default, continue), dbgTrace/ dbgTraceIfShared/dbgSleep.

Publishing

The Release and Publish workflows release every backend under one version, as CONTRIBUTING.md describes. ../../maint/TypeScript/bump-version.sh sets the version of package.json; the Release workflow runs it, tags vX.Y.Z and starts the Publish workflow, which packs and publishes the tag to npm with trusted publishing.

Can you improve this documentation?Edit on GitHub

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
←Move to previous article
→Move to next article
Ctrl+/Jump to the search field
× close