codama_attributes/
attributes.rs

1use crate::{
2    Attribute, AttributeContext, CodamaAttribute, CodamaDirective, DeriveAttribute, TryFromFilter,
3};
4use codama_errors::IteratorCombineErrors;
5use codama_syn_helpers::extensions::*;
6use std::ops::{Deref, DerefMut, Index, IndexMut};
7
8#[derive(Debug, PartialEq)]
9pub struct Attributes<'a>(pub Vec<Attribute<'a>>);
10
11impl<'a> Attributes<'a> {
12    pub fn parse(attrs: &'a [syn::Attribute], ctx: AttributeContext<'a>) -> syn::Result<Self> {
13        let attributes = Self(
14            attrs
15                .iter()
16                .map(|attr| Attribute::parse(attr, &ctx))
17                .collect_and_combine_errors()?,
18        );
19        attributes.validate_codama_type_attributes()?;
20        Ok(attributes)
21    }
22
23    pub fn validate_codama_type_attributes(&self) -> syn::Result<()> {
24        let mut errors = Vec::<syn::Error>::new();
25        let mut has_seen_type = false;
26
27        for attribute in self.0.iter().rev() {
28            if let Attribute::Codama(attribute) = attribute {
29                match &attribute.directive {
30                    CodamaDirective::Type(_) if !has_seen_type => has_seen_type = true,
31                    CodamaDirective::Type(_)
32                    | CodamaDirective::Encoding(_)
33                    | CodamaDirective::FixedSize(_)
34                        if has_seen_type =>
35                    {
36                        errors.push(syn::Error::new_spanned(
37                            attribute.ast,
38                            "This attribute is overridden by a `#[codama(type = ...)]` attribute below",
39                        ));
40                    }
41                    _ => {}
42                }
43            }
44        }
45
46        if errors.is_empty() {
47            Ok(())
48        } else {
49            // Combine all errors into one
50            let mut combined_error = errors.remove(0);
51            for error in errors {
52                combined_error.combine(error);
53            }
54            Err(combined_error)
55        }
56    }
57
58    pub fn has_any_codama_derive(&self) -> bool {
59        self.has_codama_derive("CodamaAccount")
60            || self.has_codama_derive("CodamaAccounts")
61            || self.has_codama_derive("CodamaErrors")
62            || self.has_codama_derive("CodamaInstruction")
63            || self.has_codama_derive("CodamaInstructions")
64            || self.has_codama_derive("CodamaType")
65    }
66
67    pub fn has_codama_derive(&self, derive: &str) -> bool {
68        self.has_derive(&["", "codama", "codama_macros"], derive)
69    }
70
71    pub fn has_derive(&self, prefixes: &[&str], last: &str) -> bool {
72        self.iter().filter_map(DeriveAttribute::filter).any(|attr| {
73            attr.derives
74                .iter()
75                .any(|p| prefixes.contains(&p.prefix().as_str()) && p.last_str() == last)
76        })
77    }
78
79    pub fn has_codama_attribute(&self, name: &str) -> bool {
80        self.iter()
81            .filter_map(CodamaAttribute::filter)
82            .any(|a| a.directive.name() == name)
83    }
84}
85
86impl<'a> Deref for Attributes<'a> {
87    type Target = Vec<Attribute<'a>>;
88
89    fn deref(&self) -> &Self::Target {
90        &self.0
91    }
92}
93
94impl DerefMut for Attributes<'_> {
95    fn deref_mut(&mut self) -> &mut Self::Target {
96        &mut self.0
97    }
98}
99
100impl<'a> AsRef<[Attribute<'a>]> for Attributes<'a> {
101    fn as_ref(&self) -> &[Attribute<'a>] {
102        &self.0
103    }
104}
105
106impl<'a> AsMut<[Attribute<'a>]> for Attributes<'a> {
107    fn as_mut(&mut self) -> &mut [Attribute<'a>] {
108        &mut self.0
109    }
110}
111
112impl<'a> Index<usize> for Attributes<'a> {
113    type Output = Attribute<'a>;
114
115    fn index(&self, index: usize) -> &Self::Output {
116        &self.0[index]
117    }
118}
119
120impl IndexMut<usize> for Attributes<'_> {
121    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
122        &mut self.0[index]
123    }
124}