Skip to content

Commit 523e2fb

Browse files
committed
Make tuple structs work with placeholder
1 parent a8bc11f commit 523e2fb

File tree

2 files changed

+43
-15
lines changed

2 files changed

+43
-15
lines changed

partialdebug-derive/src/lib.rs

Lines changed: 31 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -65,34 +65,50 @@ pub fn derive_placeholder(input: TokenStream) -> TokenStream {
6565
let name = &input.ident;
6666
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
6767

68-
let fields = match &input.fields {
69-
Fields::Named(FieldsNamed { named, .. }) => named,
70-
Fields::Unnamed(_) => unimplemented!(),
71-
Fields::Unit => unimplemented!(),
68+
let no_fields = punctuated::Punctuated::new();
69+
70+
let (fields, constructor) = match &input.fields {
71+
Fields::Named(FieldsNamed { named, .. }) => (named, quote! {debug_struct}),
72+
Fields::Unnamed(FieldsUnnamed { unnamed, .. }) => (unnamed, quote! {debug_tuple}),
73+
Fields::Unit => (&no_fields, quote! {debug_tuple}),
7274
};
7375

74-
let as_debug_all_fields = fields.iter().map(|field| {
75-
let name = &field.ident;
76+
let as_debug_all_fields = fields.iter().enumerate().map(|(idx, field)| {
7677
let type_name = get_type_name(&field.ty);
7778

7879
// type name or given placeholder string
7980
let placeholder_string = placeholder.as_ref().unwrap_or(&type_name);
8081

81-
quote! {
82-
.field(
83-
stringify!(#name),
84-
match ::partialdebug::AsDebug::as_debug(&self.#name){
85-
None => &::partialdebug::Placeholder(#placeholder_string),
86-
Some(__field) => __field,
87-
},
88-
)
82+
match &field.ident {
83+
None => {
84+
let idx = Index::from(idx);
85+
quote! {
86+
.field(
87+
match ::partialdebug::AsDebug::as_debug(&self.#idx){
88+
None => &::partialdebug::Placeholder(#placeholder_string),
89+
Some(__field) => __field,
90+
},
91+
)
92+
}
93+
}
94+
Some(name) => {
95+
quote! {
96+
.field(
97+
stringify!(#name),
98+
match ::partialdebug::AsDebug::as_debug(&self.#name){
99+
None => &::partialdebug::Placeholder(#placeholder_string),
100+
Some(__field) => __field,
101+
},
102+
)
103+
}
104+
}
89105
}
90106
});
91107

92108
let expanded = quote! {
93109
impl #impl_generics ::core::fmt::Debug for #name #ty_generics #where_clause{
94110
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
95-
f.debug_struct(stringify!(#name))
111+
f.#constructor(stringify!(#name))
96112

97113
#(#as_debug_all_fields)*
98114

tests/placeholder.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
use partialdebug::placeholder::PartialDebug;
2+
3+
#[derive(PartialDebug)]
4+
struct UnitStruct;
5+
6+
#[derive(PartialDebug)]
7+
struct TupleStruct(&'static str);
8+
9+
#[derive(PartialDebug)]
10+
struct NormalStruct {
11+
field: &'static str,
12+
}

0 commit comments

Comments
 (0)