Debian Codegraph @

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

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