Skip to content

Commit 8a863f3

Browse files
authored
Copy conditional compilation flags onto created constructors (#13)
(Closes #12)
1 parent 6c014e4 commit 8a863f3

2 files changed

Lines changed: 28 additions & 0 deletions

File tree

src/expand.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@ pub(crate) fn expand_struct(mut item: ItemStruct) -> proc_macro::TokenStream {
1414

1515
let default: TokenStream = attr.parse_args().unwrap();
1616

17+
// copy all the same #[cfg] conditional compilations flags for the field onto our built "constructor"
18+
// otherwise, it's possible to create a constructor for a type that may be filtered by the same #[cfg]'s, breaking compilation
19+
let cfg_attrs = field.attrs.iter().filter(|a| a.path().is_ident("cfg"));
20+
1721
let fn_name_lit = format!("__serde_inline_default_{}_{}", item.ident, i);
1822
let fn_name_ident = Ident::new(&fn_name_lit, Span::call_site());
1923
let mut return_type = field.ty.clone();
@@ -24,6 +28,7 @@ pub(crate) fn expand_struct(mut item: ItemStruct) -> proc_macro::TokenStream {
2428
inline_fns.push(quote! {
2529
#[doc(hidden)]
2630
#[allow(non_snake_case)]
31+
#( #cfg_attrs )*
2732
fn #fn_name_ident () -> #return_type {
2833
#default
2934
}

tests/test_serde_inline_default.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,26 @@ fn test_lifetime() {
4343

4444
assert_eq!(lifetime_test.test_str, "test");
4545
}
46+
47+
#[test]
48+
#[allow(dead_code)]
49+
fn test_conditional_compilation() {
50+
#[cfg(debug_assertions)]
51+
#[derive(Deserialize)]
52+
struct TypeA(u8);
53+
54+
#[cfg(not(debug_assertions))]
55+
#[derive(Deserialize)]
56+
struct TypeB(u8);
57+
58+
#[serde_inline_default]
59+
#[derive(Deserialize)]
60+
struct Test {
61+
#[cfg(debug_assertions)]
62+
#[serde_inline_default(TypeA(1))]
63+
val_a: TypeA,
64+
#[cfg(not(debug_assertions))]
65+
#[serde_inline_default(TypeB(1))]
66+
val_b: TypeB,
67+
}
68+
}

0 commit comments

Comments
 (0)