Skip to content

Commit 8099fb9

Browse files
committed
Let #[autoimpl(Default)] support #[cfg] on fields
1 parent 6851bcb commit 8099fb9

2 files changed

Lines changed: 25 additions & 12 deletions

File tree

lib/src/autoimpl/impl_misc.rs

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -302,25 +302,37 @@ impl ImplTrait for ImplDefault {
302302

303303
fn struct_items(&self, item: &ItemStruct, _: &ImplArgs) -> Result<(Toks, Toks)> {
304304
let type_ident = &item.ident;
305-
let mut inner;
306-
match &item.fields {
305+
let inner = match &item.fields {
307306
Fields::Named(fields) => {
308-
inner = quote! {};
307+
let mut toks = Toks::new();
309308
for field in fields.named.iter() {
309+
for attr in &field.attrs {
310+
if attr.path().get_ident().is_some_and(|path| path == "cfg") {
311+
attr.to_tokens(&mut toks);
312+
}
313+
}
314+
310315
let ident = field.ident.as_ref().unwrap();
311-
inner.append_all(quote! { #ident: Default::default(), });
316+
toks.append_all(quote! { #ident: Default::default(), });
312317
}
313-
inner = quote! { #type_ident { #inner } };
318+
quote! { #type_ident { #toks } }
314319
}
315320
Fields::Unnamed(fields) => {
316-
inner = quote! {};
317-
for _ in 0..fields.unnamed.len() {
318-
inner.append_all(quote! { Default::default(), });
321+
let mut toks = Toks::new();
322+
for field in fields.unnamed.iter() {
323+
for attr in &field.attrs {
324+
if attr.path().get_ident().is_some_and(|path| path == "cfg") {
325+
attr.to_tokens(&mut toks);
326+
}
327+
}
328+
329+
toks.append_all(quote! { Default::default(), });
319330
}
320-
inner = quote! { #type_ident(#inner) };
331+
quote! { #type_ident(#toks) }
321332
}
322-
Fields::Unit => inner = quote! { #type_ident },
323-
}
333+
Fields::Unit => quote! { #type_ident },
334+
};
335+
324336
let method = quote! {
325337
fn default() -> Self {
326338
#inner

tests/test-cfg/tests/autoimpl.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
use impl_tools::autoimpl;
66

7-
#[autoimpl(Clone, Debug where T: trait)]
7+
#[autoimpl(Clone, Debug, Default where T: trait)]
88
#[derive(PartialEq, Eq)]
99
struct S<T> {
1010
a: T,
@@ -31,6 +31,7 @@ impl<T> S<T> {
3131
fn test_clone_S() {
3232
let a = S::new(());
3333
assert_eq!(a.clone(), a);
34+
assert!(a != S::default());
3435
}
3536

3637
#[test]

0 commit comments

Comments
 (0)