Debian Codegraph @

build.rs

raw symbols SCIP
1 use pyo3_build_config::{
2 bail, ensure, print_feature_cfgs,
3 pyo3_build_script_impl::{
4 cargo_env_var, env_var, errors::Result, is_linking_libpython_for_target,
5 resolve_build_config, target_triple_from_env, BuildConfig, BuildConfigSource,
6 InterpreterConfig, MaximumVersionExceeded, PythonVersion,
7 },
8 warn, PythonImplementation,
9 };
10
11 /// Minimum Python version PyO3 supports.
12 struct SupportedVersions {
13 min: PythonVersion,
14 max: PythonVersion,
15 }
16
17 const SUPPORTED_VERSIONS_CPYTHON: SupportedVersions = SupportedVersions {
18 min: PythonVersion { major: 3, minor: 7 },
19 max: PythonVersion {
20 major: 3,
21 minor: 14,
22 },
23 };
24
25 const SUPPORTED_VERSIONS_PYPY: SupportedVersions = SupportedVersions {
26 min: PythonVersion {
27 major: 3,
28 minor: 11,
29 },
30 max: SUPPORTED_VERSIONS_CPYTHON.max,
31 };
32
33 const SUPPORTED_VERSIONS_GRAALPY: SupportedVersions = SupportedVersions {
34 min: PythonVersion {
35 major: 3,
36 minor: 10,
37 },
38 max: SUPPORTED_VERSIONS_CPYTHON.max,
39 };
40
41 fn ensure_python_version(interpreter_config: &InterpreterConfig) -> Result<()> {
42 // This is an undocumented env var which is only really intended to be used in CI / for testing
43 // and development.
44 if std::env::var("UNSAFE_PYO3_SKIP_VERSION_CHECK").as_deref() == Ok("1") {
45 return Ok(());
46 }
47
48 match interpreter_config.implementation {
49 PythonImplementation::CPython => {
50 let versions = SUPPORTED_VERSIONS_CPYTHON;
51 ensure!(
52 interpreter_config.version >= versions.min,
53 "the configured Python interpreter version ({}) is lower than PyO3's minimum supported version ({})",
54 interpreter_config.version,
55 versions.min,
56 );
57 let v_plus_1 = PythonVersion {
58 major: versions.max.major,
59 minor: versions.max.minor + 1,
60 };
61 if interpreter_config.version == v_plus_1 {
62 warn!(
63 "Using experimental support for the Python {}.{} ABI. \
64 Build artifacts may not be compatible with the final release of CPython, \
65 so do not distribute them.",
66 v_plus_1.major, v_plus_1.minor,
67 );
68 } else if interpreter_config.version > v_plus_1 {
69 let mut error = MaximumVersionExceeded::new(interpreter_config, versions.max);
70 if interpreter_config.is_free_threaded() {
71 error.add_help(
72 "the free-threaded build of CPython does not support the limited API so this check cannot be suppressed.",
73 );
74 return Err(error.finish().into());
75 }
76
77 if env_var("PYO3_USE_ABI3_FORWARD_COMPATIBILITY").is_none_or(|os_str| os_str != "1")
78 {
79 error.add_help("set PYO3_USE_ABI3_FORWARD_COMPATIBILITY=1 to suppress this check and build anyway using the stable ABI");
80 return Err(error.finish().into());
81 }
82 }
83 }
84 PythonImplementation::PyPy => {
85 let versions = SUPPORTED_VERSIONS_PYPY;
86 ensure!(
87 interpreter_config.version >= versions.min,
88 "the configured PyPy interpreter version ({}) is lower than PyO3's minimum supported version ({})",
89 interpreter_config.version,
90 versions.min,
91 );
92 // PyO3 does not support abi3, so we cannot offer forward compatibility
93 if interpreter_config.version > versions.max {
94 let error = MaximumVersionExceeded::new(interpreter_config, versions.max);
95 return Err(error.finish().into());
96 }
97 }
98 PythonImplementation::GraalPy => {
99 let versions = SUPPORTED_VERSIONS_GRAALPY;
100 ensure!(
101 interpreter_config.version >= versions.min,
102 "the configured GraalPy interpreter version ({}) is lower than PyO3's minimum supported version ({})",
103 interpreter_config.version,
104 versions.min,
105 );
106 // GraalPy does not support abi3, so we cannot offer forward compatibility
107 if interpreter_config.version > versions.max {
108 let error = MaximumVersionExceeded::new(interpreter_config, versions.max);
109 return Err(error.finish().into());
110 }
111 }
112 }
113
114 if interpreter_config.abi3 {
115 match interpreter_config.implementation {
116 PythonImplementation::CPython => {
117 if interpreter_config.is_free_threaded() {
118 warn!(
119 "The free-threaded build of CPython does not yet support abi3 so the build artifacts will be version-specific."
120 )
121 }
122 }
123 PythonImplementation::PyPy => warn!(
124 "PyPy does not yet support abi3 so the build artifacts will be version-specific. \
125 See https://github.com/pypy/pypy/issues/3397 for more information."
126 ),
127 PythonImplementation::GraalPy => warn!(
128 "GraalPy does not support abi3 so the build artifacts will be version-specific."
129 ),
130 }
131 }
132
133 Ok(())
134 }
135
136 fn ensure_target_pointer_width(interpreter_config: &InterpreterConfig) -> Result<()> {
137 if let Some(pointer_width) = interpreter_config.pointer_width {
138 // Try to check whether the target architecture matches the python library
139 let rust_target = match cargo_env_var("CARGO_CFG_TARGET_POINTER_WIDTH")
140 .unwrap()
141 .as_str()
142 {
143 "64" => 64,
144 "32" => 32,
145 x => bail!("unexpected Rust target pointer width: {}", x),
146 };
147
148 ensure!(
149 rust_target == pointer_width,
150 "your Rust target architecture ({}-bit) does not match your python interpreter ({}-bit)",
151 rust_target,
152 pointer_width
153 );
154 }
155 Ok(())
156 }
157
158 fn emit_link_config(build_config: &BuildConfig) -> Result<()> {
159 let interpreter_config = &build_config.interpreter_config;
160 let target_os = cargo_env_var("CARGO_CFG_TARGET_OS").unwrap();
161
162 println!(
163 "cargo:rustc-link-lib={link_model}{alias}{lib_name}",
164 link_model = if interpreter_config.shared {
165 ""
166 } else {
167 "static="
168 },
169 alias = if target_os == "windows" {
170 "pythonXY:"
171 } else {
172 ""
173 },
174 lib_name = interpreter_config.lib_name.as_ref().ok_or(
175 "attempted to link to Python shared library but config does not contain lib_name"
176 )?,
177 );
178
179 if let Some(lib_dir) = &interpreter_config.lib_dir {
180 println!("cargo:rustc-link-search=native={lib_dir}");
181 } else if matches!(build_config.source, BuildConfigSource::CrossCompile) {
182 warn!(
183 "The output binary will link to libpython, \
184 but PYO3_CROSS_LIB_DIR environment variable is not set. \
185 Ensure that the target Python library directory is \
186 in the rustc native library search path."
187 );
188 }
189
190 Ok(())
191 }
192
193 /// Prepares the PyO3 crate for compilation.
194 ///
195 /// This loads the config from pyo3-build-config and then makes some additional checks to improve UX
196 /// for users.
197 ///
198 /// Emits the cargo configuration based on this config as well as a few checks of the Rust compiler
199 /// version to enable features which aren't supported on MSRV.
200 fn configure_pyo3() -> Result<()> {
201 let target = target_triple_from_env();
202 let build_config = resolve_build_config(&target)?;
203 let interpreter_config = &build_config.interpreter_config;
204
205 if env_var("PYO3_PRINT_CONFIG").is_some_and(|os_str| os_str == "1") {
206 print_config_and_exit(interpreter_config);
207 }
208
209 ensure_python_version(interpreter_config)?;
210 ensure_target_pointer_width(interpreter_config)?;
211
212 // Serialize the whole interpreter config into DEP_PYTHON_PYO3_CONFIG env var.
213 interpreter_config.to_cargo_dep_env()?;
214
215 if is_linking_libpython_for_target(&target)
216 && !interpreter_config.suppress_build_script_link_lines
217 {
218 emit_link_config(&build_config)?;
219 }
220
221 for cfg in interpreter_config.build_script_outputs() {
222 println!("{cfg}")
223 }
224
225 // Extra lines come last, to support last write wins.
226 for line in &interpreter_config.extra_build_script_lines {
227 println!("{line}");
228 }
229
230 print_feature_cfgs();
231
232 Ok(())
233 }
234
235 fn print_config_and_exit(config: &InterpreterConfig) {
236 println!("\n-- PYO3_PRINT_CONFIG=1 is set, printing configuration and halting compile --");
237 config
238 .to_writer(std::io::stdout())
239 .expect("failed to print config to stdout");
240 println!("\nnote: unset the PYO3_PRINT_CONFIG environment variable and retry to compile with the above config");
241 std::process::exit(101);
242 }
243
244 fn main() {
245 pyo3_build_config::print_expected_cfgs();
246 if let Err(e) = configure_pyo3() {
247 eprintln!("error: {}", e.report());
248 std::process::exit(1)
249 }
250 }