Skip to content

Commit 110bfff

Browse files
authored
Merge pull request #452 from thisisthepy/feat/tp-451-aot-frontend
TypedPython AOT tier K, PR2: front-end AOT mode, native lists, nbody without CPython
2 parents bc92bd8 + 0488e50 commit 110bfff

13 files changed

Lines changed: 3569 additions & 493 deletions

File tree

‎.github/workflows/typedpython.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ jobs:
9696
run: |
9797
env $(.venv/bin/python tools/sanitizers.py env) \
9898
.venv/bin/python -m pytest -q -m "not measurement and not race_mutant" \
99-
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
99+
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
100100
101101
app-fixture:
102102
# #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 of scalar functions with an `if __name__ == "__main__"` entry and `print`, strict integers, differential-tested against CPython (#448; 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).
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

‎python-multiplatform-ksp/pyproject.toml‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,8 @@ test = ["pytest"]
3535
[tool.pytest.ini_options]
3636
testpaths = ["src/test/python"]
3737
pythonpath = ["src/main/python"]
38-
addopts = "--basetemp=.pytest_tmp"
38+
# --durations: the windows job's time must be attributable (CI run 43794350884).
39+
addopts = "--basetemp=.pytest_tmp --durations=40"
3940
# A test still running after this many seconds gets every thread's stack printed (the test is not
4041
# stopped; the CI job's timeout-minutes ends it). Added after a windows job hung for 6 hours.
4142
faulthandler_timeout = 300

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

Lines changed: 24 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
"""TypedPython AOT mode, first build step (SPEC N-17, #448; agent proposal, not owner-confirmed).
1+
"""TypedPython AOT mode, first build step (SPEC N-17, #448, #451; agent proposal, not owner-confirmed).
22
3-
`generate(entry)` returns the C text of a single-module program of scalar functions with an
3+
`generate(entry)` returns the C text of a single-module program (scalar functions, native lists of floats
4+
and ints, fixed tuples of scalars, `print` with f-strings, `sys.argv` through `int()`) with an
45
`if __name__ == "__main__":` entry; `build(entry, out)` compiles it with the platform C compiler into
56
a standalone executable that contains and loads no CPython. A program the mode cannot compile exactly
6-
as CPython computes it raises `AotError` with one finding per construct (design:
7-
docs/design/typedpython-aot.md).
7+
as CPython computes it raises `AotError` with EVERY finding of the program, one per construct, in every
8+
function (design: docs/design/typedpython-aot.md).
89
"""
910
from __future__ import annotations
1011

11-
import ast
1212
import re
1313
import tempfile
1414
from pathlib import Path
@@ -21,7 +21,8 @@ class AotError(Exception):
2121
`aotcheck.Finding` (path, line, rule, name, message)."""
2222

2323
def __init__(self, findings: list[Finding]) -> None:
24-
self.findings = sorted(findings, key=lambda f: (f.line, f.rule, f.name))
24+
unique = {(f.path, f.line, f.rule, f.name, f.message): f for f in findings} # the same finding once
25+
self.findings = sorted(unique.values(), key=lambda f: (f.line, f.rule, f.name))
2526
super().__init__("\n".join(format_finding(f) for f in self.findings))
2627

2728

@@ -33,30 +34,29 @@ def format_finding(f: Finding) -> str:
3334

3435

3536
def _lower(program) -> tuple[str | None, list[Finding]]:
36-
"""Run the front end and the verifier on the program's text; emit C or return the findings."""
37+
"""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."""
3739
from typedpython import frontend, verify
3840
from typedpython.aot import emit as emit_mod
39-
from typedpython.aot.program import MAIN, PRINT_PREFIX
40-
from typedpython.aotcheck import _decorate, _original_line, _remap_text
41+
from typedpython.aot.program import MAIN
4142

42-
text, firsts = _decorate(program.edited, ast.parse(program.edited))
4343
rel = program.rel
4444

4545
def finding(line: int, rule: str, name: str, message: str, function: str | None) -> Finding:
4646
return Finding(rel, line, "error", None, rule, name, message, function)
4747

4848
with tempfile.TemporaryDirectory(prefix="typedpython-aot-") as work:
4949
copy = Path(work) / program.path.name
50-
copy.write_text(text, encoding="utf-8")
50+
copy.write_text(program.source, encoding="utf-8")
5151
try:
52-
lowered = frontend.lower(copy)
53-
proved, diagnostics = verify.verify(lowered)
52+
lowered = frontend.lower(copy, aot=True)
53+
proved, diagnostics = verify.verify(lowered, aot=True)
5454
except Exception as e: # noqa: BLE001 - reported as a finding, not a crash
5555
first = (str(e).strip().splitlines() or [""])[0]
5656
return None, [finding(1, "aot/front-end", type(e).__name__,
5757
f"the front end failed on this program ({type(e).__name__}: {first})", None)]
5858

59-
expected = [f.name for f in program.functions] + [MAIN] + list(program.prints)
59+
expected = [f.name for f in program.functions] + [MAIN]
6060
proved_names = {f.name for f in proved.functions}
6161
found: list[Finding] = []
6262
for name in expected:
@@ -66,18 +66,22 @@ def finding(line: int, rule: str, name: str, message: str, function: str | None)
6666
mine = [d for d in diagnostics if d.function == name]
6767
if mine:
6868
for d in mine:
69-
found.append(finding(_original_line(d.source_line, firsts), "aot/verify", shown,
70-
_remap_text(f"{d.rule}: {d.message}", firsts), shown))
69+
found.append(finding(d.source_line, "aot/verify", shown, f"{d.rule}: {d.message}", shown))
7170
continue
7271
why = lowered.skipped.get(name) or proved.skipped.get(name) or "the front end did not lower it"
73-
why = _remap_text(why, firsts)
7472
m = _LINE.search(why)
7573
line = int(m.group(1)) if m else program.bodies()[name].lineno if name in program.bodies() else 1
76-
what = "print" if name.startswith(PRINT_PREFIX) else shown
77-
found.append(finding(line, "aot/front-end", what, f"the front end left `{what}` uncompiled: {why}", shown))
74+
found.append(finding(line, "aot/front-end", shown, f"the front end left `{shown}` uncompiled: {why}", shown))
7875
if found:
76+
# The functions that did pass are still emitted, to report what the back end finds in them too: a
77+
# program's findings are all reported at once, not one function's at a time. (A function that calls
78+
# one of the rejected is rejected with it, so what is emitted here is closed.)
79+
_, more = emit_mod.emit(proved, program)
80+
entry_missing = [f for f in more if f.rule == "aot/entry"]
81+
seen = {(f.line, f.rule, f.name) for f in found}
82+
found += [f for f in more if f not in entry_missing and (f.line, f.rule, f.name) not in seen]
7983
return None, found
80-
return emit_mod.emit(proved, program, firsts)
84+
return emit_mod.emit(proved, program)
8185

8286

8387
def generate(entry: Path) -> str:

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

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
Python include directory or library: the executable links no CPython."""
66
from __future__ import annotations
77

8+
import os
89
import shlex
910
import subprocess
1011
import sys
@@ -21,6 +22,29 @@
2122
_NO_FOLD = tuple(f"-fno-builtin-{n}" for n in ("sin", "cos", "tan", "exp", "log", "atan2"))
2223
FLAGS: tuple[str, ...] = cbuild.DEFAULT_FLAGS + _NO_FOLD
2324

25+
# TP_SANITIZE=1 (tools/sanitizers.py env, set by the CI sanitizer job): the executable is built with the same
26+
# flags conftest.py adds to every extension TypedPython builds, so its programs run under AddressSanitizer,
27+
# UBSan (a report ends the program) and, where the platform has one, the leak checker. -DTP_CHECK_PROVEN
28+
# makes tp_aot.h stop on a proven operation that overflows. conftest.py wraps `cbuild.compiler`, which
29+
# `command` calls, with the same flags: they are added here only when the compiler command does not already
30+
# carry them, so a run under conftest gets them once.
31+
SANITIZE_FLAGS: tuple[str, ...] = ("-fsanitize=address,undefined", "-fno-sanitize-recover=undefined", "-g",
32+
"-fno-omit-frame-pointer", "-DTP_CHECK_PROVEN")
33+
34+
35+
def sanitizing() -> bool:
36+
return os.environ.get("TP_SANITIZE") == "1"
37+
38+
39+
def _sanitized(cmd: list[str]) -> list[str]:
40+
"""`cmd` (a GCC or Clang command) with the sanitizer flags, in front of the compiler's own, once."""
41+
extra = [f for f in SANITIZE_FLAGS if f not in cmd]
42+
if not extra:
43+
return cmd
44+
if sys.platform.startswith("linux") and cmd[:1] != ["env"]: # keep the ASan preload out of the compiler
45+
return ["env", "-u", "LD_PRELOAD", *cmd, *extra]
46+
return [*cmd, *extra]
47+
2448

2549
def compile_executable(c_text: str, out: Path, keep: Path | None = None) -> Path:
2650
"""Compile `c_text` to the executable `out` and return its path."""
@@ -41,10 +65,14 @@ def command(c_file: Path, out: Path, obj_dir: Path | None = None) -> tuple[list[
4165
if cbuild._is_msvc():
4266
env = cbuild.msvc_env()
4367
obj = (obj_dir or c_file.parent) / (c_file.stem + ".obj")
44-
cmd = ([cbuild._msvc_cl(env), "/nologo"] + cbuild._msvc_flags(list(FLAGS))
68+
flags = list(FLAGS) + (["-DTP_CHECK_PROVEN"] if sanitizing() else []) # (cl.exe has no -fsanitize here)
69+
cmd = ([cbuild._msvc_cl(env), "/nologo"] + cbuild._msvc_flags(flags)
4570
+ [f"/I{RUNTIME_DIR}", str(c_file), f"/Fo{obj}", f"/Fe{out}"])
4671
return cmd, env
47-
return (cbuild.compiler() + list(FLAGS) + [f"-I{RUNTIME_DIR}", str(c_file), "-o", str(out), "-lm"]), None
72+
cc = cbuild.compiler()
73+
if sanitizing():
74+
cc = _sanitized(cc)
75+
return (cc + list(FLAGS) + [f"-I{RUNTIME_DIR}", str(c_file), "-o", str(out), "-lm"]), None
4876

4977

5078
def _compile(c_file: Path, out: Path, obj_dir: Path | None = None) -> Path:

0 commit comments

Comments
 (0)