1use crate::utils::{SingleFieldData, State};
2use proc_macro2::TokenStream;
3use quote::quote;
4use syn::{parse::Result, DeriveInput};
5
6/// Provides the hook to expand `#[derive(FromStr)]` into an implementation of `FromStr`
7pub fn expand(input: &DeriveInput, trait_name: &'static str) -> Result<TokenStream> {
8 let state = State::new(
9 input,
10 trait_name,
11 quote!(::core::str),
12 trait_name.to_lowercase(),
13 )?;
14
15 // We cannot set defaults for fields, once we do we can remove this check
16 if state.fields.len() != 1 || state.enabled_fields().len() != 1 {
17 panic_one_field(trait_name);
18 }
19
20 let single_field_data = state.assert_single_enabled_field();
21 let SingleFieldData {
22 input_type,
23 field_type,
24 trait_path,
25 casted_trait,
26 impl_generics,
27 ty_generics,
28 where_clause,
29 ..
30 } = single_field_data.clone();
31
32 let initializers = [quote!(#casted_trait::from_str(src)?)];
33 let body = single_field_data.initializer(&initializers);
34
35 Ok(quote! {
36 impl#impl_generics #trait_path for #input_type#ty_generics #where_clause
37 {
38 type Err = <#field_type as #trait_path>::Err;
39 #[inline]
40 fn from_str(src: &str) -> ::core::result::Result<Self, Self::Err> {
41 Ok(#body)
42 }
43 }
44 })
45}
46
47fn panic_one_field(trait_name: &str) -> ! {
48 panic!("Only structs with one field can derive({})", trait_name)
49}
50