Skip to content

Commit 52b4277

Browse files
authored
Merge pull request #343 from thisisthepy/release
Release: merge release into main
2 parents f44be3a + 9e38030 commit 52b4277

17 files changed

Lines changed: 641 additions & 27 deletions

‎.github/workflows/typedpython.yml‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,19 @@ jobs:
2222
strategy:
2323
fail-fast: false
2424
matrix:
25-
os: [ubuntu-latest, macos-latest]
25+
os: [ubuntu-latest, macos-latest, windows-latest]
26+
include:
27+
- os: ubuntu-latest
28+
venv_python: .venv/bin/python
29+
- os: macos-latest
30+
venv_python: .venv/bin/python
31+
# Windows builds the compiled modules with MSVC (cl.exe, found through vswhere and
32+
# vcvars64.bat by cbuild.py), so the C runtime header is compiled by a second compiler family.
33+
- os: windows-latest
34+
venv_python: .venv/Scripts/python.exe
2635
defaults:
2736
run:
37+
shell: bash
2838
working-directory: python-multiplatform-ksp
2939
steps:
3040
- uses: actions/checkout@v4
@@ -35,14 +45,14 @@ jobs:
3545
# pyrefly is pinned exactly: the gate reads its versioned type-report format.
3646
run: |
3747
uv venv .venv --python 3.15t
38-
uv pip install --python .venv/bin/python "pyrefly==1.3.2" pytest numpy
48+
uv pip install --python ${{ matrix.venv_python }} "pyrefly==1.3.2" pytest numpy
3949
4050
- name: Behaviour tests
41-
run: .venv/bin/python -m pytest -q -m "not measurement and not race_mutant"
51+
run: ${{ matrix.venv_python }} -m pytest -q -m "not measurement and not race_mutant"
4252

4353
- name: Measurements (recorded, sanity bounds only)
4454
# A shared runner is not an idle machine (AGENTS.md §8): read ratios, not absolute times.
45-
run: .venv/bin/python -m pytest -q -s -m measurement
55+
run: ${{ matrix.venv_python }} -m pytest -q -s -m measurement
4656

4757
sanitizers:
4858
# SPEC N-8: ASan/UBSan runs are the safety net outside the proof. Every extension TypedPython

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

Lines changed: 173 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,20 @@
22
33
No setuptools, no Cython: one compiler invocation, `-shared -fPIC`, on macOS
44
`-undefined dynamic_lookup` (the extension resolves the C API from the process that loads it).
5+
On Windows the compiler is MSVC (`cl /LD`, linked against the interpreter's import library); see
6+
`msvc_command` and `msvc_env`.
57
The headers and the extension suffix default to the host interpreter's (`sysconfig`), and can be
68
pointed at the CPython the app embeds (`python_include`, `ext_suffix`).
79
"""
810
from __future__ import annotations
911

1012
import importlib.machinery
1113
import importlib.util
14+
import os
15+
import platform
16+
import re
1217
import shlex
18+
import shutil
1319
import subprocess
1420
import sys
1521
import sysconfig
@@ -26,6 +32,21 @@
2632
)
2733

2834

35+
# The same intent for cl.exe: /O2; /fp:precise (no fast-math; contraction is off by default);
36+
# /we4013 makes an implicit function declaration an error; _CRT_SECURE_NO_WARNINGS silences the
37+
# C4996 deprecation of getenv and friends; /std:c11 for the C11 the generated code may use.
38+
MSVC_DEFAULT_FLAGS: tuple[str, ...] = (
39+
"/O2",
40+
"/fp:precise",
41+
"/we4013",
42+
"/std:c11",
43+
"/D_CRT_SECURE_NO_WARNINGS",
44+
)
45+
46+
# Components cl.exe needs from a Visual Studio installation (vswhere -requires).
47+
MSVC_COMPONENT = "Microsoft.VisualStudio.Component.VC.Tools.x86.x64"
48+
49+
2950
class CBuildError(RuntimeError):
3051
"""The C compiler rejected the generated source; the message carries its stderr."""
3152

@@ -43,7 +64,148 @@ def _python_include(python_include: Path | None) -> Path:
4364

4465

4566
def compiler() -> list[str]:
46-
return shlex.split(sysconfig.get_config_var("CC") or "cc")
67+
cc = sysconfig.get_config_var("CC")
68+
if not cc and sys.platform == "win32":
69+
return ["cl"]
70+
return shlex.split(cc or "cc")
71+
72+
73+
def _is_msvc() -> bool:
74+
"""MSVC drives the build on Windows, or wherever the configured compiler is cl.exe."""
75+
if sys.platform == "win32":
76+
return True
77+
cc = compiler()
78+
return bool(cc) and Path(cc[0]).stem.lower() == "cl"
79+
80+
81+
def _msvc_flags(flags: list[str] | tuple[str, ...]) -> list[str]:
82+
"""Translate a GCC-style flag list for cl.exe: `/flag` passes through, `-D`, `-U` and `-I`
83+
become `/D`, `/U` and `/I`, and every other `-flag` is GCC/Clang-only and dropped. The GCC
84+
default list maps to MSVC_DEFAULT_FLAGS."""
85+
if tuple(flags) == DEFAULT_FLAGS:
86+
return list(MSVC_DEFAULT_FLAGS)
87+
out: list[str] = []
88+
rest = list(flags)
89+
if tuple(rest[:len(DEFAULT_FLAGS)]) == DEFAULT_FLAGS: # the defaults plus extra flags
90+
out = list(MSVC_DEFAULT_FLAGS)
91+
rest = rest[len(DEFAULT_FLAGS):]
92+
for f in rest:
93+
if f.startswith("/"):
94+
out.append(f)
95+
elif f[:2] in ("-D", "-U", "-I"):
96+
out.append("/" + f[1:])
97+
return out
98+
99+
100+
def msvc_libs_dir(include: Path) -> Path:
101+
"""The directory with the interpreter's import library (python3NN.lib, python3NNt.lib for the
102+
free-threaded build): `<prefix>\\libs`. For an include directory of another CPython
103+
(`<root>\\include`) its sibling `libs` wins."""
104+
sibling = Path(include).parent / "libs"
105+
if sibling.is_dir():
106+
return sibling
107+
return Path(sys.base_prefix) / "libs"
108+
109+
110+
def free_threaded(ext_suffix: str | None = None) -> bool:
111+
"""Whether the target CPython is the free-threaded build: the `t` ABI tag of an explicit
112+
extension suffix (`.cp315t-win_amd64.pyd`), else the host interpreter's `Py_GIL_DISABLED`."""
113+
if ext_suffix:
114+
return re.search(r"\.cp\d+t-", ext_suffix) is not None
115+
return bool(sysconfig.get_config_var("Py_GIL_DISABLED"))
116+
117+
118+
def msvc_command(cl: str, c_file: Path, so: Path, include: Path, runtime: Path,
119+
flags: list[str] | tuple[str, ...] = DEFAULT_FLAGS,
120+
libs_dir: Path | None = None, gil_disabled: bool | None = None) -> list[str]:
121+
"""`cl /nologo <flags> /LD /I<include> /I<runtime> <c_file> /Fo<obj> /link /LIBPATH:<libs> /OUT:<so>`.
122+
123+
The object file goes next to the source; `/OUT` names the extension (`<name><EXT_SUFFIX>`,
124+
.pyd on Windows). Pure: no filesystem or process access beyond `libs_dir` when it is None.
125+
126+
On a free-threaded CPython `/DPy_GIL_DISABLED=1` is added: the Windows pyconfig.h does not
127+
define it, and without it `#pragma comment(lib, ...)` auto-links python3NN.lib instead of
128+
python3NNt.lib (LNK1104 on a free-threaded install, which has only the latter).
129+
"""
130+
libs = libs_dir if libs_dir is not None else msvc_libs_dir(include)
131+
obj = Path(c_file).with_suffix(".obj")
132+
ft = free_threaded() if gil_disabled is None else gil_disabled
133+
gil = ["/DPy_GIL_DISABLED=1"] if ft else []
134+
return ([cl, "/nologo"] + _msvc_flags(flags) + gil
135+
+ ["/LD", f"/I{include}", f"/I{runtime}", str(c_file), f"/Fo{obj}",
136+
"/link", f"/LIBPATH:{libs}", f"/OUT:{so}"])
137+
138+
139+
_UNSET = object()
140+
_msvc_env_cache: object = _UNSET
141+
142+
143+
def _vswhere_path() -> Path:
144+
base = os.environ.get("ProgramFiles(x86)") or os.environ.get("ProgramFiles") or r"C:\Program Files (x86)"
145+
return Path(base) / "Microsoft Visual Studio" / "Installer" / "vswhere.exe"
146+
147+
148+
def parse_env_dump(text: str) -> dict[str, str]:
149+
"""Parse the `set` output of a vcvars run (`NAME=value` per line; banner lines are skipped)."""
150+
env: dict[str, str] = {}
151+
for line in text.splitlines():
152+
name, eq, value = line.partition("=")
153+
if eq and name and not name.startswith(("[", " ")):
154+
env[name] = value
155+
return env
156+
157+
158+
def _find_vcvars() -> Path:
159+
vswhere = _vswhere_path()
160+
if not vswhere.is_file():
161+
raise CBuildError(
162+
"MSVC not found: cl.exe is not on PATH and vswhere.exe is missing "
163+
f"({vswhere}). Install Visual Studio or the Build Tools with the 'Desktop development "
164+
f"with C++' workload ({MSVC_COMPONENT}), or run from a 'x64 Native Tools' prompt.")
165+
run = subprocess.run(
166+
[str(vswhere), "-latest", "-products", "*", "-requires", MSVC_COMPONENT,
167+
"-property", "installationPath"], capture_output=True, text=True)
168+
root = run.stdout.strip().splitlines()[0].strip() if run.returncode == 0 and run.stdout.strip() else ""
169+
if not root:
170+
raise CBuildError(
171+
f"MSVC not found: vswhere.exe found no Visual Studio installation with {MSVC_COMPONENT} "
172+
"(install the 'Desktop development with C++' workload).")
173+
script = "vcvarsarm64.bat" if platform.machine().lower() in ("arm64", "aarch64") else "vcvars64.bat"
174+
vcvars = Path(root) / "VC" / "Auxiliary" / "Build" / script
175+
if not vcvars.is_file():
176+
raise CBuildError(f"MSVC not found: {vcvars} does not exist (Visual Studio at {root}).")
177+
return vcvars
178+
179+
180+
def msvc_env() -> dict[str, str] | None:
181+
"""The environment to run cl.exe in; None when cl.exe is already on PATH (use the current one).
182+
183+
Otherwise: vswhere.exe locates the newest Visual Studio with the C++ tools, vcvars64.bat is run
184+
and the environment it leaves is captured. Cached per process.
185+
"""
186+
global _msvc_env_cache
187+
if _msvc_env_cache is not _UNSET:
188+
return _msvc_env_cache # type: ignore[return-value]
189+
if shutil.which("cl"):
190+
_msvc_env_cache = None
191+
return None
192+
vcvars = _find_vcvars()
193+
env = dict(os.environ, VSCMD_SKIP_SENDTELEMETRY="1")
194+
run = subprocess.run(f'cmd /u /c "{vcvars}" && set', capture_output=True, env=env)
195+
out = run.stdout.decode("utf-16-le", errors="replace")
196+
captured = parse_env_dump(out)
197+
if run.returncode != 0 or not any(k.upper() == "INCLUDE" for k in captured):
198+
raise CBuildError(f"{vcvars} failed ({run.returncode}) or did not set INCLUDE:\n{out[-2000:]}")
199+
_msvc_env_cache = captured
200+
return captured
201+
202+
203+
def _msvc_cl(env: dict[str, str] | None) -> str:
204+
cl = shutil.which("cl", path=None if env is None else next(
205+
(v for k, v in env.items() if k.upper() == "PATH"), None))
206+
if not cl:
207+
raise CBuildError("MSVC not found: cl.exe is not on PATH (after vcvars)")
208+
return cl
47209

48210

49211
def build(c_source: str, module_name: str, out_dir: Path, runtime_dir: Path | None = None,
@@ -63,6 +225,16 @@ def build(c_source: str, module_name: str, out_dir: Path, runtime_dir: Path | No
63225
c_file = out_dir / f"{stem}.c"
64226
c_file.write_text(c_source, encoding="utf-8")
65227
so = out_dir / f"{stem}{suffix}"
228+
if _is_msvc():
229+
env = msvc_env()
230+
cmd = msvc_command(_msvc_cl(env), c_file, so, include, runtime, flags,
231+
gil_disabled=free_threaded(ext_suffix))
232+
run = subprocess.run(cmd, capture_output=True, text=True, env=env)
233+
if run.returncode != 0 or not so.is_file():
234+
# cl.exe reports its errors on stdout
235+
raise CBuildError(f"C compiler failed ({run.returncode}): {subprocess.list2cmdline(cmd)}\n"
236+
f"{run.stdout}{run.stderr}")
237+
return so
66238
cmd = compiler() + list(flags) + ["-fPIC", "-shared", f"-I{include}", f"-I{runtime}"]
67239
if sys.platform == "darwin":
68240
cmd += ["-undefined", "dynamic_lookup"]

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

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,20 @@ def c_string(data: str | bytes) -> str:
266266
return "\n ".join(pieces)
267267

268268

269+
# cl.exe rejects a string literal longer than 65535 bytes (C2026); stay well under it.
270+
MSVC_LITERAL_LIMIT = 60000
271+
272+
273+
def c_source_init(data: str) -> str:
274+
"""The initialiser of `tp_source`: a string literal, or for a source too long for MSVC's
275+
literal limit a brace list of byte values (still NUL-terminated, so `Py_CompileString` reads it)."""
276+
raw = data.encode("utf-8")
277+
if len(raw) <= MSVC_LITERAL_LIMIT:
278+
return c_string(data)
279+
rows = [", ".join(str(b) for b in raw[i:i + 24]) for i in range(0, len(raw), 24)]
280+
return "{\n " + ",\n ".join(rows) + ",\n 0\n}"
281+
282+
269283
def _ident(prefix: str, name: str) -> str:
270284
"""A C identifier for a Python name: ASCII names keep their spelling, others are hex-encoded
271285
under a distinct prefix so the two forms cannot collide."""
@@ -726,9 +740,11 @@ def generate(module: ir.Module, source_path: Path, display_path: str | None = No
726740
w("#if PY_VERSION_HEX < 0x030D0000")
727741
w('#error "typedpython extensions need CPython 3.13 or newer (PyDict_GetItemRef)"')
728742
w("#endif")
743+
w("#if !defined(_MSC_VER) || defined(__clang__) /* cl.exe warns on an unknown pragma */")
729744
w("#pragma STDC FP_CONTRACT OFF")
745+
w("#endif")
730746
w("")
731-
w(f"static const char tp_source[] =\n {c_string(source)};")
747+
w(f"static const char tp_source[] =\n {c_source_init(source)};")
732748
w(f"static const char tp_source_path[] = {c_string(display_path)};")
733749
w("")
734750
n_names, n_kw = len(mg.names), len(mg.kwtuples)

0 commit comments

Comments
 (0)