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