| 1 |
//! Implementation of a [`From`] derive macro. |
| 2 |
|
| 3 |
use std::iter; |
| 4 |
|
| 5 |
use proc_macro2::{Span, TokenStream}; |
| 6 |
use quote::{format_ident, quote, ToTokens as _, TokenStreamExt as _}; |
| 7 |
use syn::{ |
| 8 |
parse::{discouraged::Speculative as _, Parse, ParseStream}, |
| 9 |
parse_quote, |
| 10 |
punctuated::Punctuated, |
| 11 |
spanned::Spanned as _, |
| 12 |
token, Ident, |
| 13 |
}; |
| 14 |
|
| 15 |
use crate::{ |
| 16 |
parsing::Type, |
| 17 |
utils::{polyfill, Either}, |
| 18 |
}; |
| 19 |
|
| 20 |
/// Expands a [`From`] derive macro. |
| 21 |
pub fn expand(input: &syn::DeriveInput, _: &'static str) -> syn::Result<TokenStream> { |
| 22 |
match &input.data { |
| 23 |
syn::Data::Struct(data) => Expansion { |
| 24 |
attrs: StructAttribute::parse_attrs(&input.attrs, &data.fields)? |
| 25 |
.map(Into::into) |
| 26 |
.as_ref(), |
| 27 |
ident: &input.ident, |
| 28 |
variant: None, |
| 29 |
fields: &data.fields, |
| 30 |
generics: &input.generics, |
| 31 |
has_explicit_from: false, |
| 32 |
} |
| 33 |
.expand(), |
| 34 |
syn::Data::Enum(data) => { |
| 35 |
let mut has_explicit_from = false; |
| 36 |
let attrs = data |
| 37 |
.variants |
| 38 |
.iter() |
| 39 |
.map(|variant| { |
| 40 |
let attrs = |
| 41 |
VariantAttribute::parse_attrs(&variant.attrs, &variant.fields)?; |
| 42 |
if matches!( |
| 43 |
attrs, |
| 44 |
Some( |
| 45 |
VariantAttribute::From |
| 46 |
| VariantAttribute::Types(_) |
| 47 |
| VariantAttribute::Forward |
| 48 |
), |
| 49 |
) { |
| 50 |
has_explicit_from = true; |
| 51 |
} |
| 52 |
Ok(attrs) |
| 53 |
}) |
| 54 |
.collect::<syn::Result<Vec<_>>>()?; |
| 55 |
|
| 56 |
data.variants |
| 57 |
.iter() |
| 58 |
.zip(&attrs) |
| 59 |
.map(|(variant, attrs)| { |
| 60 |
Expansion { |
| 61 |
attrs: attrs.as_ref(), |
| 62 |
ident: &input.ident, |
| 63 |
variant: Some(&variant.ident), |
| 64 |
fields: &variant.fields, |
| 65 |
generics: &input.generics, |
| 66 |
has_explicit_from, |
| 67 |
} |
| 68 |
.expand() |
| 69 |
}) |
| 70 |
.collect() |
| 71 |
} |
| 72 |
syn::Data::Union(data) => Err(syn::Error::new( |
| 73 |
data.union_token.span(), |
| 74 |
"`From` cannot be derived for unions", |
| 75 |
)), |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
/// Representation of a [`From`] derive macro struct container attribute. |
| 80 |
/// |
| 81 |
/// ```rust,ignore |
| 82 |
/// #[from(<types>)] |
| 83 |
/// #[from(forward)] |
| 84 |
/// ``` |
| 85 |
enum StructAttribute { |
| 86 |
/// [`Type`]s to derive [`From`]. |
| 87 |
Types(Punctuated<Type, token::Comma>), |
| 88 |
|
| 89 |
/// Forward [`From`] implementation. |
| 90 |
Forward, |
| 91 |
} |
| 92 |
|
| 93 |
impl StructAttribute { |
| 94 |
/// Parses a [`StructAttribute`] from the provided [`syn::Attribute`]s. |
| 95 |
fn parse_attrs( |
| 96 |
attrs: impl AsRef<[syn::Attribute]>, |
| 97 |
fields: &syn::Fields, |
| 98 |
) -> syn::Result<Option<Self>> { |
| 99 |
Ok(attrs |
| 100 |
.as_ref() |
| 101 |
.iter() |
| 102 |
.filter(|attr| attr.path().is_ident("from")) |
| 103 |
.try_fold(None, |attrs, attr| { |
| 104 |
let field_attr = attr.parse_args_with(|stream: ParseStream<'_>| { |
| 105 |
Self::parse(stream, fields) |
| 106 |
})?; |
| 107 |
match (attrs, field_attr) { |
| 108 |
( |
| 109 |
Some((path, StructAttribute::Types(mut tys))), |
| 110 |
StructAttribute::Types(more), |
| 111 |
) => { |
| 112 |
tys.extend(more); |
| 113 |
Ok(Some((path, StructAttribute::Types(tys)))) |
| 114 |
} |
| 115 |
(None, field_attr) => Ok(Some((attr.path(), field_attr))), |
| 116 |
_ => Err(syn::Error::new( |
| 117 |
attr.path().span(), |
| 118 |
"only single `#[from(...)]` attribute is allowed here", |
| 119 |
)), |
| 120 |
} |
| 121 |
})? |
| 122 |
.map(|(_, attr)| attr)) |
| 123 |
} |
| 124 |
|
| 125 |
/// Parses single [`StructAttribute`]. |
| 126 |
fn parse(input: ParseStream<'_>, fields: &syn::Fields) -> syn::Result<Self> { |
| 127 |
let ahead = input.fork(); |
| 128 |
match ahead.parse::<syn::Path>() { |
| 129 |
Ok(p) if p.is_ident("forward") => { |
| 130 |
input.advance_to(&ahead); |
| 131 |
Ok(Self::Forward) |
| 132 |
} |
| 133 |
Ok(p) if p.is_ident("types") => legacy_error(&ahead, input.span(), fields), |
| 134 |
_ => input |
| 135 |
.parse_terminated(Type::parse, token::Comma) |
| 136 |
.map(Self::Types), |
| 137 |
} |
| 138 |
} |
| 139 |
} |
| 140 |
|
| 141 |
/// Representation of a [`From`] derive macro enum variant attribute. |
| 142 |
/// |
| 143 |
/// ```rust,ignore |
| 144 |
/// #[from] |
| 145 |
/// #[from(<types>)] |
| 146 |
/// #[from(forward)] |
| 147 |
/// #[from(skip)] |
| 148 |
/// ``` |
| 149 |
enum VariantAttribute { |
| 150 |
/// Explicitly derive [`From`]. |
| 151 |
From, |
| 152 |
|
| 153 |
/// [`Type`]s to derive [`From`]. |
| 154 |
Types(Punctuated<Type, token::Comma>), |
| 155 |
|
| 156 |
/// Forward [`From`] implementation. |
| 157 |
Forward, |
| 158 |
|
| 159 |
/// Skip variant. |
| 160 |
Skip, |
| 161 |
} |
| 162 |
|
| 163 |
impl VariantAttribute { |
| 164 |
/// Parses a [`VariantAttribute`] from the provided [`syn::Attribute`]s. |
| 165 |
fn parse_attrs( |
| 166 |
attrs: impl AsRef<[syn::Attribute]>, |
| 167 |
fields: &syn::Fields, |
| 168 |
) -> syn::Result<Option<Self>> { |
| 169 |
Ok(attrs |
| 170 |
.as_ref() |
| 171 |
.iter() |
| 172 |
.filter(|attr| attr.path().is_ident("from")) |
| 173 |
.try_fold(None, |mut attrs, attr| { |
| 174 |
let field_attr = Self::parse_attr(attr, fields)?; |
| 175 |
if let Some((path, _)) = attrs.replace((attr.path(), field_attr)) { |
| 176 |
Err(syn::Error::new( |
| 177 |
path.span(), |
| 178 |
"only single `#[from(...)]` attribute is allowed here", |
| 179 |
)) |
| 180 |
} else { |
| 181 |
Ok(attrs) |
| 182 |
} |
| 183 |
})? |
| 184 |
.map(|(_, attr)| attr)) |
| 185 |
} |
| 186 |
|
| 187 |
/// Parses a [`VariantAttribute`] from the single provided [`syn::Attribute`]. |
| 188 |
fn parse_attr(attr: &syn::Attribute, fields: &syn::Fields) -> syn::Result<Self> { |
| 189 |
if matches!(attr.meta, syn::Meta::Path(_)) { |
| 190 |
return Ok(Self::From); |
| 191 |
} |
| 192 |
|
| 193 |
attr.parse_args_with(|input: ParseStream<'_>| { |
| 194 |
let ahead = input.fork(); |
| 195 |
match ahead.parse::<syn::Path>() { |
| 196 |
Ok(p) if p.is_ident("forward") => { |
| 197 |
input.advance_to(&ahead); |
| 198 |
Ok(Self::Forward) |
| 199 |
} |
| 200 |
Ok(p) if p.is_ident("skip") || p.is_ident("ignore") => { |
| 201 |
input.advance_to(&ahead); |
| 202 |
Ok(Self::Skip) |
| 203 |
} |
| 204 |
Ok(p) if p.is_ident("types") => { |
| 205 |
legacy_error(&ahead, input.span(), fields) |
| 206 |
} |
| 207 |
_ => input |
| 208 |
.parse_terminated(Type::parse, token::Comma) |
| 209 |
.map(Self::Types), |
| 210 |
} |
| 211 |
}) |
| 212 |
} |
| 213 |
} |
| 214 |
|
| 215 |
impl From<StructAttribute> for VariantAttribute { |
| 216 |
fn from(value: StructAttribute) -> Self { |
| 217 |
match value { |
| 218 |
StructAttribute::Types(tys) => Self::Types(tys), |
| 219 |
StructAttribute::Forward => Self::Forward, |
| 220 |
} |
| 221 |
} |
| 222 |
} |
| 223 |
|
| 224 |
/// Expansion of a macro for generating [`From`] implementation of a struct or |
| 225 |
/// enum. |
| 226 |
struct Expansion<'a> { |
| 227 |
/// [`From`] attributes. |
| 228 |
/// |
| 229 |
/// As a [`VariantAttribute`] is superset of a [`StructAttribute`], we use |
| 230 |
/// it for both derives. |
| 231 |
attrs: Option<&'a VariantAttribute>, |
| 232 |
|
| 233 |
/// Struct or enum [`Ident`]. |
| 234 |
ident: &'a Ident, |
| 235 |
|
| 236 |
/// Variant [`Ident`] in case of enum expansion. |
| 237 |
variant: Option<&'a Ident>, |
| 238 |
|
| 239 |
/// Struct or variant [`syn::Fields`]. |
| 240 |
fields: &'a syn::Fields, |
| 241 |
|
| 242 |
/// Struct or enum [`syn::Generics`]. |
| 243 |
generics: &'a syn::Generics, |
| 244 |
|
| 245 |
/// Indicator whether one of the enum variants has |
| 246 |
/// [`VariantAttribute::From`], [`VariantAttribute::Types`] or |
| 247 |
/// [`VariantAttribute::Forward`]. |
| 248 |
/// |
| 249 |
/// Always [`false`] for structs. |
| 250 |
has_explicit_from: bool, |
| 251 |
} |
| 252 |
|
| 253 |
impl<'a> Expansion<'a> { |
| 254 |
/// Expands [`From`] implementations for a struct or an enum variant. |
| 255 |
fn expand(&self) -> syn::Result<TokenStream> { |
| 256 |
use crate::utils::FieldsExt as _; |
| 257 |
|
| 258 |
let ident = self.ident; |
| 259 |
let field_tys = self.fields.iter().map(|f| &f.ty).collect::<Vec<_>>(); |
| 260 |
let (impl_gens, ty_gens, where_clause) = self.generics.split_for_impl(); |
| 261 |
|
| 262 |
let skip_variant = self.has_explicit_from |
| 263 |
|| (self.variant.is_some() && self.fields.is_empty()); |
| 264 |
match (self.attrs, skip_variant) { |
| 265 |
(Some(VariantAttribute::Types(tys)), _) => { |
| 266 |
tys.iter().map(|ty| { |
| 267 |
let variant = self.variant.iter(); |
| 268 |
|
| 269 |
let mut from_tys = self.fields.validate_type(ty)?; |
| 270 |
let init = self.expand_fields(|ident, ty, index| { |
| 271 |
let ident = ident.into_iter(); |
| 272 |
let index = index.into_iter(); |
| 273 |
let from_ty = from_tys.next().unwrap_or_else(|| unreachable!()); |
| 274 |
quote! { |
| 275 |
#( #ident: )* <#ty as ::core::convert::From<#from_ty>>::from( |
| 276 |
value #( .#index )* |
| 277 |
), |
| 278 |
} |
| 279 |
}); |
| 280 |
|
| 281 |
Ok(quote! { |
| 282 |
#[automatically_derived] |
| 283 |
impl #impl_gens ::core::convert::From<#ty> |
| 284 |
for #ident #ty_gens #where_clause |
| 285 |
{ |
| 286 |
#[inline] |
| 287 |
fn from(value: #ty) -> Self { |
| 288 |
#ident #( :: #variant )* #init |
| 289 |
} |
| 290 |
} |
| 291 |
}) |
| 292 |
}) |
| 293 |
.collect() |
| 294 |
} |
| 295 |
(Some(VariantAttribute::From), _) | (None, false) => { |
| 296 |
let variant = self.variant.iter(); |
| 297 |
let init = self.expand_fields(|ident, _, index| { |
| 298 |
let ident = ident.into_iter(); |
| 299 |
let index = index.into_iter(); |
| 300 |
quote! { #( #ident: )* value #( . #index )*, } |
| 301 |
}); |
| 302 |
|
| 303 |
Ok(quote! { |
| 304 |
#[automatically_derived] |
| 305 |
impl #impl_gens ::core::convert::From<(#( #field_tys ),*)> |
| 306 |
for #ident #ty_gens #where_clause |
| 307 |
{ |
| 308 |
#[inline] |
| 309 |
fn from(value: (#( #field_tys ),*)) -> Self { |
| 310 |
#ident #( :: #variant )* #init |
| 311 |
} |
| 312 |
} |
| 313 |
}) |
| 314 |
} |
| 315 |
(Some(VariantAttribute::Forward), _) => { |
| 316 |
let mut i = 0; |
| 317 |
let mut gen_idents = Vec::with_capacity(self.fields.len()); |
| 318 |
let init = self.expand_fields(|ident, ty, index| { |
| 319 |
let ident = ident.into_iter(); |
| 320 |
let index = index.into_iter(); |
| 321 |
let gen_ident = format_ident!("__FromT{i}"); |
| 322 |
let out = quote! { |
| 323 |
#( #ident: )* <#ty as ::core::convert::From<#gen_ident>>::from( |
| 324 |
value #( .#index )* |
| 325 |
), |
| 326 |
}; |
| 327 |
gen_idents.push(gen_ident); |
| 328 |
i += 1; |
| 329 |
out |
| 330 |
}); |
| 331 |
|
| 332 |
let variant = self.variant.iter(); |
| 333 |
let generics = { |
| 334 |
let mut generics = self.generics.clone(); |
| 335 |
for (ty, ident) in field_tys.iter().zip(&gen_idents) { |
| 336 |
generics.make_where_clause().predicates.push( |
| 337 |
parse_quote! { #ty: ::core::convert::From<#ident> }, |
| 338 |
); |
| 339 |
generics |
| 340 |
.params |
| 341 |
.push(syn::TypeParam::from(ident.clone()).into()); |
| 342 |
} |
| 343 |
generics |
| 344 |
}; |
| 345 |
let (impl_gens, _, where_clause) = generics.split_for_impl(); |
| 346 |
|
| 347 |
Ok(quote! { |
| 348 |
#[automatically_derived] |
| 349 |
impl #impl_gens ::core::convert::From<(#( #gen_idents ),*)> |
| 350 |
for #ident #ty_gens #where_clause |
| 351 |
{ |
| 352 |
#[inline] |
| 353 |
fn from(value: (#( #gen_idents ),*)) -> Self { |
| 354 |
#ident #(:: #variant)* #init |
| 355 |
} |
| 356 |
} |
| 357 |
}) |
| 358 |
} |
| 359 |
(Some(VariantAttribute::Skip), _) | (None, true) => { |
| 360 |
Ok(TokenStream::new()) |
| 361 |
} |
| 362 |
} |
| 363 |
} |
| 364 |
|
| 365 |
/// Expands fields initialization wrapped into [`token::Brace`]s in case of |
| 366 |
/// [`syn::FieldsNamed`], or [`token::Paren`] in case of |
| 367 |
/// [`syn::FieldsUnnamed`]. |
| 368 |
fn expand_fields( |
| 369 |
&self, |
| 370 |
mut wrap: impl FnMut(Option<&Ident>, &syn::Type, Option<syn::Index>) -> TokenStream, |
| 371 |
) -> TokenStream { |
| 372 |
let surround = match self.fields { |
| 373 |
syn::Fields::Named(_) | syn::Fields::Unnamed(_) => { |
| 374 |
Some(|tokens| match self.fields { |
| 375 |
syn::Fields::Named(named) => { |
| 376 |
let mut out = TokenStream::new(); |
| 377 |
named |
| 378 |
.brace_token |
| 379 |
.surround(&mut out, |out| out.append_all(tokens)); |
| 380 |
out |
| 381 |
} |
| 382 |
syn::Fields::Unnamed(unnamed) => { |
| 383 |
let mut out = TokenStream::new(); |
| 384 |
unnamed |
| 385 |
.paren_token |
| 386 |
.surround(&mut out, |out| out.append_all(tokens)); |
| 387 |
out |
| 388 |
} |
| 389 |
syn::Fields::Unit => unreachable!(), |
| 390 |
}) |
| 391 |
} |
| 392 |
syn::Fields::Unit => None, |
| 393 |
}; |
| 394 |
|
| 395 |
surround |
| 396 |
.map(|surround| { |
| 397 |
surround(if self.fields.len() == 1 { |
| 398 |
let field = self |
| 399 |
.fields |
| 400 |
.iter() |
| 401 |
.next() |
| 402 |
.unwrap_or_else(|| unreachable!("self.fields.len() == 1")); |
| 403 |
wrap(field.ident.as_ref(), &field.ty, None) |
| 404 |
} else { |
| 405 |
self.fields |
| 406 |
.iter() |
| 407 |
.enumerate() |
| 408 |
.map(|(i, field)| { |
| 409 |
wrap(field.ident.as_ref(), &field.ty, Some(i.into())) |
| 410 |
}) |
| 411 |
.collect() |
| 412 |
}) |
| 413 |
}) |
| 414 |
.unwrap_or_default() |
| 415 |
} |
| 416 |
} |
| 417 |
|
| 418 |
/// Constructs a [`syn::Error`] for legacy syntax: `#[from(types(i32, "&str"))]`. |
| 419 |
fn legacy_error<T>( |
| 420 |
tokens: ParseStream<'_>, |
| 421 |
span: Span, |
| 422 |
fields: &syn::Fields, |
| 423 |
) -> syn::Result<T> { |
| 424 |
let content; |
| 425 |
syn::parenthesized!(content in tokens); |
| 426 |
|
| 427 |
let types = content |
| 428 |
.parse_terminated(polyfill::NestedMeta::parse, token::Comma)? |
| 429 |
.into_iter() |
| 430 |
.map(|meta| { |
| 431 |
let value = match meta { |
| 432 |
polyfill::NestedMeta::Meta(meta) => { |
| 433 |
meta.into_token_stream().to_string() |
| 434 |
} |
| 435 |
polyfill::NestedMeta::Lit(syn::Lit::Str(str)) => str.value(), |
| 436 |
polyfill::NestedMeta::Lit(_) => unreachable!(), |
| 437 |
}; |
| 438 |
if fields.len() > 1 { |
| 439 |
format!( |
| 440 |
"({})", |
| 441 |
fields |
| 442 |
.iter() |
| 443 |
.map(|_| value.clone()) |
| 444 |
.collect::<Vec<_>>() |
| 445 |
.join(", "), |
| 446 |
) |
| 447 |
} else { |
| 448 |
value |
| 449 |
} |
| 450 |
}) |
| 451 |
.chain(match fields.len() { |
| 452 |
0 => Either::Left(iter::empty()), |
| 453 |
1 => Either::Right(iter::once( |
| 454 |
fields |
| 455 |
.iter() |
| 456 |
.next() |
| 457 |
.unwrap_or_else(|| unreachable!("fields.len() == 1")) |
| 458 |
.ty |
| 459 |
.to_token_stream() |
| 460 |
.to_string(), |
| 461 |
)), |
| 462 |
_ => Either::Right(iter::once(format!( |
| 463 |
"({})", |
| 464 |
fields |
| 465 |
.iter() |
| 466 |
.map(|f| f.ty.to_token_stream().to_string()) |
| 467 |
.collect::<Vec<_>>() |
| 468 |
.join(", ") |
| 469 |
))), |
| 470 |
}) |
| 471 |
.collect::<Vec<_>>() |
| 472 |
.join(", "); |
| 473 |
|
| 474 |
Err(syn::Error::new( |
| 475 |
span, |
| 476 |
format!("legacy syntax, remove `types` and use `{types}` instead"), |
| 477 |
)) |
| 478 |
} |