From 8a863f3b320fcdc77e9ea94d825319770c77f68c Mon Sep 17 00:00:00 2001 From: nullstalgia Date: Tue, 2 Sep 2025 04:43:29 -0700 Subject: [PATCH] Copy conditional compilation flags onto created constructors (#13) (Closes #12) --- src/expand.rs | 5 +++++ tests/test_serde_inline_default.rs | 23 +++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/expand.rs b/src/expand.rs index 6aec480..496dc8b 100644 --- a/src/expand.rs +++ b/src/expand.rs @@ -14,6 +14,10 @@ pub(crate) fn expand_struct(mut item: ItemStruct) -> proc_macro::TokenStream { let default: TokenStream = attr.parse_args().unwrap(); + // copy all the same #[cfg] conditional compilations flags for the field onto our built "constructor" + // otherwise, it's possible to create a constructor for a type that may be filtered by the same #[cfg]'s, breaking compilation + let cfg_attrs = field.attrs.iter().filter(|a| a.path().is_ident("cfg")); + let fn_name_lit = format!("__serde_inline_default_{}_{}", item.ident, i); let fn_name_ident = Ident::new(&fn_name_lit, Span::call_site()); let mut return_type = field.ty.clone(); @@ -24,6 +28,7 @@ pub(crate) fn expand_struct(mut item: ItemStruct) -> proc_macro::TokenStream { inline_fns.push(quote! { #[doc(hidden)] #[allow(non_snake_case)] + #( #cfg_attrs )* fn #fn_name_ident () -> #return_type { #default } diff --git a/tests/test_serde_inline_default.rs b/tests/test_serde_inline_default.rs index cc07fc2..ed5208f 100644 --- a/tests/test_serde_inline_default.rs +++ b/tests/test_serde_inline_default.rs @@ -43,3 +43,26 @@ fn test_lifetime() { assert_eq!(lifetime_test.test_str, "test"); } + +#[test] +#[allow(dead_code)] +fn test_conditional_compilation() { + #[cfg(debug_assertions)] + #[derive(Deserialize)] + struct TypeA(u8); + + #[cfg(not(debug_assertions))] + #[derive(Deserialize)] + struct TypeB(u8); + + #[serde_inline_default] + #[derive(Deserialize)] + struct Test { + #[cfg(debug_assertions)] + #[serde_inline_default(TypeA(1))] + val_a: TypeA, + #[cfg(not(debug_assertions))] + #[serde_inline_default(TypeB(1))] + val_b: TypeB, + } +}