leanfran 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -637
- package/package.json +5 -5
- /package/{LICENSE → dist/LICENSE} +0 -0
package/README.md
CHANGED
|
@@ -1,100 +1,21 @@
|
|
|
1
|
-
|
|
1
|
+
# TypeScript
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
<a href="https://www.npmjs.com/package/leanfran"><img src="https://img.shields.io/npm/v/leanfran" alt="npm version"></a>
|
|
5
|
-
<a href="https://github.com/conao3/lean-leanfran/actions/workflows/ci.yml"><img src="https://github.com/conao3/lean-leanfran/actions/workflows/ci.yml/badge.svg?branch=master" alt="CI"></a>
|
|
6
|
-
<a href="https://github.com/conao3/lean-leanfran/blob/master/TypeScript/LICENSE"><img src="https://img.shields.io/github/license/conao3/lean-leanfran" alt="License: Apache-2.0"></a>
|
|
7
|
-
<a href="https://github.com/conao3/lean-leanfran/blob/master/TypeScript/package.json"><img src="https://img.shields.io/badge/Node-%3E%3D22.18-blue" alt="Node >=22.18"></a>
|
|
8
|
-
<a href="https://github.com/conao3/lean-leanfran/blob/master/TypeScript/lean-toolchain"><img src="https://img.shields.io/badge/Lean-v4.35.0-blue" alt="Lean v4.35.0"></a>
|
|
9
|
-
<a href="https://github.com/conao3/lean-leanfran/stargazers"><img src="https://img.shields.io/github/stars/conao3/lean-leanfran?style=flat" alt="GitHub stars"></a>
|
|
10
|
-
</p>
|
|
11
|
-
|
|
12
|
-
<p align="center">
|
|
13
|
-
<a href="#install">Install</a> ·
|
|
14
|
-
<a href="#lean-blocks">Lean blocks</a> ·
|
|
15
|
-
<a href="#values">Values</a> ·
|
|
16
|
-
<a href="#verifying-typescript-functions">Verifying TypeScript functions</a> ·
|
|
17
|
-
<a href="#examples">Examples</a> ·
|
|
18
|
-
<a href="https://www.npmjs.com/package/leanfran">npm</a>
|
|
19
|
-
</p>
|
|
20
|
-
|
|
21
|
-
# leanfran
|
|
22
|
-
|
|
23
|
-
leanfran lets you write functions in Lean 4, prove theorems about them, and call them from
|
|
24
|
-
TypeScript with plain values and Standard Schema types as arguments and results. The npm package
|
|
25
|
-
and its CLI are `leanfran`; the Lean CLI that generates the TypeScript is `leanfran-typescript`.
|
|
26
|
-
|
|
27
|
-
```ts
|
|
28
|
-
import { lean } from "leanfran"
|
|
29
|
-
import * as z from "zod"
|
|
30
|
-
import * as pricing from "./_lean/pricing.ts"
|
|
31
|
-
|
|
32
|
-
export const LineItem = z.object({
|
|
33
|
-
sku: z.string().min(1),
|
|
34
|
-
qty: z.number().int().min(1),
|
|
35
|
-
unitPrice: z.number().int().min(0),
|
|
36
|
-
})
|
|
37
|
-
|
|
38
|
-
export const pricingBlock = lean(
|
|
39
|
-
"pricing",
|
|
40
|
-
String.raw`
|
|
41
|
-
inductive Discount where
|
|
42
|
-
| none
|
|
43
|
-
| percent (p : Nat) (h : p ≤ 100)
|
|
44
|
-
| fixed (amount : Nat)
|
|
45
|
-
|
|
46
|
-
def subtotal (items : List LineItem) : Nat :=
|
|
47
|
-
items.foldl (fun acc i => acc + i.qty * i.unitPrice) 0
|
|
48
|
-
|
|
49
|
-
def total (items : List LineItem) (d : Discount) : Nat :=
|
|
50
|
-
match d with
|
|
51
|
-
| .none => subtotal items
|
|
52
|
-
| .percent p _ => subtotal items - subtotal items * p / 100
|
|
53
|
-
| .fixed a => subtotal items - a
|
|
54
|
-
|
|
55
|
-
theorem total_le (items : List LineItem) (d : Discount) : total items d ≤ subtotal items := by
|
|
56
|
-
unfold total; split <;> omega
|
|
57
|
-
`,
|
|
58
|
-
{ models: { LineItem } },
|
|
59
|
-
)
|
|
60
|
-
|
|
61
|
-
pricing.total([{ sku: "a", qty: 2, unitPrice: 100 }], { ctor: "percent", p: 10n }) // 180n
|
|
62
|
-
pricing.Discount["~standard"].validate({ percent: { p: 150 } }) // issues: Discount.percent.h: p ≤ 100
|
|
63
|
-
```
|
|
64
|
-
|
|
65
|
-
- `leanfran sync` checks the proofs with Lake and compiles the Lean code from Lean's IR to typed
|
|
66
|
-
TypeScript modules in `src/_lean/`, which you commit. They pass `tsc --strict` and run with the npm
|
|
67
|
-
package alone, in Node (22.18 or later), Bun and browsers. You do not need Lean to run them.
|
|
68
|
-
- The generated TypeScript computes what the C backend computes. A diff test runs the same Lean
|
|
69
|
-
programs natively and as TypeScript and compares the output byte for byte.
|
|
70
|
-
- Lean structures and inductive types become TypeScript types and Standard Schema values. A proof
|
|
71
|
-
field (`h : p ≤ 100`) becomes a check compiled from the proposition, so every value that reaches
|
|
72
|
-
Lean satisfies the invariants the proofs rely on. The JSON is the JSON of Lean's
|
|
73
|
-
`deriving ToJson, FromJson`, and the schemas have a JSON Schema.
|
|
74
|
-
- Lean code can use your own zod, valibot or arktype schemas (`models: { ... }`). Their constraints
|
|
75
|
-
(`min`, `max`, `minLength`, ...) become proof fields that Lean proofs may assume.
|
|
76
|
-
- `model(fn, { refines, requires, ensures })` binds a TypeScript function to Lean specifications.
|
|
77
|
-
`leanfran check` translates the function to Lean and judges your proofs
|
|
78
|
-
([Verifying TypeScript functions](#verifying-typescript-functions)).
|
|
3
|
+
[leanfran](https://github.com/conao3/lean-leanfran/blob/master/README.md) for TypeScript: write Lean blocks with `lean(...)`, use generated TypeScript types and Standard Schema values, and verify supported TypeScript functions against Lean specifications.
|
|
79
4
|
|
|
80
5
|
## Install
|
|
81
6
|
|
|
82
|
-
The npm package and the Lean CLI:
|
|
83
|
-
|
|
84
7
|
```sh
|
|
85
|
-
pnpm add leanfran
|
|
86
|
-
nix profile install 'github:conao3/lean-leanfran
|
|
8
|
+
pnpm add leanfran
|
|
9
|
+
nix profile install 'github:conao3/lean-leanfran#typescript'
|
|
87
10
|
```
|
|
88
11
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
there; write such blocks as plain template literals to run them with Bun.
|
|
12
|
+
Generation requires Lean 4.35.0 (`lean` and `lake`) on `PATH`. Generated modules run in Node 22.18 or later, Bun and browsers with the npm package.
|
|
13
|
+
|
|
14
|
+
## First Lean block
|
|
93
15
|
|
|
94
|
-
|
|
16
|
+
Put this in `src/arith.ts`:
|
|
95
17
|
|
|
96
18
|
```ts
|
|
97
|
-
// src/arith.ts
|
|
98
19
|
import { lean } from "leanfran"
|
|
99
20
|
import * as arith from "./_lean/arith.ts"
|
|
100
21
|
|
|
@@ -111,558 +32,16 @@ theorem double_eq (n : Nat) : double n = 2 * n := by
|
|
|
111
32
|
arith.double(21n) // 42n
|
|
112
33
|
```
|
|
113
34
|
|
|
114
|
-
|
|
115
|
-
leanfran sync --package <dir> [--leanfran-typescript <path>]
|
|
116
|
-
leanfran status --package <dir>
|
|
117
|
-
leanfran generate --lake-dir <dir> --output-dir <dir> [--modules <Name> ...]
|
|
118
|
-
```
|
|
119
|
-
|
|
120
|
-
- `leanfran sync` reads the `lean(...)` calls of `<dir>/src/**/*.ts` with oxc-parser
|
|
121
|
-
(the name is a string literal, the source a template literal or `String.raw`, the
|
|
122
|
-
options `imports`, `uses`, `models` and `output` an object literal), writes each
|
|
123
|
-
block to `.leanfran/workspace/LeanTsEmbed/<module>/<name>.lean`, builds it with Lake
|
|
124
|
-
and generates `_lean/<module>__<name>.ts` next to the module (and `_lean/<module>.ts`
|
|
125
|
-
when the module has one block) and `.leanfran/blocks.json`. A Lean error is reported
|
|
126
|
-
at the line of the TypeScript file with exit code 254.
|
|
127
|
-
- `uses: ["./geometry.ts:geometry"]` imports and opens another block of the package;
|
|
128
|
-
the generated module imports the types and schemas of that block's module.
|
|
129
|
-
- `models: { LineItem }` takes the user's Standard JSON Schema values (zod, valibot,
|
|
130
|
-
arktype): `sync` imports the module, reads `~standard.jsonSchema.output({ target:
|
|
131
|
-
"draft-2020-12" })` and writes a Lean structure `LeanTsModels.<module>.LineItem`
|
|
132
|
-
(opened in the block). `integer` is `Nat` when its minimum is at least 0 and `Int`
|
|
133
|
-
otherwise, `number` `Float`, `array` `List`, a property that is not required an
|
|
134
|
-
`x? : Option α` field, a string `enum` an inductive type in `LeanTsEnums.<module>`, an
|
|
135
|
-
object equal to another model that model; `minimum`, `maximum`, the exclusive
|
|
136
|
-
bounds, `minLength`, `maxLength`, `minItems` and `maxItems` become proof fields
|
|
137
|
-
(`qty_ge : 1 ≤ qty`) the Lean proofs can assume, and `pattern`, `format`,
|
|
138
|
-
`multipleOf` are listed in the structure's docstring as not assumed. Other JSON
|
|
139
|
-
Schema stops `sync` with 254 and the model and property. A model must be an
|
|
140
|
-
exported variable, a named import or a property of a namespace import: the
|
|
141
|
-
functions take and return `StandardSchemaV1.InferOutput<typeof LineItem>` (a
|
|
142
|
-
type-only import), run the model's `~standard.validate` on the arguments and return
|
|
143
|
-
plain objects.
|
|
144
|
-
- `output: { tagKey, option }` of a block and the `"leanfran"` field of `package.json`
|
|
145
|
-
(`{ "leanfran": { "tagKey": "kind", "option": "undefined" } }`, overridden by the
|
|
146
|
-
block) are the generation settings; a block and the blocks it uses must have the
|
|
147
|
-
same settings.
|
|
148
|
-
- A generated module registers its block and its settings when imported;
|
|
149
|
-
`lean(...)` throws `LeanBlockStale` when no registered module was generated from the
|
|
150
|
-
same name, source, options, model JSON Schemas and generator version, or (in Node,
|
|
151
|
-
where it reads the `package.json` above the generated module) with the current
|
|
152
|
-
settings. With `LEANFRAN_TS_AUTO_SYNC=1` it runs
|
|
153
|
-
`leanfran sync` instead, and the regenerated module is used from the next start.
|
|
154
|
-
- `leanfran status` compares the keys (which also cover the module path and the
|
|
155
|
-
`"leanfran"` field of `package.json`) with `.leanfran/blocks.json` without Lean and
|
|
156
|
-
exits with 254 when a block is stale.
|
|
157
|
-
- Commit `_lean/` and `.leanfran/blocks.json`; ignore `.leanfran/workspace/`. The
|
|
158
|
-
package then runs without Lean.
|
|
159
|
-
|
|
160
|
-
## Values
|
|
161
|
-
|
|
162
|
-
| Lean | TypeScript |
|
|
163
|
-
| ----------------------------------- | ------------------------------------------------------------------------------ |
|
|
164
|
-
| `Nat`, `Int` | `bigint` (arguments also take a safe-integer `number`) |
|
|
165
|
-
| `UInt8`..`UInt32`, `Int8`..`Int32` | `number` |
|
|
166
|
-
| `UInt64`, `USize`, `Int64`, `ISize` | `bigint` |
|
|
167
|
-
| `Bool` | `boolean` |
|
|
168
|
-
| `Char` | `string` of one code point |
|
|
169
|
-
| `String` | `string` |
|
|
170
|
-
| `Float`, `Float32` | `number` |
|
|
171
|
-
| `Unit` | `void` / `undefined` |
|
|
172
|
-
| `Option α` | `α \| null`, or `α \| undefined` with `--option undefined` |
|
|
173
|
-
| `List α`, `Array α` | `readonly α[]` (arguments), `α[]` (results) |
|
|
174
|
-
| `α × β` | `readonly [α, β]` |
|
|
175
|
-
| `Except ε α` | `{ ok: true; value: α } \| { ok: false; error: ε }` |
|
|
176
|
-
| `IO α` | `α`; an `IO.Error` is thrown as `LeanIOError` (`code` is the constructor name) |
|
|
177
|
-
| `Fin n` | `number` (`bigint` when `n > 2^32`) |
|
|
178
|
-
| structures | plain objects (`{ readonly lo: bigint; readonly hi: bigint }`) |
|
|
179
|
-
| enumerations | string literal unions (`"red" \| "green"`) |
|
|
180
|
-
| other inductive types | unions on the `--tag-key` (`{ ctor: "percent"; p: bigint } \| ...`) |
|
|
181
|
-
| `{x : α // p x}` | `α`, checked by `p` |
|
|
182
|
-
|
|
183
|
-
Arguments are checked while they are converted: a value that does not fit throws
|
|
184
|
-
`LeanValidationError`, whose `issues` (`{ message, path }`) name every place that
|
|
185
|
-
does not fit. A definition without arguments becomes a function evaluated on the
|
|
186
|
-
first call. Names are the Lean names under `--namespace` (default: the module) in
|
|
187
|
-
lowerCamelCase (`?` → `Q`, `!` → `Bang`, `'` → `Prime`); a name with more components
|
|
188
|
-
is a member of a namespace object (`Calc.add` is `export const Calc = { add }`).
|
|
189
|
-
|
|
190
|
-
### Structures, inductive types and Standard Schema
|
|
191
|
-
|
|
192
|
-
```lean
|
|
193
|
-
structure Range where
|
|
194
|
-
lo : Nat
|
|
195
|
-
hi : Nat
|
|
196
|
-
ok : lo ≤ hi
|
|
197
|
-
|
|
198
|
-
inductive Discount where
|
|
199
|
-
| none
|
|
200
|
-
| percent (p : Nat) (h : p ≤ 100)
|
|
201
|
-
| fixed (amount : Nat)
|
|
202
|
-
```
|
|
203
|
-
|
|
204
|
-
```ts
|
|
205
|
-
export type Range = { readonly lo: bigint; readonly hi: bigint }
|
|
206
|
-
export type RangeInput = {
|
|
207
|
-
readonly lo: bigint | number | string
|
|
208
|
-
readonly hi: bigint | number | string
|
|
209
|
-
}
|
|
210
|
-
export const Range: L.LeanSchema<RangeInput, Range> = L.schema<RangeInput, Range>($tRange)
|
|
211
|
-
|
|
212
|
-
Range["~standard"].validate({ lo: 3, hi: 1 }) // { issues: [{ message: "Range.ok: lo ≤ hi", path: [] }] }
|
|
213
|
-
Discount["~standard"].validate({ percent: { p: 10 } }) // { value: { ctor: "percent", p: 10n } }
|
|
214
|
-
```
|
|
215
|
-
|
|
216
|
-
- Every type is a `LeanSchema<Input, Output>`: a `StandardSchemaV1` and
|
|
217
|
-
`StandardJSONSchemaV1` (`@standard-schema/spec` 1.1.0, vendor `leanfran`) with the
|
|
218
|
-
descriptor in `desc`. Hono's `sValidator("json", Range)`, tRPC, TanStack Form and
|
|
219
|
-
zod's `z.custom` take it as it is. `Input` is the JSON of Lean's
|
|
220
|
-
`deriving ToJson`: a structure is an object (the fields of a parent flat, an `x?`
|
|
221
|
-
field omitted when `none`), a constructor without arguments is `"none"`, named
|
|
222
|
-
arguments are `{ "percent": { "p": 10 } }`, one unnamed argument `{ "tag": v }`, several
|
|
223
|
-
`{ "pair": [a, b] }`, `UInt64`/`USize` are strings. `validate` takes the JSON and the
|
|
224
|
-
TypeScript form and returns the TypeScript form; it is synchronous.
|
|
225
|
-
- A proof field (`ok : lo ≤ hi`) or the property of a subtype is checked by the
|
|
226
|
-
decision procedure Lean compiles from the proposition (`LeanTsGen.Range.mk.ok_decide`),
|
|
227
|
-
both in `validate` and in the arguments of the public functions, so the values that
|
|
228
|
-
reach Lean satisfy the propositions. A comparison with a constant is also in the
|
|
229
|
-
JSON Schema (`maximum`, `exclusiveMinimum`, `maxLength`, `maxItems`, ...).
|
|
230
|
-
- `jsonSchema.input` and `.output` take `draft-2020-12`, `draft-07` and `openapi-3.0`;
|
|
231
|
-
recursive types use `$defs`/`definitions`.
|
|
232
|
-
- `leanfran/schema` has the scalar schemas (`Nat`, `Int`, `UInt8`.., `String`, `Float`,
|
|
233
|
-
...), `toJSON` (safe integers as numbers, the others as strings), `fromJSON`,
|
|
234
|
-
`stringify` (`bigint` as JSON numbers) and `parse` (integer literals read without
|
|
235
|
-
loss through the `JSON.parse` reviver's source text).
|
|
236
|
-
- A structure with type parameters is a type per instance (`Pair Nat Bool` is
|
|
237
|
-
`PairNatBool`). A namespace of functions named as a type is merged into its schema
|
|
238
|
-
(`Point.sum` is a member of the schema `Point`).
|
|
239
|
-
- The generation settings change the TypeScript form only:
|
|
240
|
-
|
|
241
|
-
| setting | values | default | effect |
|
|
242
|
-
| -------- | ------------------------- | -------- | ---------------------------------------------------------------------------- |
|
|
243
|
-
| `tagKey` | a JavaScript identifier | `"ctor"` | the discriminant of the inductive types (`{ kind: "percent"; p: bigint }`) |
|
|
244
|
-
| `option` | `"null"` or `"undefined"` | `"null"` | `Option α` is `α \| null`, or `α \| undefined` and an optional field `x?: α` |
|
|
245
|
-
|
|
246
|
-
## Verifying TypeScript functions
|
|
247
|
-
|
|
248
|
-
```ts
|
|
249
|
-
// src/calc.ts
|
|
250
|
-
import { lean } from "leanfran"
|
|
251
|
-
import { model } from "leanfran/verify"
|
|
252
|
-
import * as spec from "./_lean/calc.ts"
|
|
253
|
-
|
|
254
|
-
export const specBlock = lean(
|
|
255
|
-
"spec",
|
|
256
|
-
String.raw`
|
|
257
|
-
def clampSpec (x lo hi : Int) : Int := max lo (min hi x)
|
|
258
|
-
def ordered (_x lo hi : Int) : Bool := lo ≤ hi
|
|
259
|
-
def inRange (_x lo hi : Int) (r : Int) : Bool := lo ≤ r && r ≤ hi
|
|
260
|
-
`,
|
|
261
|
-
)
|
|
262
|
-
|
|
263
|
-
export function clamp(x: number, lo: number, hi: number): number {
|
|
264
|
-
if (x < lo) return lo
|
|
265
|
-
if (x > hi) return hi
|
|
266
|
-
return x
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
model(clamp, {
|
|
270
|
-
refines: spec.clampSpec,
|
|
271
|
-
requires: spec.ordered,
|
|
272
|
-
ensures: { inRange: spec.inRange },
|
|
273
|
-
})
|
|
274
|
-
```
|
|
275
|
-
|
|
276
|
-
```lean
|
|
277
|
-
-- lean/Proofs/Calc.lean (next to package.json)
|
|
278
|
-
import LeanTsModel.calc
|
|
279
|
-
|
|
280
|
-
namespace LeanTsModel.calc
|
|
281
|
-
|
|
282
|
-
theorem clamp.proof.refines : clamp.obligation.refines := by
|
|
283
|
-
intro x lo hi h
|
|
284
|
-
simp only [LeanTsEmbed.calc.spec.ordered, decide_eq_true_eq] at h
|
|
285
|
-
simp only [clamp, LeanTsEmbed.calc.spec.clampSpec]
|
|
286
|
-
split <;> (try split) <;> simp_all <;> omega
|
|
287
|
-
```
|
|
35
|
+
Generate modules from the package root:
|
|
288
36
|
|
|
37
|
+
```sh
|
|
38
|
+
leanfran sync --package .
|
|
289
39
|
```
|
|
290
|
-
leanfran check --package <dir> [--leanfran-typescript <path>] [--require proved]
|
|
291
|
-
leanfran status --package <dir>
|
|
292
|
-
```
|
|
293
|
-
|
|
294
|
-
- `model(fn, { refines?, requires?, ensures? })` (`leanfran/verify`) returns the function
|
|
295
|
-
and records it; the specifications are public functions of `lean(...)` blocks (each
|
|
296
|
-
generated function carries its Lean name as `__leanName`).
|
|
297
|
-
- `leanfran check` syncs the package, reads the `model(...)` calls with oxc-parser,
|
|
298
|
-
translates each function (a `function` declaration or a `const` arrow function) into
|
|
299
|
-
`LeanTsModel.<module>.<function>` in Lean `do` notation over `LeanTsLib.Ts`
|
|
300
|
-
(`src/lean/LeanTsLib/Ts.lean`), states `<function>.obligation.refines`
|
|
301
|
-
(`∀ x, requires x = true → f x = s x`, `= Except.ok (s x)` for a function that may
|
|
302
|
-
throw), `.obligation.<label>` for each `ensures` (partial correctness for a function
|
|
303
|
-
that may throw) and `.obligation.returnsNat` for a function returning `Nat`, builds
|
|
304
|
-
the proofs of `<dir>/lean/Proofs/` one file at a time and prints each obligation as
|
|
305
|
-
`proved`, `sorry`, `axioms` (an axiom outside `propext`, `Quot.sound`,
|
|
306
|
-
`Classical.choice`), `failed` (its proof file does not build), `missing` or
|
|
307
|
-
`mismatch` (the theorem's type is not the obligation). It writes
|
|
308
|
-
`<dir>/leanfran.lock` (with a `spec_hash` of each function's AST without positions
|
|
309
|
-
and of the keys of its specification blocks); `--require proved` exits with 254
|
|
310
|
-
unless every obligation is proved. A construct outside the subset stops `check` with
|
|
311
|
-
254 and the file, line and column. Commit `leanfran.lock` with `_lean/`; `status` and the
|
|
312
|
-
replaced specifications read it.
|
|
313
|
-
- `leanfran status` also prints the obligations of the lock and marks a function whose
|
|
314
|
-
hash changed `stale` (exit code 254) without Lean.
|
|
315
|
-
- The subset: parameters and results annotated with `number`, `bigint`, `boolean`,
|
|
316
|
-
`string`, `T[]`, `readonly T[]`, `[A, B]`, `T | null`, `T | undefined`, `Nat` and `Int`
|
|
317
|
-
of `leanfran/schema`, the structures, inductive types and enums generated from a block
|
|
318
|
-
and `z.infer<typeof X>` (any type taking `typeof X`) of a model `X` of a block;
|
|
319
|
-
`const`/`let` and reassignment, compound assignment, `++`, `if`, `switch` on a string,
|
|
320
|
-
an enum or the tag of an inductive value, early `return`, `for ... of`,
|
|
321
|
-
`for (let i = a; i < b; i++)`, `while`, `break`, `continue`, `throw new Error(...)`
|
|
322
|
-
(and the built-in errors), `push` to a local array, destructuring of tuples and
|
|
323
|
-
structures; `+ - * %`, `Math.floor(a / b)`, `Math.trunc(a / b)`, bigint `/`,
|
|
324
|
-
comparisons, `===`, `!==`, `&&`, `||`, `!`, `??`, `?:`, `xs[i]`, `xs[i]!`, `.length`,
|
|
325
|
-
tuple indices, properties, object and array literals, `map`, `filter`, `reduce`,
|
|
326
|
-
`some`, `every`, `includes`, `startsWith`, `endsWith`, template literals,
|
|
327
|
-
`Math.max`/`min`/`abs`, `BigInt`, `Number`, `String` and calls of the module's model
|
|
328
|
-
functions. A `x === null` test on a parameter narrows it as in TypeScript.
|
|
329
|
-
- Loops: `for (const x of xs)` is `for x in xs` over the list, which `simp` turns into
|
|
330
|
-
`List.foldl` when the body only updates variables; a body with an early `return` or a `push`
|
|
331
|
-
under `if` is proved by induction on the list (the `forIn` equations of `List.cons`).
|
|
332
|
-
`for (let i = a; i < b; i++)` iterates `Ts.range a b`, and `Ts.range_succ` splits off the
|
|
333
|
-
last index for an induction on the bound (`sumTo` in `samples/verified-typescript`). A
|
|
334
|
-
`while` loop is Lean's partial `Loop` and cannot be unfolded in a proof.
|
|
335
|
-
- `checkModel(fn, { numRuns?, seed?, range? })` runs the specifications as a fast-check
|
|
336
|
-
property test (fast-check is an optional peer dependency): it reads the parameter
|
|
337
|
-
types from the source of the `model(...)` call, discards arguments that fail
|
|
338
|
-
`requires` and results that are not safe integers, and throws `PropertyFailure` with
|
|
339
|
-
the counterexample. `checkModule(m)` runs it for every model function of a module.
|
|
340
|
-
`arbitrary(schema, fc)` of `leanfran/schema` generates the values of a descriptor.
|
|
341
|
-
- A proved `refines` without `requires` replaces the specification: the lock records
|
|
342
|
-
it, `sync` writes `LeanTsCsimp/<module>.lean` (`@[extern "ts:src/calc.ts#addOne(n)"]
|
|
343
|
-
def addOne := @spec.succ` and an `rfl` `@[csimp]` theorem), and the emitter makes the
|
|
344
|
-
public function of the specification and every Lean function of the block that calls
|
|
345
|
-
it call the TypeScript function (the arguments pass through `toTs`, and `tsNumbers`
|
|
346
|
-
for `number` parameters, the result through `toLean`). The generated module then
|
|
347
|
-
imports the user's module; it registers its block in `<module>__<name>.block.ts`
|
|
348
|
-
first so that either module can be imported first.
|
|
349
|
-
- The proofs hold for the translation of the function and assume that `number`
|
|
350
|
-
arguments and intermediate values are safe integers (`bigint` needs no assumption),
|
|
351
|
-
that the arguments have their annotated types (`tsc --strict`, `validate` at the
|
|
352
|
-
boundary), and that the translation and `LeanTsLib.Ts` keep the meaning of
|
|
353
|
-
TypeScript, which `checkModel` and `test/verify/ts-model.test.ts` test.
|
|
354
|
-
|
|
355
|
-
## Examples
|
|
356
|
-
|
|
357
|
-
[`samples/`](https://github.com/conao3/lean-leanfran/tree/master/TypeScript/samples) holds packages with Lean blocks
|
|
358
|
-
and verified TypeScript functions. `make samples` syncs each one, runs it, compares the output with
|
|
359
|
-
its `expected.txt`, checks the proofs of the verified ones with `leanfran check --require proved`,
|
|
360
|
-
and fails when a committed generated module is out of date.
|
|
361
|
-
|
|
362
|
-
| sample | shows |
|
|
363
|
-
| ----------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
|
|
364
|
-
| [word-count](https://github.com/conao3/lean-leanfran/tree/master/TypeScript/samples/word-count) | strings and lists, a proof by induction |
|
|
365
|
-
| [roman-numerals](https://github.com/conao3/lean-leanfran/tree/master/TypeScript/samples/roman-numerals) | a lake project compiled with `leanfran generate`, a round-trip theorem checked for every number below 1000 |
|
|
366
|
-
| [todo-cli](https://github.com/conao3/lean-leanfran/tree/master/TypeScript/samples/todo-cli) | an invariant over a list kept by every operation, JSON storage, tampered JSON rejected |
|
|
367
|
-
| [generic-search](https://github.com/conao3/lean-leanfran/tree/master/TypeScript/samples/generic-search) | polymorphic functions proved for every type, called through monomorphic definitions |
|
|
368
|
-
| [pricing-api](https://github.com/conao3/lean-leanfran/tree/master/TypeScript/samples/pricing-api) | Hono with a zod model and a Lean inductive type as request body, 400 for invalid input, OpenAPI |
|
|
369
|
-
| [verified-typescript](https://github.com/conao3/lean-leanfran/tree/master/TypeScript/samples/verified-typescript) | a `for (let i ...)` loop proved equal to a recursive spec, which it then replaces; an insertion that keeps an array sorted |
|
|
370
|
-
| [sorted-search](https://github.com/conao3/lean-leanfran/tree/master/TypeScript/samples/sorted-search) | `refines` under `requires` (a scan of a sorted array) |
|
|
371
|
-
| [inventory](https://github.com/conao3/lean-leanfran/tree/master/TypeScript/samples/inventory) | a block's structure and enum in the signatures of verified functions |
|
|
372
|
-
|
|
373
|
-
[`samples/steps/`](https://github.com/conao3/lean-leanfran/tree/master/TypeScript/samples/steps) introduces one
|
|
374
|
-
feature at a time, from functions on `Nat` (01) to types shared between blocks with `uses` (09)
|
|
375
|
-
and the verification of TypeScript functions (10 to 14).
|
|
376
|
-
|
|
377
|
-
## The CLI
|
|
378
|
-
|
|
379
|
-
```
|
|
380
|
-
leanfran-typescript module generate --module-name Foo.Bar [--roots <Name> ...] [--main <Name>]
|
|
381
|
-
[--namespace <Name>] [--import <Name> ...] [--search-path <dir> ...] [--output-file <path>]
|
|
382
|
-
[--runtime-path <specifier>] [--type-module <Name>=<specifier> ...] [--model-module <Name>=<key> ...]
|
|
383
|
-
[--tag-key <key>] [--option null|undefined] [--ts-root <specifier>] [--batch <file>]
|
|
384
|
-
[--internal-only] [--output json|text]
|
|
385
|
-
leanfran-typescript project generate --lake-dir <dir> --output-dir <dir> [--modules <Name> ...]
|
|
386
|
-
leanfran-typescript obligations check --modules <Name> ... --obligations <file> [--search-path <dir> ...]
|
|
387
|
-
leanfran-typescript help | --version | --generator-version
|
|
388
|
-
```
|
|
389
|
-
|
|
390
|
-
The roots default to the module's public definitions with IR. Each root becomes a
|
|
391
|
-
public function that takes and returns TypeScript values; the internal functions it
|
|
392
|
-
calls are not exported. `--internal-only` exports the internal functions instead
|
|
393
|
-
(the diff-test calls them with runtime values). `--main` also emits the module's
|
|
394
|
-
`@[init]` chain and a call running the given function as `main`. A root whose type
|
|
395
|
-
cannot cross the boundary (type parameters, instance or proof arguments, function
|
|
396
|
-
values, nested `Option`, types without a Lean form such as a proposition without
|
|
397
|
-
`Decidable`) is listed in the summary's `skipped` with the reason. The structures and
|
|
398
|
-
inductive types of the module (and those the public functions use) are exported as
|
|
399
|
-
types and schemas (summary `types`). Exit codes: 0 success, 252 invalid parameters,
|
|
400
|
-
254 input that cannot be converted (an extern the runtime does not provide, a name
|
|
401
|
-
without IR, a constructor field named as the `--tag-key`, an invalid `--tag-key` or
|
|
402
|
-
`--option`), 255 other errors. `--batch` runs a JSON array of jobs against one environment (`leanfran sync`
|
|
403
|
-
uses it); `project generate` builds a lake project and writes `<A>/<B>.ts` per module
|
|
404
|
-
`A.B`.
|
|
405
|
-
|
|
406
|
-
```ts
|
|
407
|
-
// Generated by leanfran-typescript (generator 4) from LeanTsTest.Public. Do not edit.
|
|
408
|
-
import * as L from "leanfran/runtime"
|
|
409
|
-
import type { Obj } from "leanfran/runtime"
|
|
410
|
-
|
|
411
|
-
function l_LeanTsTest_Public_double(x_1: Obj): Obj {
|
|
412
|
-
const x_2: Obj = L.lean_nat_add(x_1, x_1)
|
|
413
|
-
return x_2
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
const $d0: L.TypeDesc<bigint> = L.natDesc
|
|
417
|
-
|
|
418
|
-
/** Lean `LeanTsTest.Public.double : Nat → Nat`. */
|
|
419
|
-
export function double(n: bigint | number): bigint {
|
|
420
|
-
return L.toTs($d0, l_LeanTsTest_Public_double(L.toLean($d0, n, "n")))
|
|
421
|
-
}
|
|
422
|
-
```
|
|
423
|
-
|
|
424
|
-
## Layout
|
|
425
|
-
|
|
426
|
-
- `LeanTs/EmitTs.lean` — the emitter: IR walk, transitive decl collection, extern
|
|
427
|
-
mapping, trampoline TCO, typed TypeScript output.
|
|
428
|
-
- `LeanTs/Marshal.lean` — the TypeScript types and descriptors of the Lean types at the
|
|
429
|
-
boundary (structures, inductive types and subtypes with their constructor layouts and
|
|
430
|
-
the deciders compiled from their proof fields) and the signatures of the public
|
|
431
|
-
functions; `LeanTs/Generate.lean` — the type aliases, descriptors and schemas, the
|
|
432
|
-
public functions, namespace objects and the skipped roots.
|
|
433
|
-
- `LeanTs/RuntimeExterns.lean` — the runtime functions the generated code may call
|
|
434
|
-
(generated from `src/runtime` by `make gen-externs`).
|
|
435
|
-
- `LeanTs/Check.lean` — `obligations check`: the state of each obligation from the type and the axioms of its proof.
|
|
436
|
-
- `Main.lean` — the CLI `leanfran-typescript`.
|
|
437
|
-
- `src/verify/` — `leanfran/verify` (`model`, `checkModel`, `checkModule`), the translation of TypeScript functions to Lean (`translate.ts`) and `leanfran check` and `status` with `leanfran.lock` (`check.ts`); `src/lean/LeanTsLib/Ts.lean` — the meaning of the TypeScript operations; `src/schema/arbitrary.ts` — fast-check arbitraries of the descriptors.
|
|
438
|
-
- `src/index.ts`, `src/embed.ts` — `lean(...)`, `LeanBlockStale` and the block keys;
|
|
439
|
-
`src/scan.ts`, `src/sync.ts`, `src/cli.ts` — the CLI `leanfran` (`sync`, `status`,
|
|
440
|
-
`generate`); `src/runtime/block.ts` — the registry the generated modules register in;
|
|
441
|
-
`src/models.ts` — the Lean structures of the user's models (`lean(..., { models })`).
|
|
442
|
-
- `src/schema/` — `leanfran/schema`: `LeanSchema` (Standard Schema and Standard JSON
|
|
443
|
-
Schema), the scalar schemas, `toJSON`, `fromJSON`, `stringify`, `parse` and the JSON
|
|
444
|
-
Schema of a descriptor (`desc.ts`).
|
|
445
|
-
- `src/runtime/` — the runtime (npm package `leanfran`, export `./runtime`):
|
|
446
|
-
`object.ts` (the `Obj` type, constructors, closures, `lean_apply`,
|
|
447
|
-
`lean_trampoline`), `nat.ts`/`int.ts`/`uint.ts`/`float.ts` (numeric tower),
|
|
448
|
-
`string.ts`, `array.ts` (Array, ByteArray, FloatArray), `io.ts` (`IO.Error`,
|
|
449
|
-
streams, panic, init chain, `main`), `marshal.ts` (the boundary: `TypeDesc`,
|
|
450
|
-
`toLean`, `toTs`, the validation of `validate`, `LeanValidationError`, `LeanIOError`), `node.ts` (the Node platform),
|
|
451
|
-
`index.ts` (re-exports; installs the Node platform when `process.getBuiltinModule`
|
|
452
|
-
exists, otherwise OS operations return `IO.Error.unsupportedOperation`).
|
|
453
|
-
- `LeanTsTest/` — the diff-test programs (`Vectors`, `HigherOrder`, `Io`, `Init`,
|
|
454
|
-
`Stress`..`Stress4`, `Verify`, `Fuzz`) and their native oracles (`*Main.lean`,
|
|
455
|
-
executables `oracle-*`), `Public` (called through the public functions) and `Json`
|
|
456
|
-
(values with `deriving ToJson, FromJson`; `oracle-json` prints their JSON).
|
|
457
|
-
- `test/difftest/` — node harnesses for the function-level diff, fuzz, deep TCO and
|
|
458
|
-
the 32-bit profile; `test/*.test.ts` — Vitest tests of the runtime and of the
|
|
459
|
-
public functions and schemas with both generation settings (`test/public.test.ts`),
|
|
460
|
-
the JSON against Lean's `ToJson` (`test/json.test.ts`), Standard Schema with Hono and
|
|
461
|
-
zod (`test/standard.test.ts`); `test/embed.test.ts` — `leanfran sync`,
|
|
462
|
-
`status` and `generate` on the fixtures `test/embed/app/` (with its committed
|
|
463
|
-
`src/_lean/` and `.leanfran/blocks.json`) and `test/project/`.
|
|
464
|
-
- `samples/` — the samples (pnpm workspace packages that link `leanfran`), `samples/run.sh` and
|
|
465
|
-
`samples/Makefile` (`test`, `verify`).
|
|
466
|
-
- `scripts/bump-version.sh` — sets the version of `package.json`, `Main.lean` and `flake.nix`;
|
|
467
|
-
the `Release` workflow runs it, tags `vX.Y.Z` and starts the `Publish` workflow, which packs and
|
|
468
|
-
publishes the tag to npm with trusted publishing.
|
|
469
|
-
|
|
470
|
-
## How it works
|
|
471
|
-
|
|
472
|
-
1. Target functions are defined in library modules so their IR is persisted in the
|
|
473
|
-
`.olean` and visible to `Lean.IR.findEnvDecl`.
|
|
474
|
-
2. From the roots, `LeanTs.collectTransitive` does a worklist DFS over
|
|
475
|
-
`findEnvDecl`, walking `fap`/`pap` callees; `.fdecl` are emitted as TS functions,
|
|
476
|
-
`.extern` map to runtime functions by their C symbol, `none` (e.g. `Nat.rec`) is
|
|
477
|
-
the boundary. Functions nothing references are not emitted.
|
|
478
|
-
3. The emitter walks `FnBody` / `Expr`, mirroring `EmitC`'s match arms. Parameters
|
|
479
|
-
and `const`s are typed from the IR types (`object`/`tobject`/erased → `Obj`,
|
|
480
|
-
`uint8`..`uint32`/`float`/`float32` → `number`, `uint64`/`usize` → `bigint`),
|
|
481
|
-
and only bindings the code reads are emitted.
|
|
482
|
-
|
|
483
|
-
### Reference counting
|
|
484
|
-
|
|
485
|
-
Constructors, arrays, `ByteArray`s and `FloatArray`s carry a reference count `rc`,
|
|
486
|
-
and the IR's reference-counting nodes run on it as in `EmitC`, so an exclusive
|
|
487
|
-
array or constructor is updated in place:
|
|
488
|
-
|
|
489
|
-
- `FnBody.inc` / `dec` -> `L.lean_inc` / `L.lean_dec` (a dec to 0 releases the
|
|
490
|
-
children); `del` -> nothing
|
|
491
|
-
- `Expr.reset` -> `L.lean_reset` (the cell when exclusive, else `null`);
|
|
492
|
-
`Expr.reuse` -> `L.lean_reuse` (writes into the cell, or allocates for `null`)
|
|
493
|
-
- `Expr.isShared` -> `L.lean_is_shared` (`rc !== 1`)
|
|
494
|
-
- `Expr.box` -> identity; `Expr.unbox` -> `L.lean_unbox` (a checked narrowing)
|
|
495
|
-
|
|
496
|
-
A value whose `rc` is not a positive integer counts as shared: a persistent value
|
|
497
|
-
(`initialize` globals, cached constants of the public functions) and a value made
|
|
498
|
-
outside the runtime are copied before they are updated. The runtime keeps `rc` at
|
|
499
|
-
least the number of references: the externs that return a part of their argument
|
|
500
|
-
(`Array.get`, `IO.Ref.get`, `Thunk.get`) inc it, a copy incs the elements, and
|
|
501
|
-
`lean_apply` incs the arguments a closure holds.
|
|
502
|
-
|
|
503
|
-
### Object / value model
|
|
504
|
-
|
|
505
|
-
- `Nat` / `Int` / `UInt64` / `USize` / `Int64` / `ISize` -> `bigint`;
|
|
506
|
-
`UInt8`/`UInt16`/`UInt32`/`Int8`/`Int16`/`Int32`/`Float`/`Float32`/`Char` -> JS
|
|
507
|
-
number (the signed ones hold the unsigned bit pattern, as `lean.h` does).
|
|
508
|
-
- ctor with fields -> `L.lean_ctor(cidx, size, usize, ssize, ...objs)` producing
|
|
509
|
-
`{ tag, fields, sdata }`: object pointers and `USize` slots are word-indexed in
|
|
510
|
-
`fields` (proj/uproj/set/uset), packed scalars live in a byte-addressed `DataView`
|
|
511
|
-
`sdata` (sproj/sset), mirroring `lean_alloc_ctor`'s three regions. Nullary ctor /
|
|
512
|
-
enum -> `cidx`. `lean_tag(x)` recovers the tag for both forms.
|
|
513
|
-
- `Bool` -> scalar `0`/`1`; extern `decEq`/`decLt`/`decLe` return `0`/`1` so the
|
|
514
|
-
emitted `switch` matches.
|
|
515
|
-
- `String` -> JS string; `String.Pos` is a UTF-8 byte offset (`get`/`next`/`prev`/
|
|
516
|
-
`extract`/`atEnd` index bytes, `utf8ByteSize` counts bytes, `length` counts code
|
|
517
|
-
points).
|
|
518
|
-
- `Array` -> JS array with an `rc` property; setters (`set`/`uset`/`push`/`pop`/
|
|
519
|
-
`swap`) update an exclusive array in place and copy a shared one. `ByteArray` ->
|
|
520
|
-
`Uint8Array` and `FloatArray` -> `Float64Array`, whose `push` grows a view over a
|
|
521
|
-
buffer with spare capacity.
|
|
522
|
-
- `case` on scalar -> `switch (x)`; on object -> `switch (L.lean_tag(x))`.
|
|
523
|
-
- self-tail-recursion -> `for (;;)` loop with staged param rebind + `continue`
|
|
524
|
-
(join points are inlined at each jump, so `continue` stays lexically inside the loop).
|
|
525
|
-
|
|
526
|
-
## Performance
|
|
527
|
-
|
|
528
|
-
`make bench` (Node.js 26, x86_64; the native column is the C backend):
|
|
529
|
-
|
|
530
|
-
| workload | n | TypeScript (s) | native C (s) |
|
|
531
|
-
| ------------------------- | --- | -------------- | ------------ |
|
|
532
|
-
| `Array.push`, `set!`, sum | 10⁴ | 0.008 | 0.005 |
|
|
533
|
-
| `Array.push`, `set!`, sum | 10⁵ | 0.046 | 0.006 |
|
|
534
|
-
| `Array.push`, `set!`, sum | 10⁶ | 0.438 | 0.016 |
|
|
535
|
-
| `fib` (loop) | 10⁵ | 0.055 | 0.072 |
|
|
536
|
-
| `naiveFib` | 25 | 0.016 | 0.005 |
|
|
537
|
-
| `String.push` | 10⁴ | 0.004 | 0.005 |
|
|
538
|
-
| `String.push` | 10⁵ | 0.018 | 0.006 |
|
|
539
|
-
| `Array.qsort` | 10⁵ | 0.425 | 0.020 |
|
|
540
|
-
|
|
541
|
-
Passing 10⁴ structures to a Lean function takes 0.024 s (zod's
|
|
542
|
-
`z.array(z.object(...)).parse` validates 10⁴ objects in 0.011 s).
|
|
543
|
-
|
|
544
|
-
## Checks
|
|
545
|
-
|
|
546
|
-
```
|
|
547
|
-
nix develop -c make check
|
|
548
|
-
```
|
|
549
|
-
|
|
550
|
-
`make check` runs `treefmt --ci`, `./test-diff.sh` (generates the `LeanTsTest`
|
|
551
|
-
modules into `test-out/` and diffs them against the native oracles), `./test-public.sh`
|
|
552
|
-
(generates `test-out/public.ts` with the default settings, `test-out/public-alt.ts`
|
|
553
|
-
with `--tag-key _tag --option undefined` and `test-out/json.ts`, and runs
|
|
554
|
-
`test/public.test.ts` and `test/json.test.ts` against `oracle-json`), `./fuzz.sh`,
|
|
555
|
-
the type check of every generated module (`vp lint test-out/**/*.ts`), `leanfran
|
|
556
|
-
status` of the embedding and verification fixtures, `test/verify/test.sh` (copies
|
|
557
|
-
`test/verify/app/` to `test-out/verify/<scene>/` and checks the states proved, sorry,
|
|
558
|
-
axioms, missing, mismatch, failed and stale, `--require proved`, the TypeScript functions
|
|
559
|
-
called through their specifications, an untranslatable function and a wrong
|
|
560
|
-
implementation that `checkModel` rejects with a counterexample), `make samples` (`leanfran check
|
|
561
|
-
--require proved` on the verified samples, `samples/run.sh` on every sample, and no difference in
|
|
562
|
-
the committed generated modules), and `vp run check` (`vp check && vp test`, which
|
|
563
|
-
includes `test/embed.test.ts`). `test-diff.sh` covers: 136 function-level
|
|
564
|
-
value assertions (numeric tower, UTF-8 `String` and its order, `Array`/`List`, packed ctors, a
|
|
565
|
-
`TodoList` sequence, closures); deep TCO (incl. closure-boundary tail `.ap`) at
|
|
566
|
-
N=1e6; a 32-bit `USize` profile; the fail-loud extern link check; runnable IO /
|
|
567
|
-
stdin / error / panic / module-init programs; four `stress` programs
|
|
568
|
-
(parser/sort/HashMap/TreeMap/numeric/monadic; ByteArray+UTF-8 + derived `Repr` +
|
|
569
|
-
`a[i]!`; HashMap/HashSet order; FloatArray + dbgTrace); and a verifier-authored
|
|
570
|
-
`verify` program (JSON printer, RLE, matrix multiply exercising borrowed `a[i]!`
|
|
571
|
-
indexing, HashMap Dijkstra). Every program must match the native binary in stdout,
|
|
572
|
-
stderr and exit code.
|
|
573
|
-
|
|
574
|
-
## Parity vs the C backend
|
|
575
|
-
|
|
576
|
-
The oracle for every diff-test is the **native C-compiled Lean binary** (each test
|
|
577
|
-
program built through `lake build` → `leanc`), not `lean --run` (the interpreter
|
|
578
|
-
shares the same naive stack behaviour as JS and would mask divergences). Every claim
|
|
579
|
-
below is enforced by `test-diff.sh` diffing node output against that native binary.
|
|
580
|
-
|
|
581
|
-
### Covered and native-verified
|
|
582
|
-
|
|
583
|
-
- **Object / value model**: constructor three-region layout (pointer/USize words +
|
|
584
|
-
packed-scalar `DataView`), nullary-ctor/enum lowering, `case`/`switch` tagging.
|
|
585
|
-
- **Numeric tower**: `Nat`/`Int` bignum (`bigint`, Euclidean div/mod), `UInt8/16/32/64`,
|
|
586
|
-
`USize`, `Float`/`Float32` (IEEE add/sub/mul/div/sqrt/cmp bit-exact; transcendentals
|
|
587
|
-
within ≤1 ULP, compared via the C `%f` 6-digit `toString`), signed fixed-width
|
|
588
|
-
`Int8..Int64`/`ISize` (unsigned storage + `asIntN` recovery, as in EmitC).
|
|
589
|
-
- **String**: UTF-8 byte-positioned `String.Pos`, get/next/prev/extract/atEnd/posOf,
|
|
590
|
-
`length` (code points) vs `utf8ByteSize` (bytes), `String.hash` (MurmurHash64A,
|
|
591
|
-
seed 11 — bit-identical so `Std.HashMap String _` iteration order matches native).
|
|
592
|
-
- **Collections**: `Array`/`List` operations (setters update an exclusive array in
|
|
593
|
-
place and copy a shared one), `ByteArray`
|
|
594
|
-
(`Uint8Array`), **`FloatArray`** (`Float64Array`: push/get!/set!/get/uget/fold/toList
|
|
595
|
-
with native OOB conventions — `get!`→`0.0`, `set!`→unchanged), `Std.HashMap`/
|
|
596
|
-
`HashSet` with native-matching bucket-order iteration.
|
|
597
|
-
- **Owned/borrowed externs**: Lean 4.35.0 emits four borrowed `@[extern]`
|
|
598
|
-
variants — three for array element access (`lean_array_get_borrowed`,
|
|
599
|
-
`lean_array_fget_borrowed`, `lean_array_uget_borrowed`) and `lean_panic_fn_borrowed`
|
|
600
|
-
(`panicCore`, borrowed default). Each returns the element without the `inc` its
|
|
601
|
-
owned twin does. So `a[i]!` and borrowed
|
|
602
|
-
indexing/projection work **uniformly** (verified by the matrix-multiply inner loop
|
|
603
|
-
in the `verify` diff-test, which lowers to `lean_array_get_borrowed`).
|
|
604
|
-
- **Control flow**: self- and mutual-recursion plus non-cyclic tail chains are loop-ified
|
|
605
|
-
through a unified trampoline (`__tc` cores returning `tc` thunks); join points are inlined so
|
|
606
|
-
`continue` stays lexically valid.
|
|
607
|
-
- **IO**: stdout/stderr/stdin (real fd, sync read), `IO.Error` formatting + entry-point
|
|
608
|
-
`uncaught exception:` reporting, `@[init]`/`initialize` module-init chain, `panic!`
|
|
609
|
-
semantics (print to stderr, return the `Inhabited` default, continue), `dbgTrace`/
|
|
610
|
-
`dbgTraceIfShared`/`dbgSleep`.
|
|
611
|
-
|
|
612
|
-
### Where leanfran is _more_ robust than the C backend
|
|
613
|
-
|
|
614
|
-
- **Closure-boundary TCO.** The native C backend does not TCO tail calls that cross a
|
|
615
|
-
closure application (CPS/continuation loops), so programs like `cpsCount`/`cpsSum`
|
|
616
|
-
abort with `Stack overflow detected` around N≈1e5. leanfran lowers tail `.ap` to an
|
|
617
|
-
apply-thunk and runs them in constant JS stack. The diff-tests therefore check value
|
|
618
|
-
equality at a native-safe N, and the no-overflow property at N=1e6 on the node side only.
|
|
619
|
-
|
|
620
|
-
### Fail-loud invariant
|
|
621
|
-
|
|
622
|
-
Any extern the runtime does not provide is a **hard generation error** (exit 254,
|
|
623
|
-
no output written) — never a silent wrong answer or a dangling runtime call. The
|
|
624
|
-
error names the exact missing C symbols so they can be implemented and retried. The
|
|
625
|
-
CLI checks the symbols against `LeanTs/RuntimeExterns.lean`, which `make gen-externs`
|
|
626
|
-
generates from the runtime's exports. `test-diff.sh` asserts an unmapped extern
|
|
627
|
-
(`lean_io_get_random_bytes`) is rejected while a mapped root generates.
|
|
628
|
-
|
|
629
|
-
### Out of scope (intentionally left fail-loud) and why
|
|
630
|
-
|
|
631
|
-
These cannot be matched byte-for-byte against the native oracle, so mapping them would
|
|
632
|
-
trade an honest hard error for a silent divergence:
|
|
633
|
-
|
|
634
|
-
- **Task / `IO.asTask` / `IO.Promise` concurrency** (`lean_task_*`, `lean_io_*_task`,
|
|
635
|
-
`lean_io_promise_*`): native runs a real OS thread pool with genuine parallelism and
|
|
636
|
-
scheduler-dependent interleaving/`waitAny`/cancellation timing; Node is single-threaded,
|
|
637
|
-
so any emulation observes a _different_ ordering wherever ordering is observable.
|
|
638
|
-
- **Filesystem metadata / enumeration** (`lean_io_metadata`, `lean_io_symlink_metadata`,
|
|
639
|
-
`lean_io_read_dir`, `lean_io_realpath`): `accessed`/`modified` timestamps, `numLinks`,
|
|
640
|
-
directory order and symlink canonicalization are host/OS state, not program state, so
|
|
641
|
-
they vary between runs and machines.
|
|
642
|
-
- **`IO.getRandomBytes`** (`lean_io_get_random_bytes`): by definition nondeterministic
|
|
643
|
-
CSPRNG output; can never equal a fixed oracle run (used as the negative-test sentinel).
|
|
644
|
-
- **Raw-mode interactive TTY** (`lean_io_prim_handle_is_tty` and termios raw mode):
|
|
645
|
-
depends on a live terminal device and real-time keystrokes; there is no reproducible
|
|
646
|
-
input stream to diff. (Pipe/redirect/file stdin is supported and tested.)
|
|
647
|
-
- **Unsafe pointer identity** (`ptrAddrUnsafe`/`isExclusiveUnsafe`/`ptrEq` used to _distinguish_
|
|
648
|
-
defeq values): real addresses are nondeterministic. The **safe** wrappers (`withPtrAddr`/
|
|
649
|
-
`withPtrEq`/`withPtrEqDecEq`) are proven address-independent and are pure Lean (they do
|
|
650
|
-
not even reach the extern), so they are faithful; the raw `lean_ptr_addr`/
|
|
651
|
-
`lean_is_exclusive_obj` are mapped to address-independent constants (`0n` / non-exclusive)
|
|
652
|
-
for the safe surface only.
|
|
653
|
-
|
|
654
|
-
## Remaining honest gaps vs EmitC
|
|
655
40
|
|
|
656
|
-
|
|
657
|
-
agree at large N (leanfran is the more robust side); value equality holds at native-safe N.
|
|
658
|
-
- `Float32` transcendentals use double-precision `Math.*` narrowed via `Math.fround`,
|
|
659
|
-
whose rounding path differs from single-precision libm (`sinf`), so they can differ by
|
|
660
|
-
more than 1 ULP at f32; the `%f` 6-digit `toString` comparison absorbs this but direct
|
|
661
|
-
bit comparison is not claimed. `Float.scaleb` uses a `Math.pow(2,e)` approximation
|
|
662
|
-
untested at extreme exponents.
|
|
663
|
-
- The 32-bit `USize` profile is covered by a literal-comparison test only (a 64-bit host
|
|
664
|
-
cannot produce a native 32-bit reference); the default 64-bit profile is native-verified.
|
|
41
|
+
Commit `src/_lean/` and `.leanfran/blocks.json`. Run sync again when you change a block; `leanfran status --package .` checks whether generated code is current.
|
|
665
42
|
|
|
666
|
-
##
|
|
43
|
+
## Next steps
|
|
667
44
|
|
|
668
|
-
|
|
45
|
+
- [Full TypeScript guide](https://github.com/conao3/lean-leanfran/blob/master/docs/typescript-guide.md): schemas, host models, verification, CLI, runtime semantics and limitations.
|
|
46
|
+
- [Samples](https://github.com/conao3/lean-leanfran/blob/master/langs/TypeScript/samples/README.md), including a pricing API and step-by-step examples.
|
|
47
|
+
- [Development](https://github.com/conao3/lean-leanfran/blob/master/CONTRIBUTING.md) and [implementation notes](https://github.com/conao3/lean-leanfran/blob/master/docs/typescript-development.md).
|
package/package.json
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "leanfran",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Write and prove functions in Lean 4, run them as TypeScript: Lean blocks in TypeScript modules, Standard Schema for Lean types, TypeScript functions verified in Lean",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
|
-
"homepage": "https://github.com/conao3/lean-leanfran/tree/master/TypeScript#readme",
|
|
6
|
+
"homepage": "https://github.com/conao3/lean-leanfran/tree/master/langs/TypeScript#readme",
|
|
7
7
|
"bugs": "https://github.com/conao3/lean-leanfran/issues",
|
|
8
8
|
"repository": {
|
|
9
9
|
"type": "git",
|
|
10
10
|
"url": "git+https://github.com/conao3/lean-leanfran.git",
|
|
11
|
-
"directory": "TypeScript"
|
|
11
|
+
"directory": "langs/TypeScript"
|
|
12
12
|
},
|
|
13
13
|
"keywords": [
|
|
14
14
|
"lean4",
|
|
@@ -52,8 +52,8 @@
|
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"@hono/standard-validator": "0.4.1",
|
|
54
54
|
"@types/node": "^26.6.6",
|
|
55
|
-
"hono": "4.13.
|
|
56
|
-
"vite-plus": "1.
|
|
55
|
+
"hono": "4.13.18",
|
|
56
|
+
"vite-plus": "1.6.0",
|
|
57
57
|
"zod": "4.6.7"
|
|
58
58
|
},
|
|
59
59
|
"peerDependencies": {
|
|
File without changes
|