Skip to main content

target_spec/
custom.rs

1// Copyright (c) The cargo-guppy Contributors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Parse custom platforms.
5
6use std::borrow::Cow;
7
8use cfg_expr::targets::{
9    Abi, Arch, Env, Families, Family, HasAtomic, HasAtomics, Os, TargetInfo, Triple, Vendor,
10};
11use serde::Deserialize;
12
13#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd)]
14#[serde(rename_all = "kebab-case")]
15pub(crate) struct TargetDefinition {
16    // TODO: it would be nice to use target-spec-json for this, but that has a
17    // few limitations as of v0.1:
18    //
19    // * target-pointer-width is a string before roughly nightly-2025-10-12 (it
20    //   was changed to an integer after that).
21    // * Os and Env deserialized to enums, but we would really like them to be strings.
22    //
23    // ---
24    arch: String,
25    #[serde(rename = "target-pointer-width", with = "target_pointer_width")]
26    pointer_width: u8,
27
28    // These parameters are not used by target-spec but are mandatory in Target, so we require them
29    // here. https://doc.rust-lang.org/nightly/nightly-rustc/rustc_target/spec/struct.Target.html
30    #[allow(dead_code)]
31    llvm_target: String,
32    #[allow(dead_code)]
33    data_layout: String,
34
35    // These are optional parameters used by target-spec.
36    #[serde(default)]
37    os: Option<String>,
38    #[serde(default)]
39    abi: Option<String>,
40    #[serde(default)]
41    env: Option<String>,
42    #[serde(default)]
43    vendor: Option<String>,
44    #[serde(default)]
45    target_family: Vec<String>,
46    #[serde(default)]
47    target_endian: Endian,
48    #[serde(default)]
49    min_atomic_width: Option<u16>,
50    #[serde(default)]
51    max_atomic_width: Option<u16>,
52    #[serde(default)]
53    panic_strategy: Option<String>,
54}
55
56impl TargetDefinition {
57    pub(crate) fn into_target_info(self, triple: Cow<'static, str>) -> TargetInfo {
58        // Per https://doc.rust-lang.org/nightly/nightly-rustc/src/rustc_target/spec/mod.rs.html,
59        // the default value for min_atomic_width is 8.
60        let min_atomic_width = self.min_atomic_width.unwrap_or(8);
61        // The default max atomic width is the pointer width.
62        let max_atomic_width = self.max_atomic_width.unwrap_or(self.pointer_width as u16);
63
64        let mut has_atomics = Vec::new();
65        // atomic_width should always be a power of two, but rather than checking that we just
66        // start counting up from 8.
67        let mut atomic_width = 8;
68        while atomic_width <= max_atomic_width {
69            if atomic_width < min_atomic_width {
70                atomic_width *= 2;
71                continue;
72            }
73            has_atomics.push(HasAtomic::IntegerSize(atomic_width));
74            if atomic_width == self.pointer_width as u16 {
75                has_atomics.push(HasAtomic::Pointer);
76            }
77            atomic_width *= 2;
78        }
79
80        let panic_strategy = match self.panic_strategy {
81            None => cfg_expr::targets::Panic::unwind,
82            Some(s) => cfg_expr::targets::Panic::new(s),
83        };
84
85        TargetInfo {
86            triple: Triple::new(triple),
87            os: self.os.map(Os::new),
88            abi: self.abi.map(Abi::new),
89            arch: Arch::new(self.arch),
90            env: self.env.map(Env::new),
91            vendor: self.vendor.map(Vendor::new),
92            families: Families::new(self.target_family.into_iter().map(Family::new)),
93            pointer_width: self.pointer_width,
94            endian: self.target_endian.to_cfg_expr(),
95            has_atomics: HasAtomics::new(has_atomics),
96            panic: panic_strategy,
97        }
98    }
99}
100
101mod target_pointer_width {
102    use serde::Deserializer;
103
104    pub(super) fn deserialize<'de, D>(deserializer: D) -> Result<u8, D::Error>
105    where
106        D: Deserializer<'de>,
107    {
108        use std::fmt;
109
110        struct PointerWidthVisitor;
111
112        impl<'de> serde::de::Visitor<'de> for PointerWidthVisitor {
113            type Value = u8;
114
115            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
116                formatter.write_str("a string or integer representing pointer width")
117            }
118
119            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
120            where
121                E: serde::de::Error,
122            {
123                value
124                    .try_into()
125                    .map_err(|_| E::custom(format!("pointer width {value} out of range for u8")))
126            }
127
128            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
129            where
130                E: serde::de::Error,
131            {
132                value
133                    .parse::<u8>()
134                    .map_err(|error| E::custom(format!("error parsing as integer: {error}")))
135            }
136        }
137
138        deserializer.deserialize_any(PointerWidthVisitor)
139    }
140}
141
142#[derive(Copy, Clone, Debug, Deserialize, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
143#[serde(rename_all = "kebab-case")]
144enum Endian {
145    #[default]
146    Little,
147    Big,
148}
149
150impl Endian {
151    fn to_cfg_expr(self) -> cfg_expr::targets::Endian {
152        match self {
153            Self::Little => cfg_expr::targets::Endian::little,
154            Self::Big => cfg_expr::targets::Endian::big,
155        }
156    }
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162    use std::{collections::BTreeMap, process::Command};
163
164    #[derive(Deserialize)]
165    #[serde(transparent)]
166    struct AllTargets(BTreeMap<String, TargetDefinition>);
167
168    #[test]
169    fn test_all_builtin_specs_recognized() {
170        let rustc_bin: String = std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_owned());
171        let output = Command::new(rustc_bin)
172            // Used for -Zunstable-options. This is test-only code so it doesn't matter.
173            .env("RUSTC_BOOTSTRAP", "1")
174            .args(["-Z", "unstable-options", "--print", "all-target-specs-json"])
175            .output()
176            .expect("rustc command succeeded");
177        assert!(output.status.success(), "rustc command succeeded");
178
179        let all_targets: AllTargets = serde_json::from_slice(&output.stdout)
180            .expect("deserializing all-target-specs-json succeeded");
181        for (triple, target_def) in all_targets.0 {
182            eprintln!("*** testing {triple}");
183            // Just make sure this doesn't panic. (If this becomes fallible in the future, then this
184            // shouldn't return an error either.)
185            target_def.clone().into_target_info(triple.clone().into());
186
187            // Do some spot checks for things like big-endian targets.
188            if triple.starts_with("powerpc-") || triple.starts_with("powerpc64-") {
189                assert_eq!(
190                    target_def.target_endian,
191                    Endian::Big,
192                    "powerpc is big-endian"
193                );
194            }
195            if triple.contains("-linux") {
196                assert!(
197                    target_def.target_family.contains(&"unix".to_owned()),
198                    "linux target_family should contain unix (was {:#?})",
199                    target_def.target_family,
200                );
201            }
202        }
203    }
204}