Skip to content

Commit

Permalink
Merge pull request #19 from aldanor/feature/propagate-attrs
Browse files Browse the repository at this point in the history
Propagate lint attributes from the parent item to the constructors
  • Loading branch information
nrc authored Mar 14, 2017
2 parents a1823d0 + f389b8e commit 6cfdc3c
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,16 +81,46 @@ fn new_impl(ast: &syn::MacroInput, fields: Option<&[syn::Field]>,
format!("Constructs a new `{}::{}`.", name, variant),
),
};
let lint_attrs = collect_parent_lint_attrs(&ast.attrs);
let lint_attrs = quote![#(#lint_attrs),*];
quote! {
impl #impl_generics #name #ty_generics #where_clause {
#[doc = #doc]
#lint_attrs
pub fn #new(#(#args),*) -> Self {
#name #qual #inits
}
}
}
}

fn collect_parent_lint_attrs(attrs: &[syn::Attribute]) -> Vec<syn::Attribute> {
fn is_lint(item: &syn::MetaItem) -> bool {
if let syn::MetaItem::List(ref ident, _) = *item {
match ident.as_ref() {
"allow" | "deny" | "forbid" | "warn" => return true,
_ => (),
}
}
false
}

fn is_cfg_attr_lint(item: &syn::MetaItem) -> bool {
if let syn::MetaItem::List(ref ident, ref items) = *item {
if ident.as_ref() == "cfg_attr" && items.len() == 2 {
if let syn::NestedMetaItem::MetaItem(ref item) = items[1] {
return is_lint(item);
}
}
}
false
}

attrs.iter().filter(|attr| {
is_lint(&attr.value) || is_cfg_attr_lint(&attr.value)
}).cloned().collect()
}

enum FieldAttr {
Default,
Value(syn::Expr),
Expand Down
10 changes: 10 additions & 0 deletions tests/test.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![deny(non_snake_case)]

#[macro_use]
extern crate derive_new;

Expand Down Expand Up @@ -275,3 +277,11 @@ fn test_more_involved_enum() {
let x = Enterprise::<u8>::new_spock(42);
assert_eq!(x, Enterprise::Spock { x: PhantomData, y: 42 });
}

#[allow(non_snake_case)]
#[derive(new, PartialEq, Debug)]
pub struct Upside { X: i32 }

#[cfg_attr(test, allow(non_snake_case))]
#[derive(new, PartialEq, Debug)]
pub struct Down { X: i32 }

0 comments on commit 6cfdc3c

Please sign in to comment.