Debian Codegraph @

third_party/rust/derive_more-impl/src/utils.rs

raw
1 #![cfg_attr(
2 not(all(feature = "add", feature = "mul")),
3 allow(dead_code),
4 allow(unused_mut)
5 )]
6
7 use proc_macro2::TokenStream;
8 use quote::{format_ident, quote, ToTokens};
9 use syn::{
10 parse_quote, punctuated::Punctuated, spanned::Spanned, Attribute, Data,
11 DeriveInput, Error, Field, Fields, FieldsNamed, FieldsUnnamed, GenericParam,
12 Generics, Ident, ImplGenerics, Index, Result, Token, Type, TypeGenerics,
13 TypeParamBound, Variant, WhereClause,
14 };
15
16 #[cfg(any(feature = "from", feature = "into"))]
17 pub(crate) use self::{either::Either, fields_ext::FieldsExt};
18
19 #[derive(Clone, Copy, Default)]
20 pub struct DeterministicState;
21
22 impl std::hash::BuildHasher for DeterministicState {
23 type Hasher = std::collections::hash_map::DefaultHasher;
24
25 fn build_hasher(&self) -> Self::Hasher {
26 Self::Hasher::default()
27 }
28 }
29
30 pub type HashMap<K, V> = std::collections::HashMap<K, V, DeterministicState>;
31 pub type HashSet<K> = std::collections::HashSet<K, DeterministicState>;
32
33 #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
34 pub enum RefType {
35 No,
36 Ref,
37 Mut,
38 }
39
40 impl RefType {
41 pub fn lifetime(self) -> TokenStream {
42 match self {
43 RefType::No => quote! {},
44 _ => quote! { '__deriveMoreLifetime },
45 }
46 }
47
48 pub fn reference(self) -> TokenStream {
49 match self {
50 RefType::No => quote! {},
51 RefType::Ref => quote! { & },
52 RefType::Mut => quote! { &mut },
53 }
54 }
55
56 pub fn mutability(self) -> TokenStream {
57 match self {
58 RefType::Mut => quote! { mut },
59 _ => quote! {},
60 }
61 }
62
63 pub fn pattern_ref(self) -> TokenStream {
64 match self {
65 RefType::Ref => quote! { ref },
66 RefType::Mut => quote! { ref mut },
67 RefType::No => quote! {},
68 }
69 }
70
71 pub fn reference_with_lifetime(self) -> TokenStream {
72 if !self.is_ref() {
73 return quote! {};
74 }
75 let lifetime = self.lifetime();
76 let mutability = self.mutability();
77 quote! { &#lifetime #mutability }
78 }
79
80 pub fn is_ref(self) -> bool {
81 !matches!(self, RefType::No)
82 }
83
84 pub fn from_attr_name(name: &str) -> Self {
85 match name {
86 "owned" => RefType::No,
87 "ref" => RefType::Ref,
88 "ref_mut" => RefType::Mut,
89 _ => panic!("`{name}` is not a `RefType`"),
90 }
91 }
92 }
93
94 pub fn numbered_vars(count: usize, prefix: &str) -> Vec<Ident> {
95 (0..count).map(|i| format_ident!("__{prefix}{i}")).collect()
96 }
97
98 pub fn field_idents<'a>(fields: &'a [&'a Field]) -> Vec<&'a Ident> {
99 fields
100 .iter()
101 .map(|f| {
102 f.ident
103 .as_ref()
104 .expect("Tried to get field names of a tuple struct")
105 })
106 .collect()
107 }
108
109 pub fn get_field_types_iter<'a>(
110 fields: &'a [&'a Field],
111 ) -> Box<dyn Iterator<Item = &'a Type> + 'a> {
112 Box::new(fields.iter().map(|f| &f.ty))
113 }
114
115 pub fn get_field_types<'a>(fields: &'a [&'a Field]) -> Vec<&'a Type> {
116 get_field_types_iter(fields).collect()
117 }
118
119 pub fn add_extra_type_param_bound_op_output<'a>(
120 generics: &'a Generics,
121 trait_ident: &'a Ident,
122 ) -> Generics {
123 let mut generics = generics.clone();
124 for type_param in &mut generics.type_params_mut() {
125 let type_ident = &type_param.ident;
126 let bound: TypeParamBound = parse_quote! {
127 ::core::ops::#trait_ident<Output=#type_ident>
128 };
129 type_param.bounds.push(bound)
130 }
131
132 generics
133 }
134
135 pub fn add_extra_ty_param_bound_op<'a>(
136 generics: &'a Generics,
137 trait_ident: &'a Ident,
138 ) -> Generics {
139 add_extra_ty_param_bound(generics, &quote! { ::core::ops::#trait_ident })
140 }
141
142 pub fn add_extra_ty_param_bound<'a>(
143 generics: &'a Generics,
144 bound: &'a TokenStream,
145 ) -> Generics {
146 let mut generics = generics.clone();
147 let bound: TypeParamBound = parse_quote! { #bound };
148 for type_param in &mut generics.type_params_mut() {
149 type_param.bounds.push(bound.clone())
150 }
151
152 generics
153 }
154
155 pub fn add_extra_ty_param_bound_ref<'a>(
156 generics: &'a Generics,
157 bound: &'a TokenStream,
158 ref_type: RefType,
159 ) -> Generics {
160 match ref_type {
161 RefType::No => add_extra_ty_param_bound(generics, bound),
162 _ => {
163 let generics = generics.clone();
164 let idents = generics.type_params().map(|x| &x.ident);
165 let ref_with_lifetime = ref_type.reference_with_lifetime();
166 add_extra_where_clauses(
167 &generics,
168 quote! {
169 where #(#ref_with_lifetime #idents: #bound),*
170 },
171 )
172 }
173 }
174 }
175
176 pub fn add_extra_generic_param(
177 generics: &Generics,
178 generic_param: TokenStream,
179 ) -> Generics {
180 let generic_param: GenericParam = parse_quote! { #generic_param };
181 let mut generics = generics.clone();
182 generics.params.push(generic_param);
183
184 generics
185 }
186
187 pub fn add_extra_generic_type_param(
188 generics: &Generics,
189 generic_param: TokenStream,
190 ) -> Generics {
191 let generic_param: GenericParam = parse_quote! { #generic_param };
192 let lifetimes: Vec<GenericParam> =
193 generics.lifetimes().map(|x| x.clone().into()).collect();
194 let type_params: Vec<GenericParam> =
195 generics.type_params().map(|x| x.clone().into()).collect();
196 let const_params: Vec<GenericParam> =
197 generics.const_params().map(|x| x.clone().into()).collect();
198 let mut generics = generics.clone();
199 generics.params = Default::default();
200 generics.params.extend(lifetimes);
201 generics.params.extend(type_params);
202 generics.params.push(generic_param);
203 generics.params.extend(const_params);
204
205 generics
206 }
207
208 pub fn add_extra_where_clauses(
209 generics: &Generics,
210 type_where_clauses: TokenStream,
211 ) -> Generics {
212 let mut type_where_clauses: WhereClause = parse_quote! { #type_where_clauses };
213 let mut new_generics = generics.clone();
214 if let Some(old_where) = new_generics.where_clause {
215 type_where_clauses.predicates.extend(old_where.predicates)
216 }
217 new_generics.where_clause = Some(type_where_clauses);
218
219 new_generics
220 }
221
222 pub fn add_where_clauses_for_new_ident<'a>(
223 generics: &'a Generics,
224 fields: &[&'a Field],
225 type_ident: &Ident,
226 type_where_clauses: TokenStream,
227 sized: bool,
228 ) -> Generics {
229 let generic_param = if fields.len() > 1 {
230 quote! { #type_ident: ::core::marker::Copy }
231 } else if sized {
232 quote! { #type_ident }
233 } else {
234 quote! { #type_ident: ?::core::marker::Sized }
235 };
236
237 let generics = add_extra_where_clauses(generics, type_where_clauses);
238 add_extra_generic_type_param(&generics, generic_param)
239 }
240
241 pub fn unnamed_to_vec(fields: &FieldsUnnamed) -> Vec<&Field> {
242 fields.unnamed.iter().collect()
243 }
244
245 pub fn named_to_vec(fields: &FieldsNamed) -> Vec<&Field> {
246 fields.named.iter().collect()
247 }
248
249 fn panic_one_field(trait_name: &str, trait_attr: &str) -> ! {
250 panic!(
251 "derive({trait_name}) only works when forwarding to a single field. \
252 Try putting #[{trait_attr}] or #[{trait_attr}(ignore)] on the fields in the struct",
253 )
254 }
255
256 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
257 pub enum DeriveType {
258 Unnamed,
259 Named,
260 Enum,
261 }
262
263 pub struct State<'input> {
264 pub input: &'input DeriveInput,
265 pub trait_name: &'static str,
266 pub trait_ident: Ident,
267 pub method_ident: Ident,
268 pub trait_path: TokenStream,
269 pub trait_path_params: Vec<TokenStream>,
270 pub trait_attr: String,
271 pub derive_type: DeriveType,
272 pub fields: Vec<&'input Field>,
273 pub variants: Vec<&'input Variant>,
274 pub variant_states: Vec<State<'input>>,
275 pub variant: Option<&'input Variant>,
276 pub generics: Generics,
277 pub default_info: FullMetaInfo,
278 full_meta_infos: Vec<FullMetaInfo>,
279 }
280
281 #[derive(Default, Clone)]
282 pub struct AttrParams {
283 pub enum_: Vec<&'static str>,
284 pub variant: Vec<&'static str>,
285 pub struct_: Vec<&'static str>,
286 pub field: Vec<&'static str>,
287 }
288
289 impl AttrParams {
290 pub fn new(params: Vec<&'static str>) -> AttrParams {
291 AttrParams {
292 enum_: params.clone(),
293 struct_: params.clone(),
294 variant: params.clone(),
295 field: params,
296 }
297 }
298 pub fn struct_(params: Vec<&'static str>) -> AttrParams {
299 AttrParams {
300 enum_: vec![],
301 struct_: params,
302 variant: vec![],
303 field: vec![],
304 }
305 }
306
307 pub fn ignore_and_forward() -> AttrParams {
308 AttrParams::new(vec!["ignore", "forward"])
309 }
310 }
311
312 impl<'input> State<'input> {
313 pub fn new<'arg_input>(
314 input: &'arg_input DeriveInput,
315 trait_name: &'static str,
316 trait_attr: String,
317 ) -> Result<State<'arg_input>> {
318 State::new_impl(input, trait_name, trait_attr, AttrParams::default(), true)
319 }
320
321 pub fn with_field_ignore<'arg_input>(
322 input: &'arg_input DeriveInput,
323 trait_name: &'static str,
324 trait_attr: String,
325 ) -> Result<State<'arg_input>> {
326 State::new_impl(
327 input,
328 trait_name,
329 trait_attr,
330 AttrParams::new(vec!["ignore"]),
331 true,
332 )
333 }
334
335 pub fn with_field_ignore_and_forward<'arg_input>(
336 input: &'arg_input DeriveInput,
337 trait_name: &'static str,
338 trait_attr: String,
339 ) -> Result<State<'arg_input>> {
340 State::new_impl(
341 input,
342 trait_name,
343 trait_attr,
344 AttrParams::new(vec!["ignore", "forward"]),
345 true,
346 )
347 }
348
349 pub fn with_field_ignore_and_refs<'arg_input>(
350 input: &'arg_input DeriveInput,
351 trait_name: &'static str,
352 trait_attr: String,
353 ) -> Result<State<'arg_input>> {
354 State::new_impl(
355 input,
356 trait_name,
357 trait_attr,
358 AttrParams::new(vec!["ignore", "owned", "ref", "ref_mut"]),
359 true,
360 )
361 }
362
363 pub fn with_attr_params<'arg_input>(
364 input: &'arg_input DeriveInput,
365 trait_name: &'static str,
366 trait_attr: String,
367 allowed_attr_params: AttrParams,
368 ) -> Result<State<'arg_input>> {
369 State::new_impl(input, trait_name, trait_attr, allowed_attr_params, true)
370 }
371
372 pub fn with_type_bound<'arg_input>(
373 input: &'arg_input DeriveInput,
374 trait_name: &'static str,
375 trait_attr: String,
376 allowed_attr_params: AttrParams,
377 add_type_bound: bool,
378 ) -> Result<State<'arg_input>> {
379 Self::new_impl(
380 input,
381 trait_name,
382 trait_attr,
383 allowed_attr_params,
384 add_type_bound,
385 )
386 }
387
388 fn new_impl<'arg_input>(
389 input: &'arg_input DeriveInput,
390 trait_name: &'static str,
391 trait_attr: String,
392 allowed_attr_params: AttrParams,
393 add_type_bound: bool,
394 ) -> Result<State<'arg_input>> {
395 let trait_name = trait_name.trim_end_matches("ToInner");
396 let trait_ident = format_ident!("{trait_name}");
397 let method_ident = format_ident!("{trait_attr}");
398 let trait_path = quote! { ::derive_more::#trait_ident };
399 let (derive_type, fields, variants): (_, Vec<_>, Vec<_>) = match input.data {
400 Data::Struct(ref data_struct) => match data_struct.fields {
401 Fields::Unnamed(ref fields) => {
402 (DeriveType::Unnamed, unnamed_to_vec(fields), vec![])
403 }
404
405 Fields::Named(ref fields) => {
406 (DeriveType::Named, named_to_vec(fields), vec![])
407 }
408 Fields::Unit => (DeriveType::Named, vec![], vec![]),
409 },
410 Data::Enum(ref data_enum) => (
411 DeriveType::Enum,
412 vec![],
413 data_enum.variants.iter().collect(),
414 ),
415 Data::Union(_) => {
416 panic!("cannot derive({trait_name}) for union")
417 }
418 };
419 let attrs: Vec<_> = if derive_type == DeriveType::Enum {
420 variants.iter().map(|v| &v.attrs).collect()
421 } else {
422 fields.iter().map(|f| &f.attrs).collect()
423 };
424
425 let (allowed_attr_params_outer, allowed_attr_params_inner) =
426 if derive_type == DeriveType::Enum {
427 (&allowed_attr_params.enum_, &allowed_attr_params.variant)
428 } else {
429 (&allowed_attr_params.struct_, &allowed_attr_params.field)
430 };
431
432 let struct_meta_info =
433 get_meta_info(&trait_attr, &input.attrs, allowed_attr_params_outer)?;
434 let meta_infos: Result<Vec<_>> = attrs
435 .iter()
436 .map(|attrs| get_meta_info(&trait_attr, attrs, allowed_attr_params_inner))
437 .collect();
438 let meta_infos = meta_infos?;
439 let first_match = meta_infos
440 .iter()
441 .filter_map(|info| info.enabled.map(|_| info))
442 .next();
443
444 // Default to enabled true, except when first attribute has explicit
445 // enabling.
446 //
447 // Except for derive Error.
448 //
449 // The way `else` case works is that if any field have any valid
450 // attribute specified, then all fields without any attributes
451 // specified are filtered out from `State::enabled_fields`.
452 //
453 // However, derive Error *infers* fields and there are cases when
454 // one of the fields may have an attribute specified, but another field
455 // would be inferred. So, for derive Error macro we default enabled
456 // to true unconditionally (i.e., even if some fields have attributes
457 // specified).
458 let default_enabled = if trait_name == "Error" {
459 true
460 } else {
461 first_match.map_or(true, |info| !info.enabled.unwrap())
462 };
463
464 let defaults = struct_meta_info.into_full(FullMetaInfo {
465 enabled: default_enabled,
466 forward: false,
467 // Default to owned true, except when first attribute has one of owned,
468 // ref or ref_mut
469 // - not a single attribute means default true
470 // - an attribute, but non of owned, ref or ref_mut means default true
471 // - an attribute, and owned, ref or ref_mut means default false
472 owned: first_match.map_or(true, |info| {
473 info.owned.is_none() && info.ref_.is_none() || info.ref_mut.is_none()
474 }),
475 ref_: false,
476 ref_mut: false,
477 info: MetaInfo::default(),
478 });
479
480 let full_meta_infos: Vec<_> = meta_infos
481 .into_iter()
482 .map(|info| info.into_full(defaults.clone()))
483 .collect();
484
485 let variant_states: Result<Vec<_>> = if derive_type == DeriveType::Enum {
486 variants
487 .iter()
488 .zip(full_meta_infos.iter().cloned())
489 .map(|(variant, info)| {
490 State::from_variant(
491 input,
492 trait_name,
493 trait_attr.clone(),
494 allowed_attr_params.clone(),
495 variant,
496 info,
497 )
498 })
499 .collect()
500 } else {
501 Ok(vec![])
502 };
503
504 let generics = if add_type_bound {
505 add_extra_ty_param_bound(&input.generics, &trait_path)
506 } else {
507 input.generics.clone()
508 };
509
510 Ok(State {
511 input,
512 trait_name,
513 trait_ident,
514 method_ident,
515 trait_path,
516 trait_path_params: vec![],
517 trait_attr,
518 // input,
519 fields,
520 variants,
521 variant_states: variant_states?,
522 variant: None,
523 derive_type,
524 generics,
525 full_meta_infos,
526 default_info: defaults,
527 })
528 }
529
530 pub fn from_variant<'arg_input>(
531 input: &'arg_input DeriveInput,
532 trait_name: &'static str,
533 trait_attr: String,
534 allowed_attr_params: AttrParams,
535 variant: &'arg_input Variant,
536 default_info: FullMetaInfo,
537 ) -> Result<State<'arg_input>> {
538 let trait_name = trait_name.trim_end_matches("ToInner");
539 let trait_ident = format_ident!("{trait_name}");
540 let method_ident = format_ident!("{trait_attr}");
541 let trait_path = quote! { ::derive_more::#trait_ident };
542 let (derive_type, fields): (_, Vec<_>) = match variant.fields {
543 Fields::Unnamed(ref fields) => {
544 (DeriveType::Unnamed, unnamed_to_vec(fields))
545 }
546
547 Fields::Named(ref fields) => (DeriveType::Named, named_to_vec(fields)),
548 Fields::Unit => (DeriveType::Named, vec![]),
549 };
550
551 let meta_infos: Result<Vec<_>> = fields
552 .iter()
553 .map(|f| &f.attrs)
554 .map(|attrs| get_meta_info(&trait_attr, attrs, &allowed_attr_params.field))
555 .collect();
556 let meta_infos = meta_infos?;
557 let full_meta_infos: Vec<_> = meta_infos
558 .into_iter()
559 .map(|info| info.into_full(default_info.clone()))
560 .collect();
561
562 let generics = add_extra_ty_param_bound(&input.generics, &trait_path);
563
564 Ok(State {
565 input,
566 trait_name,
567 trait_path,
568 trait_path_params: vec![],
569 trait_attr,
570 trait_ident,
571 method_ident,
572 // input,
573 fields,
574 variants: vec![],
575 variant_states: vec![],
576 variant: Some(variant),
577 derive_type,
578 generics,
579 full_meta_infos,
580 default_info,
581 })
582 }
583 pub fn add_trait_path_type_param(&mut self, param: TokenStream) {
584 self.trait_path_params.push(param);
585 }
586
587 pub fn assert_single_enabled_field<'state>(
588 &'state self,
589 ) -> SingleFieldData<'input, 'state> {
590 if self.derive_type == DeriveType::Enum {
591 panic_one_field(self.trait_name, &self.trait_attr);
592 }
593 let data = self.enabled_fields_data();
594 if data.fields.len() != 1 {
595 panic_one_field(self.trait_name, &self.trait_attr);
596 };
597 SingleFieldData {
598 input_type: data.input_type,
599 field: data.fields[0],
600 field_type: data.field_types[0],
601 member: data.members[0].clone(),
602 info: data.infos[0].clone(),
603 field_ident: data.field_idents[0].clone(),
604 trait_path: data.trait_path,
605 trait_path_with_params: data.trait_path_with_params.clone(),
606 casted_trait: data.casted_traits[0].clone(),
607 impl_generics: data.impl_generics.clone(),
608 ty_generics: data.ty_generics.clone(),
609 where_clause: data.where_clause,
610 multi_field_data: data,
611 }
612 }
613
614 pub fn enabled_fields_data<'state>(&'state self) -> MultiFieldData<'input, 'state> {
615 if self.derive_type == DeriveType::Enum {
616 panic!("cannot derive({}) for enum", self.trait_name)
617 }
618 let fields = self.enabled_fields();
619 let field_idents = self.enabled_fields_idents();
620 let field_indexes = self.enabled_fields_indexes();
621 let field_types: Vec<_> = fields.iter().map(|f| &f.ty).collect();
622 let members: Vec<_> = field_idents
623 .iter()
624 .map(|ident| quote! { self.#ident })
625 .collect();
626 let trait_path = &self.trait_path;
627 let trait_path_with_params = if !self.trait_path_params.is_empty() {
628 let params = self.trait_path_params.iter();
629 quote! { #trait_path<#(#params),*> }
630 } else {
631 self.trait_path.clone()
632 };
633
634 let casted_traits: Vec<_> = field_types
635 .iter()
636 .map(|field_type| quote! { <#field_type as #trait_path_with_params> })
637 .collect();
638 let (impl_generics, ty_generics, where_clause) = self.generics.split_for_impl();
639 let input_type = &self.input.ident;
640 let (variant_name, variant_type) = self.variant.map_or_else(
641 || (None, quote! { #input_type }),
642 |v| {
643 let variant_name = &v.ident;
644 (Some(variant_name), quote! { #input_type::#variant_name })
645 },
646 );
647 MultiFieldData {
648 input_type,
649 variant_type,
650 variant_name,
651 variant_info: self.default_info.clone(),
652 fields,
653 field_types,
654 field_indexes,
655 members,
656 infos: self.enabled_infos(),
657 field_idents,
658 method_ident: &self.method_ident,
659 trait_path,
660 trait_path_with_params,
661 casted_traits,
662 impl_generics,
663 ty_generics,
664 where_clause,
665 state: self,
666 }
667 }
668
669 pub fn enabled_variant_data<'state>(
670 &'state self,
671 ) -> MultiVariantData<'input, 'state> {
672 if self.derive_type != DeriveType::Enum {
673 panic!("can only derive({}) for enum", self.trait_name)
674 }
675 let variants = self.enabled_variants();
676 let trait_path = &self.trait_path;
677 let (impl_generics, ty_generics, where_clause) = self.generics.split_for_impl();
678 MultiVariantData {
679 input_type: &self.input.ident,
680 variants,
681 variant_states: self.enabled_variant_states(),
682 infos: self.enabled_infos(),
683 trait_path,
684 impl_generics,
685 ty_generics,
686 where_clause,
687 }
688 }
689
690 fn enabled_variants(&self) -> Vec<&'input Variant> {
691 self.variants
692 .iter()
693 .zip(self.full_meta_infos.iter().map(|info| info.enabled))
694 .filter(|(_, ig)| *ig)
695 .map(|(v, _)| *v)
696 .collect()
697 }
698
699 fn enabled_variant_states(&self) -> Vec<&State<'input>> {
700 self.variant_states
701 .iter()
702 .zip(self.full_meta_infos.iter().map(|info| info.enabled))
703 .filter(|(_, ig)| *ig)
704 .map(|(v, _)| v)
705 .collect()
706 }
707
708 pub fn enabled_fields(&self) -> Vec<&'input Field> {
709 self.fields
710 .iter()
711 .zip(self.full_meta_infos.iter().map(|info| info.enabled))
712 .filter(|(_, ig)| *ig)
713 .map(|(f, _)| *f)
714 .collect()
715 }
716
717 fn field_idents(&self) -> Vec<TokenStream> {
718 if self.derive_type == DeriveType::Named {
719 self.fields
720 .iter()
721 .map(|f| {
722 f.ident
723 .as_ref()
724 .expect("Tried to get field names of a tuple struct")
725 .to_token_stream()
726 })
727 .collect()
728 } else {
729 let count = self.fields.len();
730 (0..count)
731 .map(|i| Index::from(i).to_token_stream())
732 .collect()
733 }
734 }
735
736 fn enabled_fields_idents(&self) -> Vec<TokenStream> {
737 self.field_idents()
738 .into_iter()
739 .zip(self.full_meta_infos.iter().map(|info| info.enabled))
740 .filter(|(_, ig)| *ig)
741 .map(|(f, _)| f)
742 .collect()
743 }
744
745 fn enabled_fields_indexes(&self) -> Vec<usize> {
746 self.full_meta_infos
747 .iter()
748 .map(|info| info.enabled)
749 .enumerate()
750 .filter(|(_, ig)| *ig)
751 .map(|(i, _)| i)
752 .collect()
753 }
754 fn enabled_infos(&self) -> Vec<FullMetaInfo> {
755 self.full_meta_infos
756 .iter()
757 .filter(|info| info.enabled)
758 .cloned()
759 .collect()
760 }
761 }
762
763 #[derive(Clone)]
764 pub struct SingleFieldData<'input, 'state> {
765 pub input_type: &'input Ident,
766 pub field: &'input Field,
767 pub field_type: &'input Type,
768 pub field_ident: TokenStream,
769 pub member: TokenStream,
770 pub info: FullMetaInfo,
771 pub trait_path: &'state TokenStream,
772 pub trait_path_with_params: TokenStream,
773 pub casted_trait: TokenStream,
774 pub impl_generics: ImplGenerics<'state>,
775 pub ty_generics: TypeGenerics<'state>,
776 pub where_clause: Option<&'state WhereClause>,
777 multi_field_data: MultiFieldData<'input, 'state>,
778 }
779
780 #[derive(Clone)]
781 pub struct MultiFieldData<'input, 'state> {
782 pub input_type: &'input Ident,
783 pub variant_type: TokenStream,
784 pub variant_name: Option<&'input Ident>,
785 pub variant_info: FullMetaInfo,
786 pub fields: Vec<&'input Field>,
787 pub field_types: Vec<&'input Type>,
788 pub field_idents: Vec<TokenStream>,
789 pub field_indexes: Vec<usize>,
790 pub members: Vec<TokenStream>,
791 pub infos: Vec<FullMetaInfo>,
792 pub method_ident: &'state Ident,
793 pub trait_path: &'state TokenStream,
794 pub trait_path_with_params: TokenStream,
795 pub casted_traits: Vec<TokenStream>,
796 pub impl_generics: ImplGenerics<'state>,
797 pub ty_generics: TypeGenerics<'state>,
798 pub where_clause: Option<&'state WhereClause>,
799 pub state: &'state State<'input>,
800 }
801
802 pub struct MultiVariantData<'input, 'state> {
803 pub input_type: &'input Ident,
804 pub variants: Vec<&'input Variant>,
805 pub variant_states: Vec<&'state State<'input>>,
806 pub infos: Vec<FullMetaInfo>,
807 pub trait_path: &'state TokenStream,
808 pub impl_generics: ImplGenerics<'state>,
809 pub ty_generics: TypeGenerics<'state>,
810 pub where_clause: Option<&'state WhereClause>,
811 }
812
813 impl<'input, 'state> MultiFieldData<'input, 'state> {
814 pub fn initializer<T: ToTokens>(&self, initializers: &[T]) -> TokenStream {
815 let MultiFieldData {
816 variant_type,
817 field_idents,
818 ..
819 } = self;
820 if self.state.derive_type == DeriveType::Named {
821 quote! { #variant_type{#(#field_idents: #initializers),*} }
822 } else {
823 quote! { #variant_type(#(#initializers),*) }
824 }
825 }
826 pub fn matcher<T: ToTokens>(
827 &self,
828 indexes: &[usize],
829 bindings: &[T],
830 ) -> TokenStream {
831 let MultiFieldData { variant_type, .. } = self;
832 let full_bindings = (0..self.state.fields.len()).map(|i| {
833 indexes.iter().position(|index| i == *index).map_or_else(
834 || quote! { _ },
835 |found_index| bindings[found_index].to_token_stream(),
836 )
837 });
838 if self.state.derive_type == DeriveType::Named {
839 let field_idents = self.state.field_idents();
840 quote! { #variant_type{#(#field_idents: #full_bindings),*} }
841 } else {
842 quote! { #variant_type(#(#full_bindings),*) }
843 }
844 }
845 }
846
847 impl<'input, 'state> SingleFieldData<'input, 'state> {
848 pub fn initializer<T: ToTokens>(&self, initializers: &[T]) -> TokenStream {
849 self.multi_field_data.initializer(initializers)
850 }
851 }
852
853 fn get_meta_info(
854 trait_attr: &str,
855 attrs: &[Attribute],
856 allowed_attr_params: &[&str],
857 ) -> Result<MetaInfo> {
858 let mut it = attrs.iter().filter(|a| {
859 a.meta
860 .path()
861 .segments
862 .first()
863 .map(|p| p.ident == trait_attr)
864 .unwrap_or_default()
865 });
866
867 let mut info = MetaInfo::default();
868
869 let Some(attr) = it.next() else {
870 return Ok(info);
871 };
872
873 if allowed_attr_params.is_empty() {
874 return Err(Error::new(attr.span(), "Attribute is not allowed here"));
875 }
876
877 info.enabled = Some(true);
878
879 if let Some(another_attr) = it.next() {
880 return Err(Error::new(
881 another_attr.span(),
882 "Only a single attribute is allowed",
883 ));
884 }
885
886 let list = match &attr.meta {
887 syn::Meta::Path(_) => {
888 if allowed_attr_params.contains(&"ignore") {
889 return Ok(info);
890 } else {
891 return Err(Error::new(
892 attr.span(),
893 format!(
894 "Empty attribute is not allowed, add one of the following parameters: {}",
895 allowed_attr_params.join(", "),
896 ),
897 ));
898 }
899 }
900 syn::Meta::List(list) => list,
901 syn::Meta::NameValue(val) => {
902 return Err(Error::new(
903 val.span(),
904 "Attribute doesn't support name-value format here",
905 ));
906 }
907 };
908
909 parse_punctuated_nested_meta(
910 &mut info,
911 &list.parse_args_with(Punctuated::parse_terminated)?,
912 allowed_attr_params,
913 None,
914 )?;
915
916 Ok(info)
917 }
918
919 fn parse_punctuated_nested_meta(
920 info: &mut MetaInfo,
921 meta: &Punctuated<polyfill::Meta, Token![,]>,
922 allowed_attr_params: &[&str],
923 wrapper_name: Option<&str>,
924 ) -> Result<()> {
925 for meta in meta.iter() {
926 match meta {
927 polyfill::Meta::List(list) if list.path.is_ident("not") => {
928 if wrapper_name.is_some() {
929 // Only single top-level `not` attribute is allowed.
930 return Err(Error::new(
931 list.span(),
932 "Attribute doesn't support multiple multiple or nested `not` parameters",
933 ));
934 }
935 parse_punctuated_nested_meta(
936 info,
937 &list.parse_args_with(Punctuated::parse_terminated)?,
938 allowed_attr_params,
939 Some("not"),
940 )?;
941 }
942
943 polyfill::Meta::List(list) => {
944 let path = &list.path;
945 if !allowed_attr_params.iter().any(|param| path.is_ident(param)) {
946 return Err(Error::new(
947 meta.span(),
948 format!(
949 "Attribute nested parameter not supported. \
950 Supported attribute parameters are: {}",
951 allowed_attr_params.join(", "),
952 ),
953 ));
954 }
955
956 let mut parse_nested = true;
957
958 let attr_name = path.get_ident().unwrap().to_string();
959 match (wrapper_name, attr_name.as_str()) {
960 (None, "owned") => info.owned = Some(true),
961 (None, "ref") => info.ref_ = Some(true),
962 (None, "ref_mut") => info.ref_mut = Some(true),
963
964 #[cfg(any(feature = "from", feature = "into"))]
965 (None, "types")
966 | (Some("owned"), "types")
967 | (Some("ref"), "types")
968 | (Some("ref_mut"), "types") => {
969 parse_nested = false;
970 for meta in &list.parse_args_with(
971 Punctuated::<polyfill::NestedMeta, syn::token::Comma>::parse_terminated,
972 )? {
973 let typ: syn::Type = match meta {
974 polyfill::NestedMeta::Meta(meta) => {
975 let polyfill::Meta::Path(path) = meta else {
976 return Err(Error::new(
977 meta.span(),
978 format!(
979 "Attribute doesn't support type {}",
980 quote! { #meta },
981 ),
982 ));
983 };
984 syn::TypePath {
985 qself: None,
986 path: path.clone().into(),
987 }
988 .into()
989 }
990 polyfill::NestedMeta::Lit(syn::Lit::Str(s)) => s.parse()?,
991 polyfill::NestedMeta::Lit(lit) => return Err(Error::new(
992 lit.span(),
993 "Attribute doesn't support nested literals here",
994 )),
995 };
996
997 for ref_type in wrapper_name
998 .map(|n| vec![RefType::from_attr_name(n)])
999 .unwrap_or_else(|| {
1000 vec![RefType::No, RefType::Ref, RefType::Mut]
1001 })
1002 {
1003 if info
1004 .types
1005 .entry(ref_type)
1006 .or_default()
1007 .replace(typ.clone())
1008 .is_some()
1009 {
1010 return Err(Error::new(
1011 typ.span(),
1012 format!(
1013 "Duplicate type `{}` specified",
1014 quote! { #path },
1015 ),
1016 ));
1017 }
1018 }
1019 }
1020 }
1021
1022 _ => {
1023 return Err(Error::new(
1024 list.span(),
1025 format!(
1026 "Attribute doesn't support nested parameter `{}` here",
1027 quote! { #path },
1028 ),
1029 ))
1030 }
1031 };
1032
1033 if parse_nested {
1034 parse_punctuated_nested_meta(
1035 info,
1036 &list.parse_args_with(Punctuated::parse_terminated)?,
1037 allowed_attr_params,
1038 Some(&attr_name),
1039 )?;
1040 }
1041 }
1042
1043 polyfill::Meta::Path(path) => {
1044 if !allowed_attr_params.iter().any(|param| path.is_ident(param)) {
1045 return Err(Error::new(
1046 meta.span(),
1047 format!(
1048 "Attribute parameter not supported. \
1049 Supported attribute parameters are: {}",
1050 allowed_attr_params.join(", "),
1051 ),
1052 ));
1053 }
1054
1055 let attr_name = path.get_ident().unwrap().to_string();
1056 match (wrapper_name, attr_name.as_str()) {
1057 (None, "ignore") => info.enabled = Some(false),
1058 (None, "forward") => info.forward = Some(true),
1059 (Some("not"), "forward") => info.forward = Some(false),
1060 (None, "owned") => info.owned = Some(true),
1061 (None, "ref") => info.ref_ = Some(true),
1062 (None, "ref_mut") => info.ref_mut = Some(true),
1063 (None, "source") => info.source = Some(true),
1064 (Some("not"), "source") => info.source = Some(false),
1065 (None, "backtrace") => info.backtrace = Some(true),
1066 (Some("not"), "backtrace") => info.backtrace = Some(false),
1067 _ => {
1068 return Err(Error::new(
1069 path.span(),
1070 format!(
1071 "Attribute doesn't support parameter `{}` here",
1072 quote! { #path }
1073 ),
1074 ))
1075 }
1076 }
1077 }
1078 }
1079 }
1080
1081 Ok(())
1082 }
1083
1084 // TODO: Remove this eventually, once all macros migrate to
1085 // custom typed attributes parsing.
1086 /// Polyfill for [`syn`] 1.x AST.
1087 pub(crate) mod polyfill {
1088 use proc_macro2::TokenStream;
1089 use quote::ToTokens;
1090 use syn::{
1091 ext::IdentExt as _,
1092 parse::{Parse, ParseStream, Parser},
1093 token, Token,
1094 };
1095
1096 #[derive(Clone)]
1097 pub(crate) enum PathOrKeyword {
1098 Path(syn::Path),
1099 Keyword(syn::Ident),
1100 }
1101
1102 impl Parse for PathOrKeyword {
1103 fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
1104 if input.fork().parse::<syn::Path>().is_ok() {
1105 return input.parse().map(Self::Path);
1106 }
1107 syn::Ident::parse_any(input).map(Self::Keyword)
1108 }
1109 }
1110
1111 impl ToTokens for PathOrKeyword {
1112 fn to_tokens(&self, tokens: &mut TokenStream) {
1113 match self {
1114 Self::Path(p) => p.to_tokens(tokens),
1115 Self::Keyword(i) => i.to_tokens(tokens),
1116 }
1117 }
1118 }
1119
1120 impl PathOrKeyword {
1121 pub(crate) fn is_ident<I: ?Sized>(&self, ident: &I) -> bool
1122 where
1123 syn::Ident: PartialEq<I>,
1124 {
1125 match self {
1126 Self::Path(p) => p.is_ident(ident),
1127 Self::Keyword(i) => i == ident,
1128 }
1129 }
1130
1131 pub fn get_ident(&self) -> Option<&syn::Ident> {
1132 match self {
1133 Self::Path(p) => p.get_ident(),
1134 Self::Keyword(i) => Some(i),
1135 }
1136 }
1137 }
1138
1139 impl From<PathOrKeyword> for syn::Path {
1140 fn from(p: PathOrKeyword) -> Self {
1141 match p {
1142 PathOrKeyword::Path(p) => p,
1143 PathOrKeyword::Keyword(i) => i.into(),
1144 }
1145 }
1146 }
1147
1148 #[derive(Clone)]
1149 pub(crate) struct MetaList {
1150 pub(crate) path: PathOrKeyword,
1151 pub(crate) tokens: TokenStream,
1152 }
1153
1154 impl Parse for MetaList {
1155 fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
1156 let path = input.parse::<PathOrKeyword>()?;
1157 let tokens;
1158 _ = syn::parenthesized!(tokens in input);
1159 Ok(Self {
1160 path,
1161 tokens: tokens.parse()?,
1162 })
1163 }
1164 }
1165
1166 impl ToTokens for MetaList {
1167 fn to_tokens(&self, tokens: &mut TokenStream) {
1168 self.path.to_tokens(tokens);
1169 token::Paren::default()
1170 .surround(tokens, |tokens| self.tokens.to_tokens(tokens))
1171 }
1172 }
1173
1174 impl MetaList {
1175 pub fn parse_args_with<F: Parser>(&self, parser: F) -> syn::Result<F::Output> {
1176 parser.parse2(self.tokens.clone())
1177 }
1178 }
1179
1180 #[derive(Clone)]
1181 pub(crate) enum Meta {
1182 Path(PathOrKeyword),
1183 List(MetaList),
1184 }
1185
1186 impl Parse for Meta {
1187 fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
1188 let path = input.parse::<PathOrKeyword>()?;
1189 Ok(if input.peek(token::Paren) {
1190 let tokens;
1191 _ = syn::parenthesized!(tokens in input);
1192 Self::List(MetaList {
1193 path,
1194 tokens: tokens.parse()?,
1195 })
1196 } else {
1197 Self::Path(path)
1198 })
1199 }
1200 }
1201
1202 impl ToTokens for Meta {
1203 fn to_tokens(&self, tokens: &mut TokenStream) {
1204 match self {
1205 Self::Path(p) => p.to_tokens(tokens),
1206 Self::List(l) => l.to_tokens(tokens),
1207 }
1208 }
1209 }
1210
1211 #[derive(Clone)]
1212 pub(crate) enum NestedMeta {
1213 Meta(Meta),
1214 Lit(syn::Lit),
1215 }
1216
1217 impl Parse for NestedMeta {
1218 fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
1219 if input.peek(syn::Lit)
1220 && !(input.peek(syn::LitBool) && input.peek2(Token![=]))
1221 {
1222 input.parse().map(Self::Lit)
1223 } else if input.peek(syn::Ident::peek_any)
1224 || input.peek(Token![::]) && input.peek3(syn::Ident::peek_any)
1225 {
1226 input.parse().map(Self::Meta)
1227 } else {
1228 Err(input.error("expected identifier or literal"))
1229 }
1230 }
1231 }
1232
1233 impl ToTokens for NestedMeta {
1234 fn to_tokens(&self, tokens: &mut TokenStream) {
1235 match self {
1236 Self::Meta(m) => m.to_tokens(tokens),
1237 Self::Lit(l) => l.to_tokens(tokens),
1238 }
1239 }
1240 }
1241 }
1242
1243 #[derive(Clone, Debug, Default)]
1244 pub struct FullMetaInfo {
1245 pub enabled: bool,
1246 pub forward: bool,
1247 pub owned: bool,
1248 pub ref_: bool,
1249 pub ref_mut: bool,
1250 pub info: MetaInfo,
1251 }
1252
1253 #[derive(Clone, Debug, Default)]
1254 pub struct MetaInfo {
1255 pub enabled: Option<bool>,
1256 pub forward: Option<bool>,
1257 pub owned: Option<bool>,
1258 pub ref_: Option<bool>,
1259 pub ref_mut: Option<bool>,
1260 pub source: Option<bool>,
1261 pub backtrace: Option<bool>,
1262 #[cfg(any(feature = "from", feature = "into"))]
1263 pub types: HashMap<RefType, HashSet<syn::Type>>,
1264 }
1265
1266 impl MetaInfo {
1267 fn into_full(self, defaults: FullMetaInfo) -> FullMetaInfo {
1268 FullMetaInfo {
1269 enabled: self.enabled.unwrap_or(defaults.enabled),
1270 forward: self.forward.unwrap_or(defaults.forward),
1271 owned: self.owned.unwrap_or(defaults.owned),
1272 ref_: self.ref_.unwrap_or(defaults.ref_),
1273 ref_mut: self.ref_mut.unwrap_or(defaults.ref_mut),
1274 info: self,
1275 }
1276 }
1277 }
1278
1279 impl FullMetaInfo {
1280 pub fn ref_types(&self) -> Vec<RefType> {
1281 let mut ref_types = vec![];
1282 if self.owned {
1283 ref_types.push(RefType::No);
1284 }
1285 if self.ref_ {
1286 ref_types.push(RefType::Ref);
1287 }
1288 if self.ref_mut {
1289 ref_types.push(RefType::Mut);
1290 }
1291 ref_types
1292 }
1293 }
1294
1295 pub fn get_if_type_parameter_used_in_type(
1296 type_parameters: &HashSet<syn::Ident>,
1297 ty: &syn::Type,
1298 ) -> Option<syn::Type> {
1299 is_type_parameter_used_in_type(type_parameters, ty).then(|| match ty {
1300 syn::Type::Reference(syn::TypeReference { elem: ty, .. }) => (**ty).clone(),
1301 ty => ty.clone(),
1302 })
1303 }
1304
1305 pub fn is_type_parameter_used_in_type(
1306 type_parameters: &HashSet<syn::Ident>,
1307 ty: &syn::Type,
1308 ) -> bool {
1309 match ty {
1310 syn::Type::Path(ty) => {
1311 if let Some(qself) = &ty.qself {
1312 if is_type_parameter_used_in_type(type_parameters, &qself.ty) {
1313 return true;
1314 }
1315 }
1316
1317 if let Some(segment) = ty.path.segments.first() {
1318 if type_parameters.contains(&segment.ident) {
1319 return true;
1320 }
1321 }
1322
1323 ty.path.segments.iter().any(|segment| {
1324 if let syn::PathArguments::AngleBracketed(arguments) =
1325 &segment.arguments
1326 {
1327 arguments.args.iter().any(|argument| match argument {
1328 syn::GenericArgument::Type(ty) => {
1329 is_type_parameter_used_in_type(type_parameters, ty)
1330 }
1331 syn::GenericArgument::Constraint(constraint) => {
1332 type_parameters.contains(&constraint.ident)
1333 }
1334 _ => false,
1335 })
1336 } else {
1337 false
1338 }
1339 })
1340 }
1341
1342 syn::Type::Reference(ty) => {
1343 is_type_parameter_used_in_type(type_parameters, &ty.elem)
1344 }
1345
1346 _ => false,
1347 }
1348 }
1349
1350 #[cfg(any(feature = "from", feature = "into"))]
1351 mod either {
1352 use proc_macro2::TokenStream;
1353 use quote::ToTokens;
1354
1355 /// Either [`Left`] or [`Right`].
1356 ///
1357 /// [`Left`]: Either::Left
1358 /// [`Right`]: Either::Right
1359 pub(crate) enum Either<L, R> {
1360 /// Left variant.
1361 Left(L),
1362
1363 /// Right variant.
1364 Right(R),
1365 }
1366
1367 impl<L, R, T> Iterator for Either<L, R>
1368 where
1369 L: Iterator<Item = T>,
1370 R: Iterator<Item = T>,
1371 {
1372 type Item = T;
1373
1374 fn next(&mut self) -> Option<Self::Item> {
1375 match self {
1376 Either::Left(left) => left.next(),
1377 Either::Right(right) => right.next(),
1378 }
1379 }
1380 }
1381
1382 impl<L, R> ToTokens for Either<L, R>
1383 where
1384 L: ToTokens,
1385 R: ToTokens,
1386 {
1387 fn to_tokens(&self, tokens: &mut TokenStream) {
1388 match self {
1389 Either::Left(l) => l.to_tokens(tokens),
1390 Either::Right(r) => r.to_tokens(tokens),
1391 }
1392 }
1393 }
1394 }
1395
1396 #[cfg(any(feature = "from", feature = "into"))]
1397 mod fields_ext {
1398 use std::{cmp, iter};
1399
1400 use proc_macro2::TokenStream;
1401 use syn::{punctuated, spanned::Spanned as _};
1402
1403 use crate::parsing;
1404
1405 use super::Either;
1406
1407 /// Abstraction over `.len()` method to use it on type parameters.
1408 pub(crate) trait Len {
1409 /// Returns number of fields.
1410 fn len(&self) -> usize;
1411 }
1412
1413 impl Len for syn::Fields {
1414 fn len(&self) -> usize {
1415 self.len()
1416 }
1417 }
1418
1419 impl<T> Len for Vec<T> {
1420 fn len(&self) -> usize {
1421 self.len()
1422 }
1423 }
1424
1425 /// [`syn::Fields`] extension.
1426 pub(crate) trait FieldsExt: Len {
1427 /// Validates the provided [`parsing::Type`] against these [`syn::Fields`].
1428 fn validate_type<'t>(
1429 &self,
1430 ty: &'t parsing::Type,
1431 ) -> syn::Result<
1432 Either<punctuated::Iter<'t, TokenStream>, iter::Once<&'t TokenStream>>,
1433 > {
1434 match ty {
1435 parsing::Type::Tuple { items, .. } if self.len() > 1 => {
1436 match self.len().cmp(&items.len()) {
1437 cmp::Ordering::Greater => {
1438 return Err(syn::Error::new(
1439 ty.span(),
1440 format!(
1441 "wrong tuple length: expected {}, found {}. \
1442 Consider adding {} more type{}: `({})`",
1443 self.len(),
1444 items.len(),
1445 self.len() - items.len(),
1446 if self.len() - items.len() > 1 {
1447 "s"
1448 } else {
1449 ""
1450 },
1451 items
1452 .iter()
1453 .map(|item| item.to_string())
1454 .chain(
1455 (0..(self.len() - items.len()))
1456 .map(|_| "_".to_string())
1457 )
1458 .collect::<Vec<_>>()
1459 .join(", "),
1460 ),
1461 ));
1462 }
1463 cmp::Ordering::Less => {
1464 return Err(syn::Error::new(
1465 ty.span(),
1466 format!(
1467 "wrong tuple length: expected {}, found {}. \
1468 Consider removing last {} type{}: `({})`",
1469 self.len(),
1470 items.len(),
1471 items.len() - self.len(),
1472 if items.len() - self.len() > 1 {
1473 "s"
1474 } else {
1475 ""
1476 },
1477 items
1478 .iter()
1479 .take(self.len())
1480 .map(ToString::to_string)
1481 .collect::<Vec<_>>()
1482 .join(", "),
1483 ),
1484 ));
1485 }
1486 cmp::Ordering::Equal => {}
1487 }
1488 }
1489 parsing::Type::Other(other) if self.len() > 1 => {
1490 if self.len() > 1 {
1491 return Err(syn::Error::new(
1492 other.span(),
1493 format!(
1494 "expected tuple: `({}, {})`",
1495 other,
1496 (0..(self.len() - 1))
1497 .map(|_| "_")
1498 .collect::<Vec<_>>()
1499 .join(", "),
1500 ),
1501 ));
1502 }
1503 }
1504 parsing::Type::Tuple { .. } | parsing::Type::Other(_) => {}
1505 }
1506 Ok(match ty {
1507 parsing::Type::Tuple { items, .. } => Either::Left(items.iter()),
1508 parsing::Type::Other(other) => Either::Right(iter::once(other)),
1509 })
1510 }
1511 }
1512
1513 impl<T: Len + ?Sized> FieldsExt for T {}
1514 }