1use super::attr::AttrsHelper;
2use proc_macro2::{Span, TokenStream};
3use quote::{format_ident, quote};
4use syn::{
5 punctuated::Punctuated,
6 token::{Colon, Comma, PathSep, Plus, Where},
7 Data, DataEnum, DataStruct, DeriveInput, Error, Fields, Generics, Ident, Path, PathArguments,
8 PathSegment, PredicateType, Result, TraitBound, TraitBoundModifier, Type, TypeParam,
9 TypeParamBound, TypePath, WhereClause, WherePredicate,
10};
11
12use std::collections::HashMap;
13
14pub(crate) fn derive(input: &DeriveInput) -> Result<TokenStream> {
15 let impls: TokenStream = match &input.data {
16 Data::Struct(data: &DataStruct) => impl_struct(input, data),
17 Data::Enum(data: &DataEnum) => impl_enum(input, data),
18 Data::Union(_) => Err(Error::new_spanned(tokens:input, message:"Unions are not supported")),
19 }?;
20
21 let helpers: TokenStream = specialization();
22 let dummy_const: Ident = format_ident!("_DERIVE_Display_FOR_{}", input.ident);
23 Ok(quote! {
24 #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
25 const #dummy_const: () = {
26 #helpers
27 #impls
28 };
29 })
30}
31
32#[cfg(feature = "std")]
33fn specialization() -> TokenStream {
34 quote! {
35 trait DisplayToDisplayDoc {
36 fn __displaydoc_display(&self) -> Self;
37 }
38
39 impl<T: core::fmt::Display> DisplayToDisplayDoc for &T {
40 fn __displaydoc_display(&self) -> Self {
41 self
42 }
43 }
44
45 // If the `std` feature gets enabled we want to ensure that any crate
46 // using displaydoc can still reference the std crate, which is already
47 // being compiled in by whoever enabled the `std` feature in
48 // `displaydoc`, even if the crates using displaydoc are no_std.
49 extern crate std;
50
51 trait PathToDisplayDoc {
52 fn __displaydoc_display(&self) -> std::path::Display<'_>;
53 }
54
55 impl PathToDisplayDoc for std::path::Path {
56 fn __displaydoc_display(&self) -> std::path::Display<'_> {
57 self.display()
58 }
59 }
60
61 impl PathToDisplayDoc for std::path::PathBuf {
62 fn __displaydoc_display(&self) -> std::path::Display<'_> {
63 self.display()
64 }
65 }
66 }
67}
68
69#[cfg(not(feature = "std"))]
70fn specialization() -> TokenStream {
71 quote! {}
72}
73
74fn impl_struct(input: &DeriveInput, data: &DataStruct) -> Result<TokenStream> {
75 let ty = &input.ident;
76 let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
77 let where_clause = generate_where_clause(&input.generics, where_clause);
78
79 let helper = AttrsHelper::new(&input.attrs);
80
81 let display = helper.display(&input.attrs)?.map(|display| {
82 let pat = match &data.fields {
83 Fields::Named(fields) => {
84 let var = fields.named.iter().map(|field| &field.ident);
85 quote!(Self { #(#var),* })
86 }
87 Fields::Unnamed(fields) => {
88 let var = (0..fields.unnamed.len()).map(|i| format_ident!("_{}", i));
89 quote!(Self(#(#var),*))
90 }
91 Fields::Unit => quote!(_),
92 };
93 quote! {
94 impl #impl_generics core::fmt::Display for #ty #ty_generics #where_clause {
95 fn fmt(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
96 // NB: This destructures the fields of `self` into named variables (for unnamed
97 // fields, it uses _0, _1, etc as above). The `#[allow(unused_variables)]`
98 // section means it doesn't have to parse the individual field references out of
99 // the docstring.
100 #[allow(unused_variables)]
101 let #pat = self;
102 #display
103 }
104 }
105 }
106 });
107
108 Ok(quote! { #display })
109}
110
111/// Create a `where` predicate for `ident`, without any [bound][TypeParamBound]s yet.
112fn new_empty_where_type_predicate(ident: Ident) -> PredicateType {
113 let mut path_segments: Punctuated = Punctuated::<PathSegment, PathSep>::new();
114 path_segments.push_value(PathSegment {
115 ident,
116 arguments: PathArguments::None,
117 });
118 PredicateType {
119 lifetimes: None,
120 bounded_ty: Type::Path(TypePath {
121 qself: None,
122 path: Path {
123 leading_colon: None,
124 segments: path_segments,
125 },
126 }),
127 colon_token: Colon {
128 spans: [Span::call_site()],
129 },
130 bounds: Punctuated::<TypeParamBound, Plus>::new(),
131 }
132}
133
134/// Create a `where` clause that we can add [WherePredicate]s to.
135fn new_empty_where_clause() -> WhereClause {
136 WhereClause {
137 where_token: Where {
138 span: Span::call_site(),
139 },
140 predicates: Punctuated::<WherePredicate, Comma>::new(),
141 }
142}
143
144enum UseGlobalPrefix {
145 LeadingColon,
146 #[allow(dead_code)]
147 NoLeadingColon,
148}
149
150/// Create a path with segments composed of [Idents] *without* any [PathArguments].
151fn join_paths(name_segments: &[&str], use_global_prefix: UseGlobalPrefix) -> Path {
152 let mut segments = Punctuated::<PathSegment, PathSep>::new();
153 assert!(!name_segments.is_empty());
154 segments.push_value(PathSegment {
155 ident: Ident::new(name_segments[0], Span::call_site()),
156 arguments: PathArguments::None,
157 });
158 for name in name_segments[1..].iter() {
159 segments.push_punct(PathSep {
160 spans: [Span::call_site(), Span::mixed_site()],
161 });
162 segments.push_value(PathSegment {
163 ident: Ident::new(name, Span::call_site()),
164 arguments: PathArguments::None,
165 });
166 }
167 Path {
168 leading_colon: match use_global_prefix {
169 UseGlobalPrefix::LeadingColon => Some(PathSep {
170 spans: [Span::call_site(), Span::mixed_site()],
171 }),
172 UseGlobalPrefix::NoLeadingColon => None,
173 },
174 segments,
175 }
176}
177
178/// Push `new_type_predicate` onto the end of `where_clause`.
179fn append_where_clause_type_predicate(
180 where_clause: &mut WhereClause,
181 new_type_predicate: PredicateType,
182) {
183 // Push a comma at the end if there are already any `where` predicates.
184 if !where_clause.predicates.is_empty() {
185 where_clause.predicates.push_punct(punctuation:Comma {
186 spans: [Span::call_site()],
187 });
188 }
189 where_clausePunctuated
190 .predicates
191 .push_value(WherePredicate::Type(new_type_predicate));
192}
193
194/// Add a requirement for [core::fmt::Display] to a `where` predicate for some type.
195fn add_display_constraint_to_type_predicate(
196 predicate_that_needs_a_display_impl: &mut PredicateType,
197) {
198 // Create a `Path` of `::core::fmt::Display`.
199 let display_path: Path = join_paths(&["core", "fmt", "Display"], UseGlobalPrefix::LeadingColon);
200
201 let display_bound: TypeParamBound = TypeParamBound::Trait(TraitBound {
202 paren_token: None,
203 modifier: TraitBoundModifier::None,
204 lifetimes: None,
205 path: display_path,
206 });
207 if !predicate_that_needs_a_display_impl.bounds.is_empty() {
208 predicate_that_needs_a_display_impl.bounds.push_punct(punctuation:Plus {
209 spans: [Span::call_site()],
210 });
211 }
212
213 predicate_that_needs_a_display_implPunctuated
214 .bounds
215 .push_value(display_bound);
216}
217
218/// Map each declared generic type parameter to the set of all trait boundaries declared on it.
219///
220/// These boundaries may come from the declaration site:
221/// pub enum E<T: MyTrait> { ... }
222/// or a `where` clause after the parameter declarations:
223/// pub enum E<T> where T: MyTrait { ... }
224/// This method will return the boundaries from both of those cases.
225fn extract_trait_constraints_from_source(
226 where_clause: &WhereClause,
227 type_params: &[&TypeParam],
228) -> HashMap<Ident, Vec<TraitBound>> {
229 // Add trait bounds provided at the declaration site of type parameters for the struct/enum.
230 let mut param_constraint_mapping: HashMap<Ident, Vec<TraitBound>> = type_params
231 .iter()
232 .map(|type_param| {
233 let trait_bounds: Vec<TraitBound> = type_param
234 .bounds
235 .iter()
236 .flat_map(|bound| match bound {
237 TypeParamBound::Trait(trait_bound) => Some(trait_bound),
238 _ => None,
239 })
240 .cloned()
241 .collect();
242 (type_param.ident.clone(), trait_bounds)
243 })
244 .collect();
245
246 // Add trait bounds from `where` clauses, which may be type parameters or types containing
247 // those parameters.
248 for predicate in where_clause.predicates.iter() {
249 // We only care about type and not lifetime constraints here.
250 if let WherePredicate::Type(ref pred_ty) = predicate {
251 let ident = match &pred_ty.bounded_ty {
252 Type::Path(TypePath { path, qself: None }) => match path.get_ident() {
253 None => continue,
254 Some(ident) => ident,
255 },
256 _ => continue,
257 };
258 // We ignore any type constraints that aren't direct references to type
259 // parameters of the current enum of struct definition. No types can be
260 // constrained in a `where` clause unless they are a type parameter or a generic
261 // type instantiated with one of the type parameters, so by only allowing single
262 // identifiers, we can be sure that the constrained type is a type parameter
263 // that is contained in `param_constraint_mapping`.
264 if let Some((_, ref mut known_bounds)) = param_constraint_mapping
265 .iter_mut()
266 .find(|(id, _)| *id == ident)
267 {
268 for bound in pred_ty.bounds.iter() {
269 // We only care about trait bounds here.
270 if let TypeParamBound::Trait(ref bound) = bound {
271 known_bounds.push(bound.clone());
272 }
273 }
274 }
275 }
276 }
277
278 param_constraint_mapping
279}
280
281/// Hygienically add `where _: Display` to the set of [TypeParamBound]s for `ident`, creating such
282/// a set if necessary.
283fn ensure_display_in_where_clause_for_type(where_clause: &mut WhereClause, ident: Ident) {
284 for pred_ty in where_clause
285 .predicates
286 .iter_mut()
287 // Find the `where` predicate constraining the current type param, if it exists.
288 .flat_map(|predicate| match predicate {
289 WherePredicate::Type(pred_ty) => Some(pred_ty),
290 // We're looking through type constraints, not lifetime constraints.
291 _ => None,
292 })
293 {
294 // Do a complicated destructuring in order to check if the type being constrained in this
295 // `where` clause is the type we're looking for, so we can use the mutable reference to
296 // `pred_ty` if so.
297 let matches_desired_type = matches!(
298 &pred_ty.bounded_ty,
299 Type::Path(TypePath { path, .. }) if Some(&ident) == path.get_ident());
300 if matches_desired_type {
301 add_display_constraint_to_type_predicate(pred_ty);
302 return;
303 }
304 }
305
306 // If there is no `where` predicate for the current type param, we will construct one.
307 let mut new_type_predicate = new_empty_where_type_predicate(ident);
308 add_display_constraint_to_type_predicate(&mut new_type_predicate);
309 append_where_clause_type_predicate(where_clause, new_type_predicate);
310}
311
312/// For all declared type parameters, add a [core::fmt::Display] constraint, unless the type
313/// parameter already has any type constraint.
314fn ensure_where_clause_has_display_for_all_unconstrained_members(
315 where_clause: &mut WhereClause,
316 type_params: &[&TypeParam],
317) {
318 let param_constraint_mapping: HashMap> = extract_trait_constraints_from_source(where_clause, type_params);
319
320 for (ident: Ident, known_bounds: Vec) in param_constraint_mapping.into_iter() {
321 // If the type parameter has any constraints already, we don't want to touch it, to avoid
322 // breaking use cases where a type parameter only needs to impl `Debug`, for example.
323 if known_bounds.is_empty() {
324 ensure_display_in_where_clause_for_type(where_clause, ident);
325 }
326 }
327}
328
329/// Generate a `where` clause that ensures all generic type parameters `impl`
330/// [core::fmt::Display] unless already constrained.
331///
332/// This approach allows struct/enum definitions deriving [crate::Display] to avoid hardcoding
333/// a [core::fmt::Display] constraint into every type parameter.
334///
335/// If the type parameter isn't already constrained, we add a `where _: Display` clause to our
336/// display implementation to expect to be able to format every enum case or struct member.
337///
338/// In fact, we would preferably only require `where _: Display` or `where _: Debug` where the
339/// format string actually requires it. However, while [`std::fmt` defines a formal syntax for
340/// `format!()`][format syntax], it *doesn't* expose the actual logic to parse the format string,
341/// which appears to live in [`rustc_parse_format`]. While we use the [`syn`] crate to parse rust
342/// syntax, it also doesn't currently provide any method to introspect a `format!()` string. It
343/// would be nice to contribute this upstream in [`syn`].
344///
345/// [format syntax]: std::fmt#syntax
346/// [`rustc_parse_format`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_parse_format/index.html
347fn generate_where_clause(generics: &Generics, where_clause: Option<&WhereClause>) -> WhereClause {
348 let mut where_clause: WhereClause = where_clause.cloned().unwrap_or_else(new_empty_where_clause);
349 let type_params: Vec<&TypeParam> = generics.type_params().collect();
350 ensure_where_clause_has_display_for_all_unconstrained_members(&mut where_clause, &type_params);
351 where_clause
352}
353
354fn impl_enum(input: &DeriveInput, data: &DataEnum) -> Result<TokenStream> {
355 let ty = &input.ident;
356 let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
357 let where_clause = generate_where_clause(&input.generics, where_clause);
358
359 let helper = AttrsHelper::new(&input.attrs);
360
361 let displays = data
362 .variants
363 .iter()
364 .map(|variant| helper.display_with_input(&input.attrs, &variant.attrs))
365 .collect::<Result<Vec<_>>>()?;
366
367 if data.variants.is_empty() {
368 Ok(quote! {
369 impl #impl_generics core::fmt::Display for #ty #ty_generics #where_clause {
370 fn fmt(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
371 unreachable!("empty enums cannot be instantiated and thus cannot be printed")
372 }
373 }
374 })
375 } else if displays.iter().any(Option::is_some) {
376 let arms = data
377 .variants
378 .iter()
379 .zip(displays)
380 .map(|(variant, display)| {
381 let display =
382 display.ok_or_else(|| Error::new_spanned(variant, "missing doc comment"))?;
383 let ident = &variant.ident;
384 Ok(match &variant.fields {
385 Fields::Named(fields) => {
386 let var = fields.named.iter().map(|field| &field.ident);
387 quote!(Self::#ident { #(#var),* } => { #display })
388 }
389 Fields::Unnamed(fields) => {
390 let var = (0..fields.unnamed.len()).map(|i| format_ident!("_{}", i));
391 quote!(Self::#ident(#(#var),*) => { #display })
392 }
393 Fields::Unit => quote!(Self::#ident => { #display }),
394 })
395 })
396 .collect::<Result<Vec<_>>>()?;
397 Ok(quote! {
398 impl #impl_generics core::fmt::Display for #ty #ty_generics #where_clause {
399 fn fmt(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
400 #[allow(unused_variables)]
401 match self {
402 #(#arms,)*
403 }
404 }
405 }
406 })
407 } else {
408 Err(Error::new_spanned(input, "Missing doc comments"))
409 }
410}
411