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
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
use crate::ident::GetIdent;
use crate::meta::{self, MetaExt};
use syn::{
    parse_quote, punctuated::Punctuated, token::Paren, Attribute, Ident, Meta, MetaList, Result,
};

impl GetIdent for Attribute {
    /// Get ident of the [syn::Attribute::path] field.
    fn get_ident(&self) -> Option<&Ident> {
        self.path.get_ident()
    }
}

/// Extension for [syn::Attribute]
#[cfg(feature = "parsing")]
pub trait AttributeExt {
    /// Constructs and returns a new [syn::Attribute] from [syn::Meta]
    fn from_meta<M>(meta: M) -> Self
    where
        M: IntoAttribute;

    /// Takes a closure and calls it with parsed meta. After call, applys back the manipulated [syn::Meta].
    ///
    /// 1. Try [syn::Attribute::parse_meta]; return if `Err`
    /// 2. Run `f`
    /// 3. Apply back the manipulated [syn::Meta] by `f`.
    /// 4. Return the result of `f`.
    ///
    /// Note: Even `f` returns `Err`, meta will be made into self.
    fn try_meta_mut<F, R>(&mut self, f: F) -> Result<R>
    where
        F: FnOnce(&mut Meta) -> Result<R>;

    /// Returns a fake promoted list value of [syn::MetaList].
    ///
    /// If [syn::Meta::List], return inner [syn::MetaList].
    /// If [syn::Meta::Path], return a fake [syn::MetaList] with default paren and empty nested.
    /// Otherwise return `Err`
    fn promoted_list(&self) -> Result<MetaList>;

    /// Takes a closure and calls it with promoted list of parsed meta. After call, applys back the manipulated [syn::MetaList].
    ///
    /// 1. Try [syn::Attribute::parse_meta]; return if `Err`
    /// 2. Promote to [syn::Meta::List] if [syn::Meta::Path]
    /// 3. Run `f` to inner [syn::MetaList]
    /// 4. Apply back the manipulated [syn::Meta] by `f`.
    /// 5. Return the result of `f`.
    fn try_promoted_list_mut<F, R>(&mut self, paren: Paren, f: F) -> Result<R>
    where
        F: FnOnce(&mut MetaList) -> Result<R>;
}

#[cfg(feature = "parsing")]
impl AttributeExt for Attribute {
    fn from_meta<M>(meta: M) -> Self
    where
        M: IntoAttribute,
    {
        meta.into_attribute()
    }

    fn try_meta_mut<F, R>(&mut self, f: F) -> Result<R>
    where
        F: FnOnce(&mut Meta) -> Result<R>,
    {
        let mut meta = self.parse_meta()?;
        let result = f(&mut meta);
        *self = Self::from_meta(meta);
        Ok(result?)
    }

    fn promoted_list(&self) -> Result<MetaList> {
        match self.parse_meta()? {
            Meta::Path(path) => Ok(MetaList {
                path,
                paren_token: Default::default(),
                nested: Punctuated::new(),
            }),
            Meta::List(metalist) => Ok(metalist),
            other => Err(meta::err_promote_to_list(&other)),
        }
    }

    fn try_promoted_list_mut<F, R>(&mut self, paren: Paren, f: F) -> Result<R>
    where
        F: FnOnce(&mut MetaList) -> Result<R>,
    {
        self.try_meta_mut(|meta| {
            let metalist = meta.promote_to_list(paren)?;
            f(metalist)
        })
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::assert_quote_eq;
    use quote::quote;

    fn test_meta_round_trip(attr: Attribute) -> Result<()> {
        let meta = attr.parse_meta()?;
        let created = Attribute::from_meta(meta);
        assert_eq!(
            quote! { #attr }.to_string(),
            quote! { #created }.to_string()
        );
        Ok(())
    }

    #[test]
    fn run_test_meta_round_trip() {
        use syn::parse_quote;
        test_meta_round_trip(parse_quote! { #[cfg(test)] }).unwrap();
        test_meta_round_trip(parse_quote! { #[feature = "full"] }).unwrap();
        test_meta_round_trip(parse_quote! { #[cfg(all(a,b,any(c,d)))] }).unwrap();
        test_meta_round_trip(parse_quote! { #[a(b="1",d)] }).unwrap();
        test_meta_round_trip(parse_quote! { #[abc::de::ef] }).unwrap();
    }

    #[test]
    fn test_try_meta_mut() {
        let mut attr: Attribute = parse_quote! { #[cfg(test)] };
        attr.try_meta_mut(|meta| match meta {
            Meta::List(metalist) => {
                metalist.path = parse_quote! { newcfg };
                Ok(())
            }
            _ => unreachable!(),
        })
        .unwrap();
        let expected: Attribute = parse_quote! { #[newcfg(test)] };
        assert_quote_eq!(attr, expected);

        attr.try_meta_mut(|meta| match meta {
            Meta::List(metalist) => {
                metalist.nested.pop();
                metalist.nested.push(parse_quote!(a));
                metalist.nested.push(parse_quote!(b = "c"));
                metalist.nested.push(parse_quote!("d"));
                Ok(())
            }
            _ => unreachable!(),
        })
        .unwrap();
        let expected: Attribute = parse_quote! { #[newcfg(a, b="c", "d")] };
        assert_quote_eq!(attr, expected);
    }

    #[test]
    fn test_promoted_list() {
        let attr: Attribute = parse_quote! { #[derive] };
        let list = attr.promoted_list().unwrap();
        assert_quote_eq!(attr.path, list.path);
        assert!(list.nested.is_empty());
    }
}

// pub trait AttributesExt {
//     fn filter_name<'a, P>(
//         &'a self,
//         name: &'static str,
//     ) -> std::iter::Filter<std::slice::Iter<'a, Attribute>, P>
//     where
//         P: FnMut(&&'a syn::Attribute) -> bool;
// }

// impl AttributesExt for [Attribute] {
//     fn filter_name<'a, P>(
//         &'a self,
//         name: &'static str,
//     ) -> std::iter::Filter<std::slice::Iter<'a, Attribute>, P>
//     where
//         P: FnMut(&&'a syn::Attribute) -> bool,
//     {
//         let mut p = |attr: &&'a Attribute| {
//             attr.path
//                 .get_ident()
//                 .map_or(false, |ident| ident.to_string() == name)
//         };
//         self.iter().filter(p)
//     }
// }

pub trait IntoAttribute {
    fn into_attribute(self) -> Attribute;
}

impl IntoAttribute for Meta {
    fn into_attribute(self) -> Attribute {
        parse_quote!( #[ #self ] )
    }
}

impl IntoAttribute for MetaList {
    fn into_attribute(self) -> Attribute {
        Meta::List(self).into_attribute()
    }
}