| 1 |
//! Implementation of a [`fmt::Debug`] derive macro. |
| 2 |
//! |
| 3 |
//! [`fmt::Debug`]: std::fmt::Debug |
| 4 |
|
| 5 |
use proc_macro2::TokenStream; |
| 6 |
use quote::{format_ident, quote}; |
| 7 |
use syn::{ext::IdentExt as _, parse_quote, spanned::Spanned as _}; |
| 8 |
|
| 9 |
use crate::utils::{ |
| 10 |
attr::{self, ParseMultiple as _}, |
| 11 |
Either, Spanning, |
| 12 |
}; |
| 13 |
|
| 14 |
use super::{ |
| 15 |
trait_name_to_attribute_name, ContainerAttributes, ContainsGenericsExt as _, |
| 16 |
FmtAttribute, |
| 17 |
}; |
| 18 |
|
| 19 |
/// Expands a [`fmt::Debug`] derive macro. |
| 20 |
/// |
| 21 |
/// [`fmt::Debug`]: std::fmt::Debug |
| 22 |
pub fn expand(input: &syn::DeriveInput, _: &str) -> syn::Result<TokenStream> { |
| 23 |
let attr_name = format_ident!("{}", trait_name_to_attribute_name("Debug")); |
| 24 |
|
| 25 |
let attrs = ContainerAttributes::parse_attrs(&input.attrs, &attr_name)? |
| 26 |
.map(Spanning::into_inner) |
| 27 |
.unwrap_or_default(); |
| 28 |
let ident = &input.ident; |
| 29 |
|
| 30 |
let type_params = input |
| 31 |
.generics |
| 32 |
.params |
| 33 |
.iter() |
| 34 |
.filter_map(|p| match p { |
| 35 |
syn::GenericParam::Type(t) => Some(&t.ident), |
| 36 |
syn::GenericParam::Const(..) | syn::GenericParam::Lifetime(..) => None, |
| 37 |
}) |
| 38 |
.collect::<Vec<_>>(); |
| 39 |
|
| 40 |
let (bounds, body) = match &input.data { |
| 41 |
syn::Data::Struct(s) => { |
| 42 |
expand_struct(attrs, ident, s, &type_params, &attr_name) |
| 43 |
} |
| 44 |
syn::Data::Enum(e) => expand_enum(attrs, e, &type_params, &attr_name), |
| 45 |
syn::Data::Union(_) => { |
| 46 |
return Err(syn::Error::new( |
| 47 |
input.span(), |
| 48 |
"`Debug` cannot be derived for unions", |
| 49 |
)); |
| 50 |
} |
| 51 |
}?; |
| 52 |
|
| 53 |
let (impl_gens, ty_gens, where_clause) = { |
| 54 |
let (impl_gens, ty_gens, where_clause) = input.generics.split_for_impl(); |
| 55 |
let mut where_clause = where_clause |
| 56 |
.cloned() |
| 57 |
.unwrap_or_else(|| parse_quote! { where }); |
| 58 |
where_clause.predicates.extend(bounds); |
| 59 |
(impl_gens, ty_gens, where_clause) |
| 60 |
}; |
| 61 |
|
| 62 |
Ok(quote! { |
| 63 |
#[allow(deprecated)] // omit warnings on deprecated fields/variants |
| 64 |
#[allow(unreachable_code)] // omit warnings for `!` and other unreachable types |
| 65 |
#[automatically_derived] |
| 66 |
impl #impl_gens derive_more::core::fmt::Debug for #ident #ty_gens #where_clause { |
| 67 |
#[inline] |
| 68 |
fn fmt( |
| 69 |
&self, __derive_more_f: &mut derive_more::core::fmt::Formatter<'_> |
| 70 |
) -> derive_more::core::fmt::Result { |
| 71 |
#body |
| 72 |
} |
| 73 |
} |
| 74 |
}) |
| 75 |
} |
| 76 |
|
| 77 |
/// Expands a [`fmt::Debug`] derive macro for the provided struct. |
| 78 |
/// |
| 79 |
/// [`fmt::Debug`]: std::fmt::Debug |
| 80 |
fn expand_struct( |
| 81 |
attrs: ContainerAttributes, |
| 82 |
ident: &syn::Ident, |
| 83 |
s: &syn::DataStruct, |
| 84 |
type_params: &[&syn::Ident], |
| 85 |
attr_name: &syn::Ident, |
| 86 |
) -> syn::Result<(Vec<syn::WherePredicate>, TokenStream)> { |
| 87 |
let s = Expansion { |
| 88 |
attr: &attrs, |
| 89 |
fields: &s.fields, |
| 90 |
type_params, |
| 91 |
ident, |
| 92 |
attr_name, |
| 93 |
}; |
| 94 |
s.validate_attrs()?; |
| 95 |
let bounds = s.generate_bounds()?; |
| 96 |
let body = s.generate_body()?; |
| 97 |
|
| 98 |
let vars = s.fields.iter().enumerate().map(|(i, f)| { |
| 99 |
let var = f.ident.clone().unwrap_or_else(|| format_ident!("_{i}")); |
| 100 |
let member = f |
| 101 |
.ident |
| 102 |
.clone() |
| 103 |
.map_or_else(|| syn::Member::Unnamed(i.into()), syn::Member::Named); |
| 104 |
quote! { let #var = &self.#member; } |
| 105 |
}); |
| 106 |
|
| 107 |
let body = quote! { |
| 108 |
#( #vars )* |
| 109 |
#body |
| 110 |
}; |
| 111 |
|
| 112 |
Ok((bounds, body)) |
| 113 |
} |
| 114 |
|
| 115 |
/// Expands a [`fmt::Debug`] derive macro for the provided enum. |
| 116 |
/// |
| 117 |
/// [`fmt::Debug`]: std::fmt::Debug |
| 118 |
fn expand_enum( |
| 119 |
mut attrs: ContainerAttributes, |
| 120 |
e: &syn::DataEnum, |
| 121 |
type_params: &[&syn::Ident], |
| 122 |
attr_name: &syn::Ident, |
| 123 |
) -> syn::Result<(Vec<syn::WherePredicate>, TokenStream)> { |
| 124 |
if let Some(enum_fmt) = attrs.fmt.as_ref() { |
| 125 |
return Err(syn::Error::new_spanned( |
| 126 |
enum_fmt, |
| 127 |
format!( |
| 128 |
"`#[{attr_name}(\"...\", ...)]` attribute is not allowed on enum, place it on its \ |
| 129 |
variants instead", |
| 130 |
), |
| 131 |
)); |
| 132 |
} |
| 133 |
|
| 134 |
let (bounds, match_arms) = e.variants.iter().try_fold( |
| 135 |
(Vec::new(), TokenStream::new()), |
| 136 |
|(mut bounds, mut arms), variant| { |
| 137 |
let ident = &variant.ident; |
| 138 |
|
| 139 |
attrs.fmt = variant |
| 140 |
.attrs |
| 141 |
.iter() |
| 142 |
.filter(|attr| attr.path().is_ident("debug")) |
| 143 |
.try_fold(None, |mut attrs, attr| { |
| 144 |
let attr = attr.parse_args::<FmtAttribute>()?; |
| 145 |
attrs.replace(attr).map_or(Ok(()), |dup| { |
| 146 |
Err(syn::Error::new( |
| 147 |
dup.span(), |
| 148 |
format!( |
| 149 |
"multiple `#[{attr_name}(\"...\", ...)]` attributes aren't allowed", |
| 150 |
), |
| 151 |
)) |
| 152 |
})?; |
| 153 |
Ok::<_, syn::Error>(attrs) |
| 154 |
})?; |
| 155 |
|
| 156 |
let v = Expansion { |
| 157 |
attr: &attrs, |
| 158 |
fields: &variant.fields, |
| 159 |
type_params, |
| 160 |
ident, |
| 161 |
attr_name, |
| 162 |
}; |
| 163 |
v.validate_attrs()?; |
| 164 |
let arm_body = v.generate_body()?; |
| 165 |
bounds.extend(v.generate_bounds()?); |
| 166 |
|
| 167 |
let fields_idents = |
| 168 |
variant.fields.iter().enumerate().map(|(i, f)| { |
| 169 |
f.ident.clone().unwrap_or_else(|| format_ident!("_{i}")) |
| 170 |
}); |
| 171 |
let matcher = match variant.fields { |
| 172 |
syn::Fields::Named(_) => { |
| 173 |
quote! { Self::#ident { #( #fields_idents ),* } } |
| 174 |
} |
| 175 |
syn::Fields::Unnamed(_) => { |
| 176 |
quote! { Self::#ident ( #( #fields_idents ),* ) } |
| 177 |
} |
| 178 |
syn::Fields::Unit => quote! { Self::#ident }, |
| 179 |
}; |
| 180 |
|
| 181 |
arms.extend([quote! { #matcher => { #arm_body }, }]); |
| 182 |
|
| 183 |
Ok::<_, syn::Error>((bounds, arms)) |
| 184 |
}, |
| 185 |
)?; |
| 186 |
|
| 187 |
let body = if match_arms.is_empty() { |
| 188 |
quote! { match *self {} } |
| 189 |
} else { |
| 190 |
quote! { match self { #match_arms } } |
| 191 |
}; |
| 192 |
|
| 193 |
Ok((bounds, body)) |
| 194 |
} |
| 195 |
|
| 196 |
/// Representation of a [`fmt::Debug`] derive macro field attribute. |
| 197 |
/// |
| 198 |
/// ```rust,ignore |
| 199 |
/// #[debug(skip)] |
| 200 |
/// #[debug("<fmt-literal>", <fmt-args>)] |
| 201 |
/// ``` |
| 202 |
/// |
| 203 |
/// [`fmt::Debug`]: std::fmt::Debug |
| 204 |
type FieldAttribute = Either<attr::Skip, FmtAttribute>; |
| 205 |
|
| 206 |
/// Helper struct to generate [`Debug::fmt()`] implementation body and trait |
| 207 |
/// bounds for a struct or an enum variant. |
| 208 |
/// |
| 209 |
/// [`Debug::fmt()`]: std::fmt::Debug::fmt() |
| 210 |
#[derive(Debug)] |
| 211 |
struct Expansion<'a> { |
| 212 |
attr: &'a ContainerAttributes, |
| 213 |
|
| 214 |
/// Struct or enum [`Ident`](struct@syn::Ident). |
| 215 |
ident: &'a syn::Ident, |
| 216 |
|
| 217 |
/// Struct or enum [`syn::Fields`]. |
| 218 |
fields: &'a syn::Fields, |
| 219 |
|
| 220 |
/// Type parameters in this struct or enum. |
| 221 |
type_params: &'a [&'a syn::Ident], |
| 222 |
|
| 223 |
/// Name of the attributes, considered by this macro. |
| 224 |
attr_name: &'a syn::Ident, |
| 225 |
} |
| 226 |
|
| 227 |
impl Expansion<'_> { |
| 228 |
/// Validates attributes of this [`Expansion`] to be consistent. |
| 229 |
fn validate_attrs(&self) -> syn::Result<()> { |
| 230 |
if self.attr.fmt.is_some() { |
| 231 |
for field_attr in self |
| 232 |
.fields |
| 233 |
.iter() |
| 234 |
.map(|f| FieldAttribute::parse_attrs(&f.attrs, self.attr_name)) |
| 235 |
{ |
| 236 |
if let Some(FieldAttribute::Right(fmt_attr)) = |
| 237 |
field_attr?.map(Spanning::into_inner) |
| 238 |
{ |
| 239 |
return Err(syn::Error::new_spanned( |
| 240 |
fmt_attr, |
| 241 |
"`#[debug(...)]` attributes are not allowed on fields when \ |
| 242 |
`#[debug(\"...\", ...)]` is specified on struct or variant", |
| 243 |
)); |
| 244 |
} |
| 245 |
} |
| 246 |
} |
| 247 |
Ok(()) |
| 248 |
} |
| 249 |
|
| 250 |
/// Generates [`Debug::fmt()`] implementation for a struct or an enum variant. |
| 251 |
/// |
| 252 |
/// [`Debug::fmt()`]: std::fmt::Debug::fmt() |
| 253 |
fn generate_body(&self) -> syn::Result<TokenStream> { |
| 254 |
if let Some(fmt) = &self.attr.fmt { |
| 255 |
return Ok( |
| 256 |
if let Some((expr, trait_ident)) = |
| 257 |
fmt.transparent_call_on_fields(self.fields) |
| 258 |
{ |
| 259 |
quote! { derive_more::core::fmt::#trait_ident::fmt(#expr, __derive_more_f) } |
| 260 |
} else { |
| 261 |
let deref_args = fmt.additional_deref_args(self.fields); |
| 262 |
|
| 263 |
quote! { derive_more::core::write!(__derive_more_f, #fmt, #(#deref_args),*) } |
| 264 |
}, |
| 265 |
); |
| 266 |
}; |
| 267 |
|
| 268 |
match self.fields { |
| 269 |
syn::Fields::Unit => { |
| 270 |
let ident = self.ident.to_string(); |
| 271 |
Ok(quote! { |
| 272 |
derive_more::core::fmt::Formatter::write_str( |
| 273 |
__derive_more_f, |
| 274 |
#ident, |
| 275 |
) |
| 276 |
}) |
| 277 |
} |
| 278 |
syn::Fields::Unnamed(unnamed) => { |
| 279 |
let mut exhaustive = true; |
| 280 |
let ident_str = self.ident.to_string(); |
| 281 |
|
| 282 |
let out = quote! { |
| 283 |
&mut derive_more::__private::debug_tuple( |
| 284 |
__derive_more_f, |
| 285 |
#ident_str, |
| 286 |
) |
| 287 |
}; |
| 288 |
let out = unnamed.unnamed.iter().enumerate().try_fold( |
| 289 |
out, |
| 290 |
|out, (i, field)| match FieldAttribute::parse_attrs( |
| 291 |
&field.attrs, |
| 292 |
self.attr_name, |
| 293 |
)? |
| 294 |
.map(Spanning::into_inner) |
| 295 |
{ |
| 296 |
Some(FieldAttribute::Left(_skip)) => { |
| 297 |
exhaustive = false; |
| 298 |
Ok::<_, syn::Error>(out) |
| 299 |
} |
| 300 |
Some(FieldAttribute::Right(fmt_attr)) => { |
| 301 |
let deref_args = fmt_attr.additional_deref_args(self.fields); |
| 302 |
|
| 303 |
Ok(quote! { |
| 304 |
derive_more::__private::DebugTuple::field( |
| 305 |
#out, |
| 306 |
&derive_more::core::format_args!(#fmt_attr, #(#deref_args),*), |
| 307 |
) |
| 308 |
}) |
| 309 |
} |
| 310 |
None => { |
| 311 |
let ident = format_ident!("_{i}"); |
| 312 |
Ok(quote! { |
| 313 |
derive_more::__private::DebugTuple::field(#out, &#ident) |
| 314 |
}) |
| 315 |
} |
| 316 |
}, |
| 317 |
)?; |
| 318 |
Ok(if exhaustive { |
| 319 |
quote! { derive_more::__private::DebugTuple::finish(#out) } |
| 320 |
} else { |
| 321 |
quote! { derive_more::__private::DebugTuple::finish_non_exhaustive(#out) } |
| 322 |
}) |
| 323 |
} |
| 324 |
syn::Fields::Named(named) => { |
| 325 |
let mut exhaustive = true; |
| 326 |
let ident = self.ident.to_string(); |
| 327 |
|
| 328 |
let out = quote! { |
| 329 |
&mut derive_more::core::fmt::Formatter::debug_struct( |
| 330 |
__derive_more_f, |
| 331 |
#ident, |
| 332 |
) |
| 333 |
}; |
| 334 |
let out = named.named.iter().try_fold(out, |out, field| { |
| 335 |
let field_ident = field.ident.as_ref().unwrap_or_else(|| { |
| 336 |
unreachable!("`syn::Fields::Named`"); |
| 337 |
}); |
| 338 |
let field_str = field_ident.unraw().to_string(); |
| 339 |
match FieldAttribute::parse_attrs(&field.attrs, self.attr_name)? |
| 340 |
.map(Spanning::into_inner) |
| 341 |
{ |
| 342 |
Some(FieldAttribute::Left(_skip)) => { |
| 343 |
exhaustive = false; |
| 344 |
Ok::<_, syn::Error>(out) |
| 345 |
} |
| 346 |
Some(FieldAttribute::Right(fmt_attr)) => { |
| 347 |
let deref_args = |
| 348 |
fmt_attr.additional_deref_args(self.fields); |
| 349 |
|
| 350 |
Ok(quote! { |
| 351 |
derive_more::core::fmt::DebugStruct::field( |
| 352 |
#out, |
| 353 |
#field_str, |
| 354 |
&derive_more::core::format_args!( |
| 355 |
#fmt_attr, #(#deref_args),* |
| 356 |
), |
| 357 |
) |
| 358 |
}) |
| 359 |
} |
| 360 |
None => Ok(quote! { |
| 361 |
derive_more::core::fmt::DebugStruct::field( |
| 362 |
#out, #field_str, &#field_ident |
| 363 |
) |
| 364 |
}), |
| 365 |
} |
| 366 |
})?; |
| 367 |
Ok(if exhaustive { |
| 368 |
quote! { derive_more::core::fmt::DebugStruct::finish(#out) } |
| 369 |
} else { |
| 370 |
quote! { derive_more::core::fmt::DebugStruct::finish_non_exhaustive(#out) } |
| 371 |
}) |
| 372 |
} |
| 373 |
} |
| 374 |
} |
| 375 |
|
| 376 |
/// Generates trait bounds for a struct or an enum variant. |
| 377 |
fn generate_bounds(&self) -> syn::Result<Vec<syn::WherePredicate>> { |
| 378 |
let mut out = self.attr.bounds.0.clone().into_iter().collect::<Vec<_>>(); |
| 379 |
|
| 380 |
if let Some(fmt) = self.attr.fmt.as_ref() { |
| 381 |
out.extend(fmt.bounded_types(self.fields).filter_map( |
| 382 |
|(ty, trait_name)| { |
| 383 |
if !ty.contains_generics(self.type_params) { |
| 384 |
return None; |
| 385 |
} |
| 386 |
|
| 387 |
let trait_ident = format_ident!("{trait_name}"); |
| 388 |
|
| 389 |
Some(parse_quote! { #ty: derive_more::core::fmt::#trait_ident }) |
| 390 |
}, |
| 391 |
)); |
| 392 |
Ok(out) |
| 393 |
} else { |
| 394 |
self.fields.iter().try_fold(out, |mut out, field| { |
| 395 |
let ty = &field.ty; |
| 396 |
|
| 397 |
if !ty.contains_generics(self.type_params) { |
| 398 |
return Ok(out); |
| 399 |
} |
| 400 |
|
| 401 |
match FieldAttribute::parse_attrs(&field.attrs, self.attr_name)? |
| 402 |
.map(Spanning::into_inner) |
| 403 |
{ |
| 404 |
Some(FieldAttribute::Right(fmt_attr)) => { |
| 405 |
out.extend(fmt_attr.bounded_types(self.fields).map( |
| 406 |
|(ty, trait_name)| { |
| 407 |
let trait_ident = format_ident!("{trait_name}"); |
| 408 |
|
| 409 |
parse_quote! { #ty: derive_more::core::fmt::#trait_ident } |
| 410 |
}, |
| 411 |
)); |
| 412 |
} |
| 413 |
Some(FieldAttribute::Left(_skip)) => {} |
| 414 |
None => out.extend([parse_quote! { #ty: derive_more::core::fmt::Debug }]), |
| 415 |
} |
| 416 |
Ok(out) |
| 417 |
}) |
| 418 |
} |
| 419 |
} |
| 420 |
} |