| 1 |
use crate::utils::{ |
| 2 |
add_extra_generic_param, numbered_vars, replace_self::DeriveInputExt as _, |
| 3 |
AttrParams, DeriveType, MultiFieldData, State, |
| 4 |
}; |
| 5 |
use proc_macro2::TokenStream; |
| 6 |
use quote::{format_ident, quote, ToTokens}; |
| 7 |
|
| 8 |
use crate::utils::{ |
| 9 |
attr::{self, ParseMultiple as _}, |
| 10 |
HashMap, Spanning, |
| 11 |
}; |
| 12 |
|
| 13 |
/// Provides the hook to expand `#[derive(TryInto)]` into an implementation of `TryInto`. |
| 14 |
#[allow(clippy::cognitive_complexity)] |
| 15 |
pub fn expand( |
| 16 |
input: &syn::DeriveInput, |
| 17 |
trait_name: &'static str, |
| 18 |
) -> syn::Result<TokenStream> { |
| 19 |
let input = &mut input.replace_self_type(); |
| 20 |
let trait_attr = "try_into"; |
| 21 |
|
| 22 |
// TODO: Use `Vec::extract_if` once MSRV is bumped to 1.87 or above. |
| 23 |
let (error_indices, error_attrs) = input |
| 24 |
.attrs |
| 25 |
.iter() |
| 26 |
.enumerate() |
| 27 |
.filter(|(_, attr)| { |
| 28 |
attr.path().is_ident(trait_attr) |
| 29 |
&& attr.parse_args_with(detect_error_attr).is_ok() |
| 30 |
}) |
| 31 |
.map(|(i, attr)| (i, attr.clone())) |
| 32 |
.unzip::<_, _, Vec<_>, Vec<_>>(); |
| 33 |
for i in error_indices { |
| 34 |
_ = &mut input.attrs.remove(i); |
| 35 |
} |
| 36 |
let custom_error = |
| 37 |
attr::Error::parse_attrs(error_attrs, &format_ident!("{trait_attr}"))? |
| 38 |
.map(Spanning::into_inner); |
| 39 |
|
| 40 |
let state = State::with_attr_params( |
| 41 |
input, |
| 42 |
trait_name, |
| 43 |
trait_attr.into(), |
| 44 |
AttrParams { |
| 45 |
enum_: vec!["ignore", "owned", "ref", "ref_mut"], |
| 46 |
variant: vec!["ignore", "owned", "ref", "ref_mut"], |
| 47 |
struct_: vec!["ignore", "owned", "ref", "ref_mut"], |
| 48 |
field: vec!["ignore"], |
| 49 |
}, |
| 50 |
).map_err(|e| { |
| 51 |
// Temporary adjustment of attribute parsing errors until these attributes are reimplemented |
| 52 |
// via `utils::attr` machinery. |
| 53 |
let msg = &e.to_string(); |
| 54 |
if msg == "Only a single attribute is allowed" { |
| 55 |
syn::Error::new( |
| 56 |
e.span(), |
| 57 |
"Only a single attribute is allowed.\n\ |
| 58 |
For the top-level attribute, an additional `#[try_into(error(...))]` may be \ |
| 59 |
provided.", |
| 60 |
) |
| 61 |
} else if msg.starts_with( |
| 62 |
"Attribute parameter not supported. Supported attribute parameters are:", |
| 63 |
) { |
| 64 |
syn::Error::new(e.span(), format!("{msg}, error")) |
| 65 |
} else { |
| 66 |
e |
| 67 |
} |
| 68 |
})?; |
| 69 |
assert!( |
| 70 |
state.derive_type == DeriveType::Enum, |
| 71 |
"only enums can derive `TryInto`", |
| 72 |
); |
| 73 |
|
| 74 |
let mut variants_per_types = HashMap::default(); |
| 75 |
|
| 76 |
for variant_state in state.enabled_variant_data().variant_states { |
| 77 |
let multi_field_data = variant_state.enabled_fields_data(); |
| 78 |
let MultiFieldData { |
| 79 |
variant_info, |
| 80 |
field_types, |
| 81 |
.. |
| 82 |
} = multi_field_data.clone(); |
| 83 |
for ref_type in variant_info.ref_types() { |
| 84 |
variants_per_types |
| 85 |
.entry((ref_type, field_types.clone())) |
| 86 |
.or_insert_with(Vec::new) |
| 87 |
.push(multi_field_data.clone()); |
| 88 |
} |
| 89 |
} |
| 90 |
|
| 91 |
let mut tokens = TokenStream::new(); |
| 92 |
|
| 93 |
for ((ref_type, ref original_types), ref multi_field_data) in variants_per_types { |
| 94 |
let input_type = &input.ident; |
| 95 |
|
| 96 |
let pattern_ref = ref_type.pattern_ref(); |
| 97 |
let lifetime = ref_type.lifetime(); |
| 98 |
let reference_with_lifetime = ref_type.reference_with_lifetime(); |
| 99 |
|
| 100 |
let mut matchers = vec![]; |
| 101 |
let vars = &numbered_vars(original_types.len(), ""); |
| 102 |
for multi_field_data in multi_field_data { |
| 103 |
let patterns: Vec<_> = vars |
| 104 |
.iter() |
| 105 |
.map(|var| quote! { #pattern_ref #var }) |
| 106 |
.collect(); |
| 107 |
matchers.push( |
| 108 |
multi_field_data.matcher(&multi_field_data.field_indexes, &patterns), |
| 109 |
); |
| 110 |
} |
| 111 |
|
| 112 |
let vars = if vars.len() == 1 { |
| 113 |
quote! { #(#vars)* } |
| 114 |
} else { |
| 115 |
quote! { (#(#vars),*) } |
| 116 |
}; |
| 117 |
|
| 118 |
let output_type = if original_types.len() == 1 { |
| 119 |
quote! { #(#original_types)* }.to_string() |
| 120 |
} else { |
| 121 |
let types = original_types |
| 122 |
.iter() |
| 123 |
.map(|t| quote! { #t }.to_string()) |
| 124 |
.collect::<Vec<_>>(); |
| 125 |
format!("({})", types.join(", ")) |
| 126 |
}; |
| 127 |
let variant_names = multi_field_data |
| 128 |
.iter() |
| 129 |
.map(|d| { |
| 130 |
d.variant_name |
| 131 |
.expect("somehow there was no variant name") |
| 132 |
.to_string() |
| 133 |
}) |
| 134 |
.collect::<Vec<_>>() |
| 135 |
.join(", "); |
| 136 |
|
| 137 |
let generics_impl; |
| 138 |
let (_, ty_generics, where_clause) = input.generics.split_for_impl(); |
| 139 |
let (impl_generics, _, _) = if ref_type.is_ref() { |
| 140 |
generics_impl = add_extra_generic_param(&input.generics, lifetime.clone()); |
| 141 |
generics_impl.split_for_impl() |
| 142 |
} else { |
| 143 |
input.generics.split_for_impl() |
| 144 |
}; |
| 145 |
|
| 146 |
let mut error_ty = quote! { |
| 147 |
derive_more::TryIntoError<#reference_with_lifetime #input_type #ty_generics> |
| 148 |
}; |
| 149 |
let mut error_conv = quote! {}; |
| 150 |
if let Some(custom_error) = custom_error.as_ref() { |
| 151 |
error_ty = custom_error.ty.to_token_stream(); |
| 152 |
error_conv = custom_error.conv.as_ref().map_or_else( |
| 153 |
|| quote! { .map_err(derive_more::core::convert::Into::into) }, |
| 154 |
|conv| quote! { .map_err(#conv) }, |
| 155 |
); |
| 156 |
} |
| 157 |
|
| 158 |
let try_from = quote! { |
| 159 |
#[automatically_derived] |
| 160 |
impl #impl_generics derive_more::core::convert::TryFrom< |
| 161 |
#reference_with_lifetime #input_type #ty_generics |
| 162 |
> for (#(#reference_with_lifetime #original_types),*) #where_clause { |
| 163 |
type Error = #error_ty; |
| 164 |
|
| 165 |
#[inline] |
| 166 |
fn try_from( |
| 167 |
value: #reference_with_lifetime #input_type #ty_generics, |
| 168 |
) -> derive_more::core::result::Result<Self, #error_ty> { |
| 169 |
match value { |
| 170 |
#(#matchers)|* => derive_more::core::result::Result::Ok(#vars), |
| 171 |
_ => derive_more::core::result::Result::Err( |
| 172 |
derive_more::TryIntoError::new(value, #variant_names, #output_type), |
| 173 |
)#error_conv, |
| 174 |
} |
| 175 |
} |
| 176 |
} |
| 177 |
}; |
| 178 |
try_from.to_tokens(&mut tokens) |
| 179 |
} |
| 180 |
Ok(tokens) |
| 181 |
} |
| 182 |
|
| 183 |
/// Checks whether the inner of a [`syn::Attribute`] represents an [`attr::Error`]. |
| 184 |
fn detect_error_attr(input: syn::parse::ParseStream) -> syn::Result<()> { |
| 185 |
mod ident { |
| 186 |
syn::custom_keyword!(error); |
| 187 |
} |
| 188 |
|
| 189 |
let ahead = input.lookahead1(); |
| 190 |
if ahead.peek(ident::error) { |
| 191 |
let _ = input.parse::<TokenStream>(); |
| 192 |
Ok(()) |
| 193 |
} else { |
| 194 |
Err(ahead.error()) |
| 195 |
} |
| 196 |
} |