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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
use crate::ident::GetIdent;
use syn::{Attribute, Error, Ident, ImplItem, Item, ItemMod, Result, TraitItem};

/// Extension for [syn::Item]
pub trait ItemLike {
    /// Returns reference of inner attrs if not verbatim; otherwise `Err`
    fn attrs(&self) -> Result<&[Attribute]>;
    /// Returns mutable reference of inner attrs if not verbatim; otherwise `Err`
    fn attrs_mut(&mut self) -> Result<&mut Vec<Attribute>>;

    /// Returns `true` if self matches `*ItemConst`
    fn is_const(&self) -> bool;
    /// Returns `true` if self matches `Item::Fn` or `*ItemMethod`
    fn is_function_or_method(&self) -> bool;
    /// Returns `true` if self matches `*ItemType`
    fn is_type(&self) -> bool;
    /// Returns `true` if self matches `*ItemMacro`
    fn is_macro(&self) -> bool;
}

impl ItemLike for Item {
    fn attrs(&self) -> Result<&[Attribute]> {
        use syn::Item::*;
        use syn::*;
        let attrs = match self {
            Const(ItemConst { ref attrs, .. }) => attrs,
            Enum(ItemEnum { ref attrs, .. }) => attrs,
            ExternCrate(ItemExternCrate { ref attrs, .. }) => attrs,
            Fn(ItemFn { ref attrs, .. }) => attrs,
            ForeignMod(ItemForeignMod { ref attrs, .. }) => attrs,
            Impl(ItemImpl { ref attrs, .. }) => attrs,
            Macro(ItemMacro { ref attrs, .. }) => attrs,
            Macro2(ItemMacro2 { ref attrs, .. }) => attrs,
            Mod(ItemMod { ref attrs, .. }) => attrs,
            Static(ItemStatic { ref attrs, .. }) => attrs,
            Struct(ItemStruct { ref attrs, .. }) => attrs,
            Trait(ItemTrait { ref attrs, .. }) => attrs,
            TraitAlias(ItemTraitAlias { ref attrs, .. }) => attrs,
            Type(ItemType { ref attrs, .. }) => attrs,
            Union(ItemUnion { ref attrs, .. }) => attrs,
            Use(ItemUse { ref attrs, .. }) => attrs,
            other => {
                return Err(Error::new_spanned(
                    other,
                    "this kind of item doesn't have attrs",
                ))
            }
        };
        Ok(attrs)
    }

    fn attrs_mut(&mut self) -> Result<&mut Vec<Attribute>> {
        use syn::Item::*;
        use syn::*;
        let attrs = match self {
            Const(ItemConst { ref mut attrs, .. }) => attrs,
            Enum(ItemEnum { ref mut attrs, .. }) => attrs,
            ExternCrate(ItemExternCrate { ref mut attrs, .. }) => attrs,
            Fn(ItemFn { ref mut attrs, .. }) => attrs,
            ForeignMod(ItemForeignMod { ref mut attrs, .. }) => attrs,
            Impl(ItemImpl { ref mut attrs, .. }) => attrs,
            Macro(ItemMacro { ref mut attrs, .. }) => attrs,
            Macro2(ItemMacro2 { ref mut attrs, .. }) => attrs,
            Mod(ItemMod { ref mut attrs, .. }) => attrs,
            Static(ItemStatic { ref mut attrs, .. }) => attrs,
            Struct(ItemStruct { ref mut attrs, .. }) => attrs,
            Trait(ItemTrait { ref mut attrs, .. }) => attrs,
            TraitAlias(ItemTraitAlias { ref mut attrs, .. }) => attrs,
            Type(ItemType { ref mut attrs, .. }) => attrs,
            Union(ItemUnion { ref mut attrs, .. }) => attrs,
            Use(ItemUse { ref mut attrs, .. }) => attrs,
            other => {
                return Err(Error::new_spanned(
                    other,
                    "this kind of item doesn't have attrs",
                ))
            }
        };
        Ok(attrs)
    }

    fn is_const(&self) -> bool {
        matches!(self, Item::Const(_))
    }
    fn is_function_or_method(&self) -> bool {
        matches!(self, Item::Fn(_))
    }
    fn is_type(&self) -> bool {
        matches!(self, Item::Type(_))
    }
    fn is_macro(&self) -> bool {
        matches!(self, Item::Macro(_))
    }
}

impl ItemLike for ImplItem {
    fn attrs(&self) -> Result<&[Attribute]> {
        use syn::ImplItem::*;
        use syn::*;
        let attrs = match self {
            Const(ImplItemConst { ref attrs, .. }) => attrs,
            Method(ImplItemMethod { ref attrs, .. }) => attrs,
            Type(ImplItemType { ref attrs, .. }) => attrs,
            Macro(ImplItemMacro { ref attrs, .. }) => attrs,
            other => {
                return Err(Error::new_spanned(
                    other,
                    "this kind of item doesn't have attrs",
                ))
            }
        };
        Ok(attrs)
    }

    fn attrs_mut(&mut self) -> Result<&mut Vec<Attribute>> {
        use syn::ImplItem::*;
        use syn::*;
        let attrs = match self {
            Const(ImplItemConst { ref mut attrs, .. }) => attrs,
            Method(ImplItemMethod { ref mut attrs, .. }) => attrs,
            Type(ImplItemType { ref mut attrs, .. }) => attrs,
            Macro(ImplItemMacro { ref mut attrs, .. }) => attrs,
            other => {
                return Err(Error::new_spanned(
                    other,
                    "this kind of item doesn't have attrs",
                ))
            }
        };
        Ok(attrs)
    }

    fn is_const(&self) -> bool {
        matches!(self, ImplItem::Const(_))
    }
    fn is_function_or_method(&self) -> bool {
        matches!(self, ImplItem::Method(_))
    }
    fn is_type(&self) -> bool {
        matches!(self, ImplItem::Type(_))
    }
    fn is_macro(&self) -> bool {
        matches!(self, ImplItem::Macro(_))
    }
}

impl ItemLike for TraitItem {
    fn attrs(&self) -> Result<&[Attribute]> {
        use syn::TraitItem::*;
        use syn::*;
        let attrs = match self {
            Const(TraitItemConst { ref attrs, .. }) => attrs,
            Method(TraitItemMethod { ref attrs, .. }) => attrs,
            Type(TraitItemType { ref attrs, .. }) => attrs,
            Macro(TraitItemMacro { ref attrs, .. }) => attrs,
            other => {
                return Err(Error::new_spanned(
                    other,
                    "this kind of item doesn't have attrs",
                ))
            }
        };
        Ok(attrs)
    }

    fn attrs_mut(&mut self) -> Result<&mut Vec<Attribute>> {
        use syn::TraitItem::*;
        use syn::*;
        let attrs = match self {
            Const(TraitItemConst { ref mut attrs, .. }) => attrs,
            Method(TraitItemMethod { ref mut attrs, .. }) => attrs,
            Type(TraitItemType { ref mut attrs, .. }) => attrs,
            Macro(TraitItemMacro { ref mut attrs, .. }) => attrs,
            other => {
                return Err(Error::new_spanned(
                    other,
                    "this kind of item doesn't have attrs",
                ))
            }
        };
        Ok(attrs)
    }

    fn is_const(&self) -> bool {
        matches!(self, TraitItem::Const(_))
    }
    fn is_function_or_method(&self) -> bool {
        matches!(self, TraitItem::Method(_))
    }
    fn is_type(&self) -> bool {
        matches!(self, TraitItem::Type(_))
    }
    fn is_macro(&self) -> bool {
        matches!(self, TraitItem::Macro(_))
    }
}

pub trait ItemAttrExt: ItemLike {
    /// Takes a closure and calls it with separated attrs and item, as both mutable references.
    ///
    /// 1. Try to get attrs; Otherwise `Err`
    /// 2. Split `attrs` from `self` with [std::mem::replace]
    /// 3. Call the closure `f`
    /// 4. Merge `attrs` into `self`
    ///
    /// Note: During the closure call, `attrs` in `self` is always an empty.
    /// Always access `attrs` with given closure parameter.
    ///
    /// # Panics
    /// Panics if replaced `attrs` in `self` is not empty at merge step.
    fn try_split_attr_mut<F, R>(&mut self, f: F) -> Result<R>
    where
        F: FnOnce(&mut Vec<Attribute>, &mut Self) -> Result<R>,
    {
        let mut attrs = std::mem::replace(self.attrs_mut()?, Vec::new());
        let result = f(&mut attrs, self);
        let _temp = std::mem::replace(self.attrs_mut().unwrap(), attrs);
        assert!(
            _temp.is_empty(),
            "attrs changed during replacement. this behavior must be a bug."
        );
        result
    }
}

impl ItemAttrExt for Item {}
impl ItemAttrExt for ImplItem {}
impl ItemAttrExt for TraitItem {}

/// Extension for [syn::ItemMod]
pub trait ItemModExt {
    /// Returns reference of content items without braces unless a declaration
    fn items(&self) -> Option<&[Item]>;
    /// Returns reference of content items without braces unless a declaration
    fn items_mut(&mut self) -> Option<&mut Vec<Item>>;
}

impl ItemModExt for ItemMod {
    fn items(&self) -> Option<&[Item]> {
        if let Some((_, content)) = self.content.as_ref() {
            Some(content)
        } else {
            None
        }
    }
    fn items_mut(&mut self) -> Option<&mut Vec<Item>> {
        if let Some((_, content)) = self.content.as_mut() {
            Some(content)
        } else {
            None
        }
    }
}

impl GetIdent for Item {
    fn get_ident(&self) -> Option<&Ident> {
        use syn::Item::*;
        use syn::UseTree::*;
        use syn::*;
        let attrs = match self {
            Const(ItemConst { ref ident, .. }) => ident,
            Enum(ItemEnum { ref ident, .. }) => ident,
            ExternCrate(ItemExternCrate { ref ident, .. }) => ident,
            Fn(ItemFn { sig, .. }) => &sig.ident,
            Impl(ItemImpl { .. }) => unimplemented!(),
            Macro(ItemMacro { ref ident, .. }) => return ident.as_ref(),
            Macro2(ItemMacro2 { ref ident, .. }) => ident,
            Mod(ItemMod { ref ident, .. }) => ident,
            Static(ItemStatic { ref ident, .. }) => ident,
            Struct(ItemStruct { ref ident, .. }) => ident,
            Trait(ItemTrait { ref ident, .. }) => ident,
            TraitAlias(ItemTraitAlias { ref ident, .. }) => ident,
            Type(ItemType { ref ident, .. }) => ident,
            Union(ItemUnion { ref ident, .. }) => ident,
            Use(ItemUse { ref tree, .. }) => match tree {
                Name(UseName { ident }) => ident,
                _ => return None,
            },
            _ => return None,
        };
        Some(attrs)
    }
}

impl GetIdent for ImplItem {
    fn get_ident(&self) -> Option<&Ident> {
        use syn::ImplItem::*;
        use syn::*;
        let ident = match self {
            Const(ImplItemConst { ref ident, .. }) => ident,
            Method(ImplItemMethod { sig, .. }) => &sig.ident,
            Type(ImplItemType { ref ident, .. }) => ident,
            Macro(ImplItemMacro {
                mac: syn::Macro { path, .. },
                ..
            }) => return path.get_ident(),
            _ => return None,
        };
        Some(ident)
    }
}

impl GetIdent for TraitItem {
    fn get_ident(&self) -> Option<&Ident> {
        use syn::TraitItem::*;
        use syn::*;
        let ident = match self {
            Const(TraitItemConst { ref ident, .. }) => ident,
            Method(TraitItemMethod { sig, .. }) => &sig.ident,
            Type(TraitItemType { ref ident, .. }) => ident,
            Macro(TraitItemMacro {
                mac: syn::Macro { path, .. },
                ..
            }) => return path.get_ident(),
            _ => return None,
        };
        Some(ident)
    }
}

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

    #[test]
    fn test_attrs() {
        let mut item: Item = parse_quote!(
            #[test]
            type A = u32;
        );
        let expected: Attribute = parse_quote!(#[test]);
        {
            let attr = &item.attrs().unwrap()[0];
            assert_quote_eq!(attr, expected);
        }
        {
            let attr = &item.attrs_mut().unwrap()[0];
            assert_quote_eq!(attr, expected);
        }
    }

    #[test]
    fn test_items() {
        let module: ItemMod = parse_quote!(
            mod m {
                static x: usize = 0;
                fn f() {}
            }
        );
        let content = module.items().unwrap();
        assert!(matches!(content[0], Item::Static(_)));
        assert!(matches!(content[1], Item::Fn(_)));
    }

    #[test]
    fn test_items_decl() {
        let module: ItemMod = parse_quote!(
            mod m;
        );
        assert!(module.items().is_err());
    }
}