educe/trait_handlers/deref_mut/models/
field_attribute.rs1use proc_macro2::Span;
2use syn::{punctuated::Punctuated, spanned::Spanned, Attribute, Meta, Token};
3
4use crate::{panic, supported_traits::Trait};
5
6pub(crate) struct FieldAttribute {
7 pub(crate) flag: bool,
8 pub(crate) span: Span,
9}
10
11pub(crate) struct FieldAttributeBuilder {
12 pub(crate) enable_flag: bool,
13}
14
15impl FieldAttributeBuilder {
16 pub(crate) fn build_from_deref_mut_meta(&self, meta: &Meta) -> syn::Result<FieldAttribute> {
17 debug_assert!(meta.path().is_ident("DerefMut"));
18
19 let correct_usage_for_deref_mut_attribute = {
20 let mut usage = vec![];
21
22 if self.enable_flag {
23 usage.push(stringify!(#[educe(DerefMut)]));
24 }
25
26 usage
27 };
28
29 match meta {
30 Meta::Path(_) => {
31 if !self.enable_flag {
32 return Err(panic::attribute_incorrect_format(
33 meta.path().get_ident().unwrap(),
34 &correct_usage_for_deref_mut_attribute,
35 ));
36 }
37 },
38 Meta::NameValue(_) | Meta::List(_) => {
39 return Err(panic::attribute_incorrect_format(
40 meta.path().get_ident().unwrap(),
41 &correct_usage_for_deref_mut_attribute,
42 ));
43 },
44 }
45
46 Ok(FieldAttribute {
47 flag: true, span: meta.span()
48 })
49 }
50
51 pub(crate) fn build_from_attributes(
52 &self,
53 attributes: &[Attribute],
54 traits: &[Trait],
55 ) -> syn::Result<FieldAttribute> {
56 let mut output = None;
57
58 for attribute in attributes.iter() {
59 let path = attribute.path();
60
61 if path.is_ident("educe") {
62 if let Meta::List(list) = &attribute.meta {
63 let result =
64 list.parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)?;
65
66 for meta in result {
67 let path = meta.path();
68
69 let t = match Trait::from_path(path) {
70 Some(t) => t,
71 None => return Err(panic::unsupported_trait(meta.path())),
72 };
73
74 if !traits.contains(&t) {
75 return Err(panic::trait_not_used(path.get_ident().unwrap()));
76 }
77
78 if t == Trait::DerefMut {
79 if output.is_some() {
80 return Err(panic::reuse_a_trait(path.get_ident().unwrap()));
81 }
82
83 output = Some(self.build_from_deref_mut_meta(&meta)?);
84 }
85 }
86 }
87 }
88 }
89
90 Ok(output.unwrap_or(FieldAttribute {
91 flag: false, span: Span::call_site()
92 }))
93 }
94}