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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
// SPDX-FileCopyrightText: 2024 Simon Bruder <simon@sbruder.de>
//
// SPDX-License-Identifier: MPL-2.0

use std::borrow::Cow;
use std::collections::{BTreeSet, HashMap};
use std::path::PathBuf;

use cargo_metadata::DependencyKind;
use cargo_platform::{Cfg, Platform};
#[cfg(feature = "macros")]
use proc_macro2::TokenStream;
#[cfg(feature = "macros")]
use quote::{quote, ToTokens, TokenStreamExt};
use spdx::{ExceptionId, LicenseId};

/// Error type.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("cargo metadata invocation failed: {0}")]
    CargoMetadata(#[from] cargo_metadata::Error),
    #[error("parsing SPDX expression failed: {0}")]
    SpdxParse(#[from] spdx::ParseError),
    #[error("IO Error: {0}")]
    Io(#[from] std::io::Error),

    /// The crate does not specify either `license` or `license-file` in its manifest.
    #[error("no license specified for crate {0}")]
    NoLicense(String),
    /// The crate’s `license` includes license identifiers which are not standard SPDX identifiers.
    #[error("non-SPDX license identifier specified for crate {0}")]
    NonSpdxLicense(String),
    /// The crate specifies no website.
    ///
    /// This means it does not set any of the following manifest keys:
    ///
    /// - [`homepage`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-homepage-field)
    /// - [`repository`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-repository-field)
    /// - [`documentation`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-documentation-field)
    #[error("no website found for crate {0}")]
    NoWebsite(String),

    #[error("no dependency graph found")]
    NoDependencyGraph,
    #[error("no root node found in dependency graph")]
    NoRootNode,
}

type Result<T> = std::result::Result<T, Error>;

/// Licensing information returned by [`collect`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Licensing {
    /// All dependencies of the crate (including transitive dependencies and the crate itself).
    pub packages: Vec<Crate>,
    /// All SPDX licenses used by the crate and its dependencies.
    ///
    /// It does not include non-SPDX-licenses.
    /// Where such custom licenses are used,
    /// their text is only included as part of the corresponding [`Crate`].
    pub licenses: Vec<LicenseId>,
    /// All license exceptions used by the crate and its dependencies.
    pub exceptions: Vec<ExceptionId>,
}

impl Licensing {
    #[cfg(feature = "macros")]
    #[doc(hidden)]
    pub fn __macro_internal_new(
        packages: &[Crate],
        licenses: &[&str],
        exceptions: &[&str],
    ) -> Self {
        Self {
            packages: packages.to_vec(),
            licenses: licenses
                .iter()
                .map(|id| spdx::license_id(id))
                .map(Option::unwrap)
                .collect(),
            exceptions: exceptions
                .iter()
                .map(|id| spdx::exception_id(id))
                .map(Option::unwrap)
                .collect(),
        }
    }
}

#[cfg(feature = "macros")]
impl ToTokens for Licensing {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let Self {
            packages,
            licenses,
            exceptions,
        } = self;

        let licenses = licenses.iter().map(|l| l.name.to_string());
        let exceptions = exceptions.iter().map(|e| e.name.to_string());

        tokens.append_all(quote! {
            ::embed_licensing::Licensing::__macro_internal_new(
                &[#(#packages),*],
                &[#(#licenses),*],
                &[#(#exceptions),*],
            )
        })
    }
}

/// Information about a crate.
///
/// The crate can be either the crate from which [`collect`] is called,
/// or one of its dependencies.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Crate {
    /// The name of the crate.
    pub name: String,
    /// The version of the crate.
    pub version: String,
    /// The authors of the crate.
    pub authors: Vec<String>,
    /// The licenses of the crate.
    ///
    /// If the
    /// [`license`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-license-and-license-file-fields)
    /// attribute of the manifest is set,
    /// its content is be passed as an [`spdx::Expression`].
    /// Otherwise, if the
    /// [`license-file`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-license-and-license-file-fields)
    /// is specified,
    /// its content is be included as a String.
    pub license: CrateLicense,
    pub website: String,
}

impl PartialOrd for Crate {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Crate {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.name.cmp(&other.name)
    }
}

impl Crate {
    #[cfg(feature = "macros")]
    #[doc(hidden)]
    pub fn __macro_internal_new(
        name: &str,
        version: &str,
        authors: &[&str],
        license: CrateLicense,
        website: &str,
    ) -> Self {
        Self {
            name: name.to_string(),
            version: version.to_string(),
            authors: authors.iter().map(|s| s.to_string()).collect(),
            license,
            website: website.to_string(),
        }
    }
}

#[cfg(feature = "macros")]
impl ToTokens for Crate {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let Self {
            name,
            version,
            authors,
            license,
            website,
        } = self;

        tokens.append_all(quote! {
            ::embed_licensing::Crate::__macro_internal_new(#name, #version, &[#(#authors),*], #license, #website)
        })
    }
}

impl TryFrom<&cargo_metadata::Package> for Crate {
    type Error = Error;

    fn try_from(package: &cargo_metadata::Package) -> Result<Self> {
        Ok(Crate {
            name: package.name.clone(),
            version: package.version.to_string(),
            authors: package.authors.clone(),
            license: if let Some(license_expr) = &package.license {
                CrateLicense::SpdxExpression(spdx::Expression::parse_mode(
                    license_expr,
                    spdx::ParseMode::LAX,
                )?)
            } else if let Some(license_file) = &package.license_file {
                CrateLicense::Other(std::fs::read_to_string(
                    package
                        .manifest_path
                        .clone()
                        .parent()
                        .expect("the crate’s manifest path does not have a parent directory")
                        .join(license_file),
                )?)
            } else {
                return Err(Error::NoLicense(package.name.clone()));
            },
            website: package
                .homepage
                .as_ref()
                .or(package.repository.as_ref())
                .or(package.documentation.as_ref())
                .ok_or(Error::NoWebsite(package.name.clone()))
                .map(String::from)?,
        })
    }
}

/// Represents the license of a [`Crate`].
#[derive(Clone, Debug)]
#[allow(clippy::large_enum_variant)] // SpdxExpression is much more common than Other
pub enum CrateLicense {
    /// The [`Crate`]’s license is specified by a [`spdx::Expression`].
    SpdxExpression(spdx::Expression),
    /// The [`Crate`] has a custom license whose contents are included in the argument.
    Other(String),
}

impl PartialEq for CrateLicense {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::SpdxExpression(a), Self::SpdxExpression(b)) => a == b,
            (Self::Other(a), Self::Other(b)) => a == b,
            _ => false,
        }
    }
}

impl Eq for CrateLicense {}

impl CrateLicense {
    #[cfg(feature = "macros")]
    #[doc(hidden)]
    pub fn __macro_internal_new_spdx_expression(expr: &str) -> Self {
        Self::SpdxExpression(spdx::Expression::parse_mode(expr, spdx::ParseMode::LAX).unwrap())
    }
}

#[cfg(feature = "macros")]
impl ToTokens for CrateLicense {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        tokens.append_all(match self {
            Self::SpdxExpression(expr) => {
                let expr_string = expr.to_string();
                quote!(
                    ::embed_licensing::CrateLicense::__macro_internal_new_spdx_expression(#expr_string)
                )
            }
            Self::Other(content) => {
                quote!(::embed_licensing::CrateLicense::Other(#content.to_string()))
            }
        })
    }
}

#[derive(Debug, Default, PartialEq)]
pub enum CollectPlatform {
    /// Collect dependencies regardless of their target and cfg restrictions.
    #[default]
    Any,
    /// Only collect dependencies for a specific static platform.
    Static {
        /// All dependencies that require a specific target (like `x86_64-pc-windows-gnu`)
        /// will only be collected when their target matches the given one.
        target: String,
        /// Only dependencies which are satisfied by the given cfg options will be collected.
        cfg: Vec<Cfg>,
    },
    /// Only collect dependencies compatible with the current platform.
    #[cfg(feature = "current_platform")]
    Current,
}

impl CollectPlatform {
    fn target(&self) -> Option<&str> {
        match self {
            CollectPlatform::Any => None,
            CollectPlatform::Static { target, .. } => Some(target),
            #[cfg(feature = "current_platform")]
            CollectPlatform::Current => Some(current_platform::CURRENT_PLATFORM),
        }
    }

    fn cfg(&self) -> Option<Cow<[Cfg]>> {
        match self {
            CollectPlatform::Any => None,
            CollectPlatform::Static { cfg, .. } => Some(Cow::Borrowed(cfg)),
            #[cfg(feature = "current_platform")]
            CollectPlatform::Current => Some(
                serde_json::from_str::<HashMap<String, String>>(env!("CFG_OPTIONS_JSON"))
                    .expect("could not parse CFG_OPTIONS_JSON content")
                    .into_iter()
                    .map(|(opt, val)| {
                        if val.is_empty() {
                            Cfg::Name(opt)
                        } else {
                            Cfg::KeyPair(opt, val)
                        }
                    })
                    .collect(),
            ),
        }
    }
}

#[cfg(feature = "macros")]
impl syn::parse::Parse for CollectPlatform {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        use syn::{ext::IdentExt, parenthesized, Ident, LitStr, Token};

        let inner;
        parenthesized!(inner in input);

        Ok(match inner.call(Ident::parse_any)?.to_string().as_str() {
            "any" => CollectPlatform::Any,
            "static" => {
                let mut target = None;
                let mut cfg = None;

                let inner_static;
                parenthesized!(inner_static in inner);
                while !inner_static.is_empty() {
                    match inner_static.call(Ident::parse_any)?.to_string().as_str() {
                        "target" => {
                            inner_static.parse::<syn::Token![=]>()?;
                            target = Some(inner_static.parse::<LitStr>()?.value());
                        }
                        "cfg" => {
                            cfg = Some(Vec::new());

                            let inner_cfg;
                            parenthesized!(inner_cfg in inner_static);
                            while !inner_cfg.is_empty() {
                                let key = inner_cfg.call(Ident::parse_any)?;
                                if inner_cfg.parse::<syn::Token![=]>().is_ok() {
                                    let value = inner_cfg.parse::<LitStr>()?.value();
                                    cfg.as_mut()
                                        .unwrap()
                                        .push(Cfg::KeyPair(key.to_string(), value))
                                } else {
                                    cfg.as_mut().unwrap().push(Cfg::Name(key.to_string()))
                                }

                                if inner_cfg.parse::<Token![,]>().is_err() {
                                    break;
                                }
                            }
                        }
                        _ => return Err(inner_static.error("unknown static platform argument")),
                    }

                    if inner_static.parse::<Token![,]>().is_err() {
                        break;
                    }
                }

                if target.is_none() || cfg.is_none() {
                    return Err(inner_static.error("static platform must specify target and cfg"));
                }

                CollectPlatform::Static {
                    target: target.unwrap(),
                    cfg: cfg.unwrap(),
                }
            }
            #[cfg(feature = "current_platform")]
            "current" => CollectPlatform::Current,
            #[cfg(not(feature = "current_platform"))]
            "current" => return Err(inner.error("current_platform feature is not enabled")),
            _ => return Err(inner.error("unknown platform collection variant")),
        })
    }
}

/// Configuration options for the collection process.
#[derive(Debug, Default, PartialEq)]
pub struct CollectConfig {
    /// If set to `true`,
    /// [`dev-dependencies`](https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#development-dependencies)
    /// are collected
    ///
    /// Because dependents never inherit development dependencies,
    /// transitive development dependencies are never collected,
    /// even with this option set.
    pub dev: bool,
    /// If set to `true`,
    /// [`build-dependencies`](https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#build-dependencies)
    /// are collected.
    ///
    /// Unlike with development dependencies,
    /// this also applies to transitive build dependencies.
    pub build: bool,
    /// Which platform to collect for.
    ///
    /// Defaults to [`CollectPlatform::Any`].
    pub platform: CollectPlatform,
}

impl CollectConfig {
    fn kinds(&self) -> Vec<DependencyKind> {
        let mut kinds = vec![DependencyKind::Normal];
        if self.dev {
            kinds.push(DependencyKind::Development);
        }
        if self.build {
            kinds.push(DependencyKind::Build);
        }
        kinds
    }
}

#[cfg(feature = "macros")]
impl syn::parse::Parse for CollectConfig {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        use syn::{ext::IdentExt, Error, Ident, LitBool, Token};

        let mut config = Self::default();

        while !input.is_empty() {
            let key = input.call(Ident::parse_any)?;

            match key.to_string().as_str() {
                "dev" => {
                    if input.parse::<Token![=]>().is_ok() {
                        config.dev = input.parse::<LitBool>()?.value();
                    } else {
                        config.dev = true;
                    }
                }
                "build" => {
                    if input.parse::<Token![=]>().is_ok() {
                        config.build = input.parse::<LitBool>()?.value();
                    } else {
                        config.build = true;
                    }
                }
                "platform" => {
                    config.platform = input.parse()?;
                }
                _ => {
                    return Err(Error::new(key.span(), "unrecognized argument"));
                }
            }

            if input.parse::<Token![,]>().is_err() {
                break;
            }
        }

        Ok(config)
    }
}

/// Collect licensing information at runtime.
///
/// It uses the defaults of `cargo metadata`,
/// which is to search for `Cargo.toml` in the current directory and its parent directories.
///
/// To specify a manifest path, please use [`collect_from_manifest`].
pub fn collect(config: CollectConfig) -> Result<Licensing> {
    collect_internal(None::<PathBuf>, config)
}

/// Collect licensing information from given manifest path.
pub fn collect_from_manifest(
    manifest_path: impl Into<PathBuf>,
    config: CollectConfig,
) -> Result<Licensing> {
    collect_internal(Some(manifest_path), config)
}

fn collect_internal(
    manifest_path: Option<impl Into<PathBuf>>,
    config: CollectConfig,
) -> Result<Licensing> {
    let mut cmd = cargo_metadata::MetadataCommand::new();
    if let Some(manifest_path) = manifest_path {
        cmd.manifest_path(manifest_path);
    }
    let metadata = cmd.exec()?;

    let mut resolve_map = HashMap::new();
    let resolve = metadata.resolve.as_ref().ok_or(Error::NoDependencyGraph)?;
    for node in &resolve.nodes {
        resolve_map.insert(node.id.clone(), node);
    }

    let mut licensing = Licensing {
        packages: collect_tree(
            &metadata,
            &resolve_map,
            resolve_map
                .get(resolve.root.as_ref().ok_or(Error::NoRootNode)?)
                .unwrap(),
            &config,
            true,
        )?
        .into_iter()
        .collect(),
        licenses: Vec::new(),
        exceptions: Vec::new(),
    };

    for package in &licensing.packages {
        if let CrateLicense::SpdxExpression(expr) = &package.license {
            for node in expr.iter() {
                if let spdx::expression::ExprNode::Req(req) = node {
                    licensing.licenses.push(
                        req.req
                            .license
                            .id()
                            .ok_or(Error::NonSpdxLicense(package.name.clone()))?,
                    );

                    if let Some(exception) = req.req.exception {
                        licensing.exceptions.push(exception);
                    }
                }
            }
        };
    }

    licensing.packages.sort_unstable();

    licensing.licenses.sort_unstable();
    licensing.licenses.dedup();

    licensing.exceptions.sort_unstable();
    licensing.exceptions.dedup();

    Ok(licensing)
}

fn collect_tree(
    metadata: &cargo_metadata::Metadata,
    resolve: &HashMap<cargo_metadata::PackageId, &cargo_metadata::Node>,
    node: &cargo_metadata::Node,
    config: &CollectConfig,
    root: bool,
) -> Result<BTreeSet<Crate>> {
    let mut crates = BTreeSet::new();

    let package = &metadata[&node.id];

    crates.insert(package.try_into()?);

    let kinds = config.kinds();

    for dep in &node.deps {
        let mut selected_kinds = Vec::new();
        let mut mismatching_targets = Vec::new();
        let mut cfg_mismatch = false;

        for kind in &dep.dep_kinds {
            let target = kind.target.as_ref();
            let kind = kind.kind;

            if kinds.contains(&kind) {
                selected_kinds.push(kind);
            }

            if let Some(target) = target {
                match (config.platform.target(), config.platform.cfg(), target) {
                    (Some(wanted_target), _, Platform::Name(actual_target)) => {
                        if wanted_target != actual_target {
                            mismatching_targets.push(actual_target);
                        }
                    }
                    (_, Some(wanted_cfgs), Platform::Cfg(actual_cfgs)) => {
                        if !actual_cfgs.matches(&wanted_cfgs) {
                            cfg_mismatch = true;
                        }
                    }
                    (None, _, Platform::Name(_)) | (_, None, Platform::Cfg(_)) => (),
                }
            }
        }

        if selected_kinds.is_empty() || !mismatching_targets.is_empty() || cfg_mismatch {
            continue;
        }

        // Cargo does not resolve development dependencies for transitive dependencies
        // (as they are not needed to build the crate).
        // It is possible to create the following dependency loop:
        //
        // ┌──────┐   dependency    ┌──────┐
        // │      ├────────────────►│      │
        // │ pkg1 │                 │ pkg2 │
        // │      │◄────────────────┤      │
        // └──────┘  dev-dependency └──────┘
        // (also possible with dev-dependency in both directions)
        //
        // It successfully resolves with cargo,
        // as it will no longer find dependencies once it reaches pkg2 from pkg1.
        //
        // The following check ensures that this implementation also stops the recursion in this
        // case.
        if !root
            && selected_kinds.len() == 1
            && *selected_kinds.first().unwrap() == DependencyKind::Development
        {
            continue;
        }

        crates.append(&mut collect_tree(
            metadata,
            resolve,
            resolve.get(&dep.pkg).unwrap(),
            config,
            false,
        )?)
    }

    Ok(crates)
}

#[cfg(all(test, feature = "macros"))]
mod tests {
    use cargo_platform::Cfg;
    use syn::parse_quote;

    use super::{CollectConfig, CollectPlatform};

    macro_rules! should_panic_multiple {
        ($($name:ident => $body:block),* $(,)?) => {
            $(
                #[test]
                #[should_panic]
                fn $name() $body
            )*
        }
    }

    #[test]
    fn collect_config_parse_empty() {
        let config: CollectConfig = parse_quote!();
        assert_eq!(config, CollectConfig::default());
    }

    #[test]
    fn collect_config_parse_full() {
        let config: CollectConfig = parse_quote!(build, dev);
        assert_eq!(
            config,
            CollectConfig {
                build: true,
                dev: true,
                ..Default::default()
            }
        );
    }

    #[test]
    fn collect_config_parse_args() {
        let config: CollectConfig = parse_quote!(build = true, dev = true);
        assert_eq!(
            config,
            CollectConfig {
                build: true,
                dev: true,
                ..Default::default()
            }
        );

        let config: CollectConfig = parse_quote!(build = false, dev = false);
        assert_eq!(
            config,
            CollectConfig {
                build: false,
                dev: false,
                ..Default::default()
            }
        );
    }

    #[test]
    fn collect_config_parse_single_keyword() {
        let config: CollectConfig = parse_quote!(build);
        assert_eq!(
            config,
            CollectConfig {
                build: true,
                ..Default::default()
            }
        );

        let config: CollectConfig = parse_quote!(dev);
        assert_eq!(
            config,
            CollectConfig {
                dev: true,
                ..Default::default()
            }
        );
    }

    #[test]
    fn collect_config_parse_platform_any() {
        let config: CollectConfig = parse_quote!(platform(any));
        assert_eq!(
            config,
            CollectConfig {
                platform: CollectPlatform::Any,
                ..Default::default()
            }
        );
    }

    #[test]
    fn collect_config_parse_platform_static_target() {
        let config: CollectConfig =
            parse_quote!(platform(static(target = "x86_64-linux-gnu", cfg())));
        assert_eq!(
            config,
            CollectConfig {
                platform: CollectPlatform::Static {
                    target: "x86_64-linux-gnu".to_string(),
                    cfg: vec![]
                },
                ..Default::default()
            }
        );
    }

    #[test]
    fn collect_config_parse_platform_static_cfg_name() {
        let config: CollectConfig =
            parse_quote!(platform(static(target = "aarch64-apple-darwin", cfg(foo))));
        assert_eq!(
            config,
            CollectConfig {
                platform: CollectPlatform::Static {
                    target: "aarch64-apple-darwin".to_string(),
                    cfg: vec![Cfg::Name("foo".to_string())],
                },
                ..Default::default()
            }
        );
    }

    #[test]
    fn collect_config_parse_platform_static_cfg_keypair() {
        let config: CollectConfig =
            parse_quote!(platform(static(target = "x86_64-pc-windows-gnu", cfg(foo = "bar"))));
        assert_eq!(
            config,
            CollectConfig {
                platform: CollectPlatform::Static {
                    target: "x86_64-pc-windows-gnu".to_string(),
                    cfg: vec![Cfg::KeyPair("foo".to_string(), "bar".to_string())],
                },
                ..Default::default()
            }
        );
    }

    #[test]
    fn collect_config_parse_platform_static_cfg_multiple() {
        let config: CollectConfig = parse_quote!(platform(static(target = "wasm32-unknown-unknown", cfg(foo = "bar", baz))));
        assert_eq!(
            config,
            CollectConfig {
                platform: CollectPlatform::Static {
                    target: "wasm32-unknown-unknown".to_string(),
                    cfg: vec![
                        Cfg::KeyPair("foo".to_string(), "bar".to_string()),
                        Cfg::Name("baz".to_string())
                    ],
                },
                ..Default::default()
            }
        );
    }

    should_panic_multiple! {
        collect_config_macro_parse_invalid1 => { let _: CollectConfig = parse_quote!(foo); },

        collect_config_macro_parse_invalid2 => { let _: CollectConfig = parse_quote!(dev = 1); },
        collect_config_macro_parse_invalid3 => { let _: CollectConfig = parse_quote!(build = "foo"); },

        collect_config_macro_parse_invalid4 => { let _: CollectConfig = parse_quote!(platform()); },
        collect_config_macro_parse_invalid5 => { let _: CollectConfig = parse_quote!(platform(xy)); },

        collect_config_macro_parse_invalid6 => { let _: CollectConfig = parse_quote!(platform(static())); },
        collect_config_macro_parse_invalid7 => { let _: CollectConfig = parse_quote!(platform(static(target = "x86_64-unknown-linux-gnu"))); },
        collect_config_macro_parse_invalid8 => { let _: CollectConfig = parse_quote!(platform(static(cfg(unix)))); },
    }
}