Skip to content

Commit d74ce25

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

File tree

11 files changed

+125
-100
lines changed

11 files changed

+125
-100
lines changed

Diff for: compiler/rustc_codegen_ssa/src/back/apple.rs

+10-81
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
use std::env;
22
use std::ffi::OsString;
3-
use std::fmt::{Display, from_fn};
4-
use std::num::ParseIntError;
3+
use std::str::FromStr;
54
use std::path::PathBuf;
65
use std::process::Command;
76

87
use itertools::Itertools;
98
use rustc_middle::middle::exported_symbols::SymbolExportKind;
109
use rustc_session::Session;
1110
use rustc_target::spec::Target;
11+
pub(super) use rustc_target::spec::apple::OSVersion;
1212
use tracing::debug;
1313

1414
use crate::errors::{AppleDeploymentTarget, XcrunError, XcrunSdkPathWarning};
@@ -134,76 +134,6 @@ pub(super) fn add_data_and_relocation(
134134
Ok(())
135135
}
136136

137-
/// Deployment target or SDK version.
138-
///
139-
/// The size of the numbers in here are limited by Mach-O's `LC_BUILD_VERSION`.
140-
type OSVersion = (u16, u8, u8);
141-
142-
/// Parse an OS version triple (SDK version or deployment target).
143-
fn parse_version(version: &str) -> Result<OSVersion, ParseIntError> {
144-
if let Some((major, minor)) = version.split_once('.') {
145-
let major = major.parse()?;
146-
if let Some((minor, patch)) = minor.split_once('.') {
147-
Ok((major, minor.parse()?, patch.parse()?))
148-
} else {
149-
Ok((major, minor.parse()?, 0))
150-
}
151-
} else {
152-
Ok((version.parse()?, 0, 0))
153-
}
154-
}
155-
156-
pub fn pretty_version(version: OSVersion) -> impl Display {
157-
let (major, minor, patch) = version;
158-
from_fn(move |f| {
159-
write!(f, "{major}.{minor}")?;
160-
if patch != 0 {
161-
write!(f, ".{patch}")?;
162-
}
163-
Ok(())
164-
})
165-
}
166-
167-
/// Minimum operating system versions currently supported by `rustc`.
168-
fn os_minimum_deployment_target(os: &str) -> OSVersion {
169-
// When bumping a version in here, remember to update the platform-support docs too.
170-
//
171-
// NOTE: The defaults may change in future `rustc` versions, so if you are looking for the
172-
// default deployment target, prefer:
173-
// ```
174-
// $ rustc --print deployment-target
175-
// ```
176-
match os {
177-
"macos" => (10, 12, 0),
178-
"ios" => (10, 0, 0),
179-
"tvos" => (10, 0, 0),
180-
"watchos" => (5, 0, 0),
181-
"visionos" => (1, 0, 0),
182-
_ => unreachable!("tried to get deployment target for non-Apple platform"),
183-
}
184-
}
185-
186-
/// The deployment target for the given target.
187-
///
188-
/// This is similar to `os_minimum_deployment_target`, except that on certain targets it makes sense
189-
/// to raise the minimum OS version.
190-
///
191-
/// This matches what LLVM does, see in part:
192-
/// <https://github.com/llvm/llvm-project/blob/llvmorg-18.1.8/llvm/lib/TargetParser/Triple.cpp#L1900-L1932>
193-
fn minimum_deployment_target(target: &Target) -> OSVersion {
194-
match (&*target.os, &*target.arch, &*target.abi) {
195-
("macos", "aarch64", _) => (11, 0, 0),
196-
("ios", "aarch64", "macabi") => (14, 0, 0),
197-
("ios", "aarch64", "sim") => (14, 0, 0),
198-
("ios", _, _) if target.llvm_target.starts_with("arm64e") => (14, 0, 0),
199-
// Mac Catalyst defaults to 13.1 in Clang.
200-
("ios", _, "macabi") => (13, 1, 0),
201-
("tvos", "aarch64", "sim") => (14, 0, 0),
202-
("watchos", "aarch64", "sim") => (7, 0, 0),
203-
(os, _, _) => os_minimum_deployment_target(os),
204-
}
205-
}
206-
207137
/// Name of the environment variable used to fetch the deployment target on the given OS.
208138
pub fn deployment_target_env_var(os: &str) -> &'static str {
209139
match os {
@@ -219,22 +149,22 @@ pub fn deployment_target_env_var(os: &str) -> &'static str {
219149
/// Get the deployment target based on the standard environment variables, or fall back to the
220150
/// minimum version supported by `rustc`.
221151
pub fn deployment_target(sess: &Session) -> OSVersion {
222-
let min = minimum_deployment_target(&sess.target);
152+
let min = OSVersion::minimum_deployment_target(&sess.target);
223153
let env_var = deployment_target_env_var(&sess.target.os);
224154

225155
if let Ok(deployment_target) = env::var(env_var) {
226-
match parse_version(&deployment_target) {
156+
match OSVersion::from_str(&deployment_target) {
227157
Ok(version) => {
228-
let os_min = os_minimum_deployment_target(&sess.target.os);
158+
let os_min = OSVersion::os_minimum_deployment_target(&sess.target.os);
229159
// It is common that the deployment target is set a bit too low, for example on
230160
// macOS Aarch64 to also target older x86_64. So we only want to warn when variable
231161
// is lower than the minimum OS supported by rustc, not when the variable is lower
232162
// than the minimum for a specific target.
233163
if version < os_min {
234164
sess.dcx().emit_warn(AppleDeploymentTarget::TooLow {
235165
env_var,
236-
version: pretty_version(version).to_string(),
237-
os_min: pretty_version(os_min).to_string(),
166+
version: version.fmt_pretty().to_string(),
167+
os_min: os_min.fmt_pretty().to_string(),
238168
});
239169
}
240170

@@ -263,18 +193,17 @@ pub(super) fn add_version_to_llvm_target(
263193
let environment = components.next();
264194
assert_eq!(components.next(), None, "too many LLVM triple components");
265195

266-
let (major, minor, patch) = deployment_target;
267-
268196
assert!(
269197
!os.contains(|c: char| c.is_ascii_digit()),
270198
"LLVM target must not already be versioned"
271199
);
272200

201+
let version = deployment_target.fmt_full();
273202
if let Some(env) = environment {
274203
// Insert version into OS, before environment
275-
format!("{arch}-{vendor}-{os}{major}.{minor}.{patch}-{env}")
204+
format!("{arch}-{vendor}-{os}{version}-{env}")
276205
} else {
277-
format!("{arch}-{vendor}-{os}{major}.{minor}.{patch}")
206+
format!("{arch}-{vendor}-{os}{version}")
278207
}
279208
}
280209

Diff for: compiler/rustc_codegen_ssa/src/back/apple/tests.rs

+2-10
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,15 @@ use super::*;
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
}
1414

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-
}
22-
2315
#[test]
2416
#[cfg_attr(not(target_os = "macos"), ignore = "xcode-select is only available on macOS")]
2517
fn lookup_developer_dir() {

Diff for: compiler/rustc_codegen_ssa/src/back/link.rs

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

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

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

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

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

Diff for: compiler/rustc_codegen_ssa/src/back/metadata.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,7 @@ pub(super) fn elf_e_flags(architecture: Architecture, sess: &Session) -> u32 {
388388
fn macho_object_build_version_for_target(sess: &Session) -> object::write::MachOBuildVersion {
389389
/// The `object` crate demands "X.Y.Z encoded in nibbles as xxxx.yy.zz"
390390
/// e.g. minOS 14.0 = 0x000E0000, or SDK 16.2 = 0x00100200
391-
fn pack_version((major, minor, patch): (u16, u8, u8)) -> u32 {
391+
fn pack_version(apple::OSVersion { major, minor, patch }: apple::OSVersion) -> u32 {
392392
let (major, minor, patch) = (major as u32, minor as u32, patch as u32);
393393
(major << 16) | (minor << 8) | patch
394394
}

Diff for: compiler/rustc_codegen_ssa/src/lib.rs

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

Diff for: compiler/rustc_driver_impl/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -811,7 +811,7 @@ fn print_crate_info(
811811
println_info!(
812812
"{}={}",
813813
apple::deployment_target_env_var(&sess.target.os),
814-
apple::pretty_version(apple::deployment_target(sess)),
814+
apple::deployment_target(sess).fmt_pretty(),
815815
)
816816
} else {
817817
#[allow(rustc::diagnostic_outside_of_impl)]

Diff for: 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)]

Diff for: 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
BinaryFormat, Cc, DebuginfoKind, FloatAbi, FramePointer, LinkerFlavor, Lld, RustcAbi,
6-
SplitDebuginfo, StackProbeType, StaticCow, TargetOptions, cvs,
9+
SplitDebuginfo, StackProbeType, StaticCow, Target, TargetOptions, cvs,
710
};
811

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

Diff for: 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+
}

Diff for: 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;
55
pub(crate) mod bpf;
66
pub(crate) mod cygwin;

Diff for: compiler/rustc_target/src/spec/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ pub mod crt_objects;
6060
mod base;
6161
mod json;
6262

63+
pub use base::apple;
6364
pub use base::avr::ef_avr_arch;
6465

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

0 commit comments

Comments
 (0)