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 has_override_for_current_platform(&self) -> bool {
314 let platform = target_identifier();
315 self.per_platform.contains_key(&platform)
316 || platform
317 .get_subsets()
318 .into_iter()
319 .any(|subset| self.per_platform.contains_key(&subset))
320 }
321
322 pub(crate) fn map<U, F>(&self, cb: F) -> PerPlatform<U>
323 where
324 F: Fn(&T) -> U,
325 {
326 PerPlatform {
327 default: cb(&self.default),
328 per_platform: self
329 .per_platform
330 .iter()
331 .map(|(identifier, value)| (identifier.clone(), cb(value)))
332 .collect(),
333 }
334 }
335}
336
337impl<U, E> PerPlatform<Result<U, E>>
338where
339 E: std::error::Error,
340{
341 pub fn transpose(self) -> Result<PerPlatform<U>, E> {
342 Ok(PerPlatform {
343 default: self.default?,
344 per_platform: self
345 .per_platform
346 .into_iter()
347 .map(|(identifier, value)| Ok((identifier, value?)))
348 .try_collect()?,
349 })
350 }
351}
352
353impl<T: Default> Default for PerPlatform<T> {
354 fn default() -> Self {
355 Self {
356 default: T::default(),
357 per_platform: HashMap::default(),
358 }
359 }
360}
361
362struct PerPlatformVisitor<T>(std::marker::PhantomData<T>);
363
364impl<'de, T> Visitor<'de> for PerPlatformVisitor<T>
365where
366 T: DeserializeOwned,
367 T: Overridable,
368 T: Default,
369 T: Clone,
370{
371 type Value = PerPlatform<T>;
372
373 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
374 formatter.write_str("a table or nil")
375 }
376
377 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
378 where
379 A: de::MapAccess<'de>,
380 {
381 use serde_value::Value;
382
383 let mut platforms_val: Option<Value> = None;
384 let mut other_entries: Vec<(Value, Value)> = Vec::new();
385
386 while let Some(key) = map.next_key_seed(serde_util::LuaValueSeed)? {
387 if key == Value::String("platforms".to_string()) {
388 platforms_val = Some(map.next_value_seed(serde_util::LuaValueSeed)?);
389 } else {
390 other_entries.push((key, map.next_value_seed(serde_util::LuaValueSeed)?));
391 }
392 }
393
394 let mut per_platform = match platforms_val {
395 Some(val) => match val {
396 Value::Map(_) => val
397 .deserialize_into::<HashMap<Identifier, T>>()
398 .map_err(de::Error::custom)?,
399 Value::Unit => HashMap::default(),
400 val => {
401 return Err(de::Error::custom(format!(
402 "Expected platforms to be a table or nil, but got {val:?}",
403 )))
404 }
405 },
406 None => HashMap::default(),
407 };
408
409 let default = if other_entries.is_empty() {
410 T::default()
411 } else {
412 let obj =
416 serde_util::normalize_lua_value(Value::Map(other_entries.into_iter().collect()));
417 T::deserialize(obj.into_deserializer()).map_err(de::Error::custom)?
418 };
419 apply_per_platform_overrides(&mut per_platform, &default)
420 .map_err(|err: <T as PartialOverride>::Err| de::Error::custom(err.to_string()))?;
421 Ok(PerPlatform {
422 default,
423 per_platform,
424 })
425 }
426
427 fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
428 where
429 A: de::SeqAccess<'de>,
430 {
431 let default = T::deserialize(de::value::SeqAccessDeserializer::new(seq))?;
435 Ok(PerPlatform::new(default))
436 }
437
438 fn visit_unit<E>(self) -> Result<Self::Value, E>
439 where
440 E: de::Error,
441 {
442 T::on_nil().map_err(de::Error::custom)
443 }
444
445 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
446 where
447 E: de::Error,
448 {
449 let s = std::str::from_utf8(v).map_err(de::Error::custom)?;
450 self.visit_str(s)
451 }
452
453 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
454 where
455 E: de::Error,
456 {
457 self.visit_bytes(&v)
458 }
459
460 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
461 where
462 E: de::Error,
463 {
464 let default = T::deserialize(v.into_deserializer())?;
465 Ok(PerPlatform::new(default))
466 }
467}
468
469impl<'de, T> Deserialize<'de> for PerPlatform<T>
470where
471 T: DeserializeOwned,
472 T: Overridable,
473 T: Default,
474 T: Clone,
475{
476 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
477 deserializer.deserialize_any(PerPlatformVisitor(std::marker::PhantomData))
478 }
479}
480
481pub(crate) fn per_platform_from_intermediate<'de, D, I, T>(
485 deserializer: D,
486) -> Result<PerPlatform<T>, D::Error>
487where
488 D: Deserializer<'de>,
489 I: Overridable<Err: ToString>,
490 I: DeserializeOwned,
491 I: Default,
492 I: Clone,
493 T: TryFrom<I, Error: ToString>,
494{
495 PerPlatform::<I>::deserialize(deserializer)?
496 .map(|internal| {
497 T::try_from(internal.clone()).map_err(|err| serde::de::Error::custom(err.to_string()))
498 })
499 .transpose()
500}
501
502fn apply_per_platform_overrides<T>(
503 per_platform: &mut HashMap<Identifier, T>,
504 base: &T,
505) -> Result<(), T::Err>
506where
507 T: PartialOverride,
508 T: Clone,
509{
510 let per_platform_raw = per_platform.clone();
511 for (platform, overrides) in per_platform.clone() {
512 let overridden = base.apply_overrides(&overrides)?;
514 per_platform.insert(platform, overridden);
515 }
516 for (platform, overrides) in per_platform_raw {
517 for extended_platform in &platform.get_extended_platforms() {
519 if let Some(extended_overrides) = per_platform.get(extended_platform) {
520 per_platform.insert(
521 extended_platform.to_owned(),
522 extended_overrides.apply_overrides(&overrides)?,
523 );
524 }
525 }
526 }
527 Ok(())
528}
529
530#[cfg(test)]
531mod tests {
532
533 use super::*;
534 use proptest::prelude::*;
535
536 fn platform_identifier_strategy() -> impl Strategy<Value = Identifier> {
537 prop_oneof![
538 Just(Identifier::Unix),
539 Just(Identifier::Windows),
540 Just(Identifier::Win32),
541 Just(Identifier::Cygwin),
542 Just(Identifier::MacOSX),
543 Just(Identifier::Linux),
544 Just(Identifier::FreeBSD),
545 ]
546 }
547
548 #[tokio::test]
549 async fn sort_platform_identifier_more_specific_last() {
550 let mut platforms = vec![Identifier::Cygwin, Identifier::Linux, Identifier::Unix];
551 platforms.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
552 assert_eq!(
553 platforms,
554 vec![Identifier::Unix, Identifier::Cygwin, Identifier::Linux]
555 );
556 let mut platforms = vec![Identifier::Windows, Identifier::Win32];
557 platforms.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
558 assert_eq!(platforms, vec![Identifier::Win32, Identifier::Windows])
559 }
560
561 #[tokio::test]
562 async fn test_is_subset_of() {
563 assert!(Identifier::Unix.is_subset_of(&Identifier::Linux));
564 assert!(Identifier::Unix.is_subset_of(&Identifier::MacOSX));
565 assert!(!Identifier::Linux.is_subset_of(&Identifier::Unix));
566 }
567
568 #[tokio::test]
569 async fn test_is_extension_of() {
570 assert!(Identifier::Linux.is_extension_of(&Identifier::Unix));
571 assert!(Identifier::MacOSX.is_extension_of(&Identifier::Unix));
572 assert!(!Identifier::Unix.is_extension_of(&Identifier::Linux));
573 }
574
575 #[tokio::test]
576 async fn per_platform() {
577 let foo = PerPlatform {
578 default: "default",
579 per_platform: vec![
580 (Identifier::Unix, "unix"),
581 (Identifier::FreeBSD, "freebsd"),
582 (Identifier::Cygwin, "cygwin"),
583 (Identifier::Linux, "linux"),
584 ]
585 .into_iter()
586 .collect(),
587 };
588 assert_eq!(*foo.get(&Identifier::MacOSX), "unix");
589 assert_eq!(*foo.get(&Identifier::Linux), "linux");
590 assert_eq!(*foo.get(&Identifier::FreeBSD), "freebsd");
591 assert_eq!(*foo.get(&Identifier::Cygwin), "cygwin");
592 assert_eq!(*foo.get(&Identifier::Windows), "default");
593 }
594
595 #[cfg(target_os = "linux")]
596 #[tokio::test]
597 async fn test_target_identifier() {
598 run_test_target_identifier(Identifier::Linux)
599 }
600
601 #[cfg(target_os = "macos")]
602 #[tokio::test]
603 async fn test_target_identifier() {
604 run_test_target_identifier(Identifier::MacOSX)
605 }
606
607 #[cfg(target_env = "msvc")]
608 #[tokio::test]
609 async fn test_target_identifier() {
610 run_test_target_identifier(Identifier::Windows)
611 }
612
613 #[cfg(target_os = "android")]
614 #[tokio::test]
615 async fn test_target_identifier() {
616 run_test_target_identifier(Identifier::Unix)
617 }
618
619 fn run_test_target_identifier(expected: Identifier) {
620 assert_eq!(expected, target_identifier());
621 }
622
623 proptest! {
624 #[test]
625 fn supported_platforms(identifier in platform_identifier_strategy()) {
626 let identifier_str = identifier.to_string();
627 let platforms = vec![identifier_str];
628 let platform_support = Support::parse(&platforms).unwrap();
629 prop_assert!(platform_support.is_supported(&identifier))
630 }
631
632 #[test]
633 fn unsupported_platforms_only(unsupported in platform_identifier_strategy(), supported in platform_identifier_strategy()) {
634 if supported == unsupported
635 || unsupported.is_extension_of(&supported) {
636 return Ok(());
637 }
638 let identifier_str = format!("!{unsupported}");
639 let platforms = vec![identifier_str];
640 let platform_support = Support::parse(&platforms).unwrap();
641 prop_assert!(!platform_support.is_supported(&unsupported));
642 prop_assert!(platform_support.is_supported(&supported))
643 }
644
645 #[test]
646 fn supported_and_unsupported_platforms(unsupported in platform_identifier_strategy(), unspecified in platform_identifier_strategy()) {
647 if unspecified == unsupported
648 || unsupported.is_extension_of(&unspecified) {
649 return Ok(());
650 }
651 let supported_str = unspecified.to_string();
652 let unsupported_str = format!("!{unsupported}");
653 let platforms = vec![supported_str, unsupported_str];
654 let platform_support = Support::parse(&platforms).unwrap();
655 prop_assert!(platform_support.is_supported(&unspecified));
656 prop_assert!(!platform_support.is_supported(&unsupported));
657 }
658
659 #[test]
660 fn all_platforms_supported_if_none_are_specified(identifier in platform_identifier_strategy()) {
661 let platforms = vec![];
662 let platform_support = Support::parse(&platforms).unwrap();
663 prop_assert!(platform_support.is_supported(&identifier))
664 }
665
666 #[test]
667 fn conflicting_platforms(identifier in platform_identifier_strategy()) {
668 let identifier_str = identifier.to_string();
669 let identifier_str_negated = format!("!{identifier}");
670 let platforms = vec![identifier_str, identifier_str_negated];
671 let _ = Support::parse(&platforms).unwrap_err();
672 }
673
674 #[test]
675 fn extended_platforms_supported_if_supported(identifier in platform_identifier_strategy()) {
676 let identifier_str = identifier.to_string();
677 let platforms = vec![identifier_str];
678 let platform_support = Support::parse(&platforms).unwrap();
679 for identifier in identifier.get_extended_platforms() {
680 prop_assert!(platform_support.is_supported(&identifier))
681 }
682 }
683
684 #[test]
685 fn sub_platforms_unsupported_if_unsupported(identifier in platform_identifier_strategy()) {
686 let identifier_str = format!("!{identifier}");
687 let platforms = vec![identifier_str];
688 let platform_support = Support::parse(&platforms).unwrap();
689 for identifier in identifier.get_subsets() {
690 prop_assert!(!platform_support.is_supported(&identifier))
691 }
692 }
693
694 #[test]
695 fn conflicting_extended_platform_definitions(identifier in platform_identifier_strategy()) {
696 let extended_platforms = identifier.get_extended_platforms();
697 if extended_platforms.is_empty() {
698 return Ok(());
699 }
700 let supported_str = identifier.to_string();
701 let mut platforms: Vec<String> = extended_platforms.into_iter().map(|ident| format!("!{ident}")).collect();
702 platforms.push(supported_str);
703 let _ = Support::parse(&platforms).unwrap_err();
704 }
705 }
706}