-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathimpl_.rs
More file actions
4180 lines (3787 loc) · 147 KB
/
Copy pathimpl_.rs
File metadata and controls
4180 lines (3787 loc) · 147 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#[cfg(test)]
use std::cell::RefCell;
use std::{
collections::{HashMap, HashSet},
env,
ffi::{OsStr, OsString},
fmt::Display,
fs::{self, DirEntry},
io::{BufRead, BufReader, Read, Write},
path::{Path, PathBuf},
process::{Command, Stdio},
str::{self, FromStr},
};
pub use target_lexicon::Triple;
use target_lexicon::{Architecture, Environment, OperatingSystem, Vendor};
use crate::{
bail, ensure,
errors::{Context, Error, Result},
warn,
};
/// Minimum Python version PyO3 supports.
pub(crate) const MINIMUM_SUPPORTED_VERSION: PythonVersion = PythonVersion { major: 3, minor: 9 };
pub(crate) const MINIMUM_SUPPORTED_VERSION_PYPY: PythonVersion = PythonVersion {
major: 3,
minor: 11,
};
pub(crate) const MAXIMUM_SUPPORTED_VERSION_PYPY: PythonVersion = PythonVersion {
major: 3,
minor: 11,
};
pub(crate) const MINIMUM_SUPPORTED_VERSION_ABI3T: PythonVersion = PythonVersion {
major: 3,
minor: 15,
};
/// GraalPy may implement the same CPython version over multiple releases.
const MINIMUM_SUPPORTED_VERSION_GRAALPY: PythonVersion = PythonVersion {
major: 25,
minor: 0,
};
/// Maximum Python version that can be used as minimum required Python version with abi3.
pub(crate) const STABLE_ABI_MAX_MINOR: u8 = 15;
#[cfg(test)]
thread_local! {
static READ_ENV_VARS: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}
/// Gets an environment variable owned by cargo.
///
/// Environment variables set by cargo are expected to be valid UTF8.
pub fn cargo_env_var(var: &str) -> Option<String> {
env::var_os(var).map(|os_string| os_string.to_str().unwrap().into())
}
/// Gets an external environment variable, and registers the build script to rerun if
/// the variable changes.
pub fn env_var(var: &str) -> Option<OsString> {
println!("cargo:rerun-if-env-changed={var}");
#[cfg(test)]
{
READ_ENV_VARS.with(|env_vars| {
env_vars.borrow_mut().push(var.to_owned());
});
}
env::var_os(var)
}
/// Gets the compilation target triple from environment variables set by Cargo.
///
/// Must be called from a crate build script.
pub fn target_triple_from_env() -> Triple {
env::var("TARGET")
.expect("target_triple_from_env() must be called from a build script")
.parse()
.expect("Unrecognized TARGET environment variable value")
}
fn sanitize_stable_abi_version(
stable_abi_version: Option<PythonVersion>,
version: PythonVersion,
) -> Result<PythonVersion> {
if let Some(min_version) = stable_abi_version {
ensure!(
min_version <= version,
"cannot set a minimum Python version {} higher than the interpreter version {} \
(the minimum Python version is implied by the abi3-py3{} feature)",
min_version,
version,
min_version.minor
);
Ok(min_version)
} else {
Ok(version)
}
}
/// Configuration needed by PyO3 to build for the correct Python implementation.
///
/// The version and implementation fields correspond to the interpreter
/// used to host a build. These need not be the same as the implementation and
/// version fields set for the build target in the `target_abi` field.
///
/// Usually this is queried directly from the Python interpreter, or overridden using the
/// `PYO3_CONFIG_FILE` environment variable.
///
/// When the `PYO3_NO_PYTHON` variable is set, or during cross compile situations, then alternative
/// strategies are used to populate this type.
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
pub struct InterpreterConfig {
/// The host Python implementation flavor.
///
/// Serialized to `implementation`.
#[deprecated(
since = "0.29.0",
note = "please use `.implementation()` getter or `InterpreterConfigBuilder` instead"
)]
pub implementation: PythonImplementation,
/// The host Python `X.Y` version. e.g. `3.9`.
///
/// Serialized to `version`.
#[deprecated(
since = "0.29.0",
note = "please use `.version()` getter or `InterpreterConfigBuilder` instead"
)]
pub version: PythonVersion,
/// Whether link library is shared.
///
/// Serialized to `shared`.
#[deprecated(
since = "0.29.0",
note = "please use `.shared()` getter or `InterpreterConfigBuilder` instead"
)]
pub shared: bool,
target_abi: PythonAbi,
/// Serialized to `abi3`.
#[deprecated(since = "0.29.0", note = "please match against target_abi instead")]
pub abi3: bool,
/// The name of the link library defining Python.
///
/// This effectively controls the `cargo:rustc-link-lib=<name>` value to
/// control how libpython is linked. Values should not contain the `lib`
/// prefix.
///
/// Serialized to `lib_name`.
#[deprecated(
since = "0.29.0",
note = "please use `.lib_name()` getter or `InterpreterConfigBuilder` instead"
)]
pub lib_name: Option<String>,
/// The directory containing the Python library to link against.
///
/// The effectively controls the `cargo:rustc-link-search=native=<path>` value
/// to add an additional library search path for the linker.
///
/// Serialized to `lib_dir`.
#[deprecated(
since = "0.29.0",
note = "please use `.lib_dir()` getter or `InterpreterConfigBuilder` instead"
)]
pub lib_dir: Option<String>,
/// Path of host `python` executable.
///
/// This is a valid executable capable of running on the host/building machine.
/// For configurations derived by invoking a Python interpreter, it was the
/// executable invoked.
///
/// Serialized to `executable`.
#[deprecated(
since = "0.29.0",
note = "please use `.executable()` getter or `InterpreterConfigBuilder` instead"
)]
pub executable: Option<String>,
/// Width in bits of pointers on the target machine.
///
/// Serialized to `pointer_width`.
#[deprecated(
since = "0.29.0",
note = "please use `.pointer_width()` getter or `InterpreterConfigBuilder` instead"
)]
pub pointer_width: Option<u32>,
/// Additional relevant Python build flags / configuration settings.
///
/// Serialized to `build_flags`.
#[deprecated(
since = "0.29.0",
note = "please use `.build_flags()` getter or `InterpreterConfigBuilder` instead"
)]
pub build_flags: BuildFlags,
/// Whether to suppress emitting of `cargo:rustc-link-*` lines from the build script.
///
/// Typically, `pyo3`'s build script will emit `cargo:rustc-link-lib=` and
/// `cargo:rustc-link-search=` lines derived from other fields in this struct. In
/// advanced building configurations, the default logic to derive these lines may not
/// be sufficient. This field can be set to `Some(true)` to suppress the emission
/// of these lines.
///
/// If suppression is enabled, `extra_build_script_lines` should contain equivalent
/// functionality or else a build failure is likely.
#[deprecated(
since = "0.29.0",
note = "please use `.suppress_build_script_link_lines()` getter or `InterpreterConfigBuilder` instead"
)]
pub suppress_build_script_link_lines: bool,
/// Additional lines to `println!()` from Cargo build scripts.
///
/// This field can be populated to enable the `pyo3` crate to emit additional lines from its
/// its Cargo build script.
///
/// This crate doesn't populate this field itself. Rather, it is intended to be used with
/// externally provided config files to give them significant control over how the crate
/// is build/configured.
///
/// Serialized to multiple `extra_build_script_line` values.
#[deprecated(
since = "0.29.0",
note = "please use `.extra_build_script_lines()` getter or `InterpreterConfigBuilder` instead"
)]
pub extra_build_script_lines: Vec<String>,
/// macOS Python3.framework requires special rpath handling
#[deprecated(
since = "0.29.0",
note = "please use `.python_framework_prefix()` getter or `InterpreterConfigBuilder` instead"
)]
pub python_framework_prefix: Option<String>,
}
// Should no longer be deprecated once the internal fields are private
#[expect(deprecated, reason = "this impl block touches the internal fields")]
impl InterpreterConfig {
/// The Python implementation flavor.
///
/// Serialized to `implementation`.
pub fn implementation(&self) -> PythonImplementation {
self.implementation
}
/// Python `X.Y` version. e.g. `3.9`.
///
/// Serialized to `version`.
pub fn version(&self) -> PythonVersion {
self.version
}
/// Whether link library is shared.
///
/// Serialized to `shared`.
pub fn shared(&self) -> bool {
self.shared
}
/// The ABI to use for the compilation target.
/// See the documentation for the PythonAbi enum for more details.
///
/// Serialized to `target_abi`.
pub fn target_abi(&self) -> PythonAbi {
self.target_abi
}
/// Whether linking against the stable/limited Python 3 API.
///
#[deprecated(since = "0.29.0", note = "please use `target_abi()` instead")]
pub fn abi3(&self) -> bool {
matches!(self.target_abi.kind, PythonAbiKind::Stable(StableAbi::Abi3))
}
/// The name of the link library defining Python.
///
/// This effectively controls the `cargo:rustc-link-lib=<name>` value to
/// control how libpython is linked. Values should not contain the `lib`
/// prefix.
///
/// Serialized to `lib_name`.
pub fn lib_name(&self) -> Option<&str> {
self.lib_name.as_deref()
}
/// The directory containing the Python library to link against.
///
/// The effectively controls the `cargo:rustc-link-search=native=<path>` value
/// to add an additional library search path for the linker.
///
/// Serialized to `lib_dir`.
pub fn lib_dir(&self) -> Option<&str> {
self.lib_dir.as_deref()
}
/// Path of host `python` executable.
///
/// This is a valid executable capable of running on the host/building machine.
/// For configurations derived by invoking a Python interpreter, it was the
/// executable invoked.
///
/// Serialized to `executable`.
pub fn executable(&self) -> Option<&str> {
self.executable.as_deref()
}
/// Width in bits of pointers on the target machine.
///
/// Serialized to `pointer_width`.
pub fn pointer_width(&self) -> Option<u32> {
self.pointer_width
}
/// Additional relevant Python build flags / configuration settings.
///
/// Serialized to `build_flags`.
pub fn build_flags(&self) -> &BuildFlags {
&self.build_flags
}
/// Whether to suppress emitting of `cargo:rustc-link-*` lines from the build script.
pub fn suppress_build_script_link_lines(&self) -> bool {
self.suppress_build_script_link_lines
}
/// Additional lines to `println!()` from Cargo build scripts.
///
/// Serialized to multiple `extra_build_script_line` values.
pub fn extra_build_script_lines(&self) -> &[String] {
&self.extra_build_script_lines
}
/// macOS Python3.framework prefix used for special rpath handling.
pub fn python_framework_prefix(&self) -> Option<&str> {
self.python_framework_prefix.as_deref()
}
#[doc(hidden)]
pub fn build_script_outputs(&self) -> Vec<String> {
// This should have been checked during pyo3-build-config build time.
assert!(self.target_abi.version() >= MINIMUM_SUPPORTED_VERSION);
let mut out = vec![];
for i in MINIMUM_SUPPORTED_VERSION.minor..=self.target_abi.version().minor {
out.push(format!("cargo:rustc-cfg=Py_3_{i}"));
}
match self.target_abi.implementation() {
PythonImplementation::CPython => {}
PythonImplementation::PyPy => out.push("cargo:rustc-cfg=PyPy".to_owned()),
PythonImplementation::GraalPy => out.push("cargo:rustc-cfg=GraalPy".to_owned()),
PythonImplementation::RustPython => out.push("cargo:rustc-cfg=RustPython".to_owned()),
}
match self.target_abi.kind() {
PythonAbiKind::Stable(kind) => {
out.push("cargo:rustc-cfg=Py_LIMITED_API".to_owned());
if kind == StableAbi::Abi3t {
out.push("cargo:rustc-cfg=Py_GIL_DISABLED".to_owned());
}
}
PythonAbiKind::VersionSpecific(kind) => match kind {
GilUsed::FreeThreaded => {
out.push("cargo:rustc-cfg=Py_GIL_DISABLED".to_owned());
}
GilUsed::GilEnabled => {}
},
}
for flag in &self.build_flags.0 {
match flag {
// already handled by target ABI logic above
BuildFlag::Py_GIL_DISABLED => continue,
flag => out.push(format!("cargo:rustc-cfg=py_sys_config=\"{flag}\"")),
}
}
out
}
fn from_interpreter(
interpreter: impl AsRef<Path>,
abi3_version: Option<PythonVersion>,
abi3t_version: Option<PythonVersion>,
) -> Result<Self> {
const SCRIPT: &str = r#"
# Allow the script to run on Python 2, so that nicer error can be printed later.
from __future__ import print_function
import os.path
import platform
import struct
import sys
from sysconfig import get_config_var, get_platform
PYPY = platform.python_implementation() == "PyPy"
GRAALPY = platform.python_implementation() == "GraalVM"
if GRAALPY:
graalpy_ver = map(int, __graalpython__.get_graalvm_version().split('.'));
print("graalpy_major", next(graalpy_ver))
print("graalpy_minor", next(graalpy_ver))
# sys.base_prefix is missing on Python versions older than 3.3; this allows the script to continue
# so that the version mismatch can be reported in a nicer way later.
base_prefix = getattr(sys, "base_prefix", None)
if base_prefix:
# Anaconda based python distributions have a static python executable, but include
# the shared library. Use the shared library for embedding to avoid rust trying to
# LTO the static library (and failing with newer gcc's, because it is old).
ANACONDA = os.path.exists(os.path.join(base_prefix, "conda-meta"))
else:
ANACONDA = False
def print_if_set(varname, value):
if value is not None:
print(varname, value)
# Windows always uses shared linking
WINDOWS = platform.system() == "Windows"
# macOS framework packages use shared linking
FRAMEWORK = bool(get_config_var("PYTHONFRAMEWORK"))
FRAMEWORK_PREFIX = get_config_var("PYTHONFRAMEWORKPREFIX")
# unix-style shared library enabled
SHARED = bool(get_config_var("Py_ENABLE_SHARED"))
print("implementation", platform.python_implementation())
print("version_major", sys.version_info[0])
print("version_minor", sys.version_info[1])
print("shared", PYPY or GRAALPY or ANACONDA or WINDOWS or FRAMEWORK or SHARED)
print("python_framework_prefix", FRAMEWORK_PREFIX)
print_if_set("ld_version", get_config_var("LDVERSION"))
print_if_set("libdir", get_config_var("LIBDIR"))
print_if_set("base_prefix", base_prefix)
print("executable", sys.executable)
print("calcsize_pointer", struct.calcsize("P"))
print("mingw", get_platform().startswith("mingw"))
print("cygwin", get_platform().startswith("cygwin"))
print("ext_suffix", get_config_var("EXT_SUFFIX"))
print("gil_disabled", get_config_var("Py_GIL_DISABLED"))
"#;
let output = run_python_script(interpreter.as_ref(), SCRIPT)?;
let map: HashMap<String, String> = parse_script_output(&output);
ensure!(
!map.is_empty(),
"broken Python interpreter: {}",
interpreter.as_ref().display()
);
if let Some(value) = map.get("graalpy_major") {
let graalpy_version = PythonVersion {
major: value
.parse()
.context("failed to parse GraalPy major version")?,
minor: map["graalpy_minor"]
.parse()
.context("failed to parse GraalPy minor version")?,
};
ensure!(
graalpy_version >= MINIMUM_SUPPORTED_VERSION_GRAALPY,
"At least GraalPy version {} needed, got {}",
MINIMUM_SUPPORTED_VERSION_GRAALPY,
graalpy_version
);
};
let shared = map["shared"].as_str() == "True";
let python_framework_prefix = map.get("python_framework_prefix").cloned();
let version = PythonVersion {
major: map["version_major"]
.parse()
.context("failed to parse major version")?,
minor: map["version_minor"]
.parse()
.context("failed to parse minor version")?,
};
let implementation = map["implementation"].parse()?;
let gil_disabled = match map["gil_disabled"].as_str() {
"1" => true,
"0" => false,
"None" => false,
_ => panic!("Unknown Py_GIL_DISABLED value"),
};
let stable_abi_version = if !matches!(
implementation,
PythonImplementation::PyPy | PythonImplementation::GraalPy
) {
if version >= PythonVersion::PY315 {
match gil_disabled {
false => abi3t_version.or(abi3_version),
true => abi3t_version,
}
} else {
match gil_disabled {
false => abi3_version,
true => None,
}
}
} else {
None
};
let target_abi =
PythonAbi::from_build_env(implementation, version, stable_abi_version, gil_disabled)?;
let cygwin = map["cygwin"].as_str() == "True";
let lib_name = if cfg!(windows) {
default_lib_name_windows(
target_abi,
map["mingw"].as_str() == "True",
// This is the best heuristic currently available to detect debug build
// on Windows from sysconfig - e.g. ext_suffix may be
// `_d.cp312-win_amd64.pyd` for 3.12 debug build
map["ext_suffix"].starts_with("_d."),
)?
} else {
default_lib_name_unix(
target_abi,
cygwin,
map.get("ld_version").map(String::as_str),
)?
};
let lib_dir = if cfg!(windows) {
map.get("base_prefix")
.map(|base_prefix| format!("{base_prefix}\\libs"))
} else {
map.get("libdir").cloned()
};
// The reason we don't use platform.architecture() here is that it's not
// reliable on macOS. See https://stackoverflow.com/a/1405971/823869.
// Similarly, sys.maxsize is not reliable on Windows. See
// https://stackoverflow.com/questions/1405913/how-do-i-determine-if-my-python-shell-is-executing-in-32bit-or-64bit-mode-on-os/1405971#comment6209952_1405971
// and https://stackoverflow.com/a/3411134/823869.
let calcsize_pointer: u32 = map["calcsize_pointer"]
.parse()
.context("failed to parse calcsize_pointer")?;
InterpreterConfigBuilder::new(implementation, version)
.target_abi(target_abi)
.shared(shared)
.lib_name(lib_name)
.lib_dir(lib_dir)
.executable(map["executable"].clone())
.pointer_width(calcsize_pointer * 8)
.build_flags(BuildFlags::from_interpreter(interpreter)?)
.python_framework_prefix(python_framework_prefix)
.finalize()
}
/// Generate from parsed sysconfigdata file
///
/// Use [`parse_sysconfigdata`] to generate a hash map of configuration values which may be
/// used to build an [`InterpreterConfig`].
pub fn from_sysconfigdata(sysconfigdata: &Sysconfigdata) -> Result<Self> {
macro_rules! get_key {
($sysconfigdata:expr, $key:literal) => {
$sysconfigdata
.get_value($key)
.ok_or(concat!($key, " not found in sysconfigdata file"))
};
}
macro_rules! parse_key {
($sysconfigdata:expr, $key:literal) => {
get_key!($sysconfigdata, $key)?
.parse()
.context(concat!("could not parse value of ", $key))
};
}
let soabi = get_key!(sysconfigdata, "SOABI")?;
let implementation = PythonImplementation::from_soabi(soabi)?;
let version = parse_key!(sysconfigdata, "VERSION")?;
let shared = match sysconfigdata.get_value("Py_ENABLE_SHARED") {
Some("1") | Some("true") | Some("True") => true,
Some("0") | Some("false") | Some("False") => false,
_ => bail!("expected a bool (1/true/True or 0/false/False) for Py_ENABLE_SHARED"),
};
// macOS framework packages use shared linking (PYTHONFRAMEWORK is the framework name, hence the empty check)
let framework = match sysconfigdata.get_value("PYTHONFRAMEWORK") {
Some(s) => !s.is_empty(),
_ => false,
};
let python_framework_prefix = sysconfigdata
.get_value("PYTHONFRAMEWORKPREFIX")
.map(str::to_string);
let lib_dir = get_key!(sysconfigdata, "LIBDIR").ok().map(str::to_string);
let gil_disabled = match sysconfigdata.get_value("Py_GIL_DISABLED") {
Some(value) => value == "1",
None => false,
};
let cygwin = soabi.ends_with("cygwin");
let target_abi = PythonAbi::from_build_env(implementation, version, None, gil_disabled)?;
let lib_name =
default_lib_name_unix(target_abi, cygwin, sysconfigdata.get_value("LDVERSION"))?;
let pointer_width = parse_key!(sysconfigdata, "SIZEOF_VOID_P")
.map(|bytes_width: u32| bytes_width * 8)
.ok();
let build_flags = BuildFlags::from_sysconfigdata(sysconfigdata);
InterpreterConfigBuilder::new(implementation, version)
.target_abi(target_abi)
.shared(shared || framework)
.pointer_width(pointer_width)
.lib_name(lib_name)
.lib_dir(lib_dir)
.python_framework_prefix(python_framework_prefix)
.build_flags(build_flags)
.finalize()
}
/// Import an externally-provided config file.
///
/// The `abi3` features, if set, may apply an `abi3` constraint to the Python version.
pub(super) fn from_pyo3_config_file_env(target: &Triple) -> Option<Result<Self>> {
env_var("PYO3_CONFIG_FILE").map(|path| {
let path = Path::new(&path);
println!("cargo:rerun-if-changed={}", path.display());
// Absolute path is necessary because this build script is run with a cwd different to the
// original `cargo build` instruction.
ensure!(
path.is_absolute(),
"PYO3_CONFIG_FILE must be an absolute path"
);
let mut config = InterpreterConfig::from_path(path)
.context("failed to parse contents of PYO3_CONFIG_FILE")?
.apply_build_env()?;
// For config files which don't apply a lib name, apply a default which we can use
// for linking.
if config.lib_name.is_none() {
config.lib_name = Some(default_lib_name_for_target(config.target_abi, target));
}
Ok(config)
})
}
fn from_path(path: impl AsRef<Path>) -> Result<Self> {
let path = path.as_ref();
let config_file = std::fs::File::open(path)
.with_context(|| format!("failed to open PyO3 config file at {}", path.display()))?;
let reader = std::io::BufReader::new(config_file);
InterpreterConfig::from_reader(reader)
}
/// Environment variable populated via pyo3-ffi's build script
pub(crate) const PYO3_FFI_CONFIG_ENV_VAR: &str = "DEP_PYTHON_PYO3_CONFIG";
/// Environment variable populated via pyo3's build script by forwarding the value from pyo3-ffi
pub(crate) const PYO3_CONFIG_ENV_VAR: &str = "DEP_PYO3_PYTHON_PYO3_CONFIG";
pub(crate) fn from_cargo_dep_env() -> Option<Result<Self>> {
cargo_env_var(Self::PYO3_FFI_CONFIG_ENV_VAR)
.or_else(|| cargo_env_var(Self::PYO3_CONFIG_ENV_VAR))
.map(|buf| InterpreterConfig::from_reader(&*unescape(&buf)))
}
fn from_reader(reader: impl Read) -> Result<Self> {
let reader = BufReader::new(reader);
let lines = reader.lines();
macro_rules! parse_value {
($variable:ident, $value:ident) => {
$variable = Some($value.trim().parse().context(format!(
concat!(
"failed to parse ",
stringify!($variable),
" from config value '{}'"
),
$value
))?)
};
}
let mut implementation = None;
let mut version = None;
let mut shared = None;
let mut target_abi = None;
// deprecated in the struct but we still allow it to support old config files
let mut abi3 = None;
let mut lib_name = None;
let mut lib_dir = None;
let mut executable = None;
let mut pointer_width = None;
let mut build_flags: Option<BuildFlags> = None;
let mut suppress_build_script_link_lines: Option<bool> = None;
let mut extra_build_script_lines = vec![];
let mut python_framework_prefix = None;
for (i, line) in lines.enumerate() {
let line = line.context("failed to read line from config")?;
let mut split = line.splitn(2, '=');
let (key, value) = (
split
.next()
.expect("first splitn value should always be present"),
split
.next()
.ok_or_else(|| format!("expected key=value pair on line {}", i + 1))?,
);
match key {
"implementation" => parse_value!(implementation, value),
"version" => parse_value!(version, value),
"shared" => parse_value!(shared, value),
"target_abi" => parse_value!(target_abi, value),
"abi3" => parse_value!(abi3, value),
"lib_name" => parse_value!(lib_name, value),
"lib_dir" => parse_value!(lib_dir, value),
"executable" => parse_value!(executable, value),
"pointer_width" => parse_value!(pointer_width, value),
"build_flags" => parse_value!(build_flags, value),
"suppress_build_script_link_lines" => {
parse_value!(suppress_build_script_link_lines, value)
}
"extra_build_script_line" => {
extra_build_script_lines.push(value.to_string());
}
"python_framework_prefix" => parse_value!(python_framework_prefix, value),
unknown => warn!("unknown config key `{}`", unknown),
}
}
let version = version.ok_or("missing value for version")?;
let implementation = implementation.unwrap_or(PythonImplementation::CPython);
let flags_contains_free_threaded = if let Some(ref flags) = build_flags {
flags.0.contains(&BuildFlag::Py_GIL_DISABLED)
} else {
false
};
let target_abi = if let Some(target_abi) = target_abi {
ensure!(
abi3.is_none(),
"Invalid config that sets both target_abi and abi3."
);
target_abi
} else if flags_contains_free_threaded {
// This fires even if is_abi3() is True for backward compatibility reasons
PythonAbiBuilder::new(implementation, version)
.free_threaded()
.finalize()?
} else if abi3 == Some(true) {
warn!("abi3 configuration file option is deprecated since pyo3 0.29, set target_abi instead");
PythonAbiBuilder::new(implementation, version)
.stable_abi(StableAbi::Abi3)
.finalize()?
} else {
PythonAbiBuilder::new(implementation, version).finalize()?
};
let builder = InterpreterConfigBuilder::new(implementation, version)
.target_abi(target_abi)
.shared(shared.unwrap_or(true))
.lib_name(lib_name)
.lib_dir(lib_dir)
.executable(executable)
.pointer_width(pointer_width)
.build_flags(build_flags.unwrap_or_default())
.suppress_build_script_link_lines(suppress_build_script_link_lines.unwrap_or(false))
.extra_build_script_lines(extra_build_script_lines)
.python_framework_prefix(python_framework_prefix);
builder.finalize()
}
#[doc(hidden)]
/// Serialize the `InterpreterConfig` and print it to the environment for Cargo to pass along
/// to dependent packages during build time.
///
/// NB: writing to the cargo environment requires the
/// [`links`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#the-links-manifest-key)
/// manifest key to be set. In this case that means this is called by the `pyo3-ffi` crate and
/// available for dependent package build scripts in `DEP_PYTHON_PYO3_CONFIG`. See
/// documentation for the
/// [`DEP_<name>_<key>`](https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts)
/// environment variable.
pub fn to_cargo_dep_env(&self) -> Result<()> {
let mut buf = Vec::new();
self.to_writer(&mut buf)?;
// escape newlines in env var
println!("cargo:PYO3_CONFIG={}", escape(&buf));
Ok(())
}
#[doc(hidden)]
pub fn to_writer(&self, mut writer: impl Write) -> Result<()> {
macro_rules! write_line {
($value:ident) => {
writeln!(writer, "{}={}", stringify!($value), self.$value).context(concat!(
"failed to write ",
stringify!($value),
" to config"
))
};
}
macro_rules! write_option_line {
($value:ident) => {
if let Some(value) = &self.$value {
writeln!(writer, "{}={}", stringify!($value), value).context(concat!(
"failed to write ",
stringify!($value),
" to config"
))
} else {
Ok(())
}
};
}
write_line!(implementation)?;
write_line!(version)?;
write_line!(shared)?;
write_line!(target_abi)?;
write_option_line!(lib_name)?;
write_option_line!(lib_dir)?;
write_option_line!(executable)?;
write_option_line!(pointer_width)?;
write_line!(build_flags)?;
write_option_line!(python_framework_prefix)?;
write_line!(suppress_build_script_link_lines)?;
for line in &self.extra_build_script_lines {
writeln!(writer, "extra_build_script_line={line}")
.context("failed to write extra_build_script_line")?;
}
Ok(())
}
/// Run a python script using the [`InterpreterConfig::executable`].
///
/// # Panics
///
/// This function will panic if the [`executable`](InterpreterConfig::executable) is `None`.
pub fn run_python_script(&self, script: &str) -> Result<String> {
run_python_script_with_envs(
Path::new(self.executable.as_ref().expect("no interpreter executable")),
script,
std::iter::empty::<(&str, &str)>(),
)
}
/// Run a python script using the [`InterpreterConfig::executable`] with additional
/// environment variables (e.g. PYTHONPATH) set.
///
/// # Panics
///
/// This function will panic if the [`executable`](InterpreterConfig::executable) is `None`.
pub fn run_python_script_with_envs<I, K, V>(&self, script: &str, envs: I) -> Result<String>
where
I: IntoIterator<Item = (K, V)>,
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
run_python_script_with_envs(
Path::new(self.executable.as_ref().expect("no interpreter executable")),
script,
envs,
)
}
pub fn is_free_threaded(&self) -> bool {
self.target_abi.kind().is_free_threaded()
}
fn apply_build_env(mut self) -> Result<InterpreterConfig> {
let abi3_version = if self.target_abi.kind.is_free_threaded()
|| matches!(
self.target_abi.implementation,
PythonImplementation::PyPy | PythonImplementation::GraalPy
) {
None
} else {
get_abi3_version()
};
self.target_abi = PythonAbi::from_build_env(
self.implementation,
self.version,
exact_stable_abi_version(abi3_version.or(get_abi3t_version())),
self.target_abi.kind().is_free_threaded(),
)?;
Ok(self)
}
}
#[cfg_attr(test, derive(Debug))]
pub struct PythonAbiBuilder {
implementation: PythonImplementation,
version: PythonVersion,
kind: Option<PythonAbiKind>,
}
impl PythonAbiBuilder {
pub fn new(implementation: PythonImplementation, version: PythonVersion) -> PythonAbiBuilder {
PythonAbiBuilder {
implementation,
version,
kind: None,
}
}
pub fn stable_abi(self, kind: StableAbi) -> PythonAbiBuilder {
let mut build_version = self.version;
if self.version.minor > STABLE_ABI_MAX_MINOR {
warn!("Automatically falling back to {kind}-py3{STABLE_ABI_MAX_MINOR} because current Python is higher than the maximum supported");
build_version.minor = STABLE_ABI_MAX_MINOR;
}
PythonAbiBuilder {
kind: Some(PythonAbiKind::Stable(kind)),
version: build_version,
..self
}
}
pub fn free_threaded(self) -> PythonAbiBuilder {
PythonAbiBuilder {
kind: Some(PythonAbiKind::VersionSpecific(GilUsed::FreeThreaded)),
..self
}
}
pub fn finalize(self) -> Result<PythonAbi> {
// default to GIL-enabled version-specific ABI
let kind = self.kind.unwrap_or(match self.implementation {
PythonImplementation::RustPython => PythonAbiKind::Stable(StableAbi::Abi3t),
_ => PythonAbiKind::VersionSpecific(GilUsed::GilEnabled),
});
if matches!(self.implementation, PythonImplementation::RustPython) {
ensure!(matches!(kind, PythonAbiKind::Stable(StableAbi::Abi3t)),
"RustPython only supports targeting abi3t, it does not allow targeting other Python ABIs. Currently targeting '{kind}'")
}
if matches!(kind, PythonAbiKind::VersionSpecific(GilUsed::FreeThreaded))
&& self.version
< (PythonVersion {
major: 3,
minor: 13,
})
{
bail!(
"Cannot target free-threaded builds for Python versions before 3.13, tried to build for {}", self.version
)
}
Ok(PythonAbi {
implementation: self.implementation,
kind,
version: self.version,
})
}
}
#[non_exhaustive]
#[derive(Copy, Clone, PartialEq, Eq)]
#[cfg_attr(test, derive(Debug))]
pub struct PythonAbi {
implementation: PythonImplementation,
kind: PythonAbiKind,
version: PythonVersion,
}
impl Display for PythonAbi {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}-{}-{}", self.implementation, self.kind, self.version)
}
}
impl FromStr for PythonAbi {
type Err = crate::errors::Error;
fn from_str(value: &str) -> Result<Self, Self::Err> {
let mut parts = value.splitn(3, '-');
Ok(PythonAbi {
implementation: parts
.next()
.ok_or_else(|| format!("Invalid ABI string representation: {value}"))?
.parse()?,
kind: parts
.next()
.ok_or_else(|| format!("Invalid ABI string representation: {value}"))?
.parse()?,
version: parts