syn icon indicating copy to clipboard operation
syn copied to clipboard

Add attrs() and attrs_mut() getters to syn::Item

Open Robbepop opened this issue 5 years ago • 1 comments

While developing certain proc macros using syn I found getters that return the attribute slice for a generic syn::Item to be missing. The implementation is straight forward and simple, however, daunting:

Example through some extension trait

impl Attrs for syn::Item {
    fn attrs(&self) -> &[syn::Attribute] {
        use syn::Item;
        match self {
            Item::Const(syn::ItemConst { attrs, .. })
            | Item::Enum(syn::ItemEnum { attrs, .. })
            | Item::ExternCrate(syn::ItemExternCrate { attrs, .. })
            | Item::Fn(syn::ItemFn { attrs, .. })
            | Item::ForeignMod(syn::ItemForeignMod { attrs, .. })
            | Item::Impl(syn::ItemImpl { attrs, .. })
            | Item::Macro(syn::ItemMacro { attrs, .. })
            | Item::Macro2(syn::ItemMacro2 { attrs, .. })
            | Item::Mod(syn::ItemMod { attrs, .. })
            | Item::Static(syn::ItemStatic { attrs, .. })
            | Item::Struct(syn::ItemStruct { attrs, .. })
            | Item::Trait(syn::ItemTrait { attrs, .. })
            | Item::TraitAlias(syn::ItemTraitAlias { attrs, .. })
            | Item::Type(syn::ItemType { attrs, .. })
            | Item::Union(syn::ItemUnion { attrs, .. })
            | Item::Use(syn::ItemUse { attrs, .. }) => attrs,
            _ => &[],
        }
    }
}

Note that a getter for this would also have the benefit of such dependent crates to not care if syn ever adds new variants. If syn provided this dependencies could simply make use of syn handling the update.

Would you accept a PR that adds these getters? If so I'd be happy to file a PR.

Robbepop avatar Jul 01 '20 15:07 Robbepop

Seems reasonable. Please send a PR.

dtolnay avatar Jul 23 '20 18:07 dtolnay