Debian Codegraph @

third_party/rust/derive_more-impl/src/fmt/debug.rs

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