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
// Copyright (c) The cargo-guppy Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Serialized versions of platform and target features.
//!
//! Some users of `target-spec` may want to serialize and deserialize its data structures into, say,
//! TOML files. This module provides facilities for that.
//!
//! Summaries require the `summaries` feature to be enabled.

use crate::{Error, Platform, TargetFeatures};
use serde::{Deserialize, Serialize};
use std::{borrow::Cow, collections::BTreeSet};

impl Platform {
    /// Converts this `Platform` to a serializable form.
    ///
    /// Requires the `summaries` feature to be enabled.
    #[inline]
    pub fn to_summary(&self) -> PlatformSummary {
        PlatformSummary::from_platform(self)
    }
}

/// An owned, serializable version of [`Platform`].
///
/// This structure can be serialized and deserialized using `serde`.
///
/// Requires the `summaries` feature to be enabled.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub struct PlatformSummary {
    /// The platform triple.
    pub triple: String,

    /// JSON for custom platforms.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub custom_json: Option<String>,

    /// The target features used.
    pub target_features: TargetFeaturesSummary,

    /// The flags enabled.
    #[serde(skip_serializing_if = "BTreeSet::is_empty", default)]
    pub flags: BTreeSet<String>,
}

impl PlatformSummary {
    /// Creates a new `PlatformSummary` with the provided triple and default options.
    ///
    /// The default options are:
    ///
    /// * `custom_json` is set to None.
    /// * `target_features` is set to [`TargetFeaturesSummary::Unknown`].
    /// * `flags` is empty.
    pub fn new(triple_str: impl Into<String>) -> Self {
        Self {
            triple: triple_str.into(),
            custom_json: None,
            target_features: TargetFeaturesSummary::Unknown,
            flags: BTreeSet::new(),
        }
    }

    /// If this represents a custom platform, sets the target definition JSON for it.
    ///
    /// For more about target definition JSON, see [Creating a custom
    /// target](https://docs.rust-embedded.org/embedonomicon/custom-target.html) on the Rust
    /// Embedonomicon.
    pub fn with_custom_json(mut self, custom_json: impl Into<String>) -> Self {
        self.custom_json = Some(custom_json.into());
        self
    }

    /// Sets the target features for this platform.
    pub fn with_target_features(mut self, target_features: TargetFeaturesSummary) -> Self {
        self.target_features = target_features;
        self
    }

    /// Adds flags for this platform.
    pub fn with_added_flags(mut self, flags: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.flags.extend(flags.into_iter().map(|flag| flag.into()));
        self
    }

    /// Creates a new `PlatformSummary` instance from a platform.
    pub fn from_platform(platform: &Platform) -> Self {
        Self {
            triple: platform.triple_str().to_string(),
            custom_json: platform.custom_json().map(|s| s.to_owned()),
            target_features: TargetFeaturesSummary::new(platform.target_features()),
            flags: platform.flags().map(|flag| flag.to_string()).collect(),
        }
    }

    /// Converts `self` to a `Platform`.
    ///
    /// Returns an `Error` if the platform was unknown.
    pub fn to_platform(&self) -> Result<Platform, Error> {
        #[allow(unused_variables)] // in some feature branches, json isn't used
        let mut platform = if let Some(json) = &self.custom_json {
            #[cfg(not(feature = "custom"))]
            return Err(Error::CustomPlatformCreate(
                crate::errors::CustomTripleCreateError::Unavailable,
            ));

            #[cfg(feature = "custom")]
            Platform::new_custom(
                self.triple.to_owned(),
                json,
                self.target_features.to_target_features(),
            )?
        } else {
            Platform::new(
                self.triple.to_owned(),
                self.target_features.to_target_features(),
            )?
        };

        platform.add_flags(self.flags.iter().cloned());
        Ok(platform)
    }
}

/// An owned, serializable version of [`TargetFeatures`].
///
/// This type can be serialized and deserialized using `serde`.
///
/// Requires the `summaries` feature to be enabled.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
#[derive(Default)]
pub enum TargetFeaturesSummary {
    /// The target features are unknown.
    ///
    /// This is the default.
    #[default]
    Unknown,
    /// Only match the specified features.
    Features(BTreeSet<String>),
    /// Match all features.
    All,
}

impl TargetFeaturesSummary {
    /// Creates a new `TargetFeaturesSummary` from a `TargetFeatures`.
    pub fn new(target_features: &TargetFeatures) -> Self {
        match target_features {
            TargetFeatures::Unknown => TargetFeaturesSummary::Unknown,
            TargetFeatures::Features(features) => TargetFeaturesSummary::Features(
                features.iter().map(|feature| feature.to_string()).collect(),
            ),
            TargetFeatures::All => TargetFeaturesSummary::All,
        }
    }

    /// Converts `self` to a `TargetFeatures` instance.
    pub fn to_target_features(&self) -> TargetFeatures {
        match self {
            TargetFeaturesSummary::Unknown => TargetFeatures::Unknown,
            TargetFeaturesSummary::All => TargetFeatures::All,
            TargetFeaturesSummary::Features(features) => {
                let features = features
                    .iter()
                    .map(|feature| Cow::Owned(feature.clone()))
                    .collect();
                TargetFeatures::Features(features)
            }
        }
    }
}

mod platform_impl {
    use super::*;
    use serde::Deserializer;

    impl<'de> Deserialize<'de> for PlatformSummary {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            let d = PlatformSummaryDeserialize::deserialize(deserializer)?;
            match d {
                PlatformSummaryDeserialize::String(triple) => Ok(PlatformSummary {
                    triple,
                    custom_json: None,
                    target_features: TargetFeaturesSummary::default(),
                    flags: BTreeSet::default(),
                }),
                PlatformSummaryDeserialize::Full {
                    triple,
                    custom_json,
                    target_features,
                    flags,
                } => Ok(PlatformSummary {
                    triple,
                    custom_json,
                    target_features,
                    flags,
                }),
            }
        }
    }

    #[derive(Deserialize)]
    #[serde(untagged)]
    enum PlatformSummaryDeserialize {
        String(String),
        #[serde(rename_all = "kebab-case")]
        Full {
            triple: String,
            #[serde(default)]
            custom_json: Option<String>,
            /// The target features used.
            #[serde(default)]
            target_features: TargetFeaturesSummary,
            /// The flags enabled.
            #[serde(skip_serializing_if = "BTreeSet::is_empty", default)]
            flags: BTreeSet<String>,
        },
    }
}

mod target_features_impl {
    use super::*;
    use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};

    impl Serialize for TargetFeaturesSummary {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            match self {
                TargetFeaturesSummary::Unknown => "unknown".serialize(serializer),
                TargetFeaturesSummary::All => "all".serialize(serializer),
                TargetFeaturesSummary::Features(features) => features.serialize(serializer),
            }
        }
    }

    impl<'de> Deserialize<'de> for TargetFeaturesSummary {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            let d = TargetFeaturesDeserialize::deserialize(deserializer)?;
            match d {
                TargetFeaturesDeserialize::String(target_features) => {
                    match target_features.as_str() {
                        "unknown" => Ok(TargetFeaturesSummary::Unknown),
                        "all" => Ok(TargetFeaturesSummary::All),
                        other => Err(D::Error::custom(format!(
                            "unknown string for target features: {}",
                            other,
                        ))),
                    }
                }
                TargetFeaturesDeserialize::List(target_features) => {
                    Ok(TargetFeaturesSummary::Features(target_features))
                }
            }
        }
    }

    #[derive(Deserialize)]
    #[serde(untagged)]
    enum TargetFeaturesDeserialize {
        String(String),
        List(BTreeSet<String>),
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::vec_init_then_push)]

    use super::*;

    #[test]
    fn platform_deserialize_valid() {
        // Need a wrapper because of TOML restrictions
        #[derive(Debug, Deserialize, Serialize, Eq, PartialEq)]
        struct Wrapper {
            platform: PlatformSummary,
        }

        let mut valid = vec![];
        valid.push((
            r#"platform = "x86_64-unknown-linux-gnu""#,
            PlatformSummary {
                triple: "x86_64-unknown-linux-gnu".into(),
                custom_json: None,
                target_features: TargetFeaturesSummary::Unknown,
                flags: BTreeSet::new(),
            },
        ));
        valid.push((
            r#"platform = { triple = "x86_64-unknown-linux-gnu" }"#,
            PlatformSummary {
                triple: "x86_64-unknown-linux-gnu".into(),
                custom_json: None,
                target_features: TargetFeaturesSummary::Unknown,
                flags: BTreeSet::new(),
            },
        ));
        valid.push((
            r#"platform = { triple = "x86_64-unknown-linux-gnu", target-features = "unknown" }"#,
            PlatformSummary {
                triple: "x86_64-unknown-linux-gnu".into(),
                custom_json: None,
                target_features: TargetFeaturesSummary::Unknown,
                flags: BTreeSet::new(),
            },
        ));
        valid.push((
            r#"platform = { triple = "x86_64-unknown-linux-gnu", target-features = "all" }"#,
            PlatformSummary {
                triple: "x86_64-unknown-linux-gnu".into(),
                custom_json: None,
                target_features: TargetFeaturesSummary::All,
                flags: BTreeSet::new(),
            },
        ));
        valid.push((
            r#"platform = { triple = "x86_64-unknown-linux-gnu", target-features = [] }"#,
            PlatformSummary {
                triple: "x86_64-unknown-linux-gnu".into(),
                custom_json: None,
                target_features: TargetFeaturesSummary::Features(BTreeSet::new()),
                flags: BTreeSet::new(),
            },
        ));

        let custom_json = r#"{"arch":"x86_64","target-pointer-width":"64","llvm-target":"x86_64-unknown-haiku","data-layout":"e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128","os":"haiku","abi":null,"env":null,"vendor":null,"families":[],"endian":"little","min-atomic-width":null,"max-atomic-width":64,"panic-strategy":"unwind"}"#;
        let toml = format!(
            r#"platform = {{ triple = "x86_64-unknown-haiku", custom-json = '{custom_json}' }}"#
        );

        valid.push((
            &toml,
            PlatformSummary {
                triple: "x86_64-unknown-haiku".into(),
                custom_json: Some(custom_json.to_owned()),
                target_features: TargetFeaturesSummary::Unknown,
                flags: BTreeSet::new(),
            },
        ));

        let mut flags = BTreeSet::new();
        flags.insert("cargo_web".to_owned());
        valid.push((
            r#"platform = { triple = "x86_64-unknown-linux-gnu", flags = ["cargo_web"] }"#,
            PlatformSummary {
                triple: "x86_64-unknown-linux-gnu".into(),
                custom_json: None,
                target_features: TargetFeaturesSummary::Unknown,
                flags,
            },
        ));

        for (input, expected) in valid {
            let actual: Wrapper = toml::from_str(input)
                .unwrap_or_else(|err| panic!("input {} is valid: {}", input, err));
            assert_eq!(actual.platform, expected, "for input: {}", input);

            // Serialize and deserialize again.
            let serialized = toml::to_string(&actual).expect("serialized correctly");
            let actual_2: Wrapper = toml::from_str(&serialized)
                .unwrap_or_else(|err| panic!("serialized input: {} is valid: {}", input, err));
            assert_eq!(actual, actual_2, "for input: {}", input);

            // Check that custom JSON functionality works.
            if actual.platform.custom_json.is_some() {
                #[cfg(feature = "custom")]
                {
                    let platform = actual
                        .platform
                        .to_platform()
                        .expect("custom platform parsed successfully");
                    assert!(platform.is_custom(), "this is a custom platform");
                }

                #[cfg(not(feature = "custom"))]
                {
                    use crate::errors::CustomTripleCreateError;

                    let error = actual
                        .platform
                        .to_platform()
                        .expect_err("custom platforms are disabled");
                    assert!(matches!(
                        error,
                        Error::CustomPlatformCreate(CustomTripleCreateError::Unavailable)
                    ));
                }
            }
        }
    }
}

#[cfg(all(test, feature = "proptest1"))]
mod proptests {
    use super::*;
    use proptest::prelude::*;
    use std::collections::HashSet;

    proptest! {
        #[test]
        fn summary_roundtrip(platform in Platform::strategy(any::<TargetFeatures>())) {
            let summary = PlatformSummary::from_platform(&platform);
            let serialized = toml::ser::to_string(&summary).expect("serialization succeeded");

            let deserialized: PlatformSummary = toml::from_str(&serialized).expect("deserialization succeeded");
            assert_eq!(summary, deserialized, "summary and deserialized should match");
            let platform2 = deserialized.to_platform().expect("conversion to Platform succeeded");

            assert_eq!(platform.triple_str(), platform2.triple_str(), "triples match");
            assert_eq!(platform.target_features(), platform2.target_features(), "target features match");
            assert_eq!(platform.flags().collect::<HashSet<_>>(), platform2.flags().collect::<HashSet<_>>(), "flags match");
        }
    }
}