-
Notifications
You must be signed in to change notification settings - Fork 770
/
impl_.rs
2608 lines (2332 loc) · 89.7 KB
/
impl_.rs
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
//! Main implementation module included in both the `pyo3-build-config` library crate
//! and its build script.
// Optional python3.dll import library generator for Windows
#[cfg(feature = "python3-dll-a")]
#[path = "import_lib.rs"]
mod import_lib;
use std::{
collections::{HashMap, HashSet},
convert::AsRef,
env,
ffi::{OsStr, OsString},
fmt::Display,
fs::{self, DirEntry},
io::{BufRead, BufReader, Read, Write},
path::{Path, PathBuf},
process::{Command, Stdio},
str,
str::FromStr,
};
pub use target_lexicon::Triple;
use target_lexicon::{Architecture, BinaryFormat, Environment, OperatingSystem, Vendor};
use crate::{
bail, ensure,
errors::{Context, Error, Result},
warn,
};
/// Minimum Python version PyO3 supports.
const MINIMUM_SUPPORTED_VERSION: PythonVersion = PythonVersion { major: 3, minor: 7 };
/// Maximum Python version that can be used as minimum required Python version with abi3.
const ABI3_MAX_MINOR: u8 = 11;
/// 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> {
if cfg!(feature = "resolve-config") {
println!("cargo:rerun-if-env-changed={}", var);
}
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")
}
/// Configuration needed by PyO3 to build for the correct Python implementation.
///
/// 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 Python implementation flavor.
///
/// Serialized to `implementation`.
pub implementation: PythonImplementation,
/// Python `X.Y` version. e.g. `3.9`.
///
/// Serialized to `version`.
pub version: PythonVersion,
/// Whether link library is shared.
///
/// Serialized to `shared`.
pub shared: bool,
/// Whether linking against the stable/limited Python 3 API.
///
/// Serialized to `abi3`.
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`.
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`.
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`.
pub executable: Option<String>,
/// Width in bits of pointers on the target machine.
///
/// Serialized to `pointer_width`.
pub pointer_width: Option<u32>,
/// Additional relevant Python build flags / configuration settings.
///
/// Serialized to `build_flags`.
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.
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.
pub extra_build_script_lines: Vec<String>,
}
impl InterpreterConfig {
#[doc(hidden)]
pub fn emit_pyo3_cfgs(&self) {
// This should have been checked during pyo3-build-config build time.
assert!(self.version >= MINIMUM_SUPPORTED_VERSION);
// pyo3-build-config was released when Python 3.6 was supported, so minimum flag to emit is
// Py_3_6 (to avoid silently breaking users who depend on this cfg).
for i in 6..=self.version.minor {
println!("cargo:rustc-cfg=Py_3_{}", i);
}
if self.implementation.is_pypy() {
println!("cargo:rustc-cfg=PyPy");
if self.abi3 {
warn!(
"PyPy does not yet support abi3 so the build artifacts will be version-specific. \
See https://foss.heptapod.net/pypy/pypy/-/issues/3397 for more information."
);
}
} else if self.abi3 {
println!("cargo:rustc-cfg=Py_LIMITED_API");
}
for flag in &self.build_flags.0 {
println!("cargo:rustc-cfg=py_sys_config=\"{}\"", flag);
}
}
#[doc(hidden)]
pub fn from_interpreter(interpreter: impl AsRef<Path>) -> 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"
# 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"))
# 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 ANACONDA or WINDOWS or FRAMEWORK or SHARED)
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"))
"#;
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()
);
let shared = map["shared"].as_str() == "True";
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 abi3 = is_abi3();
let implementation = map["implementation"].parse()?;
let lib_name = if cfg!(windows) {
default_lib_name_windows(
version,
implementation,
abi3,
map["mingw"].as_str() == "True",
)
} else {
default_lib_name_unix(
version,
implementation,
map.get("ld_version").map(String::as_str),
)
};
let lib_dir = if cfg!(windows) {
map.get("base_prefix")
.map(|base_prefix| format!("{}\\libs", base_prefix))
} 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")?;
Ok(InterpreterConfig {
version,
implementation,
shared,
abi3,
lib_name: Some(lib_name),
lib_dir,
executable: map.get("executable").cloned(),
pointer_width: Some(calcsize_pointer * 8),
build_flags: BuildFlags::from_interpreter(interpreter)?.fixup(version),
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
})
}
/// 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 lib_dir = get_key!(sysconfigdata, "LIBDIR").ok().map(str::to_string);
let lib_name = Some(default_lib_name_unix(
version,
implementation,
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).fixup(version);
Ok(InterpreterConfig {
implementation,
version,
shared: shared || framework,
abi3: is_abi3(),
lib_dir,
lib_name,
executable: None,
pointer_width,
build_flags,
suppress_build_script_link_lines: false,
extra_build_script_lines: vec![],
})
}
#[doc(hidden)]
pub 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)
}
#[doc(hidden)]
pub fn from_cargo_dep_env() -> Option<Result<Self>> {
cargo_env_var("DEP_PYTHON_PYO3_CONFIG")
.map(|buf| InterpreterConfig::from_reader(&*unescape(&buf)))
}
#[doc(hidden)]
pub 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 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 = None;
let mut suppress_build_script_link_lines = None;
let mut extra_build_script_lines = vec![];
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),
"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());
}
unknown => bail!("unknown config key `{}`", unknown),
}
}
let version = version.ok_or("missing value for version")?;
let implementation = implementation.unwrap_or(PythonImplementation::CPython);
let abi3 = abi3.unwrap_or(false);
// Fixup lib_name if it's not set
let lib_name = lib_name.or_else(|| {
if let Ok(Ok(target)) = env::var("TARGET").map(|target| target.parse::<Triple>()) {
default_lib_name_for_target(version, implementation, abi3, &target)
} else {
None
}
});
Ok(InterpreterConfig {
implementation,
version,
shared: shared.unwrap_or(true),
abi3,
lib_name,
lib_dir,
executable,
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,
})
}
#[cfg(feature = "python3-dll-a")]
#[allow(clippy::unnecessary_wraps)]
pub fn generate_import_libs(&mut self) -> Result<()> {
// Auto generate python3.dll import libraries for Windows targets.
if self.lib_dir.is_none() {
let target = target_triple_from_env();
let py_version = if self.abi3 { None } else { Some(self.version) };
self.lib_dir =
import_lib::generate_import_lib(&target, self.implementation, py_version)?;
}
Ok(())
}
#[cfg(not(feature = "python3-dll-a"))]
#[allow(clippy::unnecessary_wraps)]
pub fn generate_import_libs(&mut self) -> Result<()> {
Ok(())
}
#[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!(abi3)?;
write_option_line!(lib_name)?;
write_option_line!(lib_dir)?;
write_option_line!(executable)?;
write_option_line!(pointer_width)?;
write_line!(build_flags)?;
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,
)
}
/// Lowers the configured version to the abi3 version, if set.
fn fixup_for_abi3_version(&mut self, abi3_version: Option<PythonVersion>) -> Result<()> {
// PyPy doesn't support abi3; don't adjust the version
if self.implementation.is_pypy() {
return Ok(());
}
if let Some(version) = abi3_version {
ensure!(
version <= self.version,
"cannot set a minimum Python version {} higher than the interpreter version {} \
(the minimum Python version is implied by the abi3-py3{} feature)",
version,
self.version,
version.minor,
);
self.version = version;
}
Ok(())
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct PythonVersion {
pub major: u8,
pub minor: u8,
}
impl PythonVersion {
const PY37: Self = PythonVersion { major: 3, minor: 7 };
}
impl Display for PythonVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}.{}", self.major, self.minor)
}
}
impl FromStr for PythonVersion {
type Err = crate::errors::Error;
fn from_str(value: &str) -> Result<Self, Self::Err> {
let mut split = value.splitn(2, '.');
let (major, minor) = (
split
.next()
.expect("first splitn value should always be present"),
split.next().ok_or("expected major.minor version")?,
);
Ok(Self {
major: major.parse().context("failed to parse major version")?,
minor: minor.parse().context("failed to parse minor version")?,
})
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum PythonImplementation {
CPython,
PyPy,
}
impl PythonImplementation {
#[doc(hidden)]
pub fn is_pypy(self) -> bool {
self == PythonImplementation::PyPy
}
#[doc(hidden)]
pub fn from_soabi(soabi: &str) -> Result<Self> {
if soabi.starts_with("pypy") {
Ok(PythonImplementation::PyPy)
} else if soabi.starts_with("cpython") {
Ok(PythonImplementation::CPython)
} else {
bail!("unsupported Python interpreter");
}
}
}
impl Display for PythonImplementation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PythonImplementation::CPython => write!(f, "CPython"),
PythonImplementation::PyPy => write!(f, "PyPy"),
}
}
}
impl FromStr for PythonImplementation {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
match s {
"CPython" => Ok(PythonImplementation::CPython),
"PyPy" => Ok(PythonImplementation::PyPy),
_ => bail!("unknown interpreter: {}", s),
}
}
}
/// Checks if we should look for a Python interpreter installation
/// to get the target interpreter configuration.
///
/// Returns `false` if `PYO3_NO_PYTHON` environment variable is set.
fn have_python_interpreter() -> bool {
env_var("PYO3_NO_PYTHON").is_none()
}
/// Checks if `abi3` or any of the `abi3-py3*` features is enabled for the PyO3 crate.
///
/// Must be called from a PyO3 crate build script.
fn is_abi3() -> bool {
cargo_env_var("CARGO_FEATURE_ABI3").is_some()
}
/// Gets the minimum supported Python version from PyO3 `abi3-py*` features.
///
/// Must be called from a PyO3 crate build script.
pub fn get_abi3_version() -> Option<PythonVersion> {
let minor_version = (MINIMUM_SUPPORTED_VERSION.minor..=ABI3_MAX_MINOR)
.find(|i| cargo_env_var(&format!("CARGO_FEATURE_ABI3_PY3{}", i)).is_some());
minor_version.map(|minor| PythonVersion { major: 3, minor })
}
/// Checks if the `extension-module` feature is enabled for the PyO3 crate.
///
/// Must be called from a PyO3 crate build script.
pub fn is_extension_module() -> bool {
cargo_env_var("CARGO_FEATURE_EXTENSION_MODULE").is_some()
}
/// Checks if we need to link to `libpython` for the current build target.
///
/// Must be called from a PyO3 crate build script.
pub fn is_linking_libpython() -> bool {
is_linking_libpython_for_target(&target_triple_from_env())
}
/// Checks if we need to link to `libpython` for the target.
///
/// Must be called from a PyO3 crate build script.
fn is_linking_libpython_for_target(target: &Triple) -> bool {
target.operating_system == OperatingSystem::Windows
|| target.environment == Environment::Android
|| target.environment == Environment::Androideabi
|| !is_extension_module()
}
/// Checks if we need to discover the Python library directory
/// to link the extension module binary.
///
/// Must be called from a PyO3 crate build script.
fn require_libdir_for_target(target: &Triple) -> bool {
let is_generating_libpython = cfg!(feature = "python3-dll-a")
&& target.operating_system == OperatingSystem::Windows
&& is_abi3();
is_linking_libpython_for_target(target) && !is_generating_libpython
}
/// Configuration needed by PyO3 to cross-compile for a target platform.
///
/// Usually this is collected from the environment (i.e. `PYO3_CROSS_*` and `CARGO_CFG_TARGET_*`)
/// when a cross-compilation configuration is detected.
#[derive(Debug, PartialEq, Eq)]
pub struct CrossCompileConfig {
/// The directory containing the Python library to link against.
pub lib_dir: Option<PathBuf>,
/// The version of the Python library to link against.
version: Option<PythonVersion>,
/// The target Python implementation hint (CPython or PyPy)
implementation: Option<PythonImplementation>,
/// The compile target triple (e.g. aarch64-unknown-linux-gnu)
target: Triple,
}
impl CrossCompileConfig {
/// Creates a new cross compile config struct from PyO3 environment variables
/// and the build environment when cross compilation mode is detected.
///
/// Returns `None` when not cross compiling.
fn try_from_env_vars_host_target(
env_vars: CrossCompileEnvVars,
host: &Triple,
target: &Triple,
) -> Result<Option<Self>> {
if env_vars.any() || Self::is_cross_compiling_from_to(host, target) {
let lib_dir = env_vars.lib_dir_path()?;
let version = env_vars.parse_version()?;
let implementation = env_vars.parse_implementation()?;
let target = target.clone();
Ok(Some(CrossCompileConfig {
lib_dir,
version,
implementation,
target,
}))
} else {
Ok(None)
}
}
/// Checks if compiling on `host` for `target` required "real" cross compilation.
///
/// Returns `false` if the target Python interpreter can run on the host.
fn is_cross_compiling_from_to(host: &Triple, target: &Triple) -> bool {
// Not cross-compiling if arch-vendor-os is all the same
// e.g. x86_64-unknown-linux-musl on x86_64-unknown-linux-gnu host
// x86_64-pc-windows-gnu on x86_64-pc-windows-msvc host
let mut compatible = host.architecture == target.architecture
&& host.vendor == target.vendor
&& host.operating_system == target.operating_system;
// Not cross-compiling to compile for 32-bit Python from windows 64-bit
compatible |= target.operating_system == OperatingSystem::Windows
&& host.operating_system == OperatingSystem::Windows;
// Not cross-compiling to compile for x86-64 Python from macOS arm64 and vice versa
compatible |= target.operating_system == OperatingSystem::Darwin
&& host.operating_system == OperatingSystem::Darwin;
!compatible
}
/// Converts `lib_dir` member field to an UTF-8 string.
///
/// The conversion can not fail because `PYO3_CROSS_LIB_DIR` variable
/// is ensured contain a valid UTF-8 string.
fn lib_dir_string(&self) -> Option<String> {
self.lib_dir
.as_ref()
.map(|s| s.to_str().unwrap().to_owned())
}
}
/// PyO3-specific cross compile environment variable values
struct CrossCompileEnvVars {
/// `PYO3_CROSS`
pyo3_cross: Option<OsString>,
/// `PYO3_CROSS_LIB_DIR`
pyo3_cross_lib_dir: Option<OsString>,
/// `PYO3_CROSS_PYTHON_VERSION`
pyo3_cross_python_version: Option<OsString>,
/// `PYO3_CROSS_PYTHON_IMPLEMENTATION`
pyo3_cross_python_implementation: Option<OsString>,
}
impl CrossCompileEnvVars {
/// Grabs the PyO3 cross-compile variables from the environment.
///
/// Registers the build script to rerun if any of the variables changes.
fn from_env() -> Self {
CrossCompileEnvVars {
pyo3_cross: env_var("PYO3_CROSS"),
pyo3_cross_lib_dir: env_var("PYO3_CROSS_LIB_DIR"),
pyo3_cross_python_version: env_var("PYO3_CROSS_PYTHON_VERSION"),
pyo3_cross_python_implementation: env_var("PYO3_CROSS_PYTHON_IMPLEMENTATION"),
}
}
/// Checks if any of the variables is set.
fn any(&self) -> bool {
self.pyo3_cross.is_some()
|| self.pyo3_cross_lib_dir.is_some()
|| self.pyo3_cross_python_version.is_some()
|| self.pyo3_cross_python_implementation.is_some()
}
/// Parses `PYO3_CROSS_PYTHON_VERSION` environment variable value
/// into `PythonVersion`.
fn parse_version(&self) -> Result<Option<PythonVersion>> {
let version = self
.pyo3_cross_python_version
.as_ref()
.map(|os_string| {
let utf8_str = os_string
.to_str()
.ok_or("PYO3_CROSS_PYTHON_VERSION is not valid a UTF-8 string")?;
utf8_str
.parse()
.context("failed to parse PYO3_CROSS_PYTHON_VERSION")
})
.transpose()?;
Ok(version)
}
/// Parses `PYO3_CROSS_PYTHON_IMPLEMENTATION` environment variable value
/// into `PythonImplementation`.
fn parse_implementation(&self) -> Result<Option<PythonImplementation>> {
let implementation = self
.pyo3_cross_python_implementation
.as_ref()
.map(|os_string| {
let utf8_str = os_string
.to_str()
.ok_or("PYO3_CROSS_PYTHON_IMPLEMENTATION is not valid a UTF-8 string")?;
utf8_str
.parse()
.context("failed to parse PYO3_CROSS_PYTHON_IMPLEMENTATION")
})
.transpose()?;
Ok(implementation)
}
/// Converts the stored `PYO3_CROSS_LIB_DIR` variable value (if any)
/// into a `PathBuf` instance.
///
/// Ensures that the path is a valid UTF-8 string.
fn lib_dir_path(&self) -> Result<Option<PathBuf>> {
let lib_dir = self.pyo3_cross_lib_dir.as_ref().map(PathBuf::from);
if let Some(dir) = lib_dir.as_ref() {
ensure!(
dir.to_str().is_some(),
"PYO3_CROSS_LIB_DIR variable value is not a valid UTF-8 string"
);
}
Ok(lib_dir)
}
}
/// Detect whether we are cross compiling and return an assembled CrossCompileConfig if so.
///
/// This function relies on PyO3 cross-compiling environment variables:
///
/// * `PYO3_CROSS`: If present, forces PyO3 to configure as a cross-compilation.
/// * `PYO3_CROSS_LIB_DIR`: If present, must be set to the directory containing
/// the target's libpython DSO and the associated `_sysconfigdata*.py` file for
/// Unix-like targets, or the Python DLL import libraries for the Windows target.
/// * `PYO3_CROSS_PYTHON_VERSION`: Major and minor version (e.g. 3.9) of the target Python
/// installation. This variable is only needed if PyO3 cannnot determine the version to target
/// from `abi3-py3*` features, or if there are multiple versions of Python present in
/// `PYO3_CROSS_LIB_DIR`.
///
/// See the [PyO3 User Guide](https://pyo3.rs/) for more info on cross-compiling.
#[deprecated(
since = "0.16.3",
note = "please use cross_compiling_from_to() instead"
)]
pub fn cross_compiling(
host: &str,
target_arch: &str,
target_vendor: &str,
target_os: &str,
) -> Result<Option<CrossCompileConfig>> {
let host: Triple = host.parse().map_err(|_| "bad host triple")?;
let architecture: Architecture = target_arch.parse().map_err(|_| "bad target arch")?;
let vendor: Vendor = target_vendor.parse().map_err(|_| "bad target vendor")?;
let operating_system: OperatingSystem = target_os.parse().map_err(|_| "bad target os")?;
// FIXME: This is a very bad approximation that only works
// for the current `CrossCompileConfig` implementation.
let environment = match operating_system {
OperatingSystem::Windows => Environment::Msvc,
_ => Environment::Gnu,
};
// FIXME: This field is currently unused.
let binary_format = BinaryFormat::Elf;
let target = Triple {
architecture,
vendor,
operating_system,
environment,
binary_format,
};
cross_compiling_from_to(&host, &target)
}
/// Detect whether we are cross compiling and return an assembled CrossCompileConfig if so.
///
/// This function relies on PyO3 cross-compiling environment variables:
///
/// * `PYO3_CROSS`: If present, forces PyO3 to configure as a cross-compilation.
/// * `PYO3_CROSS_LIB_DIR`: If present, must be set to the directory containing
/// the target's libpython DSO and the associated `_sysconfigdata*.py` file for
/// Unix-like targets, or the Python DLL import libraries for the Windows target.
/// * `PYO3_CROSS_PYTHON_VERSION`: Major and minor version (e.g. 3.9) of the target Python
/// installation. This variable is only needed if PyO3 cannnot determine the version to target
/// from `abi3-py3*` features, or if there are multiple versions of Python present in
/// `PYO3_CROSS_LIB_DIR`.
///
/// See the [PyO3 User Guide](https://pyo3.rs/) for more info on cross-compiling.
pub fn cross_compiling_from_to(
host: &Triple,
target: &Triple,
) -> Result<Option<CrossCompileConfig>> {
let env_vars = CrossCompileEnvVars::from_env();
CrossCompileConfig::try_from_env_vars_host_target(env_vars, host, target)
}
/// Detect whether we are cross compiling from Cargo and `PYO3_CROSS_*` environment
/// variables and return an assembled `CrossCompileConfig` if so.
///
/// This must be called from PyO3's build script, because it relies on environment
/// variables such as `CARGO_CFG_TARGET_OS` which aren't available at any other time.
pub fn cross_compiling_from_cargo_env() -> Result<Option<CrossCompileConfig>> {
let env_vars = CrossCompileEnvVars::from_env();
let host = Triple::host();
let target = target_triple_from_env();
CrossCompileConfig::try_from_env_vars_host_target(env_vars, &host, &target)
}
#[allow(non_camel_case_types)]
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enum BuildFlag {
Py_DEBUG,
Py_REF_DEBUG,