Debian Codegraph @

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

raw
1 //! Implementation of an [`Into`] derive macro.
2
3 use std::{
4 any::{Any, TypeId},
5 borrow::Cow,
6 iter, slice,
7 };
8
9 use proc_macro2::{Span, TokenStream};
10 use quote::{format_ident, quote, ToTokens as _};
11 use syn::{
12 ext::IdentExt as _,
13 parse::{discouraged::Speculative as _, Parse, ParseStream},
14 punctuated::Punctuated,
15 spanned::Spanned as _,
16 token,
17 };
18
19 use crate::utils::{
20 attr::{self, ParseMultiple as _},
21 polyfill,
22 replace_self::DeriveInputExt as _,
23 Either, FieldsExt, Spanning,
24 };
25
26 /// Expands an [`Into`] derive macro.
27 pub fn expand(input: &syn::DeriveInput, _: &'static str) -> syn::Result<TokenStream> {
28 let input = &input.replace_self_type();
29
30 let attr_name = format_ident!("into");
31
32 let data = match &input.data {
33 syn::Data::Struct(data) => Ok(data),
34 syn::Data::Enum(e) => Err(syn::Error::new(
35 e.enum_token.span(),
36 "`Into` cannot be derived for enums",
37 )),
38 syn::Data::Union(u) => Err(syn::Error::new(
39 u.union_token.span(),
40 "`Into` cannot be derived for unions",
41 )),
42 }?;
43
44 let struct_attr = StructAttribute::parse_attrs_with(
45 &input.attrs,
46 &attr_name,
47 &ConsiderLegacySyntax {
48 fields: &data.fields,
49 },
50 )?
51 .map(Spanning::into_inner);
52
53 let fields_data = data
54 .fields
55 .iter()
56 .enumerate()
57 .map(|(i, f)| {
58 let field_attr = FieldAttribute::parse_attrs_with(
59 &f.attrs,
60 &attr_name,
61 &ConsiderLegacySyntax {
62 fields: slice::from_ref(f),
63 },
64 )?
65 .map(Spanning::into_inner);
66
67 let skip = field_attr
68 .as_ref()
69 .map(|attr| attr.skip.is_some())
70 .unwrap_or(false);
71
72 let convs = field_attr.and_then(|attr| attr.convs);
73
74 Ok(((i, f, skip), convs))
75 })
76 .collect::<syn::Result<Vec<_>>>()?;
77 let (fields, fields_convs): (Vec<_>, Vec<_>) = fields_data.into_iter().unzip();
78
79 let struct_attr = struct_attr.or_else(|| {
80 fields_convs
81 .iter()
82 .all(Option::is_none)
83 .then(ConversionsAttribute::default)
84 .map(Either::Right)
85 });
86
87 let mut expansions: Vec<_> = fields
88 .iter()
89 .zip(fields_convs)
90 .filter_map(|(&(i, field, _), convs)| {
91 convs.map(|convs| Expansion {
92 input_ident: &input.ident,
93 input_generics: &input.generics,
94 fields: vec![(i, field)],
95 convs,
96 })
97 })
98 .collect();
99 if let Some(attr) = struct_attr {
100 expansions.push(Expansion {
101 input_ident: &input.ident,
102 input_generics: &input.generics,
103 fields: fields
104 .into_iter()
105 .filter_map(|(i, f, skip)| (!skip).then_some((i, f)))
106 .collect(),
107 convs: attr.into(),
108 });
109 }
110 expansions.into_iter().map(Expansion::expand).collect()
111 }
112
113 /// Expansion of an [`Into`] derive macro, generating [`From`] implementations for a struct.
114 struct Expansion<'a> {
115 /// [`syn::Ident`] of the struct.
116 ///
117 /// [`syn::Ident`]: struct@syn::Ident
118 input_ident: &'a syn::Ident,
119
120 /// [`syn::Generics`] of the struct.
121 input_generics: &'a syn::Generics,
122
123 /// Fields to convert from, along with their indices.
124 fields: Vec<(usize, &'a syn::Field)>,
125
126 /// Conversions to be generated.
127 convs: ConversionsAttribute,
128 }
129
130 impl Expansion<'_> {
131 fn expand(self) -> syn::Result<TokenStream> {
132 let Self {
133 input_ident,
134 input_generics,
135 fields,
136 convs,
137 } = self;
138
139 let fields_idents: Vec<_> = fields
140 .iter()
141 .map(|(i, f)| {
142 f.ident
143 .as_ref()
144 .map_or_else(|| Either::Left(syn::Index::from(*i)), Either::Right)
145 })
146 .collect();
147 let fields_tys: Vec<_> = fields.iter().map(|(_, f)| &f.ty).collect();
148 let fields_tuple = syn::Type::Tuple(syn::TypeTuple {
149 paren_token: token::Paren::default(),
150 elems: fields_tys.iter().cloned().cloned().collect(),
151 });
152
153 [
154 (&convs.owned, false, false),
155 (&convs.r#ref, true, false),
156 (&convs.ref_mut, true, true),
157 ]
158 .into_iter()
159 .filter(|(conv, _, _)| conv.consider_fields_ty || !conv.tys.is_empty())
160 .map(|(conv, ref_, mut_)| {
161 let lf = ref_.then(|| syn::Lifetime::new("'__derive_more_into", Span::call_site()));
162 let r = ref_.then(token::And::default);
163 let m = mut_.then(token::Mut::default);
164
165 let gens = if let Some(lf) = lf.clone() {
166 let mut gens = input_generics.clone();
167 gens.params.push(syn::LifetimeParam::new(lf).into());
168 Cow::Owned(gens)
169 } else {
170 Cow::Borrowed(input_generics)
171 };
172 let (impl_gens, _, where_clause) = gens.split_for_impl();
173 let (_, ty_gens, _) = input_generics.split_for_impl();
174
175 if conv.consider_fields_ty {
176 Either::Left(iter::once(&fields_tuple))
177 } else {
178 Either::Right(iter::empty())
179 }
180 .chain(&conv.tys)
181 .map(|out_ty| {
182 let tys: Vec<_> = fields_tys.validate_type(out_ty)?.collect();
183
184 Ok(quote! {
185 #[allow(clippy::unused_unit)]
186 #[allow(deprecated)] // omit warnings on deprecated fields/variants
187 #[automatically_derived]
188 impl #impl_gens derive_more::core::convert::From<#r #lf #m #input_ident #ty_gens>
189 for ( #( #r #lf #m #tys ),* ) #where_clause
190 {
191 #[inline]
192 fn from(value: #r #lf #m #input_ident #ty_gens) -> Self {
193 (#(
194 <#r #m #tys as derive_more::core::convert::From<_>>::from(
195 #r #m value. #fields_idents
196 )
197 ),*)
198 }
199 }
200 })
201 })
202 .collect::<syn::Result<TokenStream>>()
203 })
204 .collect()
205 }
206 }
207
208 /// Representation of an [`Into`] derive macro struct container attribute.
209 ///
210 /// ```rust,ignore
211 /// #[into]
212 /// #[into(<types>)]
213 /// #[into(owned(<types>), ref(<types>), ref_mut(<types>))]
214 /// ```
215 type StructAttribute = Either<attr::Empty, ConversionsAttribute>;
216
217 impl From<StructAttribute> for ConversionsAttribute {
218 fn from(v: StructAttribute) -> Self {
219 match v {
220 Either::Left(_) => ConversionsAttribute::default(),
221 Either::Right(c) => c,
222 }
223 }
224 }
225
226 type Untyped = Either<attr::Skip, Either<attr::Empty, ConversionsAttribute>>;
227 impl From<Untyped> for FieldAttribute {
228 fn from(v: Untyped) -> Self {
229 match v {
230 Untyped::Left(skip) => Self {
231 skip: Some(skip),
232 convs: None,
233 },
234 Untyped::Right(c) => Self {
235 skip: None,
236 convs: Some(match c {
237 Either::Left(_empty) => ConversionsAttribute::default(),
238 Either::Right(convs) => convs,
239 }),
240 },
241 }
242 }
243 }
244
245 /// Representation of an [`Into`] derive macro field attribute.
246 ///
247 /// ```rust,ignore
248 /// #[into]
249 /// #[into(<types>)]
250 /// #[into(owned(<types>), ref(<types>), ref_mut(<types>))]
251 /// #[into(skip)] #[into(ignore)]
252 /// ```
253 #[derive(Clone, Debug)]
254 struct FieldAttribute {
255 skip: Option<attr::Skip>,
256 convs: Option<ConversionsAttribute>,
257 }
258
259 impl Parse for FieldAttribute {
260 fn parse(_: ParseStream<'_>) -> syn::Result<Self> {
261 unreachable!("call `attr::ParseMultiple::parse_attr_with()` instead")
262 }
263 }
264
265 impl attr::ParseMultiple for FieldAttribute {
266 fn parse_attr_with<P: attr::Parser>(
267 attr: &syn::Attribute,
268 parser: &P,
269 ) -> syn::Result<Self> {
270 Untyped::parse_attr_with(attr, parser).map(Self::from)
271 }
272
273 fn merge_attrs(
274 prev: Spanning<Self>,
275 new: Spanning<Self>,
276 name: &syn::Ident,
277 ) -> syn::Result<Spanning<Self>> {
278 let skip = attr::Skip::merge_opt_attrs(
279 prev.clone().map(|v| v.skip).transpose(),
280 new.clone().map(|v| v.skip).transpose(),
281 name,
282 )?
283 .map(Spanning::into_inner);
284
285 let convs = ConversionsAttribute::merge_opt_attrs(
286 prev.clone().map(|v| v.convs).transpose(),
287 new.clone().map(|v| v.convs).transpose(),
288 name,
289 )?
290 .map(Spanning::into_inner);
291
292 Ok(Spanning::new(
293 Self { skip, convs },
294 prev.span.join(new.span).unwrap_or(prev.span),
295 ))
296 }
297 }
298
299 /// [`Into`] conversions specified by a [`ConversionsAttribute`].
300 #[derive(Clone, Debug, Default)]
301 struct Conversions {
302 /// Indicator whether these [`Conversions`] should contain a conversion into fields type.
303 consider_fields_ty: bool,
304
305 /// [`syn::Type`]s explicitly specified in a [`ConversionsAttribute`].
306 tys: Punctuated<syn::Type, token::Comma>,
307 }
308
309 /// Representation of an [`Into`] derive macro attribute describing specified [`Into`] conversions.
310 ///
311 /// ```rust,ignore
312 /// #[into(<types>)]
313 /// #[into(owned(<types>), ref(<types>), ref_mut(<types>))]
314 /// ```
315 #[derive(Clone, Debug)]
316 struct ConversionsAttribute {
317 /// [`syn::Type`]s wrapped into `owned(...)` or simply `#[into(...)]`.
318 owned: Conversions,
319
320 /// [`syn::Type`]s wrapped into `ref(...)`.
321 r#ref: Conversions,
322
323 /// [`syn::Type`]s wrapped into `ref_mut(...)`.
324 ref_mut: Conversions,
325 }
326
327 impl Default for ConversionsAttribute {
328 fn default() -> Self {
329 Self {
330 owned: Conversions {
331 consider_fields_ty: true,
332 tys: Punctuated::new(),
333 },
334 r#ref: Conversions::default(),
335 ref_mut: Conversions::default(),
336 }
337 }
338 }
339
340 impl Parse for ConversionsAttribute {
341 fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
342 let mut out = Self {
343 owned: Conversions::default(),
344 r#ref: Conversions::default(),
345 ref_mut: Conversions::default(),
346 };
347
348 let parse_inner = |ahead, convs: &mut Conversions| {
349 input.advance_to(&ahead);
350
351 if input.peek(token::Paren) {
352 let inner;
353 syn::parenthesized!(inner in input);
354
355 convs.tys.extend(
356 inner
357 .parse_terminated(syn::Type::parse, token::Comma)?
358 .into_pairs(),
359 );
360 } else {
361 convs.consider_fields_ty = true;
362 }
363
364 if input.peek(token::Comma) {
365 let comma = input.parse::<token::Comma>()?;
366 if !convs.tys.empty_or_trailing() {
367 convs.tys.push_punct(comma);
368 }
369 }
370
371 Ok(())
372 };
373
374 let mut has_wrapped_type = false;
375 let mut top_level_type = None;
376
377 while !input.is_empty() {
378 let ahead = input.fork();
379 let res = if ahead.peek(syn::Ident::peek_any) {
380 ahead.call(syn::Ident::parse_any).map(Into::into)
381 } else {
382 ahead.parse::<syn::Path>()
383 };
384 match res {
385 Ok(p) if p.is_ident("owned") => {
386 has_wrapped_type = true;
387 parse_inner(ahead, &mut out.owned)?;
388 }
389 Ok(p) if p.is_ident("ref") => {
390 has_wrapped_type = true;
391 parse_inner(ahead, &mut out.r#ref)?;
392 }
393 Ok(p) if p.is_ident("ref_mut") => {
394 has_wrapped_type = true;
395 parse_inner(ahead, &mut out.ref_mut)?;
396 }
397 _ => {
398 let ty = input.parse::<syn::Type>()?;
399 let _ = top_level_type.get_or_insert_with(|| ty.clone());
400 out.owned.tys.push_value(ty);
401
402 if input.peek(token::Comma) {
403 out.owned.tys.push_punct(input.parse::<token::Comma>()?)
404 }
405 }
406 }
407 }
408
409 if let Some(ty) = top_level_type.filter(|_| has_wrapped_type) {
410 Err(syn::Error::new(
411 ty.span(),
412 format!(
413 "mixing regular types with wrapped into `owned`/`ref`/`ref_mut` is not \
414 allowed, try wrapping this type into `owned({ty}), ref({ty}), ref_mut({ty})`",
415 ty = ty.into_token_stream(),
416 ),
417 ))
418 } else {
419 Ok(out)
420 }
421 }
422 }
423
424 impl attr::ParseMultiple for ConversionsAttribute {
425 fn merge_attrs(
426 prev: Spanning<Self>,
427 new: Spanning<Self>,
428 _: &syn::Ident,
429 ) -> syn::Result<Spanning<Self>> {
430 let Spanning {
431 span: prev_span,
432 item: mut prev,
433 } = prev;
434 let Spanning {
435 span: new_span,
436 item: new,
437 } = new;
438
439 prev.owned.tys.extend(new.owned.tys);
440 prev.owned.consider_fields_ty |= new.owned.consider_fields_ty;
441 prev.r#ref.tys.extend(new.r#ref.tys);
442 prev.r#ref.consider_fields_ty |= new.r#ref.consider_fields_ty;
443 prev.ref_mut.tys.extend(new.ref_mut.tys);
444 prev.ref_mut.consider_fields_ty |= new.ref_mut.consider_fields_ty;
445
446 Ok(Spanning::new(
447 prev,
448 prev_span.join(new_span).unwrap_or(prev_span),
449 ))
450 }
451 }
452
453 /// [`attr::Parser`] considering legacy syntax and performing [`check_legacy_syntax()`] for a
454 /// [`StructAttribute`] or a [`FieldAttribute`].
455 struct ConsiderLegacySyntax<F> {
456 /// [`syn::Field`]s the [`StructAttribute`] or [`FieldAttribute`] is parsed for.
457 fields: F,
458 }
459
460 impl<'a, F> attr::Parser for ConsiderLegacySyntax<&'a F>
461 where
462 F: FieldsExt + ?Sized,
463 &'a F: IntoIterator<Item = &'a syn::Field>,
464 {
465 fn parse<T: Parse + Any>(&self, input: ParseStream<'_>) -> syn::Result<T> {
466 if TypeId::of::<T>() == TypeId::of::<ConversionsAttribute>() {
467 check_legacy_syntax(input, self.fields)?;
468 }
469 T::parse(input)
470 }
471 }
472
473 /// [`Error`]ors for legacy syntax: `#[into(types(i32, "&str"))]`.
474 ///
475 /// [`Error`]: syn::Error
476 fn check_legacy_syntax<'a, F>(tokens: ParseStream<'_>, fields: &'a F) -> syn::Result<()>
477 where
478 F: FieldsExt + ?Sized,
479 &'a F: IntoIterator<Item = &'a syn::Field>,
480 {
481 let span = tokens.span();
482 let tokens = tokens.fork();
483
484 let map_ty = |s: String| {
485 if fields.len() > 1 {
486 format!(
487 "({})",
488 (0..fields.len())
489 .map(|_| s.as_str())
490 .collect::<Vec<_>>()
491 .join(", ")
492 )
493 } else {
494 s
495 }
496 };
497 let field = match fields.len() {
498 0 => None,
499 1 => Some(
500 fields
501 .into_iter()
502 .next()
503 .unwrap_or_else(|| unreachable!("fields.len() == 1"))
504 .ty
505 .to_token_stream()
506 .to_string(),
507 ),
508 _ => Some(format!(
509 "({})",
510 fields
511 .into_iter()
512 .map(|f| f.ty.to_token_stream().to_string())
513 .collect::<Vec<_>>()
514 .join(", ")
515 )),
516 };
517
518 let Ok(metas) = tokens.parse_terminated(polyfill::Meta::parse, token::Comma) else {
519 return Ok(());
520 };
521
522 let parse_list = |list: polyfill::MetaList, attrs: &mut Option<Vec<_>>| {
523 if !list.path.is_ident("types") {
524 return None;
525 }
526 for meta in list
527 .parse_args_with(Punctuated::<_, token::Comma>::parse_terminated)
528 .ok()?
529 {
530 attrs.get_or_insert_with(Vec::new).push(match meta {
531 polyfill::NestedMeta::Lit(syn::Lit::Str(str)) => str.value(),
532 polyfill::NestedMeta::Meta(polyfill::Meta::Path(path)) => {
533 path.into_token_stream().to_string()
534 }
535 _ => return None,
536 })
537 }
538 Some(())
539 };
540
541 let Some((top_level, owned, ref_, ref_mut)) = metas
542 .into_iter()
543 .try_fold(
544 (None, None, None, None),
545 |(mut top_level, mut owned, mut ref_, mut ref_mut), meta| {
546 let is = |name| {
547 matches!(&meta, polyfill::Meta::Path(p) if p.is_ident(name))
548 || matches!(&meta, polyfill::Meta::List(list) if list.path.is_ident(name))
549 };
550 let parse_inner = |meta, attrs: &mut Option<_>| {
551 match meta {
552 polyfill::Meta::Path(_) => {
553 let _ = attrs.get_or_insert_with(Vec::new);
554 Some(())
555 }
556 polyfill::Meta::List(list) => {
557 if let polyfill::NestedMeta::Meta(polyfill::Meta::List(list)) = list
558 .parse_args_with(Punctuated::<_, token::Comma>::parse_terminated)
559 .ok()?
560 .pop()?
561 .into_value()
562 {
563 parse_list(list, attrs)
564 } else {
565 None
566 }
567 }
568 }
569 };
570
571 match meta {
572 meta if is("owned") => parse_inner(meta, &mut owned),
573 meta if is("ref") => parse_inner(meta, &mut ref_),
574 meta if is("ref_mut") => parse_inner(meta, &mut ref_mut),
575 polyfill::Meta::List(list) => parse_list(list, &mut top_level),
576 _ => None,
577 }
578 .map(|_| (top_level, owned, ref_, ref_mut))
579 },
580 )
581 .filter(|(top_level, owned, ref_, ref_mut)| {
582 [top_level, owned, ref_, ref_mut]
583 .into_iter()
584 .any(|l| l.as_ref().is_some_and(|l| !l.is_empty()))
585 })
586 else {
587 return Ok(());
588 };
589
590 if [&owned, &ref_, &ref_mut].into_iter().any(Option::is_some) {
591 let format = |list: Option<Vec<_>>, name: &str| match list {
592 Some(l)
593 if top_level.as_ref().map_or(true, Vec::is_empty) && l.is_empty() =>
594 {
595 Some(name.to_owned())
596 }
597 Some(l) => Some(format!(
598 "{}({})",
599 name,
600 l.into_iter()
601 .chain(top_level.clone().into_iter().flatten())
602 .map(map_ty)
603 .chain(field.clone())
604 .collect::<Vec<_>>()
605 .join(", "),
606 )),
607 None => None,
608 };
609 let format = [
610 format(owned, "owned"),
611 format(ref_, "ref"),
612 format(ref_mut, "ref_mut"),
613 ]
614 .into_iter()
615 .flatten()
616 .collect::<Vec<_>>()
617 .join(", ");
618
619 Err(syn::Error::new(
620 span,
621 format!("legacy syntax, use `{format}` instead"),
622 ))
623 } else {
624 Err(syn::Error::new(
625 span,
626 format!(
627 "legacy syntax, remove `types` and use `{}` instead",
628 top_level.unwrap_or_else(|| unreachable!()).join(", "),
629 ),
630 ))
631 }
632 }