strum_macros/macros/strings/
display.rs

1use proc_macro2::{Ident, TokenStream};
2use quote::quote;
3use syn::{punctuated::Punctuated, Data, DeriveInput, Fields, LitStr, Token};
4
5use crate::helpers::{
6    non_enum_error, non_single_field_variant_error, HasStrumVariantProperties, HasTypeProperties,
7};
8
9pub fn display_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
10    let name = &ast.ident;
11    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
12    let variants = match &ast.data {
13        Data::Enum(v) => &v.variants,
14        _ => return Err(non_enum_error()),
15    };
16
17    let type_properties = ast.get_type_properties()?;
18
19    let mut arms = Vec::new();
20    for variant in variants {
21        let ident = &variant.ident;
22        let variant_properties = variant.get_variant_properties()?;
23
24        if variant_properties.disabled.is_some() {
25            continue;
26        }
27
28        if let Some(..) = variant_properties.transparent {
29            let arm = super::extract_single_field_variant_and_then(name, variant, |tok| {
30                quote! { ::core::fmt::Display::fmt(#tok, f) }
31            })
32            .map_err(|_| non_single_field_variant_error("transparent"))?;
33
34            arms.push(arm);
35            continue;
36        }
37
38        // Look at all the serialize attributes.
39        let output = variant_properties.get_preferred_name(
40            type_properties.case_style,
41            type_properties.prefix.as_ref(),
42            type_properties.suffix.as_ref(),
43        );
44
45        let params = match variant.fields {
46            Fields::Unit => quote! {},
47            Fields::Unnamed(ref unnamed_fields) => {
48                // Transform unnamed params '(String, u8)' to '(ref field0, ref field1)'
49                let names: Punctuated<_, Token!(,)> = unnamed_fields
50                    .unnamed
51                    .iter()
52                    .enumerate()
53                    .map(|(index, field)| {
54                        assert!(field.ident.is_none());
55                        let ident =
56                            syn::parse_str::<Ident>(format!("field{}", index).as_str()).unwrap();
57                        quote! { ref #ident }
58                    })
59                    .collect();
60                quote! { (#names) }
61            }
62            Fields::Named(ref field_names) => {
63                // Transform named params '{ name: String, age: u8 }' to '{ ref name, ref age }'
64                let names: Punctuated<TokenStream, Token!(,)> = field_names
65                    .named
66                    .iter()
67                    .map(|field| {
68                        let ident = field.ident.as_ref().unwrap();
69                        quote! { ref #ident }
70                    })
71                    .collect();
72
73                quote! { {#names} }
74            }
75        };
76
77        if variant_properties.to_string.is_none() && variant_properties.default.is_some() {
78            let arm = super::extract_single_field_variant_and_then(name, variant, |tok| {
79                quote! { ::core::fmt::Display::fmt(#tok, f)}
80            })
81            .map_err(|_| {
82                syn::Error::new_spanned(
83                    variant,
84                    "Default only works on newtype structs with a single String field",
85                )
86            })?;
87
88            arms.push(arm);
89            continue;
90        }
91
92        let arm = match variant.fields {
93            Fields::Named(ref field_names) => {
94                let used_vars = capture_format_string_idents(&output)?;
95                if used_vars.is_empty() {
96                    quote! { #name::#ident #params => ::core::fmt::Display::fmt(#output, f) }
97                } else {
98                    // Create args like 'name = name, age = age' for format macro
99                    let args: Punctuated<_, Token!(,)> = field_names
100                        .named
101                        .iter()
102                        .filter_map(|field| {
103                            let ident = field.ident.as_ref().unwrap();
104                            // Only contain variables that are used in format string
105                            if !used_vars.contains(ident) {
106                                None
107                            } else {
108                                Some(quote! { #ident = #ident })
109                            }
110                        })
111                        .collect();
112
113                    quote! {
114                        #[allow(unused_variables)]
115                        #name::#ident #params => ::core::fmt::Display::fmt(&format_args!(#output, #args), f)
116                    }
117                }
118            }
119            Fields::Unnamed(ref unnamed_fields) => {
120                let used_vars = capture_format_strings(&output)?;
121                if used_vars.iter().any(String::is_empty) {
122                    return Err(syn::Error::new_spanned(
123                        &output,
124                        "Empty {} is not allowed; Use manual numbering ({0})",
125                    ));
126                }
127                if used_vars.is_empty() {
128                    quote! { #name::#ident #params => ::core::fmt::Display::fmt(#output, f) }
129                } else {
130                    let args: Punctuated<_, Token!(,)> = unnamed_fields
131                        .unnamed
132                        .iter()
133                        .enumerate()
134                        .map(|(index, field)| {
135                            assert!(field.ident.is_none());
136                            syn::parse_str::<Ident>(format!("field{}", index).as_str()).unwrap()
137                        })
138                        .collect();
139                    quote! {
140                        #[allow(unused_variables)]
141                        #name::#ident #params => ::core::fmt::Display::fmt(&format!(#output, #args), f)
142                    }
143                }
144            }
145            Fields::Unit => {
146                let used_vars = capture_format_strings(&output)?;
147                if !used_vars.is_empty() {
148                    return Err(syn::Error::new_spanned(
149                        &output,
150                        "Unit variants do not support interpolation",
151                    ));
152                }
153
154                quote! { #name::#ident #params => ::core::fmt::Display::fmt(#output, f) }
155            }
156        };
157
158        arms.push(arm);
159    }
160
161    if arms.len() < variants.len() {
162        arms.push(quote! { _ => panic!("fmt() called on disabled variant.") });
163    }
164
165    Ok(quote! {
166        #[automatically_derived]
167        impl #impl_generics ::core::fmt::Display for #name #ty_generics #where_clause {
168            fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> {
169                match *self {
170                    #(#arms),*
171                }
172            }
173        }
174    })
175}
176
177fn capture_format_string_idents(string_literal: &LitStr) -> syn::Result<Vec<Ident>> {
178    capture_format_strings(string_literal)?
179        .into_iter()
180        .map(|ident| {
181            syn::parse_str::<Ident>(ident.as_str()).map_err(|_| {
182                syn::Error::new_spanned(
183                    string_literal,
184                    "Invalid identifier inside format string bracket",
185                )
186            })
187        })
188        .collect()
189}
190
191fn capture_format_strings(string_literal: &LitStr) -> syn::Result<Vec<String>> {
192    // Remove escaped brackets
193    let format_str = string_literal.value().replace("{{", "").replace("}}", "");
194
195    let mut new_var_start_index: Option<usize> = None;
196    let mut var_used = Vec::new();
197
198    for (i, chr) in format_str.bytes().enumerate() {
199        if chr == b'{' {
200            if new_var_start_index.is_some() {
201                return Err(syn::Error::new_spanned(
202                    string_literal,
203                    "Bracket opened without closing previous bracket",
204                ));
205            }
206            new_var_start_index = Some(i);
207            continue;
208        }
209
210        if chr == b'}' {
211            let start_index = new_var_start_index.take().ok_or(syn::Error::new_spanned(
212                string_literal,
213                "Bracket closed without previous opened bracket",
214            ))?;
215
216            let inside_brackets = &format_str[start_index + 1..i];
217            let ident_str = inside_brackets.split(":").next().unwrap().trim_end();
218            var_used.push(ident_str.to_owned());
219        }
220    }
221
222    Ok(var_used)
223}