1use itertools::Itertools;
2
3use miette::Diagnostic;
4use serde::{
5 de::{self, DeserializeOwned, IntoDeserializer, Visitor},
6 Deserialize, Deserializer,
7};
8use serde_enum_str::{Deserialize_enum_str, Serialize_enum_str};
9use std::{cmp::Ordering, collections::HashMap};
10use strum::IntoEnumIterator;
11use strum_macros::EnumIter;
12use thiserror::Error;
13
14use super::{display, serde_util};
15
16#[derive(Deserialize_enum_str, Serialize_enum_str, PartialEq, Eq, Hash, Debug, Clone, EnumIter)]
19#[serde(rename_all = "lowercase")]
20#[strum(serialize_all = "lowercase")]
21pub enum Identifier {
22 Unix,
24 Windows,
25 Win32,
26 Cygwin,
27 MacOSX,
28 Linux,
29 FreeBSD,
30 #[serde(other)]
31 Unknown(String),
32}
33
34impl Default for Identifier {
35 fn default() -> Self {
36 target_identifier()
37 }
38}
39
40impl PartialOrd for Identifier {
42 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
43 match (self, other) {
44 (Identifier::Unix, Identifier::Cygwin) => Some(Ordering::Less),
45 (Identifier::Unix, Identifier::MacOSX) => Some(Ordering::Less),
46 (Identifier::Unix, Identifier::Linux) => Some(Ordering::Less),
47 (Identifier::Unix, Identifier::FreeBSD) => Some(Ordering::Less),
48 (Identifier::Windows, Identifier::Win32) => Some(Ordering::Greater),
49 (Identifier::Win32, Identifier::Windows) => Some(Ordering::Less),
50 (Identifier::Cygwin, Identifier::Unix) => Some(Ordering::Greater),
51 (Identifier::MacOSX, Identifier::Unix) => Some(Ordering::Greater),
52 (Identifier::Linux, Identifier::Unix) => Some(Ordering::Greater),
53 (Identifier::FreeBSD, Identifier::Unix) => Some(Ordering::Greater),
54 _ if self == other => Some(Ordering::Equal),
55 _ => None,
56 }
57 }
58}
59
60fn target_identifier() -> Identifier {
67 if cfg!(target_env = "msvc") {
68 Identifier::Windows
69 } else if cfg!(target_os = "linux") {
70 Identifier::Linux
71 } else if cfg!(target_os = "macos") || cfg!(target_vendor = "apple") {
72 Identifier::MacOSX
73 } else if cfg!(target_os = "freebsd") {
74 Identifier::FreeBSD
75 } else if which::which("cygpath").is_ok() {
76 Identifier::Cygwin
77 } else {
78 Identifier::Unix
79 }
80}
81
82impl Identifier {
83 pub fn get_subsets(&self) -> Vec<Self> {
86 Identifier::iter()
87 .filter(|identifier| identifier.is_subset_of(self))
88 .collect()
89 }
90
91 pub fn get_extended_platforms(&self) -> Vec<Self> {
94 Identifier::iter()
95 .filter(|identifier| identifier.is_extension_of(self))
96 .collect()
97 }
98
99 fn is_subset_of(&self, other: &Identifier) -> bool {
101 self.partial_cmp(other) == Some(Ordering::Less)
102 }
103
104 fn is_extension_of(&self, other: &Identifier) -> bool {
106 self.partial_cmp(other) == Some(Ordering::Greater)
107 }
108}
109
110#[derive(Clone, Debug, PartialEq)]
112pub struct Support {
113 platform_map: HashMap<Identifier, bool>,
115}
116
117impl Default for Support {
118 fn default() -> Self {
119 Self {
120 platform_map: Identifier::iter()
121 .filter(|identifier| !matches!(identifier, Identifier::Unknown(_)))
122 .map(|identifier| (identifier, true))
123 .collect(),
124 }
125 }
126}
127
128impl<'de> Deserialize<'de> for Support {
129 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
130 where
131 D: Deserializer<'de>,
132 {
133 let platforms: Vec<String> = Vec::deserialize(deserializer)?;
134 Self::parse(&platforms).map_err(de::Error::custom)
135 }
136}
137
138impl display::AsLuaKV for Support {
139 fn display_lua(&self) -> display::LuaKV {
140 display::LuaKV {
141 key: "supported_platforms".to_string(),
142 value: display::LuaValue::List(
143 self.platforms()
144 .iter()
145 .map(|(platform, supported)| {
146 display::LuaValue::String(format!(
147 "{}{}",
148 if *supported { "" } else { "!" },
149 platform,
150 ))
151 })
152 .collect(),
153 ),
154 }
155 }
156}
157
158#[derive(Error, Debug, Diagnostic)]
159#[non_exhaustive]
160pub enum Error {
161 #[error("error when parsing platform identifier: {0}")]
162 ParseError(String),
163
164 #[error("conflicting supported platform entries")]
165 ConflictingEntries,
166}
167
168impl Support {
169 fn validate_platforms(platforms: &[String]) -> Result<HashMap<Identifier, bool>, Error> {
170 platforms
171 .iter()
172 .try_fold(HashMap::new(), |mut platforms, platform| {
173 let (is_positive_assertion, platform) = platform
177 .strip_prefix('!')
178 .map(|str| (false, str))
179 .unwrap_or((true, platform));
180
181 let platform_identifier = platform
182 .parse::<Identifier>()
183 .map_err(|err| Error::ParseError(err.to_string()))?;
184
185 if platforms
189 .get(&platform_identifier)
190 .unwrap_or(&is_positive_assertion)
191 != &is_positive_assertion
192 {
193 return Err(Error::ConflictingEntries);
194 }
195
196 platforms.insert(platform_identifier.clone(), is_positive_assertion);
197
198 let subset_or_extended_platforms = if is_positive_assertion {
199 platform_identifier.get_extended_platforms()
200 } else {
201 platform_identifier.get_subsets()
202 };
203
204 for sub_platform in subset_or_extended_platforms {
205 if platforms
206 .get(&sub_platform)
207 .unwrap_or(&is_positive_assertion)
208 != &is_positive_assertion
209 {
210 return Err(Error::ConflictingEntries);
212 }
213
214 platforms.insert(sub_platform, is_positive_assertion);
215 }
216
217 Ok(platforms)
218 })
219 }
220
221 pub fn parse(platforms: &[String]) -> Result<Self, Error> {
222 match platforms {
226 [] => Ok(Self::default()),
227 platforms if platforms.iter().any(|platform| platform.starts_with('!')) => {
228 let mut platform_map = Self::validate_platforms(platforms)?;
229
230 for identifier in Identifier::iter() {
233 if !matches!(identifier, Identifier::Unknown(_)) {
234 platform_map.entry(identifier).or_insert(true);
235 }
236 }
237
238 Ok(Self { platform_map })
239 }
240 platforms => Ok(Self {
242 platform_map: Self::validate_platforms(platforms)?,
243 }),
244 }
245 }
246
247 pub fn is_supported(&self, platform: &Identifier) -> bool {
248 self.platform_map.get(platform).cloned().unwrap_or(false)
249 }
250
251 pub(crate) fn platforms(&self) -> &HashMap<Identifier, bool> {
252 &self.platform_map
253 }
254}
255
256pub trait PartialOverride: Sized {
257 type Err: std::error::Error;
258
259 fn apply_overrides(&self, override_val: &Self) -> Result<Self, Self::Err>;
260}
261
262pub trait Overridable: PartialOverride {
263 type Err: std::error::Error;
264
265 fn on_nil<T>() -> Result<PerPlatform<T>, <Self as Overridable>::Err>
266 where
267 T: Overridable,
268 T: Default;
269}
270
271#[derive(Clone, Debug, PartialEq)]
273pub struct PerPlatform<T> {
274 pub(crate) default: T,
276 pub(crate) per_platform: HashMap<Identifier, T>,
278}
279
280impl<T> PerPlatform<T> {
281 pub(crate) fn new(default: T) -> Self {
282 Self {
283 default,
284 per_platform: HashMap::default(),
285 }
286 }
287
288 pub fn current_platform(&self) -> &T {
291 self.for_platform_identifier(&target_identifier())
292 }
293
294 fn for_platform_identifier(&self, identifier: &Identifier) -> &T {
295 self.get(identifier)
296 }
297
298 pub fn get(&self, platform: &Identifier) -> &T {
299 self.per_platform.get(platform).unwrap_or(
300 platform
301 .get_subsets()
302 .into_iter()
303 .sorted_by(|a, b| b.partial_cmp(a).unwrap_or(Ordering::Equal))
307 .find(|identifier| self.per_platform.contains_key(identifier))
308 .and_then(|identifier| self.per_platform.get(&identifier))
309 .unwrap_or(&self.default),
310 )
311 }
312
313 pub(crate) fn map<U, F>(&self, cb: F) -> PerPlatform<U>
314 where
315 F: Fn(&T) -> U,
316 {
317 PerPlatform {
318 default: cb(&self.default),
319 per_platform: self
320 .per_platform
321 .iter()
322 .map(|(identifier, value)| (identifier.clone(), cb(value)))
323 .collect(),
324 }
325 }
326}
327
328impl<U, E> PerPlatform<Result<U, E>>
329where
330 E: std::error::Error,
331{
332 pub fn transpose(self) -> Result<PerPlatform<U>, E> {
333 Ok(PerPlatform {
334 default: self.default?,
335 per_platform: self
336 .per_platform
337 .into_iter()
338 .map(|(identifier, value)| Ok((identifier, value?)))
339 .try_collect()?,
340 })
341 }
342}
343
344impl<T: Default> Default for PerPlatform<T> {
345 fn default() -> Self {
346 Self {
347 default: T::default(),
348 per_platform: HashMap::default(),
349 }
350 }
351}
352
353struct PerPlatformVisitor<T>(std::marker::PhantomData<T>);
354
355impl<'de, T> Visitor<'de> for PerPlatformVisitor<T>
356where
357 T: DeserializeOwned,
358 T: Overridable,
359 T: Default,
360 T: Clone,
361{
362 type Value = PerPlatform<T>;
363
364 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
365 formatter.write_str("a table or nil")
366 }
367
368 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
369 where
370 A: de::MapAccess<'de>,
371 {
372 use serde_value::Value;
373
374 let mut platforms_val: Option<Value> = None;
375 let mut other_entries: Vec<(Value, Value)> = Vec::new();
376
377 while let Some(key) = map.next_key_seed(serde_util::LuaValueSeed)? {
378 if key == Value::String("platforms".to_string()) {
379 platforms_val = Some(map.next_value_seed(serde_util::LuaValueSeed)?);
380 } else {
381 other_entries.push((key, map.next_value_seed(serde_util::LuaValueSeed)?));
382 }
383 }
384
385 let mut per_platform = match platforms_val {
386 Some(val) => match val {
387 Value::Map(_) => val
388 .deserialize_into::<HashMap<Identifier, T>>()
389 .map_err(de::Error::custom)?,
390 Value::Unit => HashMap::default(),
391 val => {
392 return Err(de::Error::custom(format!(
393 "Expected platforms to be a table or nil, but got {val:?}",
394 )))
395 }
396 },
397 None => HashMap::default(),
398 };
399
400 let default = if other_entries.is_empty() {
401 T::default()
402 } else {
403 let obj =
407 serde_util::normalize_lua_value(Value::Map(other_entries.into_iter().collect()));
408 T::deserialize(obj.into_deserializer()).map_err(de::Error::custom)?
409 };
410 apply_per_platform_overrides(&mut per_platform, &default)
411 .map_err(|err: <T as PartialOverride>::Err| de::Error::custom(err.to_string()))?;
412 Ok(PerPlatform {
413 default,
414 per_platform,
415 })
416 }
417
418 fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
419 where
420 A: de::SeqAccess<'de>,
421 {
422 let default = T::deserialize(de::value::SeqAccessDeserializer::new(seq))?;
426 Ok(PerPlatform::new(default))
427 }
428
429 fn visit_unit<E>(self) -> Result<Self::Value, E>
430 where
431 E: de::Error,
432 {
433 T::on_nil().map_err(de::Error::custom)
434 }
435
436 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
437 where
438 E: de::Error,
439 {
440 let s = std::str::from_utf8(v).map_err(de::Error::custom)?;
441 self.visit_str(s)
442 }
443
444 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
445 where
446 E: de::Error,
447 {
448 self.visit_bytes(&v)
449 }
450
451 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
452 where
453 E: de::Error,
454 {
455 let default = T::deserialize(v.into_deserializer())?;
456 Ok(PerPlatform::new(default))
457 }
458}
459
460impl<'de, T> Deserialize<'de> for PerPlatform<T>
461where
462 T: DeserializeOwned,
463 T: Overridable,
464 T: Default,
465 T: Clone,
466{
467 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
468 deserializer.deserialize_any(PerPlatformVisitor(std::marker::PhantomData))
469 }
470}
471
472pub(crate) fn per_platform_from_intermediate<'de, D, I, T>(
476 deserializer: D,
477) -> Result<PerPlatform<T>, D::Error>
478where
479 D: Deserializer<'de>,
480 I: Overridable<Err: ToString>,
481 I: DeserializeOwned,
482 I: Default,
483 I: Clone,
484 T: TryFrom<I, Error: ToString>,
485{
486 PerPlatform::<I>::deserialize(deserializer)?
487 .map(|internal| {
488 T::try_from(internal.clone()).map_err(|err| serde::de::Error::custom(err.to_string()))
489 })
490 .transpose()
491}
492
493fn apply_per_platform_overrides<T>(
494 per_platform: &mut HashMap<Identifier, T>,
495 base: &T,
496) -> Result<(), T::Err>
497where
498 T: PartialOverride,
499 T: Clone,
500{
501 let per_platform_raw = per_platform.clone();
502 for (platform, overrides) in per_platform.clone() {
503 let overridden = base.apply_overrides(&overrides)?;
505 per_platform.insert(platform, overridden);
506 }
507 for (platform, overrides) in per_platform_raw {
508 for extended_platform in &platform.get_extended_platforms() {
510 if let Some(extended_overrides) = per_platform.get(extended_platform) {
511 per_platform.insert(
512 extended_platform.to_owned(),
513 extended_overrides.apply_overrides(&overrides)?,
514 );
515 }
516 }
517 }
518 Ok(())
519}
520
521#[cfg(test)]
522mod tests {
523
524 use super::*;
525 use proptest::prelude::*;
526
527 fn platform_identifier_strategy() -> impl Strategy<Value = Identifier> {
528 prop_oneof![
529 Just(Identifier::Unix),
530 Just(Identifier::Windows),
531 Just(Identifier::Win32),
532 Just(Identifier::Cygwin),
533 Just(Identifier::MacOSX),
534 Just(Identifier::Linux),
535 Just(Identifier::FreeBSD),
536 ]
537 }
538
539 #[tokio::test]
540 async fn sort_platform_identifier_more_specific_last() {
541 let mut platforms = vec![Identifier::Cygwin, Identifier::Linux, Identifier::Unix];
542 platforms.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
543 assert_eq!(
544 platforms,
545 vec![Identifier::Unix, Identifier::Cygwin, Identifier::Linux]
546 );
547 let mut platforms = vec![Identifier::Windows, Identifier::Win32];
548 platforms.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
549 assert_eq!(platforms, vec![Identifier::Win32, Identifier::Windows])
550 }
551
552 #[tokio::test]
553 async fn test_is_subset_of() {
554 assert!(Identifier::Unix.is_subset_of(&Identifier::Linux));
555 assert!(Identifier::Unix.is_subset_of(&Identifier::MacOSX));
556 assert!(!Identifier::Linux.is_subset_of(&Identifier::Unix));
557 }
558
559 #[tokio::test]
560 async fn test_is_extension_of() {
561 assert!(Identifier::Linux.is_extension_of(&Identifier::Unix));
562 assert!(Identifier::MacOSX.is_extension_of(&Identifier::Unix));
563 assert!(!Identifier::Unix.is_extension_of(&Identifier::Linux));
564 }
565
566 #[tokio::test]
567 async fn per_platform() {
568 let foo = PerPlatform {
569 default: "default",
570 per_platform: vec![
571 (Identifier::Unix, "unix"),
572 (Identifier::FreeBSD, "freebsd"),
573 (Identifier::Cygwin, "cygwin"),
574 (Identifier::Linux, "linux"),
575 ]
576 .into_iter()
577 .collect(),
578 };
579 assert_eq!(*foo.get(&Identifier::MacOSX), "unix");
580 assert_eq!(*foo.get(&Identifier::Linux), "linux");
581 assert_eq!(*foo.get(&Identifier::FreeBSD), "freebsd");
582 assert_eq!(*foo.get(&Identifier::Cygwin), "cygwin");
583 assert_eq!(*foo.get(&Identifier::Windows), "default");
584 }
585
586 #[cfg(target_os = "linux")]
587 #[tokio::test]
588 async fn test_target_identifier() {
589 run_test_target_identifier(Identifier::Linux)
590 }
591
592 #[cfg(target_os = "macos")]
593 #[tokio::test]
594 async fn test_target_identifier() {
595 run_test_target_identifier(Identifier::MacOSX)
596 }
597
598 #[cfg(target_env = "msvc")]
599 #[tokio::test]
600 async fn test_target_identifier() {
601 run_test_target_identifier(Identifier::Windows)
602 }
603
604 #[cfg(target_os = "android")]
605 #[tokio::test]
606 async fn test_target_identifier() {
607 run_test_target_identifier(Identifier::Unix)
608 }
609
610 fn run_test_target_identifier(expected: Identifier) {
611 assert_eq!(expected, target_identifier());
612 }
613
614 proptest! {
615 #[test]
616 fn supported_platforms(identifier in platform_identifier_strategy()) {
617 let identifier_str = identifier.to_string();
618 let platforms = vec![identifier_str];
619 let platform_support = Support::parse(&platforms).unwrap();
620 prop_assert!(platform_support.is_supported(&identifier))
621 }
622
623 #[test]
624 fn unsupported_platforms_only(unsupported in platform_identifier_strategy(), supported in platform_identifier_strategy()) {
625 if supported == unsupported
626 || unsupported.is_extension_of(&supported) {
627 return Ok(());
628 }
629 let identifier_str = format!("!{unsupported}");
630 let platforms = vec![identifier_str];
631 let platform_support = Support::parse(&platforms).unwrap();
632 prop_assert!(!platform_support.is_supported(&unsupported));
633 prop_assert!(platform_support.is_supported(&supported))
634 }
635
636 #[test]
637 fn supported_and_unsupported_platforms(unsupported in platform_identifier_strategy(), unspecified in platform_identifier_strategy()) {
638 if unspecified == unsupported
639 || unsupported.is_extension_of(&unspecified) {
640 return Ok(());
641 }
642 let supported_str = unspecified.to_string();
643 let unsupported_str = format!("!{unsupported}");
644 let platforms = vec![supported_str, unsupported_str];
645 let platform_support = Support::parse(&platforms).unwrap();
646 prop_assert!(platform_support.is_supported(&unspecified));
647 prop_assert!(!platform_support.is_supported(&unsupported));
648 }
649
650 #[test]
651 fn all_platforms_supported_if_none_are_specified(identifier in platform_identifier_strategy()) {
652 let platforms = vec![];
653 let platform_support = Support::parse(&platforms).unwrap();
654 prop_assert!(platform_support.is_supported(&identifier))
655 }
656
657 #[test]
658 fn conflicting_platforms(identifier in platform_identifier_strategy()) {
659 let identifier_str = identifier.to_string();
660 let identifier_str_negated = format!("!{identifier}");
661 let platforms = vec![identifier_str, identifier_str_negated];
662 let _ = Support::parse(&platforms).unwrap_err();
663 }
664
665 #[test]
666 fn extended_platforms_supported_if_supported(identifier in platform_identifier_strategy()) {
667 let identifier_str = identifier.to_string();
668 let platforms = vec![identifier_str];
669 let platform_support = Support::parse(&platforms).unwrap();
670 for identifier in identifier.get_extended_platforms() {
671 prop_assert!(platform_support.is_supported(&identifier))
672 }
673 }
674
675 #[test]
676 fn sub_platforms_unsupported_if_unsupported(identifier in platform_identifier_strategy()) {
677 let identifier_str = format!("!{identifier}");
678 let platforms = vec![identifier_str];
679 let platform_support = Support::parse(&platforms).unwrap();
680 for identifier in identifier.get_subsets() {
681 prop_assert!(!platform_support.is_supported(&identifier))
682 }
683 }
684
685 #[test]
686 fn conflicting_extended_platform_definitions(identifier in platform_identifier_strategy()) {
687 let extended_platforms = identifier.get_extended_platforms();
688 if extended_platforms.is_empty() {
689 return Ok(());
690 }
691 let supported_str = identifier.to_string();
692 let mut platforms: Vec<String> = extended_platforms.into_iter().map(|ident| format!("!{ident}")).collect();
693 platforms.push(supported_str);
694 let _ = Support::parse(&platforms).unwrap_err();
695 }
696 }
697}