Skip to content

Commit 34b9e79

Browse files
authored
Merge pull request #457 from thisisthepy/feat/tp-455-aot-lib
TypedPython AOT tier K, PR3a: C-ABI library output (aot-lib)
2 parents fe231c9 + f715095 commit 34b9e79

12 files changed

Lines changed: 2047 additions & 24 deletions

File tree

‎.github/workflows/typedpython.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ jobs:
129129
run: |
130130
env $(.venv/bin/python tools/sanitizers.py env) \
131131
.venv/bin/python -m pytest -q -m "not measurement and not race_mutant" \
132-
src/test/python/test_cgen.py src/test/python/test_runtime.py src/test/python/test_pipeline.py src/test/python/test_interval_proofs.py src/test/python/test_virtual_objects.py src/test/python/test_aot_build.py
132+
src/test/python/test_cgen.py src/test/python/test_runtime.py src/test/python/test_pipeline.py src/test/python/test_interval_proofs.py src/test/python/test_virtual_objects.py src/test/python/test_aot_build.py src/test/python/test_aot_lib.py
133133
134134
app-fixture:
135135
# #45: a TypedPython-compiled module calling Kotlin through the upcall table, in the app

‎docs/SPEC.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1307,7 +1307,7 @@ All in `PM/commonTest`, so they run wherever the interpreter loads.
13071307
impure one; `ValueError` with the same message; augmented forms; INT and object operands; `bool` and
13081308
float operands skipped or `TypeError`. `Status: implemented`.
13091309
- **N-17** TypedPython AOT mode: a standalone build with no interpreter (#443; INTENT §1.4, maintainer
1310-
decision 2026-11-16). `Status: planned, not implemented; design first`. A check-only mode exists (`python -m typedpython aot-check <entry.py>`): it builds nothing and reports every construct an AOT build would refuse, as an error or as pending with its tier (K, O, S or T), and a ready status per function (#446; agent proposal, not owner-confirmed). A first AOT build step exists (`python -m typedpython aot-build`): single-module programs with an `if __name__ == "__main__"` entry, scalar functions, native `list[float]` / `list[int]` values (counted, passed, returned and aliased by name), fixed tuples of scalars returned and unpacked, `print` with f-strings (`{e}` and `{e:.Nf}`), the conditional expression, `abs`, `min` and `max`, `len(sys.argv)`, and module constants (`NAME = <constant expression>`, also annotated `int`, `float` or `bool`), strict integers (an operation not proved inside 64 bits is `aot/int-unproven`, and so is `int(sys.argv[i])`: no run-time path differs from CPython), differential-tested against CPython (a variant of nbody with its size fixed in the source builds and prints what CPython prints; nbody, spectral_norm and fannkuch as they are, are refused only for `aot/int-unproven`); the front end and verifier read the file itself in an AOT mode that is off by default (#448, #451; agent proposal, not owner-confirmed).
1310+
decision 2026-11-16). `Status: planned, not implemented; design first`. A check-only mode exists (`python -m typedpython aot-check <entry.py>`): it builds nothing and reports every construct an AOT build would refuse, as an error or as pending with its tier (K, O, S or T), and a ready status per function (#446; agent proposal, not owner-confirmed). A first AOT build step exists (`python -m typedpython aot-build`): single-module programs with an `if __name__ == "__main__"` entry, scalar functions, native `list[float]` / `list[int]` values (counted, passed, returned and aliased by name), fixed tuples of scalars returned and unpacked, `print` with f-strings (`{e}` and `{e:.Nf}`), the conditional expression, `abs`, `min` and `max`, `len(sys.argv)`, and module constants (`NAME = <constant expression>`, also annotated `int`, `float` or `bool`), strict integers (an operation not proved inside 64 bits is `aot/int-unproven`, and so is `int(sys.argv[i])`: no run-time path differs from CPython), differential-tested against CPython (a variant of nbody with its size fixed in the source builds and prints what CPython prints; nbody, spectral_norm and fannkuch as they are, are refused only for `aot/int-unproven`); the front end and verifier read the file itself in an AOT mode that is off by default (#448, #451; agent proposal, not owner-confirmed). The library output exists (`python -m typedpython aot-lib <module.py> --export f,g --prefix <p> -o <dir>`): it writes a shared library, a C header and a JSON description of the same signatures (exports with int, float, bool and list arguments as counted handles, results through out pointers, a thread-local `<p>_last_error`, no library-wide lock), and is tested through a C-ABI consumer that compares every export with CPython (#455; owner decision D5 for its existence, shape per leader decisions of 2026-11-16, not owner-confirmed).
13111311
- **Selection.** Opt-in per build; the default mode (N-1 to N-16, interpreted fallback) is unchanged.
13121312
- **Acceptance.** The whole program must pass the verifier. Every construct that the default mode would
13131313
leave interpreted or deopt from (unknown calls, unproven bounds or overflow without a compiled

‎docs/design/typedpython-aot.md‎

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -295,7 +295,7 @@ calling rules of AGENTS.md 16.
295295

296296
### 8.1 What the library exports
297297

298-
- One C function per exported Python function, `<prefix>_<module>_<function>`, with a C signature
298+
- One C function per exported Python function, `<prefix>_<function>` (as built by #455), with a C signature
299299
derived from the Python annotations. Which functions are exported is stated in the build (a list of
300300
entry functions); everything they reach is compiled, the rest of the program is dropped by the linker.
301301
- `<prefix>_init()` runs the module initialisers of section 3 once (idempotent, safe to call from any
@@ -310,20 +310,28 @@ calling rules of AGENTS.md 16.
310310
| `int` proved inside i64, `float`, `bool` | `int64_t`, `double`, `uint8_t` | `Long`, `Double`, `Boolean` |
311311
| `int` not proved inside i64 | not exportable in a signature (compile error naming the parameter); the export must narrow it or return it as a string | |
312312
| `str` | pointer and length of UTF-8 bytes; an argument is borrowed for the call, a result is owned by the caller and released with `<prefix>_free` | `String`, copied at the boundary |
313-
| `list[float]` / `list[int]` argument | pointer and length, borrowed for the call | `DoubleArray` / `LongArray`, pinned or copied as the platform requires |
313+
| `list[float]` / `list[int]`, as an argument and as a result | an opaque counted handle (`<prefix>_f64_list`, `<prefix>_i64_list`) made and read through exported list functions (`_new`, `_len`, `_data`, `_retain`, `_release`); an argument is borrowed for the call, a returned handle is owned by the caller | a class holding the handle, with `DoubleArray` / `LongArray` copied from or to the `_data` address as the app needs |
314314
| an instance of a compiled class, or any other container | an opaque handle (a counted reference) with `<prefix>_release(handle)` | a Kotlin class holding the handle, released deterministically (`close`) with a cleaner as a safety net |
315315
| `None` result | `void` | `Unit` |
316316

317+
The list row is a leader decision of 2026-11-16, not owner-confirmed. Reason: an AOT list carries a 16-byte
318+
header (count and length) before its elements, so a foreign array cannot be passed as it is; a handle
319+
also keeps Python's list identity across calls (a function that returns its argument returns the same list,
320+
and two parameters may be one list, as two names are in the source).
321+
317322
Errors: every exported function returns a status; on failure the exception's class name and message
318323
are read with `<prefix>_last_error` on the same thread, and the generated Kotlin wrapper throws a
319324
Kotlin exception carrying both. Nothing unwinds across the boundary.
320325

321-
Threads: an exported function may be called from any Kotlin thread; the runtime's per-thread state is
322-
created on first use. Two Kotlin threads calling into the library at once are two threads of the
323-
program in the sense of section 7, so objects reachable from handles and globals are "shared" for the
324-
thread-escape analysis even before tier T exists. Until that analysis exists, a library whose exports
325-
can reach shared mutable state takes one library lock around each exported call (correct, not
326-
parallel); this is the conservative first step and is stated in the generated header.
326+
Threads (leader decision 2026-11-16, not owner-confirmed; the library output is owner decision D5):
327+
there is no library-wide lock and TypedPython has no GIL-like single lock. An exported function may be
328+
called from any Kotlin thread and from several at once, so exported functions are reentrant. The error
329+
record behind `<prefix>_last_error` is thread-local. List counts are atomic in a library build (and stay
330+
non-atomic in an executable build). Module-level mutable state is refused for a library (`aot/library-state`):
331+
tier K has none, since module constants are folded at compile time and a function that assigns a
332+
module-level name makes a local. Concurrent writes to the elements of one list from several threads are the
333+
caller's responsibility, exactly as with a Kotlin array, and the generated header says so. This replaces the
334+
earlier proposal of one library lock around each exported call.
327335

328336
### 8.3 Kotlin calling Python (the downcall)
329337

@@ -444,6 +452,8 @@ no behaviour and reports every construct of a program that would be an AOT compi
444452
own.
445453
- `lru_cache` is the second object-heavy benchmark.
446454
- Packaging of the library artefact stays open: it waits for the same owner decision as #25 step 3.
455+
- Verifying the Kotlin downcall inside a GraalVM native image is issue #456 and a completion condition of tier K
456+
(leader, 2026-11-16, not owner-confirmed; AGENTS.md 13 applies to the library as it does to upcalls).
447457

448458
## 11. What this note does not establish
449459

‎python-multiplatform-ksp/src/main/python/typedpython/__main__.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""`python -m typedpython check [--mode checked|compiled] [--format text|json] PATHS...`
22
`python -m typedpython emit-c PATHS... --root DIR [--cache DIR] --manifest FILE`
33
`python -m typedpython aot-build ENTRY.py -o EXECUTABLE [--emit-c FILE.c]` (SPEC N-17, #448: exit 1 on a finding)
4+
`python -m typedpython aot-lib MODULE.py --export f,g --prefix P -o DIR [--emit-c FILE.c]` (#455: a C-ABI library)
45
56
Exit status: 0 no errors (warnings allowed), 1 errors, 2 the gate itself could not run.
67
"""
@@ -57,8 +58,20 @@ def main(argv: list[str]) -> int:
5758
aot_build.add_argument("entry", type=Path, help="the entry module (it has an `if __name__ == \"__main__\":` block)")
5859
aot_build.add_argument("-o", "--output", type=Path, required=True, help="the executable to write")
5960
aot_build.add_argument("--emit-c", type=Path, default=None, help="also keep the generated C here")
61+
aot_lib = commands.add_parser(
62+
"aot-lib", help="compile a single-module program to a C-ABI shared library with a header and a JSON "
63+
"description, with no CPython (SPEC N-17, #455)")
64+
aot_lib.add_argument("module", type=Path, help="the module (an `if __name__ == \"__main__\":` block is not compiled)")
65+
aot_lib.add_argument("--export", required=True, help="the functions to export, separated by commas")
66+
aot_lib.add_argument("--prefix", required=True, help="the C identifier every exported symbol starts with")
67+
aot_lib.add_argument("-o", "--output", type=Path, required=True, help="the directory for the library, "
68+
"<prefix>.h and <prefix>.json")
69+
aot_lib.add_argument("--emit-c", type=Path, default=None, help="also keep the generated C here")
6070
args = parser.parse_args(argv)
6171

72+
if args.command == "aot-lib":
73+
return _aot_lib(args.module, [n.strip() for n in args.export.split(",") if n.strip()], args.prefix,
74+
args.output, args.emit_c)
6275
if args.command == "aot-build":
6376
return _aot_build(args.entry, args.output, args.emit_c)
6477
if args.command == "aot-check":
@@ -123,6 +136,29 @@ def _aot_build(entry: Path, output: Path, emit_c: Path | None) -> int:
123136
return EXIT_CLEAN
124137

125138

139+
def _aot_lib(module: Path, exports: list[str], prefix: str, out_dir: Path, emit_c: Path | None) -> int:
140+
"""SPEC N-17 / #455: exit 0 when the library, its header and its description were written (their paths are
141+
printed, one per line); 1 with one line per finding on standard error, as `aot-build`; 2 when the build
142+
itself could not run."""
143+
from typedpython import aot, cbuild
144+
145+
if not module.is_file():
146+
print(f"typedpython: {module} is not a file", file=sys.stderr)
147+
return EXIT_FAILURE
148+
try:
149+
files = aot.build_library(module, out_dir, exports=exports, prefix=prefix, emit_c=emit_c)
150+
except aot.AotError as e:
151+
for f in e.findings:
152+
print(aot.format_finding(f), file=sys.stderr)
153+
return EXIT_ERRORS
154+
except (cbuild.CBuildError, PyreflyError) as e:
155+
print(f"typedpython: {e}", file=sys.stderr)
156+
return EXIT_FAILURE
157+
for path in (files.library, files.header, files.description):
158+
print(path)
159+
return EXIT_CLEAN
160+
161+
126162
def _build(paths: list[Path], cache: Path, out: Path | None) -> int:
127163
import os
128164
import shutil

‎python-multiplatform-ksp/src/main/python/typedpython/aot/__init__.py‎

Lines changed: 42 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
import re
1313
import tempfile
14+
from dataclasses import dataclass
1415
from pathlib import Path
1516

1617
from typedpython.aotcheck import Finding
@@ -33,9 +34,11 @@ def format_finding(f: Finding) -> str:
3334
_LINE = re.compile(r"\bline (\d+)")
3435

3536

36-
def _lower(program) -> tuple[str | None, list[Finding]]:
37+
def _lower(program, library=None) -> tuple[str | None, list[Finding]]:
3738
"""Run the front end and the verifier in their AOT mode on the program's file; emit C or return
38-
the findings. Every line number is the file's own."""
39+
the findings. Every line number is the file's own. `library` (`aot.library`, #455) is None for a program
40+
with an entry: what `aot-build` has always done. For a library it names the functions to compile (the
41+
exports and what they reach) and the emitter of the library's C; the entry is then not expected."""
3942
from typedpython import frontend, verify
4043
from typedpython.aot import emit as emit_mod
4144
from typedpython.aot.program import MAIN
@@ -56,7 +59,12 @@ def finding(line: int, rule: str, name: str, message: str, function: str | None)
5659
return None, [finding(1, "aot/front-end", type(e).__name__,
5760
f"the front end failed on this program ({type(e).__name__}: {first})", None)]
5861

59-
expected = [f.name for f in program.functions] + [MAIN]
62+
if library is None:
63+
expected = [f.name for f in program.functions] + [MAIN]
64+
emit_fn = emit_mod.emit
65+
else:
66+
expected = [f.name for f in program.functions if f.name in library.reachable]
67+
emit_fn = library.emit
6068
proved_names = {f.name for f in proved.functions}
6169
found: list[Finding] = []
6270
for name in expected:
@@ -76,12 +84,12 @@ def finding(line: int, rule: str, name: str, message: str, function: str | None)
7684
# The functions that did pass are still emitted, to report what the back end finds in them too: a
7785
# program's findings are all reported at once, not one function's at a time. (A function that calls
7886
# one of the rejected is rejected with it, so what is emitted here is closed.)
79-
_, more = emit_mod.emit(proved, program)
87+
_, more = emit_fn(proved, program)
8088
entry_missing = [f for f in more if f.rule == "aot/entry"]
8189
seen = {(f.line, f.rule, f.name) for f in found}
8290
found += [f for f in more if f not in entry_missing and (f.line, f.rule, f.name) not in seen]
8391
return None, found
84-
return emit_mod.emit(proved, program)
92+
return emit_fn(proved, program)
8593

8694

8795
def generate(entry: Path) -> str:
@@ -108,3 +116,32 @@ def build(entry: Path, out: Path, *, emit_c: Path | None = None) -> Path:
108116
emit_c.parent.mkdir(parents=True, exist_ok=True)
109117
emit_c.write_text(c_text, encoding="utf-8")
110118
return cc.compile_executable(c_text, Path(out), keep=emit_c)
119+
120+
121+
@dataclass(frozen=True)
122+
class LibraryFiles:
123+
"""What `build_library` wrote: the shared library, the C header `<prefix>.h` and the description
124+
`<prefix>.json` (all in the output directory)."""
125+
126+
library: Path
127+
header: Path
128+
description: Path
129+
130+
131+
def generate_library(module: Path, *, exports: list[str], prefix: str) -> tuple[str, str, dict]:
132+
"""The C text of the library, its header and its description for `module` (a module with no entry; an
133+
`if __name__ == "__main__":` block is not compiled) exporting the functions `exports` under `prefix`;
134+
raises AotError. See `typedpython.aot.library`."""
135+
from typedpython.aot import library
136+
137+
return library.generate_library(Path(module), exports=exports, prefix=prefix)
138+
139+
140+
def build_library(module: Path, out_dir: Path, *, exports: list[str], prefix: str,
141+
emit_c: Path | None = None) -> LibraryFiles:
142+
"""Compile `module` to the shared library `lib<prefix>.so` (`.dylib` on macOS, `<prefix>.dll` on Windows)
143+
and write `<prefix>.h` and `<prefix>.json` beside it in `out_dir`. `emit_c` also keeps the generated C
144+
there. See `typedpython.aot.library`."""
145+
from typedpython.aot import library
146+
147+
return library.build_library(Path(module), Path(out_dir), exports=exports, prefix=prefix, emit_c=emit_c)

0 commit comments

Comments
 (0)