Debian Codegraph @

build_ext.py

raw symbols SCIP
1 """Build optional cython modules."""
2
3 import os
4 import sys
5 import tempfile
6 from distutils.command.build_ext import build_ext
7 from os.path import join
8 from typing import Any
9
10 try:
11 from setuptools import Extension
12 except ImportError:
13 from distutils.core import Extension
14
15 utils_module = Extension(
16 "bluetooth_data_tools._utils_impl",
17 [
18 join("src", "bluetooth_data_tools", "_utils_impl.pyx"),
19 ],
20 language="c",
21 extra_compile_args=["-O3", "-g0"],
22 )
23
24 time_module = Extension(
25 "bluetooth_data_tools._time_impl",
26 [
27 join("src", "bluetooth_data_tools", "_time_impl.pyx"),
28 ],
29 language="c",
30 extra_compile_args=["-O3", "-g0"],
31 )
32 TO_CYTHONIZE = [
33 "src/bluetooth_data_tools/gap.py",
34 "src/bluetooth_data_tools/utils.py",
35 ]
36
37 EXTENSIONS = [
38 Extension(
39 ext.removeprefix("src/").removesuffix(".py").replace("/", "."),
40 [ext],
41 language="c",
42 extra_compile_args=["-O3", "-g0"],
43 )
44 for ext in TO_CYTHONIZE
45 ]
46
47
48 class BuildExt(build_ext):
49 def usable_std_flag(self) -> str | None:
50 """Return the C standard flag, or None if this compiler cannot use it.
51
52 Not every toolchain that accepts ``-std=gnu2x`` implements C23: GCC 11
53 and 12 set ``__STDC_VERSION__`` past C17 but do not provide ``nullptr``,
54 which CPython 3.13+ ``pyport.h`` then uses -- and GCC below 11 rejects
55 the flag outright. MSVC accepts ``/std:clatest`` but then mis-parses
56 ``[[maybe_unused]] PyObject *const *x;``, the C23 spelling Cython 3.3+
57 uses for ``CYTHON_UNUSED`` once ``__STDC_VERSION__`` claims C23, as an
58 expression statement (C2275) when the attribute precedes a typedef
59 name; ``[[maybe_unused]] int x;`` is fine. Compiling a probe against
60 ``Python.h`` with that exact declaration is the only reliable way to
61 tell, so do that instead of guessing from a version.
62 """
63 flag = "/std:clatest" if self.compiler.compiler_type == "msvc" else "-std=gnu2x"
64 with tempfile.TemporaryDirectory() as tmpdir:
65 probe = join(tmpdir, "probe.c")
66 with open(probe, "w") as handle:
67 handle.write(
68 "#include <Python.h>\n"
69 "int main(void) {\n"
70 " int first = 0;\n"
71 " [[maybe_unused]] PyObject *const *probe = NULL;\n"
72 " return first;\n"
73 "}\n"
74 )
75 # The probe writes the compiler's own errors to the build log when
76 # the flag is unusable; say so, or a successful build looks broken.
77 print(f"probing {flag}; compiler errors below are expected if unusable")
78 try:
79 self.compiler.compile(
80 [probe],
81 output_dir=tmpdir,
82 include_dirs=self.include_dirs,
83 extra_postargs=[flag],
84 )
85 except Exception:
86 return None
87 return flag
88
89 def build_extensions(self) -> None:
90 if self.parallel is None: # type: ignore[has-type, unused-ignore]
91 self.parallel = os.cpu_count() or 1
92 std_flag = self.usable_std_flag()
93 if std_flag is not None:
94 for ext in self.extensions:
95 if std_flag not in ext.extra_compile_args:
96 ext.extra_compile_args = [*ext.extra_compile_args, std_flag]
97 try:
98 super().build_extensions()
99 except Exception:
100 # A silent fallback here ships an extension-less wheel that only
101 # fails much later (auditwheel) or not at all. Callers that need
102 # the native modules opt into a hard failure.
103 if os.environ.get("REQUIRE_CYTHON"):
104 raise
105
106
107 def build(setup_kwargs: Any) -> None:
108 if os.environ.get("SKIP_CYTHON", False):
109 return
110 try:
111 from Cython.Build import cythonize # noqa: PLC0415
112
113 setup_kwargs.update(
114 dict(
115 ext_modules=cythonize(
116 [
117 # _time_impl cimports posix.time, so there is no
118 # sys/time.h to include on Windows. time.py only ever
119 # loads it on Linux; building it elsewhere is a
120 # guaranteed compile error.
121 *([] if sys.platform == "win32" else [time_module]),
122 utils_module,
123 *EXTENSIONS,
124 ],
125 compiler_directives={"language_level": "3"}, # Python 3
126 ),
127 cmdclass=dict(build_ext=BuildExt),
128 )
129 )
130 setup_kwargs["exclude_package_data"] = {
131 pkg: ["*.c"] for pkg in setup_kwargs["packages"]
132 }
133 except Exception:
134 if os.environ.get("REQUIRE_CYTHON"):
135 raise