| 1 |
//! Implementation of an [`Into`] derive macro. |
| 2 |
|
| 3 |
use std::{borrow::Cow, iter}; |
| 4 |
|
| 5 |
use proc_macro2::{Span, TokenStream}; |
| 6 |
use quote::{quote, ToTokens as _}; |
| 7 |
use syn::{ |
| 8 |
ext::IdentExt as _, |
| 9 |
parse::{discouraged::Speculative as _, Parse, ParseStream}, |
| 10 |
punctuated::Punctuated, |
| 11 |
spanned::Spanned as _, |
| 12 |
token, Ident, |
| 13 |
}; |
| 14 |
|
| 15 |
use crate::{ |
| 16 |
parsing::Type, |
| 17 |
utils::{polyfill, Either, FieldsExt as _}, |
| 18 |
}; |
| 19 |
|
| 20 |
/// Expands an [`Into`] derive macro. |
| 21 |
pub fn expand(input: &syn::DeriveInput, _: &'static str) -> syn::Result<TokenStream> { |
| 22 |
let data = match &input.data { |
| 23 |
syn::Data::Struct(data) => Ok(data), |
| 24 |
syn::Data::Enum(e) => Err(syn::Error::new( |
| 25 |
e.enum_token.span(), |
| 26 |
"`Into` cannot be derived for enums", |
| 27 |
)), |
| 28 |
syn::Data::Union(u) => Err(syn::Error::new( |
| 29 |
u.union_token.span(), |
| 30 |
"`Into` cannot be derived for unions", |
| 31 |
)), |
| 32 |
}?; |
| 33 |
|
| 34 |
let attr = StructAttribute::parse_attrs(&input.attrs, &data.fields)? |
| 35 |
.unwrap_or_else(|| StructAttribute { |
| 36 |
owned: Some(Punctuated::new()), |
| 37 |
r#ref: None, |
| 38 |
ref_mut: None, |
| 39 |
}); |
| 40 |
let ident = &input.ident; |
| 41 |
let fields = data |
| 42 |
.fields |
| 43 |
.iter() |
| 44 |
.enumerate() |
| 45 |
.filter_map(|(i, f)| match SkipFieldAttribute::parse_attrs(&f.attrs) { |
| 46 |
Ok(None) => Some(Ok(( |
| 47 |
&f.ty, |
| 48 |
f.ident |
| 49 |
.as_ref() |
| 50 |
.map_or_else(|| Either::Right(syn::Index::from(i)), Either::Left), |
| 51 |
))), |
| 52 |
Ok(Some(_)) => None, |
| 53 |
Err(e) => Some(Err(e)), |
| 54 |
}) |
| 55 |
.collect::<syn::Result<Vec<_>>>()?; |
| 56 |
let (fields_tys, fields_idents): (Vec<_>, Vec<_>) = fields.into_iter().unzip(); |
| 57 |
let (fields_tys, fields_idents) = (&fields_tys, &fields_idents); |
| 58 |
|
| 59 |
let expand = |tys: Option<Punctuated<_, _>>, r: bool, m: bool| { |
| 60 |
let Some(tys) = tys else { |
| 61 |
return Either::Left(iter::empty()); |
| 62 |
}; |
| 63 |
|
| 64 |
let lf = |
| 65 |
r.then(|| syn::Lifetime::new("'__derive_more_into", Span::call_site())); |
| 66 |
let r = r.then(token::And::default); |
| 67 |
let m = m.then(token::Mut::default); |
| 68 |
|
| 69 |
let gens = if let Some(lf) = lf.clone() { |
| 70 |
let mut gens = input.generics.clone(); |
| 71 |
gens.params.push(syn::LifetimeParam::new(lf).into()); |
| 72 |
Cow::Owned(gens) |
| 73 |
} else { |
| 74 |
Cow::Borrowed(&input.generics) |
| 75 |
}; |
| 76 |
|
| 77 |
Either::Right( |
| 78 |
if tys.is_empty() { |
| 79 |
Either::Left(iter::once(Type::tuple(fields_tys.clone()))) |
| 80 |
} else { |
| 81 |
Either::Right(tys.into_iter()) |
| 82 |
} |
| 83 |
.map(move |ty| { |
| 84 |
let tys = fields_tys.validate_type(&ty)?.collect::<Vec<_>>(); |
| 85 |
let (impl_gens, _, where_clause) = gens.split_for_impl(); |
| 86 |
let (_, ty_gens, _) = input.generics.split_for_impl(); |
| 87 |
|
| 88 |
Ok(quote! { |
| 89 |
#[automatically_derived] |
| 90 |
impl #impl_gens ::core::convert::From<#r #lf #m #ident #ty_gens> |
| 91 |
for ( #( #r #lf #m #tys ),* ) #where_clause |
| 92 |
{ |
| 93 |
#[inline] |
| 94 |
fn from(value: #r #lf #m #ident #ty_gens) -> Self { |
| 95 |
(#( |
| 96 |
<#r #m #tys as ::core::convert::From<_>>::from( |
| 97 |
#r #m value. #fields_idents |
| 98 |
) |
| 99 |
),*) |
| 100 |
} |
| 101 |
} |
| 102 |
}) |
| 103 |
}), |
| 104 |
) |
| 105 |
}; |
| 106 |
|
| 107 |
[ |
| 108 |
expand(attr.owned, false, false), |
| 109 |
expand(attr.r#ref, true, false), |
| 110 |
expand(attr.ref_mut, true, true), |
| 111 |
] |
| 112 |
.into_iter() |
| 113 |
.flatten() |
| 114 |
.collect() |
| 115 |
} |
| 116 |
|
| 117 |
/// Representation of an [`Into`] derive macro struct container attribute. |
| 118 |
/// |
| 119 |
/// ```rust,ignore |
| 120 |
/// #[into(<types>)] |
| 121 |
/// #[into(owned(<types>), ref(<types>), ref_mut(<types>))] |
| 122 |
/// ``` |
| 123 |
#[derive(Debug, Default)] |
| 124 |
struct StructAttribute { |
| 125 |
/// [`Type`]s wrapped into `owned(...)` or simply `#[into(...)]`. |
| 126 |
owned: Option<Punctuated<Type, token::Comma>>, |
| 127 |
|
| 128 |
/// [`Type`]s wrapped into `ref(...)`. |
| 129 |
r#ref: Option<Punctuated<Type, token::Comma>>, |
| 130 |
|
| 131 |
/// [`Type`]s wrapped into `ref_mut(...)`. |
| 132 |
ref_mut: Option<Punctuated<Type, token::Comma>>, |
| 133 |
} |
| 134 |
|
| 135 |
impl StructAttribute { |
| 136 |
/// Parses a [`StructAttribute`] from the provided [`syn::Attribute`]s. |
| 137 |
fn parse_attrs( |
| 138 |
attrs: impl AsRef<[syn::Attribute]>, |
| 139 |
fields: &syn::Fields, |
| 140 |
) -> syn::Result<Option<Self>> { |
| 141 |
fn infer<T>(v: T) -> T |
| 142 |
where |
| 143 |
T: for<'a> FnOnce(ParseStream<'a>) -> syn::Result<StructAttribute>, |
| 144 |
{ |
| 145 |
v |
| 146 |
} |
| 147 |
|
| 148 |
attrs |
| 149 |
.as_ref() |
| 150 |
.iter() |
| 151 |
.filter(|attr| attr.path().is_ident("into")) |
| 152 |
.try_fold(None, |mut attrs, attr| { |
| 153 |
let merge = |out: &mut Option<_>, tys| match (out.as_mut(), tys) { |
| 154 |
(None, Some(tys)) => { |
| 155 |
*out = Some::<Punctuated<_, _>>(tys); |
| 156 |
} |
| 157 |
(Some(out), Some(tys)) => out.extend(tys), |
| 158 |
(Some(_), None) | (None, None) => {} |
| 159 |
}; |
| 160 |
|
| 161 |
let field_attr = |
| 162 |
attr.parse_args_with(infer(|stream| Self::parse(stream, fields)))?; |
| 163 |
let out = attrs.get_or_insert_with(Self::default); |
| 164 |
merge(&mut out.owned, field_attr.owned); |
| 165 |
merge(&mut out.r#ref, field_attr.r#ref); |
| 166 |
merge(&mut out.ref_mut, field_attr.ref_mut); |
| 167 |
|
| 168 |
Ok(attrs) |
| 169 |
}) |
| 170 |
} |
| 171 |
|
| 172 |
/// Parses a single [`StructAttribute`]. |
| 173 |
fn parse(content: ParseStream<'_>, fields: &syn::Fields) -> syn::Result<Self> { |
| 174 |
check_legacy_syntax(content, fields)?; |
| 175 |
|
| 176 |
let mut out = Self::default(); |
| 177 |
|
| 178 |
let parse_inner = |ahead, types: &mut Option<_>| { |
| 179 |
content.advance_to(&ahead); |
| 180 |
|
| 181 |
let types = types.get_or_insert_with(Punctuated::new); |
| 182 |
if content.peek(token::Paren) { |
| 183 |
let inner; |
| 184 |
syn::parenthesized!(inner in content); |
| 185 |
|
| 186 |
types.extend( |
| 187 |
inner |
| 188 |
.parse_terminated(Type::parse, token::Comma)? |
| 189 |
.into_pairs(), |
| 190 |
); |
| 191 |
} |
| 192 |
if content.peek(token::Comma) { |
| 193 |
let comma = content.parse::<token::Comma>()?; |
| 194 |
if !types.empty_or_trailing() { |
| 195 |
types.push_punct(comma); |
| 196 |
} |
| 197 |
} |
| 198 |
|
| 199 |
Ok(()) |
| 200 |
}; |
| 201 |
|
| 202 |
let mut has_wrapped_type = false; |
| 203 |
let mut top_level_type = None; |
| 204 |
|
| 205 |
while !content.is_empty() { |
| 206 |
let ahead = content.fork(); |
| 207 |
let res = if ahead.peek(Ident::peek_any) { |
| 208 |
ahead.call(Ident::parse_any).map(Into::into) |
| 209 |
} else { |
| 210 |
ahead.parse::<syn::Path>() |
| 211 |
}; |
| 212 |
match res { |
| 213 |
Ok(p) if p.is_ident("owned") => { |
| 214 |
has_wrapped_type = true; |
| 215 |
parse_inner(ahead, &mut out.owned)?; |
| 216 |
} |
| 217 |
Ok(p) if p.is_ident("ref") => { |
| 218 |
has_wrapped_type = true; |
| 219 |
parse_inner(ahead, &mut out.r#ref)?; |
| 220 |
} |
| 221 |
Ok(p) if p.is_ident("ref_mut") => { |
| 222 |
has_wrapped_type = true; |
| 223 |
parse_inner(ahead, &mut out.ref_mut)?; |
| 224 |
} |
| 225 |
_ => { |
| 226 |
let ty = content.parse::<Type>()?; |
| 227 |
let _ = top_level_type.get_or_insert_with(|| ty.clone()); |
| 228 |
out.owned.get_or_insert_with(Punctuated::new).push_value(ty); |
| 229 |
|
| 230 |
if content.peek(token::Comma) { |
| 231 |
out.owned |
| 232 |
.get_or_insert_with(Punctuated::new) |
| 233 |
.push_punct(content.parse::<token::Comma>()?) |
| 234 |
} |
| 235 |
} |
| 236 |
} |
| 237 |
} |
| 238 |
|
| 239 |
if let Some(ty) = top_level_type.filter(|_| has_wrapped_type) { |
| 240 |
Err(syn::Error::new( |
| 241 |
ty.span(), |
| 242 |
format!( |
| 243 |
"mixing regular types with wrapped into \ |
| 244 |
`owned`/`ref`/`ref_mut` is not allowed, try wrapping \ |
| 245 |
this type into `owned({ty}), ref({ty}), ref_mut({ty})`", |
| 246 |
ty = ty.into_token_stream(), |
| 247 |
), |
| 248 |
)) |
| 249 |
} else { |
| 250 |
Ok(out) |
| 251 |
} |
| 252 |
} |
| 253 |
} |
| 254 |
|
| 255 |
/// `#[into(skip)]` field attribute. |
| 256 |
struct SkipFieldAttribute; |
| 257 |
|
| 258 |
impl SkipFieldAttribute { |
| 259 |
/// Parses a [`SkipFieldAttribute`] from the provided [`syn::Attribute`]s. |
| 260 |
fn parse_attrs(attrs: impl AsRef<[syn::Attribute]>) -> syn::Result<Option<Self>> { |
| 261 |
Ok(attrs |
| 262 |
.as_ref() |
| 263 |
.iter() |
| 264 |
.filter(|attr| attr.path().is_ident("into")) |
| 265 |
.try_fold(None, |mut attrs, attr| { |
| 266 |
let field_attr = attr.parse_args::<SkipFieldAttribute>()?; |
| 267 |
if let Some((path, _)) = attrs.replace((attr.path(), field_attr)) { |
| 268 |
Err(syn::Error::new( |
| 269 |
path.span(), |
| 270 |
"only single `#[into(...)]` attribute is allowed here", |
| 271 |
)) |
| 272 |
} else { |
| 273 |
Ok(attrs) |
| 274 |
} |
| 275 |
})? |
| 276 |
.map(|(_, attr)| attr)) |
| 277 |
} |
| 278 |
} |
| 279 |
|
| 280 |
impl Parse for SkipFieldAttribute { |
| 281 |
fn parse(content: ParseStream) -> syn::Result<Self> { |
| 282 |
match content.parse::<syn::Path>()? { |
| 283 |
p if p.is_ident("skip") | p.is_ident("ignore") => Ok(Self), |
| 284 |
p => Err(syn::Error::new( |
| 285 |
p.span(), |
| 286 |
format!("expected `skip`, found: `{}`", p.into_token_stream()), |
| 287 |
)), |
| 288 |
} |
| 289 |
} |
| 290 |
} |
| 291 |
|
| 292 |
/// [`Error`]ors for legacy syntax: `#[into(types(i32, "&str"))]`. |
| 293 |
fn check_legacy_syntax( |
| 294 |
tokens: ParseStream<'_>, |
| 295 |
fields: &syn::Fields, |
| 296 |
) -> syn::Result<()> { |
| 297 |
let span = tokens.span(); |
| 298 |
let tokens = tokens.fork(); |
| 299 |
|
| 300 |
let map_ty = |s: String| { |
| 301 |
if fields.len() > 1 { |
| 302 |
format!( |
| 303 |
"({})", |
| 304 |
(0..fields.len()) |
| 305 |
.map(|_| s.as_str()) |
| 306 |
.collect::<Vec<_>>() |
| 307 |
.join(", ") |
| 308 |
) |
| 309 |
} else { |
| 310 |
s |
| 311 |
} |
| 312 |
}; |
| 313 |
let field = match fields.len() { |
| 314 |
0 => None, |
| 315 |
1 => Some( |
| 316 |
fields |
| 317 |
.iter() |
| 318 |
.next() |
| 319 |
.unwrap_or_else(|| unreachable!("fields.len() == 1")) |
| 320 |
.ty |
| 321 |
.to_token_stream() |
| 322 |
.to_string(), |
| 323 |
), |
| 324 |
_ => Some(format!( |
| 325 |
"({})", |
| 326 |
fields |
| 327 |
.iter() |
| 328 |
.map(|f| f.ty.to_token_stream().to_string()) |
| 329 |
.collect::<Vec<_>>() |
| 330 |
.join(", ") |
| 331 |
)), |
| 332 |
}; |
| 333 |
|
| 334 |
let Ok(metas) = tokens.parse_terminated(polyfill::Meta::parse, token::Comma) else { |
| 335 |
return Ok(()); |
| 336 |
}; |
| 337 |
|
| 338 |
let parse_list = |list: polyfill::MetaList, attrs: &mut Option<Vec<_>>| { |
| 339 |
if !list.path.is_ident("types") { |
| 340 |
return None; |
| 341 |
} |
| 342 |
for meta in list |
| 343 |
.parse_args_with(Punctuated::<_, token::Comma>::parse_terminated) |
| 344 |
.ok()? |
| 345 |
{ |
| 346 |
attrs.get_or_insert_with(Vec::new).push(match meta { |
| 347 |
polyfill::NestedMeta::Lit(syn::Lit::Str(str)) => str.value(), |
| 348 |
polyfill::NestedMeta::Meta(polyfill::Meta::Path(path)) => { |
| 349 |
path.into_token_stream().to_string() |
| 350 |
} |
| 351 |
_ => return None, |
| 352 |
}) |
| 353 |
} |
| 354 |
Some(()) |
| 355 |
}; |
| 356 |
|
| 357 |
let Some((top_level, owned, ref_, ref_mut)) = metas |
| 358 |
.into_iter() |
| 359 |
.try_fold( |
| 360 |
(None, None, None, None), |
| 361 |
|(mut top_level, mut owned, mut ref_, mut ref_mut), meta| { |
| 362 |
let is = |name| { |
| 363 |
matches!(&meta, polyfill::Meta::Path(p) if p.is_ident(name)) |
| 364 |
|| matches!(&meta, polyfill::Meta::List(list) if list.path.is_ident(name)) |
| 365 |
}; |
| 366 |
let parse_inner = |meta, attrs: &mut Option<_>| { |
| 367 |
match meta { |
| 368 |
polyfill::Meta::Path(_) => { |
| 369 |
let _ = attrs.get_or_insert_with(Vec::new); |
| 370 |
Some(()) |
| 371 |
} |
| 372 |
polyfill::Meta::List(list) => { |
| 373 |
if let polyfill::NestedMeta::Meta(polyfill::Meta::List(list)) = list |
| 374 |
.parse_args_with(Punctuated::<_, token::Comma>::parse_terminated) |
| 375 |
.ok()? |
| 376 |
.pop()? |
| 377 |
.into_value() |
| 378 |
{ |
| 379 |
parse_list(list, attrs) |
| 380 |
} else { |
| 381 |
None |
| 382 |
} |
| 383 |
} |
| 384 |
} |
| 385 |
}; |
| 386 |
|
| 387 |
match meta { |
| 388 |
meta if is("owned") => parse_inner(meta, &mut owned), |
| 389 |
meta if is("ref") => parse_inner(meta, &mut ref_), |
| 390 |
meta if is("ref_mut") => parse_inner(meta, &mut ref_mut), |
| 391 |
polyfill::Meta::List(list) => parse_list(list, &mut top_level), |
| 392 |
_ => None, |
| 393 |
} |
| 394 |
.map(|_| (top_level, owned, ref_, ref_mut)) |
| 395 |
}, |
| 396 |
) |
| 397 |
.filter(|(top_level, owned, ref_, ref_mut)| { |
| 398 |
[top_level, owned, ref_, ref_mut] |
| 399 |
.into_iter() |
| 400 |
.any(|l| l.as_ref().map_or(false, |l| !l.is_empty())) |
| 401 |
}) |
| 402 |
else { |
| 403 |
return Ok(()); |
| 404 |
}; |
| 405 |
|
| 406 |
if [&owned, &ref_, &ref_mut].into_iter().any(Option::is_some) { |
| 407 |
let format = |list: Option<Vec<_>>, name: &str| match list { |
| 408 |
Some(l) |
| 409 |
if top_level.as_ref().map_or(true, Vec::is_empty) && l.is_empty() => |
| 410 |
{ |
| 411 |
Some(name.to_owned()) |
| 412 |
} |
| 413 |
Some(l) => Some(format!( |
| 414 |
"{}({})", |
| 415 |
name, |
| 416 |
l.into_iter() |
| 417 |
.chain(top_level.clone().into_iter().flatten()) |
| 418 |
.map(map_ty) |
| 419 |
.chain(field.clone()) |
| 420 |
.collect::<Vec<_>>() |
| 421 |
.join(", "), |
| 422 |
)), |
| 423 |
None => None, |
| 424 |
}; |
| 425 |
let format = [ |
| 426 |
format(owned, "owned"), |
| 427 |
format(ref_, "ref"), |
| 428 |
format(ref_mut, "ref_mut"), |
| 429 |
] |
| 430 |
.into_iter() |
| 431 |
.flatten() |
| 432 |
.collect::<Vec<_>>() |
| 433 |
.join(", "); |
| 434 |
|
| 435 |
Err(syn::Error::new( |
| 436 |
span, |
| 437 |
format!("legacy syntax, use `{format}` instead"), |
| 438 |
)) |
| 439 |
} else { |
| 440 |
Err(syn::Error::new( |
| 441 |
span, |
| 442 |
format!( |
| 443 |
"legacy syntax, remove `types` and use `{}` instead", |
| 444 |
top_level.unwrap_or_else(|| unreachable!()).join(", "), |
| 445 |
), |
| 446 |
)) |
| 447 |
} |
| 448 |
} |