Skip to content

Commit 82453a4

Browse files
committed
refactor: Move Apple OSVersion (back) to rustc_target
Also convert OSVersion into a proper struct for better type-safety.
1 parent ffa9afe commit 82453a4

File tree

11 files changed

+126
-101
lines changed

11 files changed

+126
-101
lines changed
+10-81
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
use std::env;
2-
use std::fmt::{Display, from_fn};
3-
use std::num::ParseIntError;
2+
use std::str::FromStr;
43

54
use rustc_session::Session;
65
use rustc_target::spec::Target;
6+
pub(super) use rustc_target::spec::apple::OSVersion;
77

88
use crate::errors::AppleDeploymentTarget;
99

@@ -26,76 +26,6 @@ pub(super) fn macho_platform(target: &Target) -> u32 {
2626
}
2727
}
2828

29-
/// Deployment target or SDK version.
30-
///
31-
/// The size of the numbers in here are limited by Mach-O's `LC_BUILD_VERSION`.
32-
type OSVersion = (u16, u8, u8);
33-
34-
/// Parse an OS version triple (SDK version or deployment target).
35-
fn parse_version(version: &str) -> Result<OSVersion, ParseIntError> {
36-
if let Some((major, minor)) = version.split_once('.') {
37-
let major = major.parse()?;
38-
if let Some((minor, patch)) = minor.split_once('.') {
39-
Ok((major, minor.parse()?, patch.parse()?))
40-
} else {
41-
Ok((major, minor.parse()?, 0))
42-
}
43-
} else {
44-
Ok((version.parse()?, 0, 0))
45-
}
46-
}
47-
48-
pub fn pretty_version(version: OSVersion) -> impl Display {
49-
let (major, minor, patch) = version;
50-
from_fn(move |f| {
51-
write!(f, "{major}.{minor}")?;
52-
if patch != 0 {
53-
write!(f, ".{patch}")?;
54-
}
55-
Ok(())
56-
})
57-
}
58-
59-
/// Minimum operating system versions currently supported by `rustc`.
60-
fn os_minimum_deployment_target(os: &str) -> OSVersion {
61-
// When bumping a version in here, remember to update the platform-support docs too.
62-
//
63-
// NOTE: The defaults may change in future `rustc` versions, so if you are looking for the
64-
// default deployment target, prefer:
65-
// ```
66-
// $ rustc --print deployment-target
67-
// ```
68-
match os {
69-
"macos" => (10, 12, 0),
70-
"ios" => (10, 0, 0),
71-
"tvos" => (10, 0, 0),
72-
"watchos" => (5, 0, 0),
73-
"visionos" => (1, 0, 0),
74-
_ => unreachable!("tried to get deployment target for non-Apple platform"),
75-
}
76-
}
77-
78-
/// The deployment target for the given target.
79-
///
80-
/// This is similar to `os_minimum_deployment_target`, except that on certain targets it makes sense
81-
/// to raise the minimum OS version.
82-
///
83-
/// This matches what LLVM does, see in part:
84-
/// <https://github.com/llvm/llvm-project/blob/llvmorg-18.1.8/llvm/lib/TargetParser/Triple.cpp#L1900-L1932>
85-
fn minimum_deployment_target(target: &Target) -> OSVersion {
86-
match (&*target.os, &*target.arch, &*target.abi) {
87-
("macos", "aarch64", _) => (11, 0, 0),
88-
("ios", "aarch64", "macabi") => (14, 0, 0),
89-
("ios", "aarch64", "sim") => (14, 0, 0),
90-
("ios", _, _) if target.llvm_target.starts_with("arm64e") => (14, 0, 0),
91-
// Mac Catalyst defaults to 13.1 in Clang.
92-
("ios", _, "macabi") => (13, 1, 0),
93-
("tvos", "aarch64", "sim") => (14, 0, 0),
94-
("watchos", "aarch64", "sim") => (7, 0, 0),
95-
(os, _, _) => os_minimum_deployment_target(os),
96-
}
97-
}
98-
9929
/// Name of the environment variable used to fetch the deployment target on the given OS.
10030
pub fn deployment_target_env_var(os: &str) -> &'static str {
10131
match os {
@@ -111,22 +41,22 @@ pub fn deployment_target_env_var(os: &str) -> &'static str {
11141
/// Get the deployment target based on the standard environment variables, or fall back to the
11242
/// minimum version supported by `rustc`.
11343
pub fn deployment_target(sess: &Session) -> OSVersion {
114-
let min = minimum_deployment_target(&sess.target);
44+
let min = OSVersion::minimum_deployment_target(&sess.target);
11545
let env_var = deployment_target_env_var(&sess.target.os);
11646

11747
if let Ok(deployment_target) = env::var(env_var) {
118-
match parse_version(&deployment_target) {
48+
match OSVersion::from_str(&deployment_target) {
11949
Ok(version) => {
120-
let os_min = os_minimum_deployment_target(&sess.target.os);
50+
let os_min = OSVersion::os_minimum_deployment_target(&sess.target.os);
12151
// It is common that the deployment target is set a bit too low, for example on
12252
// macOS Aarch64 to also target older x86_64. So we only want to warn when variable
12353
// is lower than the minimum OS supported by rustc, not when the variable is lower
12454
// than the minimum for a specific target.
12555
if version < os_min {
12656
sess.dcx().emit_warn(AppleDeploymentTarget::TooLow {
12757
env_var,
128-
version: pretty_version(version).to_string(),
129-
os_min: pretty_version(os_min).to_string(),
58+
version: version.fmt_pretty().to_string(),
59+
os_min: os_min.fmt_pretty().to_string(),
13060
});
13161
}
13262

@@ -155,17 +85,16 @@ pub(super) fn add_version_to_llvm_target(
15585
let environment = components.next();
15686
assert_eq!(components.next(), None, "too many LLVM triple components");
15787

158-
let (major, minor, patch) = deployment_target;
159-
16088
assert!(
16189
!os.contains(|c: char| c.is_ascii_digit()),
16290
"LLVM target must not already be versioned"
16391
);
16492

93+
let version = deployment_target.fmt_full();
16594
if let Some(env) = environment {
16695
// Insert version into OS, before environment
167-
format!("{arch}-{vendor}-{os}{major}.{minor}.{patch}-{env}")
96+
format!("{arch}-{vendor}-{os}{version}-{env}")
16897
} else {
169-
format!("{arch}-{vendor}-{os}{major}.{minor}.{patch}")
98+
format!("{arch}-{vendor}-{os}{version}")
17099
}
171100
}
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,13 @@
1-
use super::{add_version_to_llvm_target, parse_version};
1+
use super::{OSVersion, add_version_to_llvm_target};
22

33
#[test]
44
fn test_add_version_to_llvm_target() {
55
assert_eq!(
6-
add_version_to_llvm_target("aarch64-apple-macosx", (10, 14, 1)),
6+
add_version_to_llvm_target("aarch64-apple-macosx", OSVersion::new(10, 14, 1)),
77
"aarch64-apple-macosx10.14.1"
88
);
99
assert_eq!(
10-
add_version_to_llvm_target("aarch64-apple-ios-simulator", (16, 1, 0)),
10+
add_version_to_llvm_target("aarch64-apple-ios-simulator", OSVersion::new(16, 1, 0)),
1111
"aarch64-apple-ios16.1.0-simulator"
1212
);
1313
}
14-
15-
#[test]
16-
fn test_parse_version() {
17-
assert_eq!(parse_version("10"), Ok((10, 0, 0)));
18-
assert_eq!(parse_version("10.12"), Ok((10, 12, 0)));
19-
assert_eq!(parse_version("10.12.6"), Ok((10, 12, 6)));
20-
assert_eq!(parse_version("9999.99.99"), Ok((9999, 99, 99)));
21-
}

compiler/rustc_codegen_ssa/src/back/link.rs

+3-4
Original file line numberDiff line numberDiff line change
@@ -3114,8 +3114,7 @@ fn add_apple_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavo
31143114
_ => bug!("invalid OS/ABI combination for Apple target: {target_os}, {target_abi}"),
31153115
};
31163116

3117-
let (major, minor, patch) = apple::deployment_target(sess);
3118-
let min_version = format!("{major}.{minor}.{patch}");
3117+
let min_version = apple::deployment_target(sess).fmt_full().to_string();
31193118

31203119
// The SDK version is used at runtime when compiling with a newer SDK / version of Xcode:
31213120
// - By dyld to give extra warnings and errors, see e.g.:
@@ -3184,10 +3183,10 @@ fn add_apple_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavo
31843183

31853184
// The presence of `-mmacosx-version-min` makes CC default to
31863185
// macOS, and it sets the deployment target.
3187-
let (major, minor, patch) = apple::deployment_target(sess);
3186+
let version = apple::deployment_target(sess).fmt_full();
31883187
// Intentionally pass this as a single argument, Clang doesn't
31893188
// seem to like it otherwise.
3190-
cmd.cc_arg(&format!("-mmacosx-version-min={major}.{minor}.{patch}"));
3189+
cmd.cc_arg(&format!("-mmacosx-version-min={version}"));
31913190

31923191
// macOS has no environment, so with these two, we've told CC the
31933192
// four desired parameters.

compiler/rustc_codegen_ssa/src/back/metadata.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -426,7 +426,7 @@ pub(crate) fn create_object_file(sess: &Session) -> Option<write::Object<'static
426426
fn macho_object_build_version_for_target(sess: &Session) -> object::write::MachOBuildVersion {
427427
/// The `object` crate demands "X.Y.Z encoded in nibbles as xxxx.yy.zz"
428428
/// e.g. minOS 14.0 = 0x000E0000, or SDK 16.2 = 0x00100200
429-
fn pack_version((major, minor, patch): (u16, u8, u8)) -> u32 {
429+
fn pack_version(apple::OSVersion { major, minor, patch }: apple::OSVersion) -> u32 {
430430
let (major, minor, patch) = (major as u32, minor as u32, patch as u32);
431431
(major << 16) | (minor << 8) | patch
432432
}

compiler/rustc_codegen_ssa/src/lib.rs

-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
#![doc(rust_logo)]
77
#![feature(assert_matches)]
88
#![feature(box_patterns)]
9-
#![feature(debug_closure_helpers)]
109
#![feature(file_buffered)]
1110
#![feature(if_let_guard)]
1211
#![feature(let_chains)]

compiler/rustc_driver_impl/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -776,7 +776,7 @@ fn print_crate_info(
776776
println_info!(
777777
"{}={}",
778778
apple::deployment_target_env_var(&sess.target.os),
779-
apple::pretty_version(apple::deployment_target(sess)),
779+
apple::deployment_target(sess).fmt_pretty(),
780780
)
781781
} else {
782782
#[allow(rustc::diagnostic_outside_of_impl)]

compiler/rustc_target/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
1313
#![doc(rust_logo)]
1414
#![feature(assert_matches)]
15+
#![feature(debug_closure_helpers)]
1516
#![feature(iter_intersperse)]
1617
#![feature(let_chains)]
1718
#![feature(rustc_attrs)]

compiler/rustc_target/src/spec/base/apple/mod.rs

+96-1
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
use std::borrow::Cow;
22
use std::env;
3+
use std::fmt::{Display, from_fn};
4+
use std::num::ParseIntError;
5+
use std::str::FromStr;
36

47
use crate::spec::{
58
Cc, DebuginfoKind, FloatAbi, FramePointer, LinkerFlavor, Lld, SplitDebuginfo, StackProbeType,
6-
StaticCow, TargetOptions, cvs,
9+
StaticCow, Target, TargetOptions, cvs,
710
};
811

912
#[cfg(test)]
@@ -217,3 +220,95 @@ fn link_env_remove(os: &'static str) -> StaticCow<[StaticCow<str>]> {
217220
cvs!["MACOSX_DEPLOYMENT_TARGET"]
218221
}
219222
}
223+
224+
/// Deployment target or SDK version.
225+
///
226+
/// The size of the numbers in here are limited by Mach-O's `LC_BUILD_VERSION`.
227+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
228+
pub struct OSVersion {
229+
pub major: u16,
230+
pub minor: u8,
231+
pub patch: u8,
232+
}
233+
234+
impl FromStr for OSVersion {
235+
type Err = ParseIntError;
236+
237+
/// Parse an OS version triple (SDK version or deployment target).
238+
fn from_str(version: &str) -> Result<Self, ParseIntError> {
239+
if let Some((major, minor)) = version.split_once('.') {
240+
let major = major.parse()?;
241+
if let Some((minor, patch)) = minor.split_once('.') {
242+
Ok(Self { major, minor: minor.parse()?, patch: patch.parse()? })
243+
} else {
244+
Ok(Self { major, minor: minor.parse()?, patch: 0 })
245+
}
246+
} else {
247+
Ok(Self { major: version.parse()?, minor: 0, patch: 0 })
248+
}
249+
}
250+
}
251+
252+
impl OSVersion {
253+
pub fn new(major: u16, minor: u8, patch: u8) -> Self {
254+
Self { major, minor, patch }
255+
}
256+
257+
pub fn fmt_pretty(self) -> impl Display {
258+
let Self { major, minor, patch } = self;
259+
from_fn(move |f| {
260+
write!(f, "{major}.{minor}")?;
261+
if patch != 0 {
262+
write!(f, ".{patch}")?;
263+
}
264+
Ok(())
265+
})
266+
}
267+
268+
pub fn fmt_full(self) -> impl Display {
269+
let Self { major, minor, patch } = self;
270+
from_fn(move |f| write!(f, "{major}.{minor}.{patch}"))
271+
}
272+
273+
/// Minimum operating system versions currently supported by `rustc`.
274+
pub fn os_minimum_deployment_target(os: &str) -> Self {
275+
// When bumping a version in here, remember to update the platform-support docs too.
276+
//
277+
// NOTE: The defaults may change in future `rustc` versions, so if you are looking for the
278+
// default deployment target, prefer:
279+
// ```
280+
// $ rustc --print deployment-target
281+
// ```
282+
let (major, minor, patch) = match os {
283+
"macos" => (10, 12, 0),
284+
"ios" => (10, 0, 0),
285+
"tvos" => (10, 0, 0),
286+
"watchos" => (5, 0, 0),
287+
"visionos" => (1, 0, 0),
288+
_ => unreachable!("tried to get deployment target for non-Apple platform"),
289+
};
290+
Self { major, minor, patch }
291+
}
292+
293+
/// The deployment target for the given target.
294+
///
295+
/// This is similar to `os_minimum_deployment_target`, except that on certain targets it makes sense
296+
/// to raise the minimum OS version.
297+
///
298+
/// This matches what LLVM does, see in part:
299+
/// <https://github.com/llvm/llvm-project/blob/llvmorg-18.1.8/llvm/lib/TargetParser/Triple.cpp#L1900-L1932>
300+
pub fn minimum_deployment_target(target: &Target) -> Self {
301+
let (major, minor, patch) = match (&*target.os, &*target.arch, &*target.abi) {
302+
("macos", "aarch64", _) => (11, 0, 0),
303+
("ios", "aarch64", "macabi") => (14, 0, 0),
304+
("ios", "aarch64", "sim") => (14, 0, 0),
305+
("ios", _, _) if target.llvm_target.starts_with("arm64e") => (14, 0, 0),
306+
// Mac Catalyst defaults to 13.1 in Clang.
307+
("ios", _, "macabi") => (13, 1, 0),
308+
("tvos", "aarch64", "sim") => (14, 0, 0),
309+
("watchos", "aarch64", "sim") => (7, 0, 0),
310+
(os, _, _) => return Self::os_minimum_deployment_target(os),
311+
};
312+
Self { major, minor, patch }
313+
}
314+
}

compiler/rustc_target/src/spec/base/apple/tests.rs

+9
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use super::OSVersion;
12
use crate::spec::targets::{
23
aarch64_apple_darwin, aarch64_apple_ios_sim, aarch64_apple_visionos_sim,
34
aarch64_apple_watchos_sim, i686_apple_darwin, x86_64_apple_darwin, x86_64_apple_ios,
@@ -42,3 +43,11 @@ fn macos_link_environment_unmodified() {
4243
);
4344
}
4445
}
46+
47+
#[test]
48+
fn test_parse_version() {
49+
assert_eq!("10".parse(), Ok(OSVersion::new(10, 0, 0)));
50+
assert_eq!("10.12".parse(), Ok(OSVersion::new(10, 12, 0)));
51+
assert_eq!("10.12.6".parse(), Ok(OSVersion::new(10, 12, 6)));
52+
assert_eq!("9999.99.99".parse(), Ok(OSVersion::new(9999, 99, 99)));
53+
}

compiler/rustc_target/src/spec/base/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
pub(crate) mod aix;
22
pub(crate) mod android;
3-
pub(crate) mod apple;
3+
pub mod apple;
44
pub(crate) mod avr_gnu;
55
pub(crate) mod bpf;
66
pub(crate) mod dragonfly;

compiler/rustc_target/src/spec/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ pub mod abi {
6767
mod base;
6868
mod json;
6969

70+
pub use base::apple;
7071
pub use base::avr_gnu::ef_avr_arch;
7172

7273
/// Linker is called through a C/C++ compiler.

0 commit comments

Comments
 (0)