codama_attributes/
codama_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
56
57
58
59
60
61
62
63
64
use crate::{utils::SetOnce, AccountDirective, AttributeContext, CodamaDirective};
use codama_syn_helpers::extensions::*;

#[derive(Debug, PartialEq)]
pub struct CodamaAttribute<'a> {
    pub ast: &'a syn::Attribute,
    pub directive: CodamaDirective,
}

impl<'a> CodamaAttribute<'a> {
    pub fn parse(ast: &'a syn::Attribute, ctx: &AttributeContext) -> 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 #[codama(...)] attribute.
        let list = attr.meta.require_list()?;
        if !list.path.is_strict("codama") {
            return Err(list.path.error("expected #[codama(...)]"));
        };

        let mut directive = SetOnce::<CodamaDirective>::new("codama");
        list.each(|ref meta| directive.set(CodamaDirective::parse(&meta, ctx)?, meta))?;
        Ok(Self {
            ast,
            directive: directive.take(attr)?,
        })
    }

    pub fn account(&self) -> Option<&AccountDirective> {
        match &self.directive {
            CodamaDirective::Account(a) => Some(a),
            _ => None,
        }
    }
}

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

    #[test]
    fn test_codama_attribute() {
        let ast = parse_quote! { #[codama(type = boolean)] };
        let file = syn::File::empty();
        let ctx = AttributeContext::File(&file);
        let attribute = CodamaAttribute::parse(&ast, &ctx).unwrap();

        assert_eq!(attribute.ast, &ast);
        assert!(matches!(attribute.directive, CodamaDirective::Type(_)));
    }

    #[test]
    fn test_feature_gated_codama_attribute() {
        let ast = parse_quote! { #[cfg_attr(feature = "some_feature", codama(type = boolean))] };
        let file = syn::File::empty();
        let ctx = AttributeContext::File(&file);
        let attribute = CodamaAttribute::parse(&ast, &ctx).unwrap();

        assert_eq!(attribute.ast, &ast);
        assert!(matches!(attribute.directive, CodamaDirective::Type(_)));
    }
}