leanfran 0.6.0__tar.gz → 0.7.0__tar.gz

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.
@@ -0,0 +1,47 @@
1
+ /result
2
+ /.claude-dev/
3
+ /langs/Rust/result
4
+ /langs/Rust/.lake/
5
+ /langs/Rust/target/
6
+ /langs/Rust/test-out/
7
+ /langs/Rust/**/.leanfran/workspace/
8
+ /langs/Rust/.lake-aeneas/
9
+ /langs/Python/result
10
+ /langs/Python/.lake/
11
+ /langs/Python/test-out/
12
+ /langs/Python/**/.leanfran/
13
+ /langs/Python/**/__pycache__/
14
+ /langs/Python/.venv/
15
+ /langs/Python/dist/
16
+ /langs/TypeScript/.lake
17
+ /langs/TypeScript/**/*.olean
18
+ /langs/TypeScript/result
19
+ /langs/TypeScript/node_modules
20
+ /langs/TypeScript/dist
21
+ /langs/TypeScript/test-out
22
+ /langs/TypeScript/**/.leanfran/workspace/
23
+ /langs/TypeScript/test/embed/app/node_modules
24
+ /langs/TypeScript/test/verify/app/node_modules
25
+ /langs/TypeScript/samples/**/node_modules
26
+ /langs/TypeScript/samples/**/.lake
27
+ /langs/Clojure/result
28
+ /langs/Clojure/.lake/
29
+ /langs/Clojure/**/.leanfran/
30
+ /langs/Clojure/**/.cpcache/
31
+ /langs/Clojure/.nrepl-port
32
+ /langs/Clojure/.lsp/
33
+ /langs/Clojure/.clj-kondo/*
34
+ !/langs/Clojure/.clj-kondo/config.edn
35
+ /langs/Clojure/test-out/
36
+ /langs/Clojure/target/
37
+ !/langs/Clojure/resources/clj-kondo.exports/io.github.conao3/
38
+ /langs/PHP/.lake/
39
+ /langs/PHP/vendor/
40
+ /langs/PHP/test-out/
41
+ /langs/PHP/samples/*/composer.lock
42
+ /langs/PHP/samples/*/lean/.lake/
43
+ /langs/PHP/samples/*/vendor/
44
+ /Rust/**/target/
45
+ /Rust/**/.lake/
46
+ /Rust/**/.lake-aeneas/
47
+ /Rust/**/test-out/
@@ -0,0 +1,62 @@
1
+ Metadata-Version: 2.5
2
+ Name: leanfran
3
+ Version: 0.7.0
4
+ Summary: Run Lean 4 code as Python: a runtime for code generated from Lean's IR, Lean blocks in Python files, and pydantic models for Lean types
5
+ Project-URL: Repository, https://github.com/conao3/lean-leanfran/tree/master/langs/Python
6
+ License-Expression: Apache-2.0
7
+ Classifier: Framework :: Pydantic :: 2
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Topic :: Software Development :: Compilers
10
+ Requires-Python: >=3.12
11
+ Requires-Dist: pydantic>=2.11
12
+ Description-Content-Type: text/markdown
13
+
14
+ # Python
15
+
16
+ [leanfran](https://github.com/conao3/lean-leanfran/blob/master/README.md) for Python: write Lean blocks with `lean(...)`, expose Lean types as pydantic models, and verify supported Python functions against Lean specifications.
17
+
18
+ ## Install
19
+
20
+ ```sh
21
+ uv add leanfran
22
+ nix profile install 'github:conao3/lean-leanfran#python'
23
+ ```
24
+
25
+ Generation also requires Lean 4.35.0 (`lean` and `lake`) on `PATH`. Generated modules run with the Python package and pydantic.
26
+
27
+ ## First Lean block
28
+
29
+ Create `src/myapp/__init__.py` and put this in `src/myapp/arith.py`:
30
+
31
+ ```python
32
+ from leanfran import lean
33
+
34
+ arith = lean("arith", r"""
35
+ def double (n : Nat) : Nat := n + n
36
+
37
+ theorem double_eq (n : Nat) : double n = 2 * n := by
38
+ unfold double; omega
39
+ """)
40
+ ```
41
+
42
+ Generate the Python modules:
43
+
44
+ ```sh
45
+ leanfran sync --package src/myapp
46
+ ```
47
+
48
+ Then call the function from your application:
49
+
50
+ ```python
51
+ from myapp.arith import arith
52
+
53
+ assert arith.double(21) == 42
54
+ ```
55
+
56
+ Commit `src/myapp/_lean/` with your package, and add `.leanfran/` to `.gitignore`. Run sync again when you change a Lean block.
57
+
58
+ ## Next steps
59
+
60
+ - [Full Python guide](https://github.com/conao3/lean-leanfran/blob/master/docs/python-guide.md): pydantic models, JSON, `@model`, verification, CLI and limitations.
61
+ - [Samples](https://github.com/conao3/lean-leanfran/blob/master/langs/Python/samples/README.md), including pricing, word count and step-by-step examples.
62
+ - [Development](https://github.com/conao3/lean-leanfran/blob/master/CONTRIBUTING.md) and [implementation notes](https://github.com/conao3/lean-leanfran/blob/master/docs/python-development.md).
@@ -0,0 +1,49 @@
1
+ # Python
2
+
3
+ [leanfran](https://github.com/conao3/lean-leanfran/blob/master/README.md) for Python: write Lean blocks with `lean(...)`, expose Lean types as pydantic models, and verify supported Python functions against Lean specifications.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ uv add leanfran
9
+ nix profile install 'github:conao3/lean-leanfran#python'
10
+ ```
11
+
12
+ Generation also requires Lean 4.35.0 (`lean` and `lake`) on `PATH`. Generated modules run with the Python package and pydantic.
13
+
14
+ ## First Lean block
15
+
16
+ Create `src/myapp/__init__.py` and put this in `src/myapp/arith.py`:
17
+
18
+ ```python
19
+ from leanfran import lean
20
+
21
+ arith = lean("arith", r"""
22
+ def double (n : Nat) : Nat := n + n
23
+
24
+ theorem double_eq (n : Nat) : double n = 2 * n := by
25
+ unfold double; omega
26
+ """)
27
+ ```
28
+
29
+ Generate the Python modules:
30
+
31
+ ```sh
32
+ leanfran sync --package src/myapp
33
+ ```
34
+
35
+ Then call the function from your application:
36
+
37
+ ```python
38
+ from myapp.arith import arith
39
+
40
+ assert arith.double(21) == 42
41
+ ```
42
+
43
+ Commit `src/myapp/_lean/` with your package, and add `.leanfran/` to `.gitignore`. Run sync again when you change a Lean block.
44
+
45
+ ## Next steps
46
+
47
+ - [Full Python guide](https://github.com/conao3/lean-leanfran/blob/master/docs/python-guide.md): pydantic models, JSON, `@model`, verification, CLI and limitations.
48
+ - [Samples](https://github.com/conao3/lean-leanfran/blob/master/langs/Python/samples/README.md), including pricing, word count and step-by-step examples.
49
+ - [Development](https://github.com/conao3/lean-leanfran/blob/master/CONTRIBUTING.md) and [implementation notes](https://github.com/conao3/lean-leanfran/blob/master/docs/python-development.md).
@@ -0,0 +1,14 @@
1
+ from pathlib import Path
2
+
3
+ from hatchling.builders.hooks.plugin.interface import BuildHookInterface
4
+
5
+
6
+ class CustomBuildHook(BuildHookInterface):
7
+ def initialize(self, version, build_data):
8
+ root = Path(self.root)
9
+ license_file = root / "LICENSE"
10
+ if not license_file.is_file():
11
+ license_file = root.parents[1] / "LICENSE"
12
+ if not license_file.is_file():
13
+ raise FileNotFoundError("The distribution requires the repository LICENSE")
14
+ build_data["force_include"][str(license_file)] = "LICENSE"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "leanfran"
3
- version = "0.6.0"
3
+ version = "0.7.0"
4
4
  description = "Run Lean 4 code as Python: a runtime for code generated from Lean's IR, Lean blocks in Python files, and pydantic models for Lean types"
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -13,7 +13,7 @@ classifiers = [
13
13
  ]
14
14
 
15
15
  [project.urls]
16
- Repository = "https://github.com/conao3/lean-leanfran/tree/master/Python"
16
+ Repository = "https://github.com/conao3/lean-leanfran/tree/master/langs/Python"
17
17
 
18
18
  [project.scripts]
19
19
  leanfran = "leanfran.cli:main"
@@ -25,11 +25,13 @@ dev = ["pytest>=8", "pytest-icdiff>=0.9", "hypothesis>=6", "fastapi>=0.115", "ht
25
25
  requires = ["hatchling"]
26
26
  build-backend = "hatchling.build"
27
27
 
28
+ [tool.hatch.build.hooks.custom]
29
+
28
30
  [tool.hatch.build.targets.wheel]
29
31
  packages = ["src/leanfran"]
30
32
 
31
33
  [tool.hatch.build.targets.sdist]
32
- include = ["/src/leanfran", "/README.md", "/LICENSE", "/pyproject.toml"]
34
+ include = ["/src/leanfran", "/README.md", "/pyproject.toml", "/hatch_build.py"]
33
35
 
34
36
  [tool.ruff]
35
37
  line-length = 120
leanfran-0.6.0/.gitignore DELETED
@@ -1,8 +0,0 @@
1
- /result
2
- /.lake/
3
- /test-out/
4
- /.claude-dev/
5
- **/.leanfran/
6
- __pycache__/
7
- /.venv/
8
- /dist/
leanfran-0.6.0/PKG-INFO DELETED
@@ -1,388 +0,0 @@
1
- Metadata-Version: 2.5
2
- Name: leanfran
3
- Version: 0.6.0
4
- Summary: Run Lean 4 code as Python: a runtime for code generated from Lean's IR, Lean blocks in Python files, and pydantic models for Lean types
5
- Project-URL: Repository, https://github.com/conao3/lean-leanfran/tree/master/Python
6
- License-Expression: Apache-2.0
7
- License-File: LICENSE
8
- Classifier: Framework :: Pydantic :: 2
9
- Classifier: Programming Language :: Python :: 3
10
- Classifier: Topic :: Software Development :: Compilers
11
- Requires-Python: >=3.12
12
- Requires-Dist: pydantic>=2.11
13
- Description-Content-Type: text/markdown
14
-
15
- <p align="center">
16
- <img src="https://raw.githubusercontent.com/conao3/lean-leanfran/master/Python/docs/assets/banner.png" alt="leanfran: write and prove functions in Lean 4, run them as Python" width="880">
17
- </p>
18
-
19
- <p align="center"><strong>Write and prove functions in Lean 4, run them as Python</strong></p>
20
-
21
- <p align="center">
22
- <a href="https://pypi.org/project/leanfran/"><img src="https://img.shields.io/pypi/v/leanfran" alt="PyPI version"></a>
23
- <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>
24
- <a href="https://github.com/conao3/lean-leanfran/blob/master/Python/LICENSE"><img src="https://img.shields.io/github/license/conao3/lean-leanfran" alt="License: Apache-2.0"></a>
25
- <a href="https://github.com/conao3/lean-leanfran/blob/master/Python/pyproject.toml"><img src="https://img.shields.io/badge/Python-%3E%3D3.12-blue" alt="Python >=3.12"></a>
26
- <a href="https://github.com/conao3/lean-leanfran/blob/master/Python/lean-toolchain"><img src="https://img.shields.io/badge/Lean-v4.35.0-blue" alt="Lean v4.35.0"></a>
27
- <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>
28
- </p>
29
-
30
- <p align="center">
31
- <a href="#install">Install</a> ·
32
- <a href="#lean-blocks">Lean blocks</a> ·
33
- <a href="#values">Values</a> ·
34
- <a href="#verifying-python-functions">Verifying Python functions</a> ·
35
- <a href="#examples">Examples</a> ·
36
- <a href="#performance">Performance</a> ·
37
- <a href="https://pypi.org/project/leanfran/">PyPI</a>
38
- </p>
39
-
40
- # leanfran
41
-
42
- leanfran lets you write functions in Lean 4, prove theorems about them, and call them from Python
43
- with pydantic models as arguments and results. The PyPI distribution is `leanfran`; you import
44
- it as `leanfran`.
45
-
46
- ```python
47
- from pydantic import BaseModel, Field
48
- from leanfran import lean
49
-
50
-
51
- class LineItem(BaseModel):
52
- sku: str
53
- qty: int = Field(ge=1)
54
- unitPrice: int = Field(ge=0)
55
-
56
-
57
- pricing = lean("pricing", r"""
58
- inductive Discount where
59
- | none
60
- | percent (p : Nat) (h : p ≤ 100)
61
- | fixed (amount : Nat)
62
-
63
- def subtotal (items : List LineItem) : Nat :=
64
- items.foldl (fun acc i => acc + i.qty * i.unitPrice) 0
65
-
66
- def total (items : List LineItem) (d : Discount) : Nat :=
67
- match d with
68
- | .none => subtotal items
69
- | .percent p _ => subtotal items - subtotal items * p / 100
70
- | .fixed a => subtotal items - a
71
-
72
- theorem total_le (items : List LineItem) (d : Discount) : total items d ≤ subtotal items := by
73
- unfold total; split <;> omega
74
- """, models=[LineItem])
75
-
76
- items = [LineItem(sku="a", qty=2, unitPrice=100)]
77
- pricing.total(items, pricing.Discount.percent(p=10)) # 180
78
- pricing.Discount.percent(p=150) # pydantic.ValidationError: p: Input should be less than or equal to 100
79
- ```
80
-
81
- - `leanfran sync` checks the proofs with Lake and compiles the Lean code from Lean's IR to plain
82
- Python. It writes the generated modules to `<package>/_lean/`, and they ship with your package.
83
- To run them you need the `leanfran` wheel and pydantic. You do not need Lean.
84
- - The generated Python computes what the C backend computes. A diff test runs the same Lean
85
- programs natively and as Python and compares the output byte for byte. The generated code keeps
86
- reference counting, so `Array` updates happen in place as in C.
87
- - Lean structures and inductive types become pydantic models. A proof field (`h : p ≤ 100`) becomes
88
- a validator that runs a decision procedure compiled from the proposition, so every value that
89
- reaches Lean satisfies the invariants the proofs rely on. A comparison with a constant also becomes
90
- an annotated-types constraint (`Le(100)`) that pydantic-core checks and the JSON Schema shows. The
91
- JSON of the models is the JSON of Lean's `deriving ToJson, FromJson`.
92
- - Lean code can use your own pydantic models (`models=[...]`). Their field constraints
93
- (`ge`, `gt`, `le`, `lt`, `min_length`, `max_length`) become proof fields that Lean proofs may assume.
94
- - The models work wherever pydantic does: `TypeAdapter`, `model_validate_json`, JSON Schema, FastAPI
95
- request and response types.
96
- - `@model` binds a plain Python function to Lean specifications. `leanfran check` translates the
97
- function to Lean and judges your proofs ([Verifying Python functions](#verifying-python-functions)).
98
-
99
- ## Install
100
-
101
- The Python package and the Lean CLI:
102
-
103
- ```sh
104
- uv add leanfran # the runtime, lean(), leanfran sync
105
- nix profile install 'github:conao3/lean-leanfran?dir=Python' # the Lean CLI `leanfran-python`
106
- ```
107
-
108
- `leanfran sync` also needs `lake` and the Lean toolchain of `lean-toolchain` (v4.35.0) on `PATH`.
109
-
110
- ## Lean blocks
111
-
112
- `lean(name, source, *, imports=(), uses=(), models=())` defines a Lean block of the calling module,
113
- which must belong to a package. The block's definitions live in the namespace
114
- `LeanPythonEmbed.<module>.<name>`. The returned module exposes them under their names relative to it
115
- (`Discount.percent`, `total`).
116
-
117
- ```sh
118
- leanfran sync --package src/myapp
119
- ```
120
-
121
- `leanfran sync` imports every module of the package, writes each block to a Lake workspace in
122
- `.leanfran/workspace/`, builds it, and generates `src/myapp/_lean/<module>__<name>.py` and
123
- `src/myapp/_lean/blocks.json`. Lean errors point at the Python file:
124
-
125
- ```
126
- leanfran: src/myapp/m.py:6: error: (lean block m, Lean 4:28) Tactic `rfl` failed: ...
127
- ```
128
-
129
- Add `.leanfran/` to `.gitignore` and commit `<package>/_lean/`.
130
-
131
- At run time `lean(...)` compares a hash of the block (its source, imports, uses, the Lean structures
132
- of its models and the generator version) with `blocks.json`. If the block changed since the last
133
- sync, it raises `LeanBlockStale`. With `LEANFRAN_PYTHON_AUTO_SYNC=1` it runs `leanfran sync` instead.
134
-
135
- - `imports=["Std.Data.HashMap"]`: Lean modules to import.
136
- - `uses=["geometry"]`: other blocks of the module (or `"pkg.mod:name"`) to import and open. The
137
- block shares their types and does not generate them again.
138
- - `models=[LineItem]`: pydantic models available as Lean structures (below).
139
-
140
- ## Values
141
-
142
- | Lean | Python |
143
- |---|---|
144
- | `Nat` | `int` (`leanfran.types.Nat` = `Annotated[int, Ge(0)]`) |
145
- | `Int` | `int` |
146
- | `UInt8` … `UInt64`, `USize`, `Int8` … `Int64` | `int` with the range as `Ge`/`Le` |
147
- | `Fin n` | `Annotated[int, Ge(0), Lt(n)]` |
148
- | `Bool` | `bool` |
149
- | `Char` | `str` of one character |
150
- | `String` | `str` |
151
- | `Float`, `Float32` | `float` |
152
- | `Unit` | `None` |
153
- | `Option α` | `α \| None` |
154
- | `List α`, `Array α` | `list[α]` |
155
- | `α × β` | `tuple[α, β]` |
156
- | `{x : α // p x}` | `Annotated[α, AfterValidator(p)]` |
157
- | structure | a frozen, strict pydantic model |
158
- | inductive type, constructors without arguments | `enum.StrEnum` |
159
- | other inductive type | a model per constructor, subclasses of the type's class |
160
- | `IO α` | `α`; an `IO.Error` is raised as `LeanIOError` (an `OSError`) |
161
-
162
- The generated functions check arguments while they convert them: `pub.double(-1)` raises
163
- `ValidationError` with the location of the bad value. Constants are functions without arguments
164
- (`answer()`).
165
-
166
- Constructors and structures take keyword arguments (`Shape.rect(width=1, height=2)`); unnamed
167
- constructor arguments are `a0`, `a1`, …. Inductive values work with `match`:
168
-
169
- ```python
170
- match shape:
171
- case geometry.Shape.rect(width=w, height=h):
172
- ...
173
- ```
174
-
175
- ### JSON
176
-
177
- The JSON of a generated model is the JSON of Lean's derived `ToJson`: a structure is an object, a
178
- constructor without arguments is its name (`"dot"`), a constructor with named arguments is
179
- `{"rect": {"width": 1, "height": 2}}`, with unnamed arguments `{"num": 7}` or `{"pair": [1, "x"]}`.
180
- `tests/test_json.py` compares the generated models with a native Lean program that prints `toJson`.
181
-
182
- ### Your pydantic models in Lean
183
-
184
- `models=[LineItem]` writes a Lean structure for each model (and the models its fields use) to the
185
- namespace `LeanPythonModels.<python module>`, and the block opens that namespace:
186
-
187
- ```lean
188
- structure LineItem where
189
- sku : String
190
- qty : Nat
191
- qty_ge : 1 ≤ qty
192
- unitPrice : Nat
193
- ```
194
-
195
- `int` with a lower bound of at least 0 becomes `Nat`; the other bounds and `min_length`/`max_length`
196
- become proof fields. Field types:
197
-
198
- - `int`, `bool`, `str`, `float`, `list[T]`, `tuple[...]`, `T | None`, other models
199
- - enums: an inductive type `LeanPythonModels.<module>.<Enum>` with a constructor per member
200
- - `Literal["a", "b"]`: `LeanPythonLiterals.<module>.<Model>_<field>`
201
- - unions of models: `LeanPythonUnions.<module>.<Model>_<field>`, a constructor per model holding it
202
- as `val`
203
-
204
- Lean proofs cannot assume `multiple_of`, `pattern` or validators; the structure's docstring lists
205
- them. Generated functions take and return your classes. Values that skipped validation
206
- (`model_construct`) go through validation again on the way to Lean.
207
-
208
- ## Verifying Python functions
209
-
210
- `@model` binds a typed, pure Python function to specifications written in a Lean block. The function
211
- stays ordinary Python. `leanfran check` translates it to Lean and checks your proofs, and
212
- `check_model` runs the same specifications as a Hypothesis property test.
213
-
214
- ```python
215
- from leanfran import lean
216
- from leanfran.verify import model
217
-
218
- spec = lean("spec", r"""
219
- def clampSpec (x lo hi : Int) : Int := max lo (min hi x)
220
- def ordered (_x lo hi : Int) : Bool := lo ≤ hi
221
- def inRange (_x lo hi : Int) (r : Int) : Bool := lo ≤ r && r ≤ hi
222
- """)
223
-
224
- @model(refines=spec.clampSpec, requires=spec.ordered, ensures={"in_range": spec.inRange})
225
- def clamp(x: int, lo: int, hi: int) -> int:
226
- if x < lo:
227
- return lo
228
- if x > hi:
229
- return hi
230
- return x
231
- ```
232
-
233
- `leanfran check --package calc` writes the translation and one obligation per specification:
234
-
235
- ```lean
236
- def LeanPythonModel.calc.calc.clamp (x : Int) (lo : Int) (hi : Int) : Int := Id.run do
237
- if ((decide (x < lo))) then
238
- return lo
239
- if ((decide (x > hi))) then
240
- return hi
241
- return x
242
-
243
- abbrev LeanPythonModel.calc.calc.clamp.obligation.refines : Prop :=
244
- ∀ (x : Int) (lo : Int) (hi : Int), ordered x lo hi = true → clamp x lo hi = clampSpec x lo hi
245
- ```
246
-
247
- Then it judges the theorems `<function>.proof.<label>` of `lean/Proofs/*.lean` next to
248
- `pyproject.toml`:
249
-
250
- ```lean
251
- import LeanPythonModel.calc.calc
252
- open LeanPythonEmbed.calc.spec.spec
253
- namespace LeanPythonModel.«calc».«calc»
254
-
255
- theorem clamp.proof.refines : clamp.obligation.refines := by
256
- intro x lo hi h
257
- simp only [ordered, decide_eq_true_eq] at h
258
- simp only [clamp, clampSpec]
259
- split <;> (try split) <;> simp_all <;> omega
260
- ```
261
-
262
- ```
263
- proved calc.calc:clamp refines
264
- proved calc.calc:clamp in_range
265
- sorry calc.calc:sum_to refines
266
- missing calc.calc:sum_abs nonneg
267
- ```
268
-
269
- Under `simp`, a `for` loop over a list becomes `List.foldl` (`forIn_pure_yield_eq_foldl`), so you
270
- prove a loop by induction on the list (`tests/verify/lean/Proofs/Calc.lean` proves `sum_abs`).
271
-
272
- The states:
273
-
274
- | state | meaning |
275
- |---|---|
276
- | `proved` | the theorem holds |
277
- | `sorry` | the proof uses `sorry` |
278
- | `axioms` | the proof uses non-standard axioms |
279
- | `failed` | the proof file does not build |
280
- | `missing` | no theorem for the obligation |
281
- | `mismatch` | the theorem states something else |
282
- | `unextracted` | the obligation's statement is not defined |
283
-
284
- With `--require proved`, `leanfran check` exits with 254 unless every obligation is proved. It
285
- writes the result to `leanfran.lock` with a hash of each function's source. `leanfran status`
286
- reads the lock file without Lean and marks changed functions `stale`.
287
-
288
- - `refines=s`: `f x = s x` (`Except.ok (s x)` for a function that may fail); `requires=p`: `p x = true →`
289
- before each obligation; `ensures={"label": q}`: `q x (f x) = true`. A function annotated `-> Nat`
290
- also gets `returns_nat` (`0 ≤ f x`).
291
- - The translation: `int` is `Int` (a `Nat` parameter is a `Nat` converted to `Int` on entry);
292
- statements become Lean `do` notation (`let mut`, `for`, `while`, `break`, `continue`, early
293
- `return`); indexing, `//`, `%`, `assert` and `raise` make the function return
294
- `Py.M α = Except Py.Exc α`, with Python's negative indices and floor division (`LeanPythonLib.Py`).
295
- Supported: `int`, `bool`, `str`, `float`, `list`, `tuple`, `T | None`, pydantic models (as the
296
- Lean structures of `models=`), `len`, `abs`, `min`, `max`, `sum`, list comprehensions, `append` on
297
- local lists, and calls of other `@model` functions of the module.
298
- - `check_model(f)` / `check_module(m)` generate arguments from the annotations (pydantic constraints
299
- included), skip those failing `requires`, and compare with `refines` and `ensures`.
300
-
301
- ## Examples
302
-
303
- [`samples/`](https://github.com/conao3/lean-leanfran/tree/master/Python/samples) holds Python packages with Lean
304
- blocks. `make samples` syncs each one, runs it, and compares the output with its `expected.txt`.
305
-
306
- | sample | shows |
307
- |---|---|
308
- | [word-count](https://github.com/conao3/lean-leanfran/tree/master/Python/samples/word-count) | strings and lists, a proof by induction |
309
- | [roman-numerals](https://github.com/conao3/lean-leanfran/tree/master/Python/samples/roman-numerals) | a round-trip theorem checked for every number below 1000 (`decide +kernel`) |
310
- | [todo-cli](https://github.com/conao3/lean-leanfran/tree/master/Python/samples/todo-cli) | an invariant over a list kept by every operation, JSON storage, tampered JSON rejected |
311
- | [pricing-api](https://github.com/conao3/lean-leanfran/tree/master/Python/samples/pricing-api) | FastAPI with a pydantic model and a Lean inductive type as request body, 422 for invalid input |
312
-
313
- [`samples/steps/`](https://github.com/conao3/lean-leanfran/tree/master/Python/samples/steps) introduces one
314
- feature at a time, from functions on `Nat` (01) to types shared between blocks with `uses=` (09).
315
-
316
- ## The CLI
317
-
318
- The Python package installs `leanfran`:
319
-
320
- ```
321
- leanfran sync --package <dir> [--leanfran-python <path>]
322
- leanfran check --package <dir> [--leanfran-python <path>] [--require proved]
323
- leanfran status --package <dir>
324
- ```
325
-
326
- `--leanfran-python` defaults to `$LEANFRAN_PYTHON_CLI`, then `leanfran-python` on `PATH`. The Lean CLI
327
- `leanfran-python` does the compilation:
328
-
329
- ```
330
- leanfran-python module generate --module-name <Name> [--roots <Name> ...] [--namespace <Name>]
331
- [--import <Name> ...] [--search-path <dir> ...] [--output-file <path>] [--internal-only]
332
- [--output json|text] [--type-module <Name>=<module> ...] [--model-module <Name>=<module> ...]
333
- [--batch <file>]
334
- leanfran-python obligations check --modules <Name> ... --obligations <file> [--search-path <dir> ...]
335
- leanfran-python --version | --generator-version | help
336
- ```
337
-
338
- `module generate` writes one Python module with the IR of the roots and of everything they call
339
- (Init and Std included), and public functions and types for the roots. It reports the definitions it
340
- cannot expose (polymorphic functions, functions over functions) as skipped. Both CLIs use the exit
341
- codes 0 success, 252 invalid parameters, 254 input that cannot be converted, 255 other errors.
342
-
343
- ## Performance
344
-
345
- `make bench` (CPython 3.14, x86_64; the native column is the C backend):
346
-
347
- | workload | n | Python (s) | native C (s) |
348
- |---|---|---|---|
349
- | `Array.push`, `set!`, sum | 10⁴ | 0.017 | 0.005 |
350
- | `Array.push`, `set!`, sum | 10⁵ | 0.179 | 0.006 |
351
- | `Array.push`, `set!`, sum | 10⁶ | 1.796 | 0.017 |
352
- | `fib` (loop) | 10⁵ | 0.176 | 0.074 |
353
- | `naiveFib` | 25 | 0.149 | 0.005 |
354
- | `String.push` | 10⁴ | 0.012 | 0.005 |
355
- | `String.push` | 10⁵ | 0.227 | 0.006 |
356
- | `Array.qsort` | 10⁵ | 1.929 | 0.020 |
357
-
358
- Passing 10⁴ models to a Lean function takes 0.036 s (pydantic's `TypeAdapter(list[Model])` validates
359
- 10⁴ dicts in 0.009 s).
360
-
361
- ## Development
362
-
363
- ```sh
364
- nix develop -c make check # treefmt, the diff tests against the C backend, pytest, the samples
365
- nix develop -c make bench
366
- ```
367
-
368
- - `LeanPython/EmitPy.lean`: IR → Python. `LeanPython/Marshal.lean`, `LeanPython/Generate.lean`: public
369
- types and functions. `LeanPython/Check.lean`: `obligations check`. `Main.lean`: the CLI.
370
- - `src/leanfran/runtime.py`, `io_externs.py`: the runtime (`lean_*` are the C names of Lean's
371
- externs). `marshal.py`, `types.py`: pydantic types. `embed.py`, `sync.py`, `models.py`, `cli.py`:
372
- `lean(...)` and `leanfran sync`. `verify.py`, `translate.py`, `check.py`: `@model` and
373
- `leanfran check`; `lean/LeanPythonLib/Py.lean` holds Python's semantics in Lean.
374
- - `LeanPythonTest/`: Lean programs of the tests; `test-diff.sh` runs `Vectors` and `Io` natively and
375
- as Python.
376
-
377
- ## Limitations
378
-
379
- - leanfran does not expose polymorphic functions, functions taking or returning functions, or
380
- `Thunk`/`Task`/`IO.Ref`/`ByteArray` in public signatures. They still run inside Lean code.
381
- - `Task`s run synchronously.
382
- - Building a `String` with `String.push` copies the string each time (Python `bytes`), so it grows
383
- quadratically.
384
- - The translation of Python functions covers the subset above; the guarantee is partial correctness.
385
-
386
- ## License
387
-
388
- [Apache-2.0](https://github.com/conao3/lean-leanfran/blob/master/Python/LICENSE)
leanfran-0.6.0/README.md DELETED
@@ -1,374 +0,0 @@
1
- <p align="center">
2
- <img src="https://raw.githubusercontent.com/conao3/lean-leanfran/master/Python/docs/assets/banner.png" alt="leanfran: write and prove functions in Lean 4, run them as Python" width="880">
3
- </p>
4
-
5
- <p align="center"><strong>Write and prove functions in Lean 4, run them as Python</strong></p>
6
-
7
- <p align="center">
8
- <a href="https://pypi.org/project/leanfran/"><img src="https://img.shields.io/pypi/v/leanfran" alt="PyPI version"></a>
9
- <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>
10
- <a href="https://github.com/conao3/lean-leanfran/blob/master/Python/LICENSE"><img src="https://img.shields.io/github/license/conao3/lean-leanfran" alt="License: Apache-2.0"></a>
11
- <a href="https://github.com/conao3/lean-leanfran/blob/master/Python/pyproject.toml"><img src="https://img.shields.io/badge/Python-%3E%3D3.12-blue" alt="Python >=3.12"></a>
12
- <a href="https://github.com/conao3/lean-leanfran/blob/master/Python/lean-toolchain"><img src="https://img.shields.io/badge/Lean-v4.35.0-blue" alt="Lean v4.35.0"></a>
13
- <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>
14
- </p>
15
-
16
- <p align="center">
17
- <a href="#install">Install</a> ·
18
- <a href="#lean-blocks">Lean blocks</a> ·
19
- <a href="#values">Values</a> ·
20
- <a href="#verifying-python-functions">Verifying Python functions</a> ·
21
- <a href="#examples">Examples</a> ·
22
- <a href="#performance">Performance</a> ·
23
- <a href="https://pypi.org/project/leanfran/">PyPI</a>
24
- </p>
25
-
26
- # leanfran
27
-
28
- leanfran lets you write functions in Lean 4, prove theorems about them, and call them from Python
29
- with pydantic models as arguments and results. The PyPI distribution is `leanfran`; you import
30
- it as `leanfran`.
31
-
32
- ```python
33
- from pydantic import BaseModel, Field
34
- from leanfran import lean
35
-
36
-
37
- class LineItem(BaseModel):
38
- sku: str
39
- qty: int = Field(ge=1)
40
- unitPrice: int = Field(ge=0)
41
-
42
-
43
- pricing = lean("pricing", r"""
44
- inductive Discount where
45
- | none
46
- | percent (p : Nat) (h : p ≤ 100)
47
- | fixed (amount : Nat)
48
-
49
- def subtotal (items : List LineItem) : Nat :=
50
- items.foldl (fun acc i => acc + i.qty * i.unitPrice) 0
51
-
52
- def total (items : List LineItem) (d : Discount) : Nat :=
53
- match d with
54
- | .none => subtotal items
55
- | .percent p _ => subtotal items - subtotal items * p / 100
56
- | .fixed a => subtotal items - a
57
-
58
- theorem total_le (items : List LineItem) (d : Discount) : total items d ≤ subtotal items := by
59
- unfold total; split <;> omega
60
- """, models=[LineItem])
61
-
62
- items = [LineItem(sku="a", qty=2, unitPrice=100)]
63
- pricing.total(items, pricing.Discount.percent(p=10)) # 180
64
- pricing.Discount.percent(p=150) # pydantic.ValidationError: p: Input should be less than or equal to 100
65
- ```
66
-
67
- - `leanfran sync` checks the proofs with Lake and compiles the Lean code from Lean's IR to plain
68
- Python. It writes the generated modules to `<package>/_lean/`, and they ship with your package.
69
- To run them you need the `leanfran` wheel and pydantic. You do not need Lean.
70
- - The generated Python computes what the C backend computes. A diff test runs the same Lean
71
- programs natively and as Python and compares the output byte for byte. The generated code keeps
72
- reference counting, so `Array` updates happen in place as in C.
73
- - Lean structures and inductive types become pydantic models. A proof field (`h : p ≤ 100`) becomes
74
- a validator that runs a decision procedure compiled from the proposition, so every value that
75
- reaches Lean satisfies the invariants the proofs rely on. A comparison with a constant also becomes
76
- an annotated-types constraint (`Le(100)`) that pydantic-core checks and the JSON Schema shows. The
77
- JSON of the models is the JSON of Lean's `deriving ToJson, FromJson`.
78
- - Lean code can use your own pydantic models (`models=[...]`). Their field constraints
79
- (`ge`, `gt`, `le`, `lt`, `min_length`, `max_length`) become proof fields that Lean proofs may assume.
80
- - The models work wherever pydantic does: `TypeAdapter`, `model_validate_json`, JSON Schema, FastAPI
81
- request and response types.
82
- - `@model` binds a plain Python function to Lean specifications. `leanfran check` translates the
83
- function to Lean and judges your proofs ([Verifying Python functions](#verifying-python-functions)).
84
-
85
- ## Install
86
-
87
- The Python package and the Lean CLI:
88
-
89
- ```sh
90
- uv add leanfran # the runtime, lean(), leanfran sync
91
- nix profile install 'github:conao3/lean-leanfran?dir=Python' # the Lean CLI `leanfran-python`
92
- ```
93
-
94
- `leanfran sync` also needs `lake` and the Lean toolchain of `lean-toolchain` (v4.35.0) on `PATH`.
95
-
96
- ## Lean blocks
97
-
98
- `lean(name, source, *, imports=(), uses=(), models=())` defines a Lean block of the calling module,
99
- which must belong to a package. The block's definitions live in the namespace
100
- `LeanPythonEmbed.<module>.<name>`. The returned module exposes them under their names relative to it
101
- (`Discount.percent`, `total`).
102
-
103
- ```sh
104
- leanfran sync --package src/myapp
105
- ```
106
-
107
- `leanfran sync` imports every module of the package, writes each block to a Lake workspace in
108
- `.leanfran/workspace/`, builds it, and generates `src/myapp/_lean/<module>__<name>.py` and
109
- `src/myapp/_lean/blocks.json`. Lean errors point at the Python file:
110
-
111
- ```
112
- leanfran: src/myapp/m.py:6: error: (lean block m, Lean 4:28) Tactic `rfl` failed: ...
113
- ```
114
-
115
- Add `.leanfran/` to `.gitignore` and commit `<package>/_lean/`.
116
-
117
- At run time `lean(...)` compares a hash of the block (its source, imports, uses, the Lean structures
118
- of its models and the generator version) with `blocks.json`. If the block changed since the last
119
- sync, it raises `LeanBlockStale`. With `LEANFRAN_PYTHON_AUTO_SYNC=1` it runs `leanfran sync` instead.
120
-
121
- - `imports=["Std.Data.HashMap"]`: Lean modules to import.
122
- - `uses=["geometry"]`: other blocks of the module (or `"pkg.mod:name"`) to import and open. The
123
- block shares their types and does not generate them again.
124
- - `models=[LineItem]`: pydantic models available as Lean structures (below).
125
-
126
- ## Values
127
-
128
- | Lean | Python |
129
- |---|---|
130
- | `Nat` | `int` (`leanfran.types.Nat` = `Annotated[int, Ge(0)]`) |
131
- | `Int` | `int` |
132
- | `UInt8` … `UInt64`, `USize`, `Int8` … `Int64` | `int` with the range as `Ge`/`Le` |
133
- | `Fin n` | `Annotated[int, Ge(0), Lt(n)]` |
134
- | `Bool` | `bool` |
135
- | `Char` | `str` of one character |
136
- | `String` | `str` |
137
- | `Float`, `Float32` | `float` |
138
- | `Unit` | `None` |
139
- | `Option α` | `α \| None` |
140
- | `List α`, `Array α` | `list[α]` |
141
- | `α × β` | `tuple[α, β]` |
142
- | `{x : α // p x}` | `Annotated[α, AfterValidator(p)]` |
143
- | structure | a frozen, strict pydantic model |
144
- | inductive type, constructors without arguments | `enum.StrEnum` |
145
- | other inductive type | a model per constructor, subclasses of the type's class |
146
- | `IO α` | `α`; an `IO.Error` is raised as `LeanIOError` (an `OSError`) |
147
-
148
- The generated functions check arguments while they convert them: `pub.double(-1)` raises
149
- `ValidationError` with the location of the bad value. Constants are functions without arguments
150
- (`answer()`).
151
-
152
- Constructors and structures take keyword arguments (`Shape.rect(width=1, height=2)`); unnamed
153
- constructor arguments are `a0`, `a1`, …. Inductive values work with `match`:
154
-
155
- ```python
156
- match shape:
157
- case geometry.Shape.rect(width=w, height=h):
158
- ...
159
- ```
160
-
161
- ### JSON
162
-
163
- The JSON of a generated model is the JSON of Lean's derived `ToJson`: a structure is an object, a
164
- constructor without arguments is its name (`"dot"`), a constructor with named arguments is
165
- `{"rect": {"width": 1, "height": 2}}`, with unnamed arguments `{"num": 7}` or `{"pair": [1, "x"]}`.
166
- `tests/test_json.py` compares the generated models with a native Lean program that prints `toJson`.
167
-
168
- ### Your pydantic models in Lean
169
-
170
- `models=[LineItem]` writes a Lean structure for each model (and the models its fields use) to the
171
- namespace `LeanPythonModels.<python module>`, and the block opens that namespace:
172
-
173
- ```lean
174
- structure LineItem where
175
- sku : String
176
- qty : Nat
177
- qty_ge : 1 ≤ qty
178
- unitPrice : Nat
179
- ```
180
-
181
- `int` with a lower bound of at least 0 becomes `Nat`; the other bounds and `min_length`/`max_length`
182
- become proof fields. Field types:
183
-
184
- - `int`, `bool`, `str`, `float`, `list[T]`, `tuple[...]`, `T | None`, other models
185
- - enums: an inductive type `LeanPythonModels.<module>.<Enum>` with a constructor per member
186
- - `Literal["a", "b"]`: `LeanPythonLiterals.<module>.<Model>_<field>`
187
- - unions of models: `LeanPythonUnions.<module>.<Model>_<field>`, a constructor per model holding it
188
- as `val`
189
-
190
- Lean proofs cannot assume `multiple_of`, `pattern` or validators; the structure's docstring lists
191
- them. Generated functions take and return your classes. Values that skipped validation
192
- (`model_construct`) go through validation again on the way to Lean.
193
-
194
- ## Verifying Python functions
195
-
196
- `@model` binds a typed, pure Python function to specifications written in a Lean block. The function
197
- stays ordinary Python. `leanfran check` translates it to Lean and checks your proofs, and
198
- `check_model` runs the same specifications as a Hypothesis property test.
199
-
200
- ```python
201
- from leanfran import lean
202
- from leanfran.verify import model
203
-
204
- spec = lean("spec", r"""
205
- def clampSpec (x lo hi : Int) : Int := max lo (min hi x)
206
- def ordered (_x lo hi : Int) : Bool := lo ≤ hi
207
- def inRange (_x lo hi : Int) (r : Int) : Bool := lo ≤ r && r ≤ hi
208
- """)
209
-
210
- @model(refines=spec.clampSpec, requires=spec.ordered, ensures={"in_range": spec.inRange})
211
- def clamp(x: int, lo: int, hi: int) -> int:
212
- if x < lo:
213
- return lo
214
- if x > hi:
215
- return hi
216
- return x
217
- ```
218
-
219
- `leanfran check --package calc` writes the translation and one obligation per specification:
220
-
221
- ```lean
222
- def LeanPythonModel.calc.calc.clamp (x : Int) (lo : Int) (hi : Int) : Int := Id.run do
223
- if ((decide (x < lo))) then
224
- return lo
225
- if ((decide (x > hi))) then
226
- return hi
227
- return x
228
-
229
- abbrev LeanPythonModel.calc.calc.clamp.obligation.refines : Prop :=
230
- ∀ (x : Int) (lo : Int) (hi : Int), ordered x lo hi = true → clamp x lo hi = clampSpec x lo hi
231
- ```
232
-
233
- Then it judges the theorems `<function>.proof.<label>` of `lean/Proofs/*.lean` next to
234
- `pyproject.toml`:
235
-
236
- ```lean
237
- import LeanPythonModel.calc.calc
238
- open LeanPythonEmbed.calc.spec.spec
239
- namespace LeanPythonModel.«calc».«calc»
240
-
241
- theorem clamp.proof.refines : clamp.obligation.refines := by
242
- intro x lo hi h
243
- simp only [ordered, decide_eq_true_eq] at h
244
- simp only [clamp, clampSpec]
245
- split <;> (try split) <;> simp_all <;> omega
246
- ```
247
-
248
- ```
249
- proved calc.calc:clamp refines
250
- proved calc.calc:clamp in_range
251
- sorry calc.calc:sum_to refines
252
- missing calc.calc:sum_abs nonneg
253
- ```
254
-
255
- Under `simp`, a `for` loop over a list becomes `List.foldl` (`forIn_pure_yield_eq_foldl`), so you
256
- prove a loop by induction on the list (`tests/verify/lean/Proofs/Calc.lean` proves `sum_abs`).
257
-
258
- The states:
259
-
260
- | state | meaning |
261
- |---|---|
262
- | `proved` | the theorem holds |
263
- | `sorry` | the proof uses `sorry` |
264
- | `axioms` | the proof uses non-standard axioms |
265
- | `failed` | the proof file does not build |
266
- | `missing` | no theorem for the obligation |
267
- | `mismatch` | the theorem states something else |
268
- | `unextracted` | the obligation's statement is not defined |
269
-
270
- With `--require proved`, `leanfran check` exits with 254 unless every obligation is proved. It
271
- writes the result to `leanfran.lock` with a hash of each function's source. `leanfran status`
272
- reads the lock file without Lean and marks changed functions `stale`.
273
-
274
- - `refines=s`: `f x = s x` (`Except.ok (s x)` for a function that may fail); `requires=p`: `p x = true →`
275
- before each obligation; `ensures={"label": q}`: `q x (f x) = true`. A function annotated `-> Nat`
276
- also gets `returns_nat` (`0 ≤ f x`).
277
- - The translation: `int` is `Int` (a `Nat` parameter is a `Nat` converted to `Int` on entry);
278
- statements become Lean `do` notation (`let mut`, `for`, `while`, `break`, `continue`, early
279
- `return`); indexing, `//`, `%`, `assert` and `raise` make the function return
280
- `Py.M α = Except Py.Exc α`, with Python's negative indices and floor division (`LeanPythonLib.Py`).
281
- Supported: `int`, `bool`, `str`, `float`, `list`, `tuple`, `T | None`, pydantic models (as the
282
- Lean structures of `models=`), `len`, `abs`, `min`, `max`, `sum`, list comprehensions, `append` on
283
- local lists, and calls of other `@model` functions of the module.
284
- - `check_model(f)` / `check_module(m)` generate arguments from the annotations (pydantic constraints
285
- included), skip those failing `requires`, and compare with `refines` and `ensures`.
286
-
287
- ## Examples
288
-
289
- [`samples/`](https://github.com/conao3/lean-leanfran/tree/master/Python/samples) holds Python packages with Lean
290
- blocks. `make samples` syncs each one, runs it, and compares the output with its `expected.txt`.
291
-
292
- | sample | shows |
293
- |---|---|
294
- | [word-count](https://github.com/conao3/lean-leanfran/tree/master/Python/samples/word-count) | strings and lists, a proof by induction |
295
- | [roman-numerals](https://github.com/conao3/lean-leanfran/tree/master/Python/samples/roman-numerals) | a round-trip theorem checked for every number below 1000 (`decide +kernel`) |
296
- | [todo-cli](https://github.com/conao3/lean-leanfran/tree/master/Python/samples/todo-cli) | an invariant over a list kept by every operation, JSON storage, tampered JSON rejected |
297
- | [pricing-api](https://github.com/conao3/lean-leanfran/tree/master/Python/samples/pricing-api) | FastAPI with a pydantic model and a Lean inductive type as request body, 422 for invalid input |
298
-
299
- [`samples/steps/`](https://github.com/conao3/lean-leanfran/tree/master/Python/samples/steps) introduces one
300
- feature at a time, from functions on `Nat` (01) to types shared between blocks with `uses=` (09).
301
-
302
- ## The CLI
303
-
304
- The Python package installs `leanfran`:
305
-
306
- ```
307
- leanfran sync --package <dir> [--leanfran-python <path>]
308
- leanfran check --package <dir> [--leanfran-python <path>] [--require proved]
309
- leanfran status --package <dir>
310
- ```
311
-
312
- `--leanfran-python` defaults to `$LEANFRAN_PYTHON_CLI`, then `leanfran-python` on `PATH`. The Lean CLI
313
- `leanfran-python` does the compilation:
314
-
315
- ```
316
- leanfran-python module generate --module-name <Name> [--roots <Name> ...] [--namespace <Name>]
317
- [--import <Name> ...] [--search-path <dir> ...] [--output-file <path>] [--internal-only]
318
- [--output json|text] [--type-module <Name>=<module> ...] [--model-module <Name>=<module> ...]
319
- [--batch <file>]
320
- leanfran-python obligations check --modules <Name> ... --obligations <file> [--search-path <dir> ...]
321
- leanfran-python --version | --generator-version | help
322
- ```
323
-
324
- `module generate` writes one Python module with the IR of the roots and of everything they call
325
- (Init and Std included), and public functions and types for the roots. It reports the definitions it
326
- cannot expose (polymorphic functions, functions over functions) as skipped. Both CLIs use the exit
327
- codes 0 success, 252 invalid parameters, 254 input that cannot be converted, 255 other errors.
328
-
329
- ## Performance
330
-
331
- `make bench` (CPython 3.14, x86_64; the native column is the C backend):
332
-
333
- | workload | n | Python (s) | native C (s) |
334
- |---|---|---|---|
335
- | `Array.push`, `set!`, sum | 10⁴ | 0.017 | 0.005 |
336
- | `Array.push`, `set!`, sum | 10⁵ | 0.179 | 0.006 |
337
- | `Array.push`, `set!`, sum | 10⁶ | 1.796 | 0.017 |
338
- | `fib` (loop) | 10⁵ | 0.176 | 0.074 |
339
- | `naiveFib` | 25 | 0.149 | 0.005 |
340
- | `String.push` | 10⁴ | 0.012 | 0.005 |
341
- | `String.push` | 10⁵ | 0.227 | 0.006 |
342
- | `Array.qsort` | 10⁵ | 1.929 | 0.020 |
343
-
344
- Passing 10⁴ models to a Lean function takes 0.036 s (pydantic's `TypeAdapter(list[Model])` validates
345
- 10⁴ dicts in 0.009 s).
346
-
347
- ## Development
348
-
349
- ```sh
350
- nix develop -c make check # treefmt, the diff tests against the C backend, pytest, the samples
351
- nix develop -c make bench
352
- ```
353
-
354
- - `LeanPython/EmitPy.lean`: IR → Python. `LeanPython/Marshal.lean`, `LeanPython/Generate.lean`: public
355
- types and functions. `LeanPython/Check.lean`: `obligations check`. `Main.lean`: the CLI.
356
- - `src/leanfran/runtime.py`, `io_externs.py`: the runtime (`lean_*` are the C names of Lean's
357
- externs). `marshal.py`, `types.py`: pydantic types. `embed.py`, `sync.py`, `models.py`, `cli.py`:
358
- `lean(...)` and `leanfran sync`. `verify.py`, `translate.py`, `check.py`: `@model` and
359
- `leanfran check`; `lean/LeanPythonLib/Py.lean` holds Python's semantics in Lean.
360
- - `LeanPythonTest/`: Lean programs of the tests; `test-diff.sh` runs `Vectors` and `Io` natively and
361
- as Python.
362
-
363
- ## Limitations
364
-
365
- - leanfran does not expose polymorphic functions, functions taking or returning functions, or
366
- `Thunk`/`Task`/`IO.Ref`/`ByteArray` in public signatures. They still run inside Lean code.
367
- - `Task`s run synchronously.
368
- - Building a `String` with `String.push` copies the string each time (Python `bytes`), so it grows
369
- quadratically.
370
- - The translation of Python functions covers the subset above; the guarantee is partial correctness.
371
-
372
- ## License
373
-
374
- [Apache-2.0](https://github.com/conao3/lean-leanfran/blob/master/Python/LICENSE)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes