1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
|
//! Implementation of a [`fmt::Debug`] derive macro.
//!
//! [`fmt::Debug`]: std::fmt::Debug
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::{
parse::{Error, Parse, ParseStream, Result},
parse_quote,
spanned::Spanned as _,
Ident,
};
use super::{BoundsAttribute, FmtAttribute};
/// Expands a [`fmt::Debug`] derive macro.
///
/// [`fmt::Debug`]: std::fmt::Debug
pub fn expand(input: &syn::DeriveInput, _: &str) -> Result<TokenStream> {
let attrs = ContainerAttributes::parse_attrs(&input.attrs)?;
let ident = &input.ident;
let (bounds, body) = match &input.data {
syn::Data::Struct(s) => expand_struct(attrs, ident, s),
syn::Data::Enum(e) => expand_enum(attrs, e),
syn::Data::Union(_) => {
return Err(Error::new(
input.span(),
"`Debug` cannot be derived for unions",
));
}
}?;
let (impl_gens, ty_gens, where_clause) = {
let (impl_gens, ty_gens, where_clause) = input.generics.split_for_impl();
let mut where_clause = where_clause
.cloned()
.unwrap_or_else(|| parse_quote! { where });
where_clause.predicates.extend(bounds);
(impl_gens, ty_gens, where_clause)
};
Ok(quote! {
#[automatically_derived]
impl #impl_gens ::core::fmt::Debug for #ident #ty_gens
#where_clause
{
fn fmt(
&self, __derive_more_f: &mut ::core::fmt::Formatter<'_>
) -> ::core::fmt::Result {
#body
}
}
})
}
/// Expands a [`fmt::Debug`] derive macro for the provided struct.
///
/// [`fmt::Debug`]: std::fmt::Debug
fn expand_struct(
attrs: ContainerAttributes,
ident: &Ident,
s: &syn::DataStruct,
) -> Result<(Vec<syn::WherePredicate>, TokenStream)> {
let s = Expansion {
attr: &attrs,
fields: &s.fields,
ident,
};
let bounds = s.generate_bounds()?;
let body = s.generate_body()?;
let vars = s.fields.iter().enumerate().map(|(i, f)| {
let var = f.ident.clone().unwrap_or_else(|| format_ident!("_{i}"));
let member = f
.ident
.clone()
.map_or_else(|| syn::Member::Unnamed(i.into()), syn::Member::Named);
quote! { let #var = &self.#member; }
});
let body = quote! {
#( #vars )*
#body
};
Ok((bounds, body))
}
/// Expands a [`fmt::Debug`] derive macro for the provided enum.
///
/// [`fmt::Debug`]: std::fmt::Debug
fn expand_enum(
attrs: ContainerAttributes,
e: &syn::DataEnum,
) -> Result<(Vec<syn::WherePredicate>, TokenStream)> {
let (bounds, match_arms) = e.variants.iter().try_fold(
(Vec::new(), TokenStream::new()),
|(mut bounds, mut arms), variant| {
let ident = &variant.ident;
let v = Expansion {
attr: &attrs,
fields: &variant.fields,
ident,
};
let arm_body = v.generate_body()?;
bounds.extend(v.generate_bounds()?);
let fields_idents =
variant.fields.iter().enumerate().map(|(i, f)| {
f.ident.clone().unwrap_or_else(|| format_ident!("_{i}"))
});
let matcher = match variant.fields {
syn::Fields::Named(_) => {
quote! { Self::#ident { #( #fields_idents ),* } }
}
syn::Fields::Unnamed(_) => {
quote! { Self::#ident ( #( #fields_idents ),* ) }
}
syn::Fields::Unit => quote! { Self::#ident },
};
arms.extend([quote! { #matcher => { #arm_body }, }]);
Ok::<_, Error>((bounds, arms))
},
)?;
let body = match_arms
.is_empty()
.then(|| quote! { match *self {} })
.unwrap_or_else(|| quote! { match self { #match_arms } });
Ok((bounds, body))
}
/// Representation of a [`fmt::Debug`] derive macro container attribute.
///
/// ```rust,ignore
/// #[debug(bound(<bounds>))]
/// ```
///
/// [`fmt::Debug`]: std::fmt::Debug
#[derive(Debug, Default)]
struct ContainerAttributes {
/// Additional trait bounds.
bounds: BoundsAttribute,
}
impl ContainerAttributes {
/// Parses [`ContainerAttributes`] from the provided [`syn::Attribute`]s.
fn parse_attrs(attrs: impl AsRef<[syn::Attribute]>) -> Result<Self> {
attrs
.as_ref()
.iter()
.filter(|attr| attr.path().is_ident("debug"))
.try_fold(ContainerAttributes::default(), |mut attrs, attr| {
let attr = attr.parse_args::<ContainerAttributes>()?;
attrs.bounds.0.extend(attr.bounds.0);
Ok(attrs)
})
}
}
impl Parse for ContainerAttributes {
fn parse(input: ParseStream) -> Result<Self> {
BoundsAttribute::check_legacy_fmt(input)?;
input.parse().map(|bounds| ContainerAttributes { bounds })
}
}
/// Representation of a [`fmt::Debug`] derive macro field attribute.
///
/// ```rust,ignore
/// #[debug("<fmt_literal>", <fmt_args>)]
/// #[debug(skip)]
/// ```
///
/// [`fmt::Debug`]: std::fmt::Debug
enum FieldAttribute {
/// [`fmt`] attribute.
///
/// [`fmt`]: std::fmt
Fmt(FmtAttribute),
/// Attribute for skipping field.
Skip,
}
impl FieldAttribute {
/// Parses [`ContainerAttributes`] from the provided [`syn::Attribute`]s.
fn parse_attrs(attrs: impl AsRef<[syn::Attribute]>) -> Result<Option<Self>> {
Ok(attrs
.as_ref()
.iter()
.filter(|attr| attr.path().is_ident("debug"))
.try_fold(None, |mut attrs, attr| {
let field_attr = attr.parse_args::<FieldAttribute>()?;
if let Some((path, _)) = attrs.replace((attr.path(), field_attr)) {
Err(Error::new(
path.span(),
"only single `#[debug(...)]` attribute is allowed here",
))
} else {
Ok(attrs)
}
})?
.map(|(_, attr)| attr))
}
}
impl Parse for FieldAttribute {
fn parse(input: ParseStream) -> Result<Self> {
FmtAttribute::check_legacy_fmt(input)?;
if input.peek(syn::LitStr) {
input.parse().map(Self::Fmt)
} else {
let _ = input.parse::<syn::Path>().and_then(|p| {
if ["skip", "ignore"].into_iter().any(|i| p.is_ident(i)) {
Ok(p)
} else {
Err(Error::new(
p.span(),
"unknown attribute, expected `skip` or `ignore`",
))
}
})?;
Ok(Self::Skip)
}
}
}
/// Helper struct to generate [`Debug::fmt()`] implementation body and trait
/// bounds for a struct or an enum variant.
///
/// [`Debug::fmt()`]: std::fmt::Debug::fmt()
#[derive(Debug)]
struct Expansion<'a> {
attr: &'a ContainerAttributes,
/// Struct or enum [`Ident`](struct@Ident).
ident: &'a Ident,
/// Struct or enum [`syn::Fields`].
fields: &'a syn::Fields,
}
impl<'a> Expansion<'a> {
/// Generates [`Debug::fmt()`] implementation for a struct or an enum variant.
///
/// [`Debug::fmt()`]: std::fmt::Debug::fmt()
fn generate_body(&self) -> Result<TokenStream> {
match self.fields {
syn::Fields::Unit => {
let ident = self.ident.to_string();
Ok(quote! {
::core::fmt::Formatter::write_str(
__derive_more_f,
#ident,
)
})
}
syn::Fields::Unnamed(unnamed) => {
let mut exhaustive = true;
let ident_str = self.ident.to_string();
let out = quote! {
&mut ::derive_more::__private::debug_tuple(
__derive_more_f,
#ident_str,
)
};
let out = unnamed.unnamed.iter().enumerate().try_fold(
out,
|out, (i, field)| match FieldAttribute::parse_attrs(&field.attrs)? {
Some(FieldAttribute::Skip) => {
exhaustive = false;
Ok::<_, Error>(out)
}
Some(FieldAttribute::Fmt(fmt)) => Ok(quote! {
::derive_more::__private::DebugTuple::field(
#out,
&::core::format_args!(#fmt),
)
}),
None => {
let ident = format_ident!("_{i}");
Ok(quote! {
::derive_more::__private::DebugTuple::field(#out, #ident)
})
}
},
)?;
Ok(if exhaustive {
quote! { ::derive_more::__private::DebugTuple::finish(#out) }
} else {
quote! { ::derive_more::__private::DebugTuple::finish_non_exhaustive(#out) }
})
}
syn::Fields::Named(named) => {
let mut exhaustive = true;
let ident = self.ident.to_string();
let out = quote! {
&mut ::core::fmt::Formatter::debug_struct(
__derive_more_f,
#ident,
)
};
let out = named.named.iter().try_fold(out, |out, field| {
let field_ident = field.ident.as_ref().unwrap_or_else(|| {
unreachable!("`syn::Fields::Named`");
});
let field_str = field_ident.to_string();
match FieldAttribute::parse_attrs(&field.attrs)? {
Some(FieldAttribute::Skip) => {
exhaustive = false;
Ok::<_, Error>(out)
}
Some(FieldAttribute::Fmt(fmt)) => Ok(quote! {
::core::fmt::DebugStruct::field(
#out,
#field_str,
&::core::format_args!(#fmt),
)
}),
None => Ok(quote! {
::core::fmt::DebugStruct::field(#out, #field_str, #field_ident)
}),
}
})?;
Ok(if exhaustive {
quote! { ::core::fmt::DebugStruct::finish(#out) }
} else {
quote! { ::core::fmt::DebugStruct::finish_non_exhaustive(#out) }
})
}
}
}
/// Generates trait bounds for a struct or an enum variant.
fn generate_bounds(&self) -> Result<Vec<syn::WherePredicate>> {
self.fields.iter().try_fold(
self.attr.bounds.0.clone().into_iter().collect::<Vec<_>>(),
|mut out, field| {
let fmt_attr =
FieldAttribute::parse_attrs(&field.attrs)?.and_then(|attr| {
match attr {
FieldAttribute::Fmt(fmt) => Some(fmt),
FieldAttribute::Skip => None,
}
});
let ty = &field.ty;
if let Some(attr) = fmt_attr {
out.extend(attr.bounded_types(self.fields).map(
|(ty, trait_name)| {
let trait_name = format_ident!("{trait_name}");
parse_quote! { #ty: ::core::fmt::#trait_name }
},
));
} else {
out.extend([parse_quote! { #ty: ::core::fmt::Debug }]);
}
Ok(out)
},
)
}
}
|