Skip to main content

tusks_lib/parsing/util/
attr.rs

1use syn::{Attribute, Field, FnArg, ItemFn, ItemMod, ItemStruct, ItemUse};
2
3/// Helper trait for all syn nodes that expose `attrs: Vec<Attribute>`
4pub trait HasAttributes {
5    fn attrs(&self) -> &[Attribute];
6}
7
8/// Public trait for attribute checking
9pub trait AttributeCheck {
10    fn has_attr(&self, name: &str) -> bool;
11}
12
13/* -------------------------------------------------------
14 * Generic AttributeCheck implementation
15 * -------------------------------------------------------*/
16impl<T: HasAttributes> AttributeCheck for T {
17    fn has_attr(&self, name: &str) -> bool {
18        self.attrs().iter().any(|attr| {
19            match attr.path().segments.last() {
20                Some(seg) => seg.ident == name,
21                None => false,
22            }
23        })
24    }
25}
26
27/* -------------------------------------------------------
28 * HasAttributes implementations for syn types
29 * -------------------------------------------------------*/
30
31impl HasAttributes for ItemFn {
32    fn attrs(&self) -> &[Attribute] {
33        &self.attrs
34    }
35}
36
37impl HasAttributes for Field {
38    fn attrs(&self) -> &[Attribute] {
39        &self.attrs
40    }
41}
42
43impl HasAttributes for FnArg {
44    fn attrs(&self) -> &[Attribute] {
45        match self {
46            FnArg::Typed(pat_type) => &pat_type.attrs,
47            FnArg::Receiver(receiver) => &receiver.attrs,
48        }
49    }
50}
51
52impl HasAttributes for ItemStruct {
53    fn attrs(&self) -> &[Attribute] {
54        &self.attrs
55    }
56}
57
58impl HasAttributes for ItemMod {
59    fn attrs(&self) -> &[Attribute] {
60        &self.attrs
61    }
62}
63
64impl HasAttributes for ItemUse {
65    fn attrs(&self) -> &[Attribute] {
66        &self.attrs
67    }
68}