Debian Codegraph @

debian/missing-sources/derive_more-impl/src/from_str.rs

raw
1 //! Implementation of a [`FromStr`] derive macro.
2
3 #[cfg(doc)]
4 use std::str::FromStr;
5 use std::{collections::HashMap, iter};
6
7 use proc_macro2::TokenStream;
8 use quote::{format_ident, quote, ToTokens};
9 use syn::{parse::Parse, parse_quote, spanned::Spanned as _};
10
11 use crate::utils::{
12 attr::{self, ParseMultiple as _},
13 Either, GenericsSearch, Spanning,
14 };
15
16 /// Expands a [`FromStr`] derive macro.
17 pub fn expand(input: &syn::DeriveInput, _: &'static str) -> syn::Result<TokenStream> {
18 match &input.data {
19 syn::Data::Struct(data) => Ok(if data.fields.is_empty() {
20 FlatExpansion::try_from(input)?.into_token_stream()
21 } else {
22 ForwardExpansion::try_from(input)?.into_token_stream()
23 }),
24 syn::Data::Enum(_) => Ok(FlatExpansion::try_from(input)?.into_token_stream()),
25 syn::Data::Union(data) => Err(syn::Error::new(
26 data.union_token.span(),
27 "`FromStr` cannot be derived for unions",
28 )),
29 }
30 }
31
32 /// Expansion of a macro for generating a forwarding [`FromStr`] implementation of a struct.
33 struct ForwardExpansion<'i> {
34 /// [`syn::Ident`] and [`syn::Generics`] of the struct.
35 ///
36 /// [`syn::Ident`]: struct@syn::Ident
37 self_ty: (&'i syn::Ident, &'i syn::Generics),
38
39 /// [`syn::Field`] representing the wrapped type to forward implementation on.
40 inner: &'i syn::Field,
41
42 /// Optional [`attr::Error`] enabling conversion into a custom error type.
43 custom_error: Option<attr::Error>,
44 }
45
46 impl<'i> TryFrom<&'i syn::DeriveInput> for ForwardExpansion<'i> {
47 type Error = syn::Error;
48
49 fn try_from(input: &'i syn::DeriveInput) -> syn::Result<Self> {
50 let syn::Data::Struct(data) = &input.data else {
51 return Err(syn::Error::new(
52 input.span(),
53 "expected a struct for forward `FromStr` derive",
54 ));
55 };
56
57 // TODO: Unite these two conditions via `&&` once MSRV is bumped to 1.88 or above.
58 if data.fields.len() != 1 {
59 return Err(syn::Error::new(
60 data.fields.span(),
61 "only structs with single field can derive `FromStr`",
62 ));
63 }
64 let Some(inner) = data.fields.iter().next() else {
65 return Err(syn::Error::new(
66 data.fields.span(),
67 "only structs with single field can derive `FromStr`",
68 ));
69 };
70
71 let custom_error =
72 attr::Error::parse_attrs(&input.attrs, &format_ident!("from_str"))?
73 .map(Spanning::into_inner);
74
75 Ok(Self {
76 self_ty: (&input.ident, &input.generics),
77 inner,
78 custom_error,
79 })
80 }
81 }
82
83 impl ToTokens for ForwardExpansion<'_> {
84 /// Expands a forwarding [`FromStr`] implementations for a struct.
85 fn to_tokens(&self, tokens: &mut TokenStream) {
86 let inner_ty = &self.inner.ty;
87 let ty = self.self_ty.0;
88
89 let generics_search = GenericsSearch::from(self.self_ty.1);
90 let mut generics = self.self_ty.1.clone();
91 if generics_search.any_in(inner_ty) {
92 generics.make_where_clause().predicates.push(parse_quote! {
93 #inner_ty: derive_more::core::str::FromStr
94 });
95 }
96 let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
97
98 let constructor = self.inner.self_constructor([parse_quote! { v }]);
99
100 let mut error_ty =
101 quote! { <#inner_ty as derive_more::core::str::FromStr>::Err };
102 let mut error_conv = quote! {};
103 if let Some(custom_error) = &self.custom_error {
104 error_ty = custom_error.ty.to_token_stream();
105 error_conv = custom_error.conv.as_ref().map_or_else(
106 || quote! { .map_err(derive_more::core::convert::Into::into) },
107 |conv| quote! { .map_err(#conv) },
108 );
109 }
110
111 quote! {
112 #[automatically_derived]
113 impl #impl_generics derive_more::core::str::FromStr for #ty #ty_generics #where_clause {
114 type Err = #error_ty;
115
116 #[inline]
117 fn from_str(s: &str) -> derive_more::core::result::Result<Self, Self::Err> {
118 derive_more::core::str::FromStr::from_str(s).map(|v| #constructor)#error_conv
119 }
120 }
121 }.to_tokens(tokens);
122 }
123 }
124
125 /// Expansion of a macro for generating a flat [`FromStr`] implementation of an enum or a struct.
126 struct FlatExpansion<'i> {
127 /// [`syn::Ident`] and [`syn::Generics`] of the enum/struct.
128 ///
129 /// [`syn::Ident`]: struct@syn::Ident
130 self_ty: (&'i syn::Ident, &'i syn::Generics),
131
132 /// [`syn::Ident`]s along with the matched values (enum variants or struct itself), and
133 /// a value-specific [`attr::RenameAll`] overriding [`FlatExpansion::rename_all`], if any.
134 ///
135 /// [`syn::Ident`]: struct@syn::Ident
136 matches: Vec<(
137 &'i syn::Ident,
138 Either<&'i syn::DataStruct, &'i syn::Variant>,
139 Option<attr::RenameAll>,
140 )>,
141
142 /// [`FlatExpansion::matches`] grouped by its similar representation for detecting whether their
143 /// case-insensitivity should be disabled.
144 similar_matches: HashMap<String, Vec<&'i syn::Ident>>,
145
146 /// Optional [`attr::RenameAll`] indicating the case conversion to be applied to all the matched
147 /// values (enum variants or struct itself).
148 rename_all: Option<attr::RenameAll>,
149
150 /// Optional [`attr::Error`] enabling conversion into a custom error type.
151 custom_error: Option<attr::Error>,
152 }
153
154 impl<'i> TryFrom<&'i syn::DeriveInput> for FlatExpansion<'i> {
155 type Error = syn::Error;
156
157 fn try_from(input: &'i syn::DeriveInput) -> syn::Result<Self> {
158 let attr_ident = &format_ident!("from_str");
159
160 let matches = match &input.data {
161 syn::Data::Struct(data) => {
162 if !data.fields.is_empty() {
163 return Err(syn::Error::new(
164 data.fields.span(),
165 "only structs with no fields can derive `FromStr`",
166 ));
167 }
168 vec![(&input.ident, Either::Left(data), None)]
169 }
170 syn::Data::Enum(data) => data
171 .variants
172 .iter()
173 .map(|variant| {
174 if !variant.fields.is_empty() {
175 return Err(syn::Error::new(
176 variant.fields.span(),
177 "only enums with no fields can derive `FromStr`",
178 ));
179 }
180 let attr =
181 attr::RenameAll::parse_attrs(&variant.attrs, attr_ident)?
182 .map(Spanning::into_inner);
183 Ok((&variant.ident, Either::Right(variant), attr))
184 })
185 .collect::<syn::Result<_>>()?,
186 syn::Data::Union(_) => {
187 return Err(syn::Error::new(
188 input.span(),
189 "expected an enum or a struct for flat `FromStr` derive",
190 ))
191 }
192 };
193
194 let FlatContainerAttributes {
195 rename_all,
196 error: custom_error,
197 } = FlatContainerAttributes::parse_attrs(&input.attrs, attr_ident)?
198 .map(Spanning::into_inner)
199 .unwrap_or_default();
200
201 let mut similar_matches = <HashMap<_, Vec<_>>>::new();
202 if rename_all.is_none() {
203 for (ident, _, renaming) in &matches {
204 let name = ident.to_string();
205 let lowercased = name.to_lowercase();
206 if let Some(rename) = renaming {
207 let renamed_lowercased = rename.convert_case(&name);
208 if renamed_lowercased != lowercased {
209 similar_matches
210 .entry(renamed_lowercased)
211 .or_default()
212 .push(*ident);
213 }
214 }
215 similar_matches.entry(lowercased).or_default().push(*ident);
216 }
217 }
218
219 let mut exact_matches = <HashMap<String, Vec<String>>>::new();
220 for (ident, _, renaming) in &matches {
221 let name = ident.to_string();
222 let exact = if let Some(default_renaming) = &rename_all {
223 renaming
224 .as_ref()
225 .unwrap_or(default_renaming)
226 .convert_case(&name)
227 } else if let Some(renaming) = renaming {
228 renaming.convert_case(&name)
229 } else {
230 let lowercased = name.to_lowercase();
231 if similar_matches[&lowercased].len() > 1 {
232 name.clone()
233 } else {
234 lowercased
235 }
236 };
237 exact_matches.entry(exact).or_default().push(name);
238 }
239 if let Some((string, variants)) =
240 exact_matches.into_iter().find(|(_, vs)| vs.len() > 1)
241 {
242 return Err(syn::Error::new(
243 input.ident.span(),
244 format!(
245 "`{}` variants cannot have the same \"{string}\" string representation",
246 variants.join("`, `"),
247 ),
248 ));
249 }
250
251 Ok(Self {
252 self_ty: (&input.ident, &input.generics),
253 matches,
254 similar_matches,
255 rename_all,
256 custom_error,
257 })
258 }
259 }
260
261 impl ToTokens for FlatExpansion<'_> {
262 /// Expands a flat [`FromStr`] implementations for an enum.
263 fn to_tokens(&self, tokens: &mut TokenStream) {
264 let ty = self.self_ty.0;
265 let (impl_generics, ty_generics, where_clause) =
266 self.self_ty.1.split_for_impl();
267 let ty_name = ty.to_string();
268
269 let scrutinee_lowercased = self
270 .rename_all
271 .is_none()
272 .then(|| quote! { .to_lowercase().as_str() });
273 let match_arms = if let Some(default_renaming) = self.rename_all {
274 self.matches
275 .iter()
276 .map(|(ident, value, renaming)| {
277 let converted = renaming
278 .unwrap_or(default_renaming)
279 .convert_case(&ident.to_string());
280 let constructor = value.self_constructor_empty();
281
282 quote! { #converted => #constructor, }
283 })
284 .collect::<Vec<_>>()
285 } else {
286 self.matches
287 .iter()
288 .map(|(ident, value, renaming)| {
289 let name = ident.to_string();
290 let constructor = value.self_constructor_empty();
291 if let Some(rename) = renaming {
292 let exact_name = rename.convert_case(&name);
293
294 quote! { _ if s == #exact_name => #constructor, }
295 } else {
296 let lowercased = name.to_lowercase();
297 let exact_guard = (self.similar_matches[&lowercased].len() > 1)
298 .then(|| quote! { if s == #name });
299
300 quote! { #lowercased #exact_guard => #constructor, }
301 }
302 })
303 .collect()
304 };
305
306 let default_error = quote! { derive_more::FromStrError::new(#ty_name) };
307 let mut error_ty = quote! { derive_more::FromStrError };
308 let mut error_val = default_error.clone();
309 if let Some(custom_error) = &self.custom_error {
310 error_ty = custom_error.ty.to_token_stream();
311 error_val = custom_error.conv.as_ref().map_or_else(
312 || quote! { derive_more::core::convert::Into::into(#default_error) },
313 |conv| quote! { (#conv)(#default_error) },
314 );
315 }
316
317 quote! {
318 #[allow(unreachable_code)] // for empty enums
319 #[automatically_derived]
320 impl #impl_generics derive_more::core::str::FromStr for #ty #ty_generics #where_clause {
321 type Err = #error_ty;
322
323 fn from_str(s: &str) -> derive_more::core::result::Result<
324 Self, <Self as derive_more::core::str::FromStr>::Err,
325 > {
326 derive_more::core::result::Result::Ok(match s #scrutinee_lowercased {
327 #( #match_arms )*
328 _ => return derive_more::core::result::Result::Err(#error_val),
329 })
330 }
331 }
332 }.to_tokens(tokens);
333 }
334 }
335
336 /// Extension of [`syn::Fields`] used by this expansion.
337 trait FieldsExt {
338 /// Generates a `name`d constructor with the provided `values` assigned to these
339 /// [`syn::Fields`].
340 ///
341 /// # Panics
342 ///
343 /// If number of provided `values` doesn't match number of these [`syn::Fields`].
344 fn constructor(
345 &self,
346 name: &syn::Path,
347 values: impl IntoIterator<Item = syn::Ident>,
348 ) -> TokenStream;
349
350 /// Generates a `Self` type constructor with the provided `values` assigned to these
351 /// [`syn::Fields`].
352 ///
353 /// # Panics
354 ///
355 /// If number of provided `values` doesn't match number of these [`syn::Fields`].
356 fn self_constructor(
357 &self,
358 values: impl IntoIterator<Item = syn::Ident>,
359 ) -> TokenStream {
360 self.constructor(&self.self_ty(), values)
361 }
362
363 /// Generates a `Self` type constructor with no fields.
364 ///
365 /// # Panics
366 ///
367 /// If these [`syn::Fields`] are not [empty].
368 ///
369 /// [empty]: syn::Fields::is_empty
370 fn self_constructor_empty(&self) -> TokenStream {
371 self.self_constructor(iter::empty())
372 }
373
374 /// Returns a [`syn::Path`] representing a `Self` type of these [`syn::Fields`].
375 fn self_ty(&self) -> syn::Path {
376 parse_quote! { Self }
377 }
378 }
379
380 impl FieldsExt for syn::Fields {
381 fn constructor(
382 &self,
383 name: &syn::Path,
384 values: impl IntoIterator<Item = syn::Ident>,
385 ) -> TokenStream {
386 let values = values.into_iter();
387 let fields = match self {
388 Self::Named(fields) => {
389 let initializers = fields.named.iter().zip(values).map(|(f, value)| {
390 let ident = &f.ident;
391 quote! { #ident: #value }
392 });
393 Some(quote! { { #( #initializers, )*} })
394 }
395 Self::Unnamed(_) => Some(quote! { ( #( #values, )* ) }),
396 Self::Unit => None,
397 };
398 quote! { #name #fields }
399 }
400 }
401
402 impl FieldsExt for syn::Field {
403 fn constructor(
404 &self,
405 name: &syn::Path,
406 values: impl IntoIterator<Item = syn::Ident>,
407 ) -> TokenStream {
408 let mut values = values.into_iter();
409 let value = values.next().expect("expected a single value");
410 if values.next().is_some() {
411 panic!("expected a single value");
412 }
413
414 if let Some(ident) = &self.ident {
415 quote! { #name { #ident: #value } }
416 } else {
417 quote! { #name(#value) }
418 }
419 }
420 }
421
422 impl FieldsExt for syn::Variant {
423 fn constructor(
424 &self,
425 name: &syn::Path,
426 values: impl IntoIterator<Item = syn::Ident>,
427 ) -> TokenStream {
428 self.fields.constructor(name, values)
429 }
430
431 fn self_ty(&self) -> syn::Path {
432 let variant = &self.ident;
433
434 parse_quote! { Self::#variant }
435 }
436 }
437
438 impl FieldsExt for syn::DataStruct {
439 fn constructor(
440 &self,
441 name: &syn::Path,
442 values: impl IntoIterator<Item = syn::Ident>,
443 ) -> TokenStream {
444 self.fields.constructor(name, values)
445 }
446 }
447
448 impl<L: FieldsExt, R: FieldsExt> FieldsExt for Either<&L, &R> {
449 fn constructor(
450 &self,
451 name: &syn::Path,
452 values: impl IntoIterator<Item = syn::Ident>,
453 ) -> TokenStream {
454 match self {
455 Self::Left(l) => l.constructor(name, values),
456 Self::Right(r) => r.constructor(name, values),
457 }
458 }
459
460 fn self_ty(&self) -> syn::Path {
461 match self {
462 Self::Left(l) => l.self_ty(),
463 Self::Right(r) => r.self_ty(),
464 }
465 }
466 }
467
468 /// Representation of possible [`FromStr`] derive macro attributes placed on an enum or a struct for
469 /// a [`FlatExpansion`].
470 ///
471 /// ```rust,ignore
472 /// #[<attribute>(rename_all = "<casing>")]
473 /// #[<attribute>(error(<ty>))]
474 /// #[<attribute>(error(<ty>, <conv>))]
475 /// ```
476 ///
477 /// Both `#[<attribute>(rename_all = "<casing>")]` and `#[<attribute>(error(<ty>[, <conv>]))]` can
478 /// be specified only once.
479 #[derive(Default)]
480 struct FlatContainerAttributes {
481 /// [`attr::RenameAll`] for case conversion.
482 rename_all: Option<attr::RenameAll>,
483
484 /// [`attr::Error`] for conversion into a custom error type.
485 error: Option<attr::Error>,
486 }
487
488 impl Parse for FlatContainerAttributes {
489 fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
490 mod ident {
491 use syn::custom_keyword;
492
493 custom_keyword!(error);
494 custom_keyword!(rename_all);
495 }
496
497 let ahead = input.lookahead1();
498 if ahead.peek(ident::error) {
499 Ok(Self {
500 error: Some(input.parse()?),
501 ..Default::default()
502 })
503 } else if ahead.peek(ident::rename_all) {
504 Ok(Self {
505 rename_all: Some(input.parse()?),
506 ..Default::default()
507 })
508 } else {
509 Err(ahead.error())
510 }
511 }
512 }
513
514 impl attr::ParseMultiple for FlatContainerAttributes {
515 fn merge_attrs(
516 prev: Spanning<Self>,
517 new: Spanning<Self>,
518 name: &syn::Ident,
519 ) -> syn::Result<Spanning<Self>> {
520 let Spanning {
521 span: prev_span,
522 item: mut prev,
523 } = prev;
524 let Spanning {
525 span: new_span,
526 item: new,
527 } = new;
528
529 if new
530 .rename_all
531 .and_then(|n| prev.rename_all.replace(n))
532 .is_some()
533 {
534 return Err(syn::Error::new(
535 new_span,
536 format!("multiple `#[{name}(rename_all=\"...\")]` attributes aren't allowed"),
537 ));
538 }
539
540 if prev.error.is_some() && new.error.is_some() {
541 return Err(syn::Error::new(
542 new_span,
543 format!(
544 "multiple `#[{name}(error(\"...\")]` attributes aren't allowed",
545 ),
546 ));
547 }
548
549 prev.error = prev.error.or(new.error);
550
551 Ok(Spanning::new(
552 prev,
553 prev_span.join(new_span).unwrap_or(prev_span),
554 ))
555 }
556 }