Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Item::attrs to get the attributes of an item if available #1281

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,32 @@ impl Item {
_ => unreachable!(),
}
}

#[cfg(feature = "parsing")]
pub fn attrs(&self) -> Option<&Vec<Attribute>> {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have a similar implementation of this in a crate here: parse_attributes.rs#L336

I was able to have it simply return &[Attribute], and for Item::Verbatim it just returns &[]. Not sure if that is better or not.

match self {
Item::ExternCrate(ItemExternCrate { attrs, .. })
| Item::Use(ItemUse { attrs, .. })
| Item::Static(ItemStatic { attrs, .. })
| Item::Const(ItemConst { attrs, .. })
| Item::Fn(ItemFn { attrs, .. })
| Item::Mod(ItemMod { attrs, .. })
| Item::ForeignMod(ItemForeignMod { attrs, .. })
| Item::Type(ItemType { attrs, .. })
| Item::Struct(ItemStruct { attrs, .. })
| Item::Enum(ItemEnum { attrs, .. })
| Item::Union(ItemUnion { attrs, .. })
| Item::Trait(ItemTrait { attrs, .. })
| Item::TraitAlias(ItemTraitAlias { attrs, .. })
| Item::Impl(ItemImpl { attrs, .. })
| Item::Macro(ItemMacro { attrs, .. })
| Item::Macro2(ItemMacro2 { attrs, .. }) => Some(attrs),
Item::Verbatim(_) => None,

#[cfg(syn_no_non_exhaustive)]
_ => unreachable!(),
}
}
}

impl From<DeriveInput> for Item {
Expand Down