Skip to content

Commit 4a9d30f

Browse files
authored
Merge pull request #463 from thisisthepy/feat/tp-462-aot-int-compiler
TypedPython AOT tier K, PR4b: unproved ints compile as tagged values; spectral-norm and the original nbody build
2 parents ac85ccf + a6a29fa commit 4a9d30f

20 files changed

Lines changed: 4059 additions & 199 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 src/test/python/test_aot_lib.py src/test/python/test_aot_int.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 src/test/python/test_aot_int.py src/test/python/test_aot_repr.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). 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). The big-integer runtime exists (`runtime/tp_aot_int.h`), is not yet used by the back end, and is differential-tested against the reference interpreter (#460; design decision D1 (a), leader 2026-11-16, 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`), exact integers (#462; design decision D1 (a), leader 2026-11-16, not owner-confirmed): an int proved inside 64 bits is a plain `int64_t` and generates the code it always generated, and any other int is a small-int / big-integer value of `runtime/tp_aot_int.h`, with CPython's results, exception classes and messages for `+ - *`, `//`, `%`, comparisons (also with floats, exactly), `/` of two ints, `float()`, `abs`, `min`, `max`, `range` loops, list indexing, `print` and f-strings (the 4300-digit limit included), and `int(sys.argv[i])` for every argument (the reference's `repr` of the string in the message, non-UTF-8 bytes as the reference decodes them); `--strict-int` keeps the earlier rule that an operation not proved inside 64 bits is `aot/int-unproven`; a value not proved to fit 64 bits stored into a `list[int]` is `aot/int-list-store` (lists of big integers are the next step); differential-tested against CPython (spectral_norm.py and nbody.py as they are build and print what CPython prints for valid and invalid arguments; fannkuch.py is refused only for its two list stores; the three give the earlier `aot/int-unproven` sets under `--strict-int`); 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; an `int` result that is outside 64 bits fails the call with an `OverflowError` that says so, an ABI-level rule with no counterpart in the source language, #462), 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). The big-integer runtime exists (`runtime/tp_aot_int.h`), is differential-tested against the reference interpreter (#460; design decision D1 (a), leader 2026-11-16, not owner-confirmed), and the back end includes it only in a program that has an int not proved inside 64 bits (#462).
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: 51 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,49 @@ Adopted: (b), with (a) available as a build option for programs that want a guar
201201
code; (c) is excluded because its result differs from CPython's (leader decision D1, 2026-11-16, not
202202
owner-confirmed).
203203

204+
**What is implemented (#462; design decision D1 (a), leader 2026-11-16, not owner-confirmed; the representation was
205+
approved by the leader on 2026-11-16, not owner-confirmed; everything below that is not so marked is an agent proposal,
206+
not owner-confirmed).**
207+
208+
- *Representation.* An int is RAW (an `int64_t`, computed exactly as before) or TAGGED (`tpa_int` of
209+
`runtime/tp_aot_int.h`: owned references that are released at the function's cleanup point and when a local is
210+
rebound, as lists are; parameters are borrowed; a returned value is owned by the caller). A program decides per name,
211+
parameter, return and tuple element by a fixpoint over all its functions (`aot/rep.py`, which states the rule and is
212+
tested at the level of the IR). A value is RAW when it is an int constant, `len(...)`, the loop variable of a `range`
213+
loop whose bounds are RAW, an element read from a `list[int]`, a call result whose callee returns RAW, a parameter
214+
whose every call site passes RAW (a library export also receives int64 from outside), or the result of an operation
215+
the IR marks proved AND the sound re-proof (below) proves AND whose operands are all RAW. Everything else is TAGGED:
216+
an unproved operation, any operation with a TAGGED operand, `int(sys.argv[i])`, and what flows from them.
217+
- *A proved flag is not enough.* The front end's and the verifier's proofs read every int as one inside 64 bits (an
218+
operation that is not proved is clamped to int64, "it would have deopted"; a parameter or a call result is "any
219+
int64"), which is false of a TAGGED value; a guard `if a < b:` cuts the interval of `a` by that false interval of a
220+
TAGGED `b`, and the length the verifier gives a list created with a TAGGED length lets a proved index skip its bounds
221+
check on a list that is shorter. So the proved flags are a candidate only: `verify.sound_proofs` walks the verified IR
222+
again with intervals that hold of unbounded integers, given the inference as its oracle (a RAW name or return is
223+
int64, a TAGGED one, `int(sys.argv[i])` and every operation that is not proved are unbounded, nothing is clamped), and
224+
an operation is RAW, and a proved index skips its check, only when it is proved there too. Inference and re-proof are
225+
one fixpoint (the re-proof runs again after every rise to TAGGED). This replaced a "taint" rule (a name compared with
226+
a TAGGED value could not be trusted) that missed the list-length path. Agent proposal, not owner-confirmed. The cases
227+
it exists for (a RAW addition that would wrap for each kind of guard, an index past the end of a shorter list) are in
228+
the IR-level and differential tests.
229+
- *Exactness.* Operations on TAGGED values are the runtime's exact functions (`+ - *`, `//`, `%`, comparison chains,
230+
`abs`, `min` and `max`, truthiness, `range` loops with TAGGED bounds, list indexing with the reference's IndexError
231+
for an index that does not fit, `print` and f-strings with the 4300-digit limit's ValueError). `int / int` is accepted
232+
for every operand (correctly rounded; two RAW operands within plus or minus 2**53 are divided directly). An int meets a
233+
float as CPython does: arithmetic converts the int with its OverflowError (where the operation runs, after the other
234+
operand was evaluated), comparison is exact and never converts. `int(sys.argv[i])` is exact for every argument: the
235+
reference's `repr` of the string in the message (a table of the non-printable code points of Unicode 17.0 generated by
236+
`python-multiplatform-ksp/tools/gen_aot_nonprintable.py`), and bytes that are not valid UTF-8 as the lone surrogates
237+
the reference's argument decoding produces. On Windows the arguments arrive as UTF-16 (`wmain`); that path is reasoned
238+
from the reference's documentation, not observed on the machine that wrote it.
239+
- *Strict mode.* `--strict-int` on `aot-build` and `aot-lib` (`strict_int=True`) makes any int the compiler cannot prove
240+
inside 64 bits a compile error, `aot/int-unproven`, with the message of the earlier step. It is off by default.
241+
- *Still refused.* The elements of a `list[int]` are 64-bit ints: a value that is not proved to fit 64 bits stored into
242+
one (an element store, `[v] * n`, a list display) is the finding `aot/int-list-store`, and lists of big integers
243+
arrive in the next step (a side table for the elements outside 64 bits, ABI version 2, and with them fannkuch.py,
244+
which is refused for exactly its two list stores). An int literal or a module constant outside 64 bits is still
245+
`aot/int-literal` / `aot/constant`. spectral_norm.py and nbody.py (reading `sys.argv`) build and run.
246+
204247
CPython limits conversion between an int and a decimal string to 4300 digits by default and raises
205248
ValueError beyond that, in `str`, `print`, f-strings and `int(str)`. The AOT runtime reproduces that
206249
limit and its messages exactly (leader, 2026-11-16). CPython lets a program change the limit with
@@ -316,13 +359,19 @@ calling rules of AGENTS.md 16.
316359

317360
| Python type | C ABI | Kotlin side |
318361
|---|---|---|
319-
| `int` proved inside i64, `float`, `bool` | `int64_t`, `double`, `uint8_t` | `Long`, `Double`, `Boolean` |
320-
| `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 | |
362+
| `int`, `float`, `bool` | `int64_t`, `double`, `uint8_t` | `Long`, `Double`, `Boolean` |
363+
| `int` held as a big-integer-capable value inside the function (#462) | A parameter arrives as `int64_t` and is converted where the compiled function holds it so. A result (also an element of a tuple) is converted back with a fit check: one that does not fit `int64_t` fails the call with -1 and the error record `OverflowError`, message "the int result of `<function>` does not fit in 64 bits", and no out value is written. The same call with smaller inputs succeeds. `abi_version` stays 1 (no signature changes) | `Long`; the failed call throws `TypedPythonAotException` as for any other error |
321364
| `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 |
322365
| `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 |
323366
| 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 |
324367
| `None` result | `void` | `Unit` |
325368

369+
The int rows are an agent proposal, not owner-confirmed (the representation they serve, design decision D1 (a), was
370+
approved by the leader on 2026-11-16, not owner-confirmed). The result rule is an ABI-level rule with no counterpart in
371+
the source language, like the null-handle `TypeError`: the source language's int has no limit and the C ABI's has, and
372+
the generated header says so in its Errors paragraph (only for a library that has such a result; the header of a library
373+
whose ints are all proved inside 64 bits is what it was). Lists of big integers do not cross the boundary in this step.
374+
326375
The list row is a leader decision of 2026-11-16, not owner-confirmed. Reason: an AOT list carries a 16-byte
327376
header (count and length) before its elements, so a foreign array cannot be passed as it is; a handle
328377
also keeps Python's list identity across calls (a function that returns its argument returns the same list,

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

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
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`
3-
`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)
3+
`python -m typedpython aot-build ENTRY.py -o EXECUTABLE [--emit-c FILE.c] [--strict-int]` (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] [--strict-int]` (#455: a C-ABI library)
5+
6+
`--strict-int` (#462; design decision D1 (a), leader 2026-11-16, not owner-confirmed): an int not proved inside 64 bits is a
7+
compile error (`aot/int-unproven`) instead of a big-integer-capable value.
58
69
Exit status: 0 no errors (warnings allowed), 1 errors, 2 the gate itself could not run.
710
"""
@@ -58,6 +61,8 @@ def main(argv: list[str]) -> int:
5861
aot_build.add_argument("entry", type=Path, help="the entry module (it has an `if __name__ == \"__main__\":` block)")
5962
aot_build.add_argument("-o", "--output", type=Path, required=True, help="the executable to write")
6063
aot_build.add_argument("--emit-c", type=Path, default=None, help="also keep the generated C here")
64+
aot_build.add_argument("--strict-int", action="store_true",
65+
help="an int operation not proved to stay inside 64 bits is a compile error (no big integers)")
6166
aot_lib = commands.add_parser(
6267
"aot-lib", help="compile a single-module program to a C-ABI shared library with a header and a JSON "
6368
"description, with no CPython (SPEC N-17, #455)")
@@ -67,13 +72,15 @@ def main(argv: list[str]) -> int:
6772
aot_lib.add_argument("-o", "--output", type=Path, required=True, help="the directory for the library, "
6873
"<prefix>.h and <prefix>.json")
6974
aot_lib.add_argument("--emit-c", type=Path, default=None, help="also keep the generated C here")
75+
aot_lib.add_argument("--strict-int", action="store_true",
76+
help="an int operation not proved to stay inside 64 bits is a compile error (no big integers)")
7077
args = parser.parse_args(argv)
7178

7279
if args.command == "aot-lib":
7380
return _aot_lib(args.module, [n.strip() for n in args.export.split(",") if n.strip()], args.prefix,
74-
args.output, args.emit_c)
81+
args.output, args.emit_c, args.strict_int)
7582
if args.command == "aot-build":
76-
return _aot_build(args.entry, args.output, args.emit_c)
83+
return _aot_build(args.entry, args.output, args.emit_c, args.strict_int)
7784
if args.command == "aot-check":
7885
return _aot_check(args.entry, args.strict_int, args.json)
7986
if args.command == "emit-c":
@@ -114,7 +121,7 @@ def _aot_check(entry: Path, strict_int: bool, as_json: bool) -> int:
114121
return EXIT_ERRORS if report.blocking else EXIT_CLEAN
115122

116123

117-
def _aot_build(entry: Path, output: Path, emit_c: Path | None) -> int:
124+
def _aot_build(entry: Path, output: Path, emit_c: Path | None, strict_int: bool = False) -> int:
118125
"""SPEC N-17 / #448: exit 0 when the executable was built; 1 with one line per finding on standard error
119126
(`path:line: error rule: message`) when the program is outside what the mode compiles exactly; 2 when
120127
the build itself could not run (no such file, no C compiler, the compiler failed)."""
@@ -124,7 +131,7 @@ def _aot_build(entry: Path, output: Path, emit_c: Path | None) -> int:
124131
print(f"typedpython: {entry} is not a file", file=sys.stderr)
125132
return EXIT_FAILURE
126133
try:
127-
exe = aot.build(entry, output, emit_c=emit_c)
134+
exe = aot.build(entry, output, emit_c=emit_c, strict_int=strict_int)
128135
except aot.AotError as e:
129136
for f in e.findings:
130137
print(aot.format_finding(f), file=sys.stderr)
@@ -136,7 +143,8 @@ def _aot_build(entry: Path, output: Path, emit_c: Path | None) -> int:
136143
return EXIT_CLEAN
137144

138145

139-
def _aot_lib(module: Path, exports: list[str], prefix: str, out_dir: Path, emit_c: Path | None) -> int:
146+
def _aot_lib(module: Path, exports: list[str], prefix: str, out_dir: Path, emit_c: Path | None,
147+
strict_int: bool = False) -> int:
140148
"""SPEC N-17 / #455: exit 0 when the library, its header and its description were written (their paths are
141149
printed, one per line); 1 with one line per finding on standard error, as `aot-build`; 2 when the build
142150
itself could not run."""
@@ -146,7 +154,8 @@ def _aot_lib(module: Path, exports: list[str], prefix: str, out_dir: Path, emit_
146154
print(f"typedpython: {module} is not a file", file=sys.stderr)
147155
return EXIT_FAILURE
148156
try:
149-
files = aot.build_library(module, out_dir, exports=exports, prefix=prefix, emit_c=emit_c)
157+
files = aot.build_library(module, out_dir, exports=exports, prefix=prefix, emit_c=emit_c,
158+
strict_int=strict_int)
150159
except aot.AotError as e:
151160
for f in e.findings:
152161
print(aot.format_finding(f), file=sys.stderr)

0 commit comments

Comments
 (0)