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, Serialize};
12
13#[derive(Clone, Debug, Deserialize, Serialize, 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, Serializer};
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    pub(super) fn serialize<S>(value: &u8, serializer: S) -> Result<S::Ok, S::Error>
142    where
143        S: Serializer,
144    {
145        // Should change this in the future to serialize as an integer?
146        serializer.serialize_str(&value.to_string())
147    }
148}
149
150#[derive(
151    Copy, Clone, Debug, Deserialize, Serialize, Default, Eq, Hash, Ord, PartialEq, PartialOrd,
152)]
153#[serde(rename_all = "kebab-case")]
154enum Endian {
155    #[default]
156    Little,
157    Big,
158}
159
160impl Endian {
161    fn to_cfg_expr(self) -> cfg_expr::targets::Endian {
162        match self {
163            Self::Little => cfg_expr::targets::Endian::little,
164            Self::Big => cfg_expr::targets::Endian::big,
165        }
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172    use std::{collections::BTreeMap, process::Command};
173
174    #[derive(Deserialize)]
175    #[serde(transparent)]
176    struct AllTargets(BTreeMap<String, TargetDefinition>);
177
178    #[test]
179    fn test_all_builtin_specs_recognized() {
180        let rustc_bin: String = std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_owned());
181        let output = Command::new(rustc_bin)
182            // Used for -Zunstable-options. This is test-only code so it doesn't matter.
183            .env("RUSTC_BOOTSTRAP", "1")
184            .args(["-Z", "unstable-options", "--print", "all-target-specs-json"])
185            .output()
186            .expect("rustc command succeeded");
187        assert!(output.status.success(), "rustc command succeeded");
188
189        let all_targets: AllTargets = serde_json::from_slice(&output.stdout)
190            .expect("deserializing all-target-specs-json succeeded");
191        for (triple, target_def) in all_targets.0 {
192            eprintln!("*** testing {triple}");
193            // Just make sure this doesn't panic. (If this becomes fallible in the future, then this
194            // shouldn't return an error either.)
195            target_def.clone().into_target_info(triple.clone().into());
196            let json =
197                serde_json::to_string(&target_def).expect("target def serialized successfully");
198            eprintln!("* minified json: {json}");
199            let target_def_2 = serde_json::from_str(&json).expect("target def 2 deserialized");
200            assert_eq!(target_def, target_def_2, "matches");
201
202            // Do some spot checks for things like big-endian targets.
203            if triple.starts_with("powerpc-") || triple.starts_with("powerpc64-") {
204                assert_eq!(
205                    target_def.target_endian,
206                    Endian::Big,
207                    "powerpc is big-endian"
208                );
209            }
210            if triple.contains("-linux") {
211                assert!(
212                    target_def.target_family.contains(&"unix".to_owned()),
213                    "linux target_family should contain unix (was {:#?})",
214                    target_def.target_family,
215                );
216            }
217        }
218    }
219}