codama_attributes/
derive_attribute.rs

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
use codama_syn_helpers::extensions::*;

#[derive(Debug, PartialEq)]
pub struct DeriveAttribute<'a> {
    pub ast: &'a syn::Attribute,
    pub derives: Vec<syn::Path>,
}

impl<'a> DeriveAttribute<'a> {
    pub fn parse(ast: &'a syn::Attribute) -> syn::Result<Self> {
        // Check if the attribute is feature-gated.
        let unfeatured = ast.unfeatured();
        let attr = unfeatured.as_ref().unwrap_or(ast);

        // Check if the attribute is a #[derive(...)] attribute.
        let list = attr.meta.require_list()?;
        if !list.path.is_strict("derive") {
            return Err(list.path.error("expected #[derive(...)]"));
        };

        // Parse the list of derives.
        let derives = list.parse_comma_args::<syn::Path>()?;
        Ok(Self { ast, derives })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use syn::parse_quote;

    #[test]
    fn test_derive_attribute() {
        let ast = parse_quote! { #[derive(Debug, PartialEq)] };
        let attribute = DeriveAttribute::parse(&ast).unwrap();

        assert_eq!(attribute.ast, &ast);
        assert_eq!(
            attribute.derives,
            [(parse_quote! { Debug }), (parse_quote! { PartialEq }),]
        );
    }

    #[test]
    fn test_feature_gated_derive_attribute() {
        let ast = parse_quote! { #[cfg_attr(feature = "some_feature", derive(Debug, PartialEq))] };
        let attribute = DeriveAttribute::parse(&ast).unwrap();

        assert_eq!(attribute.ast, &ast);
        assert_eq!(
            attribute.derives,
            [(parse_quote! { Debug }), (parse_quote! { PartialEq })]
        );
    }
}