rustc_builtin_macros/deriving/generic/
mod.rs

1//! Some code that abstracts away much of the boilerplate of writing
2//! `derive` instances for traits. Among other things it manages getting
3//! access to the fields of the 4 different sorts of structs and enum
4//! variants, as well as creating the method and impl ast instances.
5//!
6//! Supported features (fairly exhaustive):
7//!
8//! - Methods taking any number of parameters of any type, and returning
9//!   any type, other than vectors, bottom and closures.
10//! - Generating `impl`s for types with type parameters and lifetimes
11//!   (e.g., `Option<T>`), the parameters are automatically given the
12//!   current trait as a bound. (This includes separate type parameters
13//!   and lifetimes for methods.)
14//! - Additional bounds on the type parameters (`TraitDef.additional_bounds`)
15//!
16//! The most important thing for implementors is the `Substructure` and
17//! `SubstructureFields` objects. The latter groups 5 possibilities of the
18//! arguments:
19//!
20//! - `Struct`, when `Self` is a struct (including tuple structs, e.g
21//!   `struct T(i32, char)`).
22//! - `EnumMatching`, when `Self` is an enum and all the arguments are the
23//!   same variant of the enum (e.g., `Some(1)`, `Some(3)` and `Some(4)`)
24//! - `EnumDiscr` when `Self` is an enum, for comparing the enum discriminants.
25//! - `StaticEnum` and `StaticStruct` for static methods, where the type
26//!   being derived upon is either an enum or struct respectively. (Any
27//!   argument with type Self is just grouped among the non-self
28//!   arguments.)
29//!
30//! In the first two cases, the values from the corresponding fields in
31//! all the arguments are grouped together.
32//!
33//! The non-static cases have `Option<ident>` in several places associated
34//! with field `expr`s. This represents the name of the field it is
35//! associated with. It is only not `None` when the associated field has
36//! an identifier in the source code. For example, the `x`s in the
37//! following snippet
38//!
39//! ```rust
40//! struct A {
41//!     x: i32,
42//! }
43//!
44//! struct B(i32);
45//!
46//! enum C {
47//!     C0(i32),
48//!     C1 { x: i32 }
49//! }
50//! ```
51//!
52//! The `i32`s in `B` and `C0` don't have an identifier, so the
53//! `Option<ident>`s would be `None` for them.
54//!
55//! In the static cases, the structure is summarized, either into the just
56//! spans of the fields or a list of spans and the field idents (for tuple
57//! structs and record structs, respectively), or a list of these, for
58//! enums (one for each variant). For empty struct and empty enum
59//! variants, it is represented as a count of 0.
60//!
61//! # "`cs`" functions
62//!
63//! The `cs_...` functions ("combine substructure") are designed to
64//! make life easier by providing some pre-made recipes for common
65//! threads; mostly calling the function being derived on all the
66//! arguments and then combining them back together in some way (or
67//! letting the user chose that). They are not meant to be the only
68//! way to handle the structures that this code creates.
69//!
70//! # Examples
71//!
72//! The following simplified `PartialEq` is used for in-code examples:
73//!
74//! ```rust
75//! trait PartialEq {
76//!     fn eq(&self, other: &Self) -> bool;
77//! }
78//!
79//! impl PartialEq for i32 {
80//!     fn eq(&self, other: &i32) -> bool {
81//!         *self == *other
82//!     }
83//! }
84//! ```
85//!
86//! Some examples of the values of `SubstructureFields` follow, using the
87//! above `PartialEq`, `A`, `B` and `C`.
88//!
89//! ## Structs
90//!
91//! When generating the `expr` for the `A` impl, the `SubstructureFields` is
92//!
93//! ```text
94//! Struct(vec![FieldInfo {
95//!     span: <span of x>,
96//!     name: Some(<ident of x>),
97//!     self_: <expr for &self.x>,
98//!     other: vec![<expr for &other.x>],
99//! }])
100//! ```
101//!
102//! For the `B` impl, called with `B(a)` and `B(b)`,
103//!
104//! ```text
105//! Struct(vec![FieldInfo {
106//!     span: <span of i32>,
107//!     name: None,
108//!     self_: <expr for &a>,
109//!     other: vec![<expr for &b>],
110//! }])
111//! ```
112//!
113//! ## Enums
114//!
115//! When generating the `expr` for a call with `self == C0(a)` and `other
116//! == C0(b)`, the SubstructureFields is
117//!
118//! ```text
119//! EnumMatching(
120//!     0,
121//!     <ast::Variant for C0>,
122//!     vec![FieldInfo {
123//!         span: <span of i32>,
124//!         name: None,
125//!         self_: <expr for &a>,
126//!         other: vec![<expr for &b>],
127//!     }],
128//! )
129//! ```
130//!
131//! For `C1 {x}` and `C1 {x}`,
132//!
133//! ```text
134//! EnumMatching(
135//!     1,
136//!     <ast::Variant for C1>,
137//!     vec![FieldInfo {
138//!         span: <span of x>,
139//!         name: Some(<ident of x>),
140//!         self_: <expr for &self.x>,
141//!         other: vec![<expr for &other.x>],
142//!     }],
143//! )
144//! ```
145//!
146//! For the discriminants,
147//!
148//! ```text
149//! EnumDiscr(
150//!     &[<ident of self discriminant>, <ident of other discriminant>],
151//!     <expr to combine with>,
152//! )
153//! ```
154//!
155//! Note that this setup doesn't allow for the brute-force "match every variant
156//! against every other variant" approach, which is bad because it produces a
157//! quadratic amount of code (see #15375).
158//!
159//! ## Static
160//!
161//! A static method on the types above would result in,
162//!
163//! ```text
164//! StaticStruct(<ast::VariantData of A>, Named(vec![(<ident of x>, <span of x>)]))
165//!
166//! StaticStruct(<ast::VariantData of B>, Unnamed(vec![<span of x>]))
167//!
168//! StaticEnum(
169//!     <ast::EnumDef of C>,
170//!     vec![
171//!         (<ident of C0>, <span of C0>, Unnamed(vec![<span of i32>])),
172//!         (<ident of C1>, <span of C1>, Named(vec![(<ident of x>, <span of x>)])),
173//!     ],
174//! )
175//! ```
176
177use std::cell::RefCell;
178use std::ops::Not;
179use std::{iter, vec};
180
181pub(crate) use StaticFields::*;
182pub(crate) use SubstructureFields::*;
183use rustc_ast::ptr::P;
184use rustc_ast::{
185    self as ast, AnonConst, BindingMode, ByRef, EnumDef, Expr, GenericArg, GenericParamKind,
186    Generics, Mutability, PatKind, VariantData,
187};
188use rustc_attr_parsing::{AttributeKind, AttributeParser, ReprPacked};
189use rustc_expand::base::{Annotatable, ExtCtxt};
190use rustc_hir::Attribute;
191use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
192use thin_vec::{ThinVec, thin_vec};
193use ty::{Bounds, Path, Ref, Self_, Ty};
194
195use crate::{deriving, errors};
196
197pub(crate) mod ty;
198
199pub(crate) struct TraitDef<'a> {
200    /// The span for the current #[derive(Foo)] header.
201    pub span: Span,
202
203    /// Path of the trait, including any type parameters
204    pub path: Path,
205
206    /// Whether to skip adding the current trait as a bound to the type parameters of the type.
207    pub skip_path_as_bound: bool,
208
209    /// Whether `Copy` is needed as an additional bound on type parameters in a packed struct.
210    pub needs_copy_as_bound_if_packed: bool,
211
212    /// Additional bounds required of any type parameters of the type,
213    /// other than the current trait
214    pub additional_bounds: Vec<Ty>,
215
216    /// Can this trait be derived for unions?
217    pub supports_unions: bool,
218
219    pub methods: Vec<MethodDef<'a>>,
220
221    pub associated_types: Vec<(Ident, Ty)>,
222
223    pub is_const: bool,
224}
225
226pub(crate) struct MethodDef<'a> {
227    /// name of the method
228    pub name: Symbol,
229    /// List of generics, e.g., `R: rand::Rng`
230    pub generics: Bounds,
231
232    /// Is there is a `&self` argument? If not, it is a static function.
233    pub explicit_self: bool,
234
235    /// Arguments other than the self argument.
236    pub nonself_args: Vec<(Ty, Symbol)>,
237
238    /// Returns type
239    pub ret_ty: Ty,
240
241    pub attributes: ast::AttrVec,
242
243    pub fieldless_variants_strategy: FieldlessVariantsStrategy,
244
245    pub combine_substructure: RefCell<CombineSubstructureFunc<'a>>,
246}
247
248/// How to handle fieldless enum variants.
249#[derive(PartialEq)]
250pub(crate) enum FieldlessVariantsStrategy {
251    /// Combine fieldless variants into a single match arm.
252    /// This assumes that relevant information has been handled
253    /// by looking at the enum's discriminant.
254    Unify,
255    /// Don't do anything special about fieldless variants. They are
256    /// handled like any other variant.
257    Default,
258    /// If all variants of the enum are fieldless, expand the special
259    /// `AllFieldLessEnum` substructure, so that the entire enum can be handled
260    /// at once.
261    SpecializeIfAllVariantsFieldless,
262}
263
264/// All the data about the data structure/method being derived upon.
265pub(crate) struct Substructure<'a> {
266    /// ident of self
267    pub type_ident: Ident,
268    /// Verbatim access to any non-selflike arguments, i.e. arguments that
269    /// don't have type `&Self`.
270    pub nonselflike_args: &'a [P<Expr>],
271    pub fields: &'a SubstructureFields<'a>,
272}
273
274/// Summary of the relevant parts of a struct/enum field.
275pub(crate) struct FieldInfo {
276    pub span: Span,
277    /// None for tuple structs/normal enum variants, Some for normal
278    /// structs/struct enum variants.
279    pub name: Option<Ident>,
280    /// The expression corresponding to this field of `self`
281    /// (specifically, a reference to it).
282    pub self_expr: P<Expr>,
283    /// The expressions corresponding to references to this field in
284    /// the other selflike arguments.
285    pub other_selflike_exprs: Vec<P<Expr>>,
286}
287
288#[derive(Copy, Clone)]
289pub(crate) enum IsTuple {
290    No,
291    Yes,
292}
293
294/// Fields for a static method
295pub(crate) enum StaticFields {
296    /// Tuple and unit structs/enum variants like this.
297    Unnamed(Vec<Span>, IsTuple),
298    /// Normal structs/struct variants.
299    Named(Vec<(Ident, Span, Option<AnonConst>)>),
300}
301
302/// A summary of the possible sets of fields.
303pub(crate) enum SubstructureFields<'a> {
304    /// A non-static method where `Self` is a struct.
305    Struct(&'a ast::VariantData, Vec<FieldInfo>),
306
307    /// A non-static method handling the entire enum at once
308    /// (after it has been determined that none of the enum
309    /// variants has any fields).
310    AllFieldlessEnum(&'a ast::EnumDef),
311
312    /// Matching variants of the enum: variant index, ast::Variant,
313    /// fields: the field name is only non-`None` in the case of a struct
314    /// variant.
315    EnumMatching(&'a ast::Variant, Vec<FieldInfo>),
316
317    /// The discriminant of an enum. The first field is a `FieldInfo` for the discriminants, as
318    /// if they were fields. The second field is the expression to combine the
319    /// discriminant expression with; it will be `None` if no match is necessary.
320    EnumDiscr(FieldInfo, Option<P<Expr>>),
321
322    /// A static method where `Self` is a struct.
323    StaticStruct(&'a ast::VariantData, StaticFields),
324
325    /// A static method where `Self` is an enum.
326    StaticEnum(&'a ast::EnumDef),
327}
328
329/// Combine the values of all the fields together. The last argument is
330/// all the fields of all the structures.
331pub(crate) type CombineSubstructureFunc<'a> =
332    Box<dyn FnMut(&ExtCtxt<'_>, Span, &Substructure<'_>) -> BlockOrExpr + 'a>;
333
334pub(crate) fn combine_substructure(
335    f: CombineSubstructureFunc<'_>,
336) -> RefCell<CombineSubstructureFunc<'_>> {
337    RefCell::new(f)
338}
339
340struct TypeParameter {
341    bound_generic_params: ThinVec<ast::GenericParam>,
342    ty: P<ast::Ty>,
343}
344
345/// The code snippets built up for derived code are sometimes used as blocks
346/// (e.g. in a function body) and sometimes used as expressions (e.g. in a match
347/// arm). This structure avoids committing to either form until necessary,
348/// avoiding the insertion of any unnecessary blocks.
349///
350/// The statements come before the expression.
351pub(crate) struct BlockOrExpr(ThinVec<ast::Stmt>, Option<P<Expr>>);
352
353impl BlockOrExpr {
354    pub(crate) fn new_stmts(stmts: ThinVec<ast::Stmt>) -> BlockOrExpr {
355        BlockOrExpr(stmts, None)
356    }
357
358    pub(crate) fn new_expr(expr: P<Expr>) -> BlockOrExpr {
359        BlockOrExpr(ThinVec::new(), Some(expr))
360    }
361
362    pub(crate) fn new_mixed(stmts: ThinVec<ast::Stmt>, expr: Option<P<Expr>>) -> BlockOrExpr {
363        BlockOrExpr(stmts, expr)
364    }
365
366    // Converts it into a block.
367    fn into_block(mut self, cx: &ExtCtxt<'_>, span: Span) -> P<ast::Block> {
368        if let Some(expr) = self.1 {
369            self.0.push(cx.stmt_expr(expr));
370        }
371        cx.block(span, self.0)
372    }
373
374    // Converts it into an expression.
375    fn into_expr(self, cx: &ExtCtxt<'_>, span: Span) -> P<Expr> {
376        if self.0.is_empty() {
377            match self.1 {
378                None => cx.expr_block(cx.block(span, ThinVec::new())),
379                Some(expr) => expr,
380            }
381        } else if let [stmt] = self.0.as_slice()
382            && let ast::StmtKind::Expr(expr) = &stmt.kind
383            && self.1.is_none()
384        {
385            // There's only a single statement expression. Pull it out.
386            expr.clone()
387        } else {
388            // Multiple statements and/or expressions.
389            cx.expr_block(self.into_block(cx, span))
390        }
391    }
392}
393
394/// This method helps to extract all the type parameters referenced from a
395/// type. For a type parameter `<T>`, it looks for either a `TyPath` that
396/// is not global and starts with `T`, or a `TyQPath`.
397/// Also include bound generic params from the input type.
398fn find_type_parameters(
399    ty: &ast::Ty,
400    ty_param_names: &[Symbol],
401    cx: &ExtCtxt<'_>,
402) -> Vec<TypeParameter> {
403    use rustc_ast::visit;
404
405    struct Visitor<'a, 'b> {
406        cx: &'a ExtCtxt<'b>,
407        ty_param_names: &'a [Symbol],
408        bound_generic_params_stack: ThinVec<ast::GenericParam>,
409        type_params: Vec<TypeParameter>,
410    }
411
412    impl<'a, 'b> visit::Visitor<'a> for Visitor<'a, 'b> {
413        fn visit_ty(&mut self, ty: &'a ast::Ty) {
414            let stack_len = self.bound_generic_params_stack.len();
415            if let ast::TyKind::BareFn(bare_fn) = &ty.kind
416                && !bare_fn.generic_params.is_empty()
417            {
418                // Given a field `x: for<'a> fn(T::SomeType<'a>)`, we wan't to account for `'a` so
419                // that we generate `where for<'a> T::SomeType<'a>: ::core::clone::Clone`. #122622
420                self.bound_generic_params_stack.extend(bare_fn.generic_params.iter().cloned());
421            }
422
423            if let ast::TyKind::Path(_, path) = &ty.kind
424                && let Some(segment) = path.segments.first()
425                && self.ty_param_names.contains(&segment.ident.name)
426            {
427                self.type_params.push(TypeParameter {
428                    bound_generic_params: self.bound_generic_params_stack.clone(),
429                    ty: P(ty.clone()),
430                });
431            }
432
433            visit::walk_ty(self, ty);
434            self.bound_generic_params_stack.truncate(stack_len);
435        }
436
437        // Place bound generic params on a stack, to extract them when a type is encountered.
438        fn visit_poly_trait_ref(&mut self, trait_ref: &'a ast::PolyTraitRef) {
439            let stack_len = self.bound_generic_params_stack.len();
440            self.bound_generic_params_stack.extend(trait_ref.bound_generic_params.iter().cloned());
441
442            visit::walk_poly_trait_ref(self, trait_ref);
443
444            self.bound_generic_params_stack.truncate(stack_len);
445        }
446
447        fn visit_mac_call(&mut self, mac: &ast::MacCall) {
448            self.cx.dcx().emit_err(errors::DeriveMacroCall { span: mac.span() });
449        }
450    }
451
452    let mut visitor = Visitor {
453        cx,
454        ty_param_names,
455        bound_generic_params_stack: ThinVec::new(),
456        type_params: Vec::new(),
457    };
458    visit::Visitor::visit_ty(&mut visitor, ty);
459
460    visitor.type_params
461}
462
463impl<'a> TraitDef<'a> {
464    pub(crate) fn expand(
465        self,
466        cx: &ExtCtxt<'_>,
467        mitem: &ast::MetaItem,
468        item: &'a Annotatable,
469        push: &mut dyn FnMut(Annotatable),
470    ) {
471        self.expand_ext(cx, mitem, item, push, false);
472    }
473
474    pub(crate) fn expand_ext(
475        self,
476        cx: &ExtCtxt<'_>,
477        mitem: &ast::MetaItem,
478        item: &'a Annotatable,
479        push: &mut dyn FnMut(Annotatable),
480        from_scratch: bool,
481    ) {
482        match item {
483            Annotatable::Item(item) => {
484                let is_packed = matches!(
485                    AttributeParser::parse_limited(cx.sess, &item.attrs, sym::repr, item.span, true),
486                    Some(Attribute::Parsed(AttributeKind::Repr(r))) if r.iter().any(|(x, _)| matches!(x, ReprPacked(..)))
487                );
488
489                let newitem = match &item.kind {
490                    ast::ItemKind::Struct(ident, struct_def, generics) => self.expand_struct_def(
491                        cx,
492                        struct_def,
493                        *ident,
494                        generics,
495                        from_scratch,
496                        is_packed,
497                    ),
498                    ast::ItemKind::Enum(ident, enum_def, generics) => {
499                        // We ignore `is_packed` here, because `repr(packed)`
500                        // enums cause an error later on.
501                        //
502                        // This can only cause further compilation errors
503                        // downstream in blatantly illegal code, so it is fine.
504                        self.expand_enum_def(cx, enum_def, *ident, generics, from_scratch)
505                    }
506                    ast::ItemKind::Union(ident, struct_def, generics) => {
507                        if self.supports_unions {
508                            self.expand_struct_def(
509                                cx,
510                                struct_def,
511                                *ident,
512                                generics,
513                                from_scratch,
514                                is_packed,
515                            )
516                        } else {
517                            cx.dcx().emit_err(errors::DeriveUnion { span: mitem.span });
518                            return;
519                        }
520                    }
521                    _ => unreachable!(),
522                };
523                // Keep the lint attributes of the previous item to control how the
524                // generated implementations are linted
525                let mut attrs = newitem.attrs.clone();
526                attrs.extend(
527                    item.attrs
528                        .iter()
529                        .filter(|a| {
530                            a.has_any_name(&[
531                                sym::allow,
532                                sym::warn,
533                                sym::deny,
534                                sym::forbid,
535                                sym::stable,
536                                sym::unstable,
537                            ])
538                        })
539                        .cloned(),
540                );
541                push(Annotatable::Item(P(ast::Item { attrs, ..(*newitem).clone() })))
542            }
543            _ => unreachable!(),
544        }
545    }
546
547    /// Given that we are deriving a trait `DerivedTrait` for a type like:
548    ///
549    /// ```ignore (only-for-syntax-highlight)
550    /// struct Struct<'a, ..., 'z, A, B: DeclaredTrait, C, ..., Z>
551    /// where
552    ///     C: WhereTrait,
553    /// {
554    ///     a: A,
555    ///     b: B::Item,
556    ///     b1: <B as DeclaredTrait>::Item,
557    ///     c1: <C as WhereTrait>::Item,
558    ///     c2: Option<<C as WhereTrait>::Item>,
559    ///     ...
560    /// }
561    /// ```
562    ///
563    /// create an impl like:
564    ///
565    /// ```ignore (only-for-syntax-highlight)
566    /// impl<'a, ..., 'z, A, B: DeclaredTrait, C, ..., Z>
567    /// where
568    ///     C: WhereTrait,
569    ///     A: DerivedTrait + B1 + ... + BN,
570    ///     B: DerivedTrait + B1 + ... + BN,
571    ///     C: DerivedTrait + B1 + ... + BN,
572    ///     B::Item: DerivedTrait + B1 + ... + BN,
573    ///     <C as WhereTrait>::Item: DerivedTrait + B1 + ... + BN,
574    ///     ...
575    /// {
576    ///     ...
577    /// }
578    /// ```
579    ///
580    /// where B1, ..., BN are the bounds given by `bounds_paths`.'. Z is a phantom type, and
581    /// therefore does not get bound by the derived trait.
582    fn create_derived_impl(
583        &self,
584        cx: &ExtCtxt<'_>,
585        type_ident: Ident,
586        generics: &Generics,
587        field_tys: Vec<P<ast::Ty>>,
588        methods: Vec<P<ast::AssocItem>>,
589        is_packed: bool,
590    ) -> P<ast::Item> {
591        let trait_path = self.path.to_path(cx, self.span, type_ident, generics);
592
593        // Transform associated types from `deriving::ty::Ty` into `ast::AssocItem`
594        let associated_types = self.associated_types.iter().map(|&(ident, ref type_def)| {
595            P(ast::AssocItem {
596                id: ast::DUMMY_NODE_ID,
597                span: self.span,
598                vis: ast::Visibility {
599                    span: self.span.shrink_to_lo(),
600                    kind: ast::VisibilityKind::Inherited,
601                    tokens: None,
602                },
603                attrs: ast::AttrVec::new(),
604                kind: ast::AssocItemKind::Type(Box::new(ast::TyAlias {
605                    defaultness: ast::Defaultness::Final,
606                    ident,
607                    generics: Generics::default(),
608                    where_clauses: ast::TyAliasWhereClauses::default(),
609                    bounds: Vec::new(),
610                    ty: Some(type_def.to_ty(cx, self.span, type_ident, generics)),
611                })),
612                tokens: None,
613            })
614        });
615
616        let mut where_clause = ast::WhereClause::default();
617        where_clause.span = generics.where_clause.span;
618        let ctxt = self.span.ctxt();
619        let span = generics.span.with_ctxt(ctxt);
620
621        // Create the generic parameters
622        let params: ThinVec<_> = generics
623            .params
624            .iter()
625            .map(|param| match &param.kind {
626                GenericParamKind::Lifetime { .. } => param.clone(),
627                GenericParamKind::Type { .. } => {
628                    // Extra restrictions on the generics parameters to the
629                    // type being derived upon.
630                    let bounds: Vec<_> = self
631                        .additional_bounds
632                        .iter()
633                        .map(|p| {
634                            cx.trait_bound(
635                                p.to_path(cx, self.span, type_ident, generics),
636                                self.is_const,
637                            )
638                        })
639                        .chain(
640                            // Add a bound for the current trait.
641                            self.skip_path_as_bound
642                                .not()
643                                .then(|| cx.trait_bound(trait_path.clone(), self.is_const)),
644                        )
645                        .chain({
646                            // Add a `Copy` bound if required.
647                            if is_packed && self.needs_copy_as_bound_if_packed {
648                                let p = deriving::path_std!(marker::Copy);
649                                Some(cx.trait_bound(
650                                    p.to_path(cx, self.span, type_ident, generics),
651                                    self.is_const,
652                                ))
653                            } else {
654                                None
655                            }
656                        })
657                        .chain(
658                            // Also add in any bounds from the declaration.
659                            param.bounds.iter().cloned(),
660                        )
661                        .collect();
662
663                    cx.typaram(param.ident.span.with_ctxt(ctxt), param.ident, bounds, None)
664                }
665                GenericParamKind::Const { ty, kw_span, .. } => {
666                    let const_nodefault_kind = GenericParamKind::Const {
667                        ty: ty.clone(),
668                        kw_span: kw_span.with_ctxt(ctxt),
669
670                        // We can't have default values inside impl block
671                        default: None,
672                    };
673                    let mut param_clone = param.clone();
674                    param_clone.kind = const_nodefault_kind;
675                    param_clone
676                }
677            })
678            .map(|mut param| {
679                // Remove all attributes, because there might be helper attributes
680                // from other macros that will not be valid in the expanded implementation.
681                param.attrs.clear();
682                param
683            })
684            .collect();
685
686        // and similarly for where clauses
687        where_clause.predicates.extend(generics.where_clause.predicates.iter().map(|clause| {
688            ast::WherePredicate {
689                attrs: clause.attrs.clone(),
690                kind: clause.kind.clone(),
691                id: ast::DUMMY_NODE_ID,
692                span: clause.span.with_ctxt(ctxt),
693                is_placeholder: false,
694            }
695        }));
696
697        let ty_param_names: Vec<Symbol> = params
698            .iter()
699            .filter(|param| matches!(param.kind, ast::GenericParamKind::Type { .. }))
700            .map(|ty_param| ty_param.ident.name)
701            .collect();
702
703        if !ty_param_names.is_empty() {
704            for field_ty in field_tys {
705                let field_ty_params = find_type_parameters(&field_ty, &ty_param_names, cx);
706
707                for field_ty_param in field_ty_params {
708                    // if we have already handled this type, skip it
709                    if let ast::TyKind::Path(_, p) = &field_ty_param.ty.kind
710                        && let [sole_segment] = &*p.segments
711                        && ty_param_names.contains(&sole_segment.ident.name)
712                    {
713                        continue;
714                    }
715                    let mut bounds: Vec<_> = self
716                        .additional_bounds
717                        .iter()
718                        .map(|p| {
719                            cx.trait_bound(
720                                p.to_path(cx, self.span, type_ident, generics),
721                                self.is_const,
722                            )
723                        })
724                        .collect();
725
726                    // Require the current trait.
727                    if !self.skip_path_as_bound {
728                        bounds.push(cx.trait_bound(trait_path.clone(), self.is_const));
729                    }
730
731                    // Add a `Copy` bound if required.
732                    if is_packed && self.needs_copy_as_bound_if_packed {
733                        let p = deriving::path_std!(marker::Copy);
734                        bounds.push(cx.trait_bound(
735                            p.to_path(cx, self.span, type_ident, generics),
736                            self.is_const,
737                        ));
738                    }
739
740                    if !bounds.is_empty() {
741                        let predicate = ast::WhereBoundPredicate {
742                            bound_generic_params: field_ty_param.bound_generic_params,
743                            bounded_ty: field_ty_param.ty,
744                            bounds,
745                        };
746
747                        let kind = ast::WherePredicateKind::BoundPredicate(predicate);
748                        let predicate = ast::WherePredicate {
749                            attrs: ThinVec::new(),
750                            kind,
751                            id: ast::DUMMY_NODE_ID,
752                            span: self.span,
753                            is_placeholder: false,
754                        };
755                        where_clause.predicates.push(predicate);
756                    }
757                }
758            }
759        }
760
761        let trait_generics = Generics { params, where_clause, span };
762
763        // Create the reference to the trait.
764        let trait_ref = cx.trait_ref(trait_path);
765
766        let self_params: Vec<_> = generics
767            .params
768            .iter()
769            .map(|param| match param.kind {
770                GenericParamKind::Lifetime { .. } => {
771                    GenericArg::Lifetime(cx.lifetime(param.ident.span.with_ctxt(ctxt), param.ident))
772                }
773                GenericParamKind::Type { .. } => {
774                    GenericArg::Type(cx.ty_ident(param.ident.span.with_ctxt(ctxt), param.ident))
775                }
776                GenericParamKind::Const { .. } => {
777                    GenericArg::Const(cx.const_ident(param.ident.span.with_ctxt(ctxt), param.ident))
778                }
779            })
780            .collect();
781
782        // Create the type of `self`.
783        let path = cx.path_all(self.span, false, vec![type_ident], self_params);
784        let self_type = cx.ty_path(path);
785
786        let attrs = thin_vec![cx.attr_word(sym::automatically_derived, self.span),];
787        let opt_trait_ref = Some(trait_ref);
788
789        cx.item(
790            self.span,
791            attrs,
792            ast::ItemKind::Impl(Box::new(ast::Impl {
793                safety: ast::Safety::Default,
794                polarity: ast::ImplPolarity::Positive,
795                defaultness: ast::Defaultness::Final,
796                constness: if self.is_const { ast::Const::Yes(DUMMY_SP) } else { ast::Const::No },
797                generics: trait_generics,
798                of_trait: opt_trait_ref,
799                self_ty: self_type,
800                items: methods.into_iter().chain(associated_types).collect(),
801            })),
802        )
803    }
804
805    fn expand_struct_def(
806        &self,
807        cx: &ExtCtxt<'_>,
808        struct_def: &'a VariantData,
809        type_ident: Ident,
810        generics: &Generics,
811        from_scratch: bool,
812        is_packed: bool,
813    ) -> P<ast::Item> {
814        let field_tys: Vec<P<ast::Ty>> =
815            struct_def.fields().iter().map(|field| field.ty.clone()).collect();
816
817        let methods = self
818            .methods
819            .iter()
820            .map(|method_def| {
821                let (explicit_self, selflike_args, nonselflike_args, nonself_arg_tys) =
822                    method_def.extract_arg_details(cx, self, type_ident, generics);
823
824                let body = if from_scratch || method_def.is_static() {
825                    method_def.expand_static_struct_method_body(
826                        cx,
827                        self,
828                        struct_def,
829                        type_ident,
830                        &nonselflike_args,
831                    )
832                } else {
833                    method_def.expand_struct_method_body(
834                        cx,
835                        self,
836                        struct_def,
837                        type_ident,
838                        &selflike_args,
839                        &nonselflike_args,
840                        is_packed,
841                    )
842                };
843
844                method_def.create_method(
845                    cx,
846                    self,
847                    type_ident,
848                    generics,
849                    explicit_self,
850                    nonself_arg_tys,
851                    body,
852                )
853            })
854            .collect();
855
856        self.create_derived_impl(cx, type_ident, generics, field_tys, methods, is_packed)
857    }
858
859    fn expand_enum_def(
860        &self,
861        cx: &ExtCtxt<'_>,
862        enum_def: &'a EnumDef,
863        type_ident: Ident,
864        generics: &Generics,
865        from_scratch: bool,
866    ) -> P<ast::Item> {
867        let mut field_tys = Vec::new();
868
869        for variant in &enum_def.variants {
870            field_tys.extend(variant.data.fields().iter().map(|field| field.ty.clone()));
871        }
872
873        let methods = self
874            .methods
875            .iter()
876            .map(|method_def| {
877                let (explicit_self, selflike_args, nonselflike_args, nonself_arg_tys) =
878                    method_def.extract_arg_details(cx, self, type_ident, generics);
879
880                let body = if from_scratch || method_def.is_static() {
881                    method_def.expand_static_enum_method_body(
882                        cx,
883                        self,
884                        enum_def,
885                        type_ident,
886                        &nonselflike_args,
887                    )
888                } else {
889                    method_def.expand_enum_method_body(
890                        cx,
891                        self,
892                        enum_def,
893                        type_ident,
894                        selflike_args,
895                        &nonselflike_args,
896                    )
897                };
898
899                method_def.create_method(
900                    cx,
901                    self,
902                    type_ident,
903                    generics,
904                    explicit_self,
905                    nonself_arg_tys,
906                    body,
907                )
908            })
909            .collect();
910
911        let is_packed = false; // enums are never packed
912        self.create_derived_impl(cx, type_ident, generics, field_tys, methods, is_packed)
913    }
914}
915
916impl<'a> MethodDef<'a> {
917    fn call_substructure_method(
918        &self,
919        cx: &ExtCtxt<'_>,
920        trait_: &TraitDef<'_>,
921        type_ident: Ident,
922        nonselflike_args: &[P<Expr>],
923        fields: &SubstructureFields<'_>,
924    ) -> BlockOrExpr {
925        let span = trait_.span;
926        let substructure = Substructure { type_ident, nonselflike_args, fields };
927        let mut f = self.combine_substructure.borrow_mut();
928        let f: &mut CombineSubstructureFunc<'_> = &mut *f;
929        f(cx, span, &substructure)
930    }
931
932    fn get_ret_ty(
933        &self,
934        cx: &ExtCtxt<'_>,
935        trait_: &TraitDef<'_>,
936        generics: &Generics,
937        type_ident: Ident,
938    ) -> P<ast::Ty> {
939        self.ret_ty.to_ty(cx, trait_.span, type_ident, generics)
940    }
941
942    fn is_static(&self) -> bool {
943        !self.explicit_self
944    }
945
946    // The return value includes:
947    // - explicit_self: The `&self` arg, if present.
948    // - selflike_args: Expressions for `&self` (if present) and also any other
949    //   args with the same type (e.g. the `other` arg in `PartialEq::eq`).
950    // - nonselflike_args: Expressions for all the remaining args.
951    // - nonself_arg_tys: Additional information about all the args other than
952    //   `&self`.
953    fn extract_arg_details(
954        &self,
955        cx: &ExtCtxt<'_>,
956        trait_: &TraitDef<'_>,
957        type_ident: Ident,
958        generics: &Generics,
959    ) -> (Option<ast::ExplicitSelf>, ThinVec<P<Expr>>, Vec<P<Expr>>, Vec<(Ident, P<ast::Ty>)>) {
960        let mut selflike_args = ThinVec::new();
961        let mut nonselflike_args = Vec::new();
962        let mut nonself_arg_tys = Vec::new();
963        let span = trait_.span;
964
965        let explicit_self = self.explicit_self.then(|| {
966            let (self_expr, explicit_self) = ty::get_explicit_self(cx, span);
967            selflike_args.push(self_expr);
968            explicit_self
969        });
970
971        for (ty, name) in self.nonself_args.iter() {
972            let ast_ty = ty.to_ty(cx, span, type_ident, generics);
973            let ident = Ident::new(*name, span);
974            nonself_arg_tys.push((ident, ast_ty));
975
976            let arg_expr = cx.expr_ident(span, ident);
977
978            match ty {
979                // Selflike (`&Self`) arguments only occur in non-static methods.
980                Ref(box Self_, _) if !self.is_static() => selflike_args.push(arg_expr),
981                Self_ => cx.dcx().span_bug(span, "`Self` in non-return position"),
982                _ => nonselflike_args.push(arg_expr),
983            }
984        }
985
986        (explicit_self, selflike_args, nonselflike_args, nonself_arg_tys)
987    }
988
989    fn create_method(
990        &self,
991        cx: &ExtCtxt<'_>,
992        trait_: &TraitDef<'_>,
993        type_ident: Ident,
994        generics: &Generics,
995        explicit_self: Option<ast::ExplicitSelf>,
996        nonself_arg_tys: Vec<(Ident, P<ast::Ty>)>,
997        body: BlockOrExpr,
998    ) -> P<ast::AssocItem> {
999        let span = trait_.span;
1000        // Create the generics that aren't for `Self`.
1001        let fn_generics = self.generics.to_generics(cx, span, type_ident, generics);
1002
1003        let args = {
1004            let self_arg = explicit_self.map(|explicit_self| {
1005                let ident = Ident::with_dummy_span(kw::SelfLower).with_span_pos(span);
1006                ast::Param::from_self(ast::AttrVec::default(), explicit_self, ident)
1007            });
1008            let nonself_args =
1009                nonself_arg_tys.into_iter().map(|(name, ty)| cx.param(span, name, ty));
1010            self_arg.into_iter().chain(nonself_args).collect()
1011        };
1012
1013        let ret_type = self.get_ret_ty(cx, trait_, generics, type_ident);
1014
1015        let method_ident = Ident::new(self.name, span);
1016        let fn_decl = cx.fn_decl(args, ast::FnRetTy::Ty(ret_type));
1017        let body_block = body.into_block(cx, span);
1018
1019        let trait_lo_sp = span.shrink_to_lo();
1020
1021        let sig = ast::FnSig { header: ast::FnHeader::default(), decl: fn_decl, span };
1022        let defaultness = ast::Defaultness::Final;
1023
1024        // Create the method.
1025        P(ast::AssocItem {
1026            id: ast::DUMMY_NODE_ID,
1027            attrs: self.attributes.clone(),
1028            span,
1029            vis: ast::Visibility {
1030                span: trait_lo_sp,
1031                kind: ast::VisibilityKind::Inherited,
1032                tokens: None,
1033            },
1034            kind: ast::AssocItemKind::Fn(Box::new(ast::Fn {
1035                defaultness,
1036                sig,
1037                ident: method_ident,
1038                generics: fn_generics,
1039                contract: None,
1040                body: Some(body_block),
1041                define_opaque: None,
1042            })),
1043            tokens: None,
1044        })
1045    }
1046
1047    /// The normal case uses field access.
1048    ///
1049    /// ```
1050    /// #[derive(PartialEq)]
1051    /// # struct Dummy;
1052    /// struct A { x: u8, y: u8 }
1053    ///
1054    /// // equivalent to:
1055    /// impl PartialEq for A {
1056    ///     fn eq(&self, other: &A) -> bool {
1057    ///         self.x == other.x && self.y == other.y
1058    ///     }
1059    /// }
1060    /// ```
1061    ///
1062    /// But if the struct is `repr(packed)`, we can't use something like
1063    /// `&self.x` because that might cause an unaligned ref. So for any trait
1064    /// method that takes a reference, we use a local block to force a copy.
1065    /// This requires that the field impl `Copy`.
1066    ///
1067    /// ```rust,ignore (example)
1068    /// # struct A { x: u8, y: u8 }
1069    /// impl PartialEq for A {
1070    ///     fn eq(&self, other: &A) -> bool {
1071    ///         // Desugars to `{ self.x }.eq(&{ other.y }) && ...`
1072    ///         { self.x } == { other.y } && { self.y } == { other.y }
1073    ///     }
1074    /// }
1075    /// impl Hash for A {
1076    ///     fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
1077    ///         ::core::hash::Hash::hash(&{ self.x }, state);
1078    ///         ::core::hash::Hash::hash(&{ self.y }, state);
1079    ///     }
1080    /// }
1081    /// ```
1082    fn expand_struct_method_body<'b>(
1083        &self,
1084        cx: &ExtCtxt<'_>,
1085        trait_: &TraitDef<'b>,
1086        struct_def: &'b VariantData,
1087        type_ident: Ident,
1088        selflike_args: &[P<Expr>],
1089        nonselflike_args: &[P<Expr>],
1090        is_packed: bool,
1091    ) -> BlockOrExpr {
1092        assert!(selflike_args.len() == 1 || selflike_args.len() == 2);
1093
1094        let selflike_fields =
1095            trait_.create_struct_field_access_fields(cx, selflike_args, struct_def, is_packed);
1096        self.call_substructure_method(
1097            cx,
1098            trait_,
1099            type_ident,
1100            nonselflike_args,
1101            &Struct(struct_def, selflike_fields),
1102        )
1103    }
1104
1105    fn expand_static_struct_method_body(
1106        &self,
1107        cx: &ExtCtxt<'_>,
1108        trait_: &TraitDef<'_>,
1109        struct_def: &VariantData,
1110        type_ident: Ident,
1111        nonselflike_args: &[P<Expr>],
1112    ) -> BlockOrExpr {
1113        let summary = trait_.summarise_struct(cx, struct_def);
1114
1115        self.call_substructure_method(
1116            cx,
1117            trait_,
1118            type_ident,
1119            nonselflike_args,
1120            &StaticStruct(struct_def, summary),
1121        )
1122    }
1123
1124    /// ```
1125    /// #[derive(PartialEq)]
1126    /// # struct Dummy;
1127    /// enum A {
1128    ///     A1,
1129    ///     A2(i32)
1130    /// }
1131    /// ```
1132    ///
1133    /// is equivalent to:
1134    ///
1135    /// ```
1136    /// #![feature(core_intrinsics)]
1137    /// enum A {
1138    ///     A1,
1139    ///     A2(i32)
1140    /// }
1141    /// impl ::core::cmp::PartialEq for A {
1142    ///     #[inline]
1143    ///     fn eq(&self, other: &A) -> bool {
1144    ///         let __self_discr = ::core::intrinsics::discriminant_value(self);
1145    ///         let __arg1_discr = ::core::intrinsics::discriminant_value(other);
1146    ///         __self_discr == __arg1_discr
1147    ///             && match (self, other) {
1148    ///                 (A::A2(__self_0), A::A2(__arg1_0)) => *__self_0 == *__arg1_0,
1149    ///                 _ => true,
1150    ///             }
1151    ///     }
1152    /// }
1153    /// ```
1154    ///
1155    /// Creates a discriminant check combined with a match for a tuple of all
1156    /// `selflike_args`, with an arm for each variant with fields, possibly an
1157    /// arm for each fieldless variant (if `unify_fieldless_variants` is not
1158    /// `Unify`), and possibly a default arm.
1159    fn expand_enum_method_body<'b>(
1160        &self,
1161        cx: &ExtCtxt<'_>,
1162        trait_: &TraitDef<'b>,
1163        enum_def: &'b EnumDef,
1164        type_ident: Ident,
1165        mut selflike_args: ThinVec<P<Expr>>,
1166        nonselflike_args: &[P<Expr>],
1167    ) -> BlockOrExpr {
1168        assert!(
1169            !selflike_args.is_empty(),
1170            "static methods must use `expand_static_enum_method_body`",
1171        );
1172
1173        let span = trait_.span;
1174        let variants = &enum_def.variants;
1175
1176        // Traits that unify fieldless variants always use the discriminant(s).
1177        let unify_fieldless_variants =
1178            self.fieldless_variants_strategy == FieldlessVariantsStrategy::Unify;
1179
1180        // For zero-variant enum, this function body is unreachable. Generate
1181        // `match *self {}`. This produces machine code identical to `unsafe {
1182        // core::intrinsics::unreachable() }` while being safe and stable.
1183        if variants.is_empty() {
1184            selflike_args.truncate(1);
1185            let match_arg = cx.expr_deref(span, selflike_args.pop().unwrap());
1186            let match_arms = ThinVec::new();
1187            let expr = cx.expr_match(span, match_arg, match_arms);
1188            return BlockOrExpr(ThinVec::new(), Some(expr));
1189        }
1190
1191        let prefixes = iter::once("__self".to_string())
1192            .chain(
1193                selflike_args
1194                    .iter()
1195                    .enumerate()
1196                    .skip(1)
1197                    .map(|(arg_count, _selflike_arg)| format!("__arg{arg_count}")),
1198            )
1199            .collect::<Vec<String>>();
1200
1201        // Build a series of let statements mapping each selflike_arg
1202        // to its discriminant value.
1203        //
1204        // e.g. for `PartialEq::eq` builds two statements:
1205        // ```
1206        // let __self_discr = ::core::intrinsics::discriminant_value(self);
1207        // let __arg1_discr = ::core::intrinsics::discriminant_value(other);
1208        // ```
1209        let get_discr_pieces = |cx: &ExtCtxt<'_>| {
1210            let discr_idents: Vec<_> = prefixes
1211                .iter()
1212                .map(|name| Ident::from_str_and_span(&format!("{name}_discr"), span))
1213                .collect();
1214
1215            let mut discr_exprs: Vec<_> = discr_idents
1216                .iter()
1217                .map(|&ident| cx.expr_addr_of(span, cx.expr_ident(span, ident)))
1218                .collect();
1219
1220            let self_expr = discr_exprs.remove(0);
1221            let other_selflike_exprs = discr_exprs;
1222            let discr_field = FieldInfo { span, name: None, self_expr, other_selflike_exprs };
1223
1224            let discr_let_stmts: ThinVec<_> = iter::zip(&discr_idents, &selflike_args)
1225                .map(|(&ident, selflike_arg)| {
1226                    let variant_value = deriving::call_intrinsic(
1227                        cx,
1228                        span,
1229                        sym::discriminant_value,
1230                        thin_vec![selflike_arg.clone()],
1231                    );
1232                    cx.stmt_let(span, false, ident, variant_value)
1233                })
1234                .collect();
1235
1236            (discr_field, discr_let_stmts)
1237        };
1238
1239        // There are some special cases involving fieldless enums where no
1240        // match is necessary.
1241        let all_fieldless = variants.iter().all(|v| v.data.fields().is_empty());
1242        if all_fieldless {
1243            if variants.len() > 1 {
1244                match self.fieldless_variants_strategy {
1245                    FieldlessVariantsStrategy::Unify => {
1246                        // If the type is fieldless and the trait uses the discriminant and
1247                        // there are multiple variants, we need just an operation on
1248                        // the discriminant(s).
1249                        let (discr_field, mut discr_let_stmts) = get_discr_pieces(cx);
1250                        let mut discr_check = self.call_substructure_method(
1251                            cx,
1252                            trait_,
1253                            type_ident,
1254                            nonselflike_args,
1255                            &EnumDiscr(discr_field, None),
1256                        );
1257                        discr_let_stmts.append(&mut discr_check.0);
1258                        return BlockOrExpr(discr_let_stmts, discr_check.1);
1259                    }
1260                    FieldlessVariantsStrategy::SpecializeIfAllVariantsFieldless => {
1261                        return self.call_substructure_method(
1262                            cx,
1263                            trait_,
1264                            type_ident,
1265                            nonselflike_args,
1266                            &AllFieldlessEnum(enum_def),
1267                        );
1268                    }
1269                    FieldlessVariantsStrategy::Default => (),
1270                }
1271            } else if let [variant] = variants.as_slice() {
1272                // If there is a single variant, we don't need an operation on
1273                // the discriminant(s). Just use the most degenerate result.
1274                return self.call_substructure_method(
1275                    cx,
1276                    trait_,
1277                    type_ident,
1278                    nonselflike_args,
1279                    &EnumMatching(variant, Vec::new()),
1280                );
1281            }
1282        }
1283
1284        // These arms are of the form:
1285        // (Variant1, Variant1, ...) => Body1
1286        // (Variant2, Variant2, ...) => Body2
1287        // ...
1288        // where each tuple has length = selflike_args.len()
1289        let mut match_arms: ThinVec<ast::Arm> = variants
1290            .iter()
1291            .filter(|&v| !(unify_fieldless_variants && v.data.fields().is_empty()))
1292            .map(|variant| {
1293                // A single arm has form (&VariantK, &VariantK, ...) => BodyK
1294                // (see "Final wrinkle" note below for why.)
1295
1296                let fields = trait_.create_struct_pattern_fields(cx, &variant.data, &prefixes);
1297
1298                let sp = variant.span.with_ctxt(trait_.span.ctxt());
1299                let variant_path = cx.path(sp, vec![type_ident, variant.ident]);
1300                let by_ref = ByRef::No; // because enums can't be repr(packed)
1301                let mut subpats = trait_.create_struct_patterns(
1302                    cx,
1303                    variant_path,
1304                    &variant.data,
1305                    &prefixes,
1306                    by_ref,
1307                );
1308
1309                // `(VariantK, VariantK, ...)` or just `VariantK`.
1310                let single_pat = if subpats.len() == 1 {
1311                    subpats.pop().unwrap()
1312                } else {
1313                    cx.pat_tuple(span, subpats)
1314                };
1315
1316                // For the BodyK, we need to delegate to our caller,
1317                // passing it an EnumMatching to indicate which case
1318                // we are in.
1319                //
1320                // Now, for some given VariantK, we have built up
1321                // expressions for referencing every field of every
1322                // Self arg, assuming all are instances of VariantK.
1323                // Build up code associated with such a case.
1324                let substructure = EnumMatching(variant, fields);
1325                let arm_expr = self
1326                    .call_substructure_method(
1327                        cx,
1328                        trait_,
1329                        type_ident,
1330                        nonselflike_args,
1331                        &substructure,
1332                    )
1333                    .into_expr(cx, span);
1334
1335                cx.arm(span, single_pat, arm_expr)
1336            })
1337            .collect();
1338
1339        // Add a default arm to the match, if necessary.
1340        let first_fieldless = variants.iter().find(|v| v.data.fields().is_empty());
1341        let default = match first_fieldless {
1342            Some(v) if unify_fieldless_variants => {
1343                // We need a default case that handles all the fieldless
1344                // variants. The index and actual variant aren't meaningful in
1345                // this case, so just use dummy values.
1346                Some(
1347                    self.call_substructure_method(
1348                        cx,
1349                        trait_,
1350                        type_ident,
1351                        nonselflike_args,
1352                        &EnumMatching(v, Vec::new()),
1353                    )
1354                    .into_expr(cx, span),
1355                )
1356            }
1357            _ if variants.len() > 1 && selflike_args.len() > 1 => {
1358                // Because we know that all the arguments will match if we reach
1359                // the match expression we add the unreachable intrinsics as the
1360                // result of the default which should help llvm in optimizing it.
1361                Some(deriving::call_unreachable(cx, span))
1362            }
1363            _ => None,
1364        };
1365        if let Some(arm) = default {
1366            match_arms.push(cx.arm(span, cx.pat_wild(span), arm));
1367        }
1368
1369        // Create a match expression with one arm per discriminant plus
1370        // possibly a default arm, e.g.:
1371        //      match (self, other) {
1372        //          (Variant1, Variant1, ...) => Body1
1373        //          (Variant2, Variant2, ...) => Body2,
1374        //          ...
1375        //          _ => ::core::intrinsics::unreachable(),
1376        //      }
1377        let get_match_expr = |mut selflike_args: ThinVec<P<Expr>>| {
1378            let match_arg = if selflike_args.len() == 1 {
1379                selflike_args.pop().unwrap()
1380            } else {
1381                cx.expr(span, ast::ExprKind::Tup(selflike_args))
1382            };
1383            cx.expr_match(span, match_arg, match_arms)
1384        };
1385
1386        // If the trait uses the discriminant and there are multiple variants, we need
1387        // to add a discriminant check operation before the match. Otherwise, the match
1388        // is enough.
1389        if unify_fieldless_variants && variants.len() > 1 {
1390            let (discr_field, mut discr_let_stmts) = get_discr_pieces(cx);
1391
1392            // Combine a discriminant check with the match.
1393            let mut discr_check_plus_match = self.call_substructure_method(
1394                cx,
1395                trait_,
1396                type_ident,
1397                nonselflike_args,
1398                &EnumDiscr(discr_field, Some(get_match_expr(selflike_args))),
1399            );
1400            discr_let_stmts.append(&mut discr_check_plus_match.0);
1401            BlockOrExpr(discr_let_stmts, discr_check_plus_match.1)
1402        } else {
1403            BlockOrExpr(ThinVec::new(), Some(get_match_expr(selflike_args)))
1404        }
1405    }
1406
1407    fn expand_static_enum_method_body(
1408        &self,
1409        cx: &ExtCtxt<'_>,
1410        trait_: &TraitDef<'_>,
1411        enum_def: &EnumDef,
1412        type_ident: Ident,
1413        nonselflike_args: &[P<Expr>],
1414    ) -> BlockOrExpr {
1415        self.call_substructure_method(
1416            cx,
1417            trait_,
1418            type_ident,
1419            nonselflike_args,
1420            &StaticEnum(enum_def),
1421        )
1422    }
1423}
1424
1425// general helper methods.
1426impl<'a> TraitDef<'a> {
1427    fn summarise_struct(&self, cx: &ExtCtxt<'_>, struct_def: &VariantData) -> StaticFields {
1428        let mut named_idents = Vec::new();
1429        let mut just_spans = Vec::new();
1430        for field in struct_def.fields() {
1431            let sp = field.span.with_ctxt(self.span.ctxt());
1432            match field.ident {
1433                Some(ident) => named_idents.push((ident, sp, field.default.clone())),
1434                _ => just_spans.push(sp),
1435            }
1436        }
1437
1438        let is_tuple = match struct_def {
1439            ast::VariantData::Tuple(..) => IsTuple::Yes,
1440            _ => IsTuple::No,
1441        };
1442        match (just_spans.is_empty(), named_idents.is_empty()) {
1443            (false, false) => cx
1444                .dcx()
1445                .span_bug(self.span, "a struct with named and unnamed fields in generic `derive`"),
1446            // named fields
1447            (_, false) => Named(named_idents),
1448            // unnamed fields
1449            (false, _) => Unnamed(just_spans, is_tuple),
1450            // empty
1451            _ => Named(Vec::new()),
1452        }
1453    }
1454
1455    fn create_struct_patterns(
1456        &self,
1457        cx: &ExtCtxt<'_>,
1458        struct_path: ast::Path,
1459        struct_def: &'a VariantData,
1460        prefixes: &[String],
1461        by_ref: ByRef,
1462    ) -> ThinVec<P<ast::Pat>> {
1463        prefixes
1464            .iter()
1465            .map(|prefix| {
1466                let pieces_iter =
1467                    struct_def.fields().iter().enumerate().map(|(i, struct_field)| {
1468                        let sp = struct_field.span.with_ctxt(self.span.ctxt());
1469                        let ident = self.mk_pattern_ident(prefix, i);
1470                        let path = ident.with_span_pos(sp);
1471                        (
1472                            sp,
1473                            struct_field.ident,
1474                            cx.pat(
1475                                path.span,
1476                                PatKind::Ident(BindingMode(by_ref, Mutability::Not), path, None),
1477                            ),
1478                        )
1479                    });
1480
1481                let struct_path = struct_path.clone();
1482                match *struct_def {
1483                    VariantData::Struct { .. } => {
1484                        let field_pats = pieces_iter
1485                            .map(|(sp, ident, pat)| {
1486                                if ident.is_none() {
1487                                    cx.dcx().span_bug(
1488                                        sp,
1489                                        "a braced struct with unnamed fields in `derive`",
1490                                    );
1491                                }
1492                                ast::PatField {
1493                                    ident: ident.unwrap(),
1494                                    is_shorthand: false,
1495                                    attrs: ast::AttrVec::new(),
1496                                    id: ast::DUMMY_NODE_ID,
1497                                    span: pat.span.with_ctxt(self.span.ctxt()),
1498                                    pat,
1499                                    is_placeholder: false,
1500                                }
1501                            })
1502                            .collect();
1503                        cx.pat_struct(self.span, struct_path, field_pats)
1504                    }
1505                    VariantData::Tuple(..) => {
1506                        let subpats = pieces_iter.map(|(_, _, subpat)| subpat).collect();
1507                        cx.pat_tuple_struct(self.span, struct_path, subpats)
1508                    }
1509                    VariantData::Unit(..) => cx.pat_path(self.span, struct_path),
1510                }
1511            })
1512            .collect()
1513    }
1514
1515    fn create_fields<F>(&self, struct_def: &'a VariantData, mk_exprs: F) -> Vec<FieldInfo>
1516    where
1517        F: Fn(usize, &ast::FieldDef, Span) -> Vec<P<ast::Expr>>,
1518    {
1519        struct_def
1520            .fields()
1521            .iter()
1522            .enumerate()
1523            .map(|(i, struct_field)| {
1524                // For this field, get an expr for each selflike_arg. E.g. for
1525                // `PartialEq::eq`, one for each of `&self` and `other`.
1526                let sp = struct_field.span.with_ctxt(self.span.ctxt());
1527                let mut exprs: Vec<_> = mk_exprs(i, struct_field, sp);
1528                let self_expr = exprs.remove(0);
1529                let other_selflike_exprs = exprs;
1530                FieldInfo {
1531                    span: sp.with_ctxt(self.span.ctxt()),
1532                    name: struct_field.ident,
1533                    self_expr,
1534                    other_selflike_exprs,
1535                }
1536            })
1537            .collect()
1538    }
1539
1540    fn mk_pattern_ident(&self, prefix: &str, i: usize) -> Ident {
1541        Ident::from_str_and_span(&format!("{prefix}_{i}"), self.span)
1542    }
1543
1544    fn create_struct_pattern_fields(
1545        &self,
1546        cx: &ExtCtxt<'_>,
1547        struct_def: &'a VariantData,
1548        prefixes: &[String],
1549    ) -> Vec<FieldInfo> {
1550        self.create_fields(struct_def, |i, _struct_field, sp| {
1551            prefixes
1552                .iter()
1553                .map(|prefix| {
1554                    let ident = self.mk_pattern_ident(prefix, i);
1555                    cx.expr_path(cx.path_ident(sp, ident))
1556                })
1557                .collect()
1558        })
1559    }
1560
1561    fn create_struct_field_access_fields(
1562        &self,
1563        cx: &ExtCtxt<'_>,
1564        selflike_args: &[P<Expr>],
1565        struct_def: &'a VariantData,
1566        is_packed: bool,
1567    ) -> Vec<FieldInfo> {
1568        self.create_fields(struct_def, |i, struct_field, sp| {
1569            selflike_args
1570                .iter()
1571                .map(|selflike_arg| {
1572                    // Note: we must use `struct_field.span` rather than `sp` in the
1573                    // `unwrap_or_else` case otherwise the hygiene is wrong and we get
1574                    // "field `0` of struct `Point` is private" errors on tuple
1575                    // structs.
1576                    let mut field_expr = cx.expr(
1577                        sp,
1578                        ast::ExprKind::Field(
1579                            selflike_arg.clone(),
1580                            struct_field.ident.unwrap_or_else(|| {
1581                                Ident::from_str_and_span(&i.to_string(), struct_field.span)
1582                            }),
1583                        ),
1584                    );
1585                    if is_packed {
1586                        // Fields in packed structs are wrapped in a block, e.g. `&{self.0}`,
1587                        // causing a copy instead of a (potentially misaligned) reference.
1588                        field_expr = cx.expr_block(
1589                            cx.block(struct_field.span, thin_vec![cx.stmt_expr(field_expr)]),
1590                        );
1591                    }
1592                    cx.expr_addr_of(sp, field_expr)
1593                })
1594                .collect()
1595        })
1596    }
1597}
1598
1599/// The function passed to `cs_fold` is called repeatedly with a value of this
1600/// type. It describes one part of the code generation. The result is always an
1601/// expression.
1602pub(crate) enum CsFold<'a> {
1603    /// The basic case: a field expression for one or more selflike args. E.g.
1604    /// for `PartialEq::eq` this is something like `self.x == other.x`.
1605    Single(&'a FieldInfo),
1606
1607    /// The combination of two field expressions. E.g. for `PartialEq::eq` this
1608    /// is something like `<field1 equality> && <field2 equality>`.
1609    Combine(Span, P<Expr>, P<Expr>),
1610
1611    // The fallback case for a struct or enum variant with no fields.
1612    Fieldless,
1613}
1614
1615/// Folds over fields, combining the expressions for each field in a sequence.
1616/// Statics may not be folded over.
1617pub(crate) fn cs_fold<F>(
1618    use_foldl: bool,
1619    cx: &ExtCtxt<'_>,
1620    trait_span: Span,
1621    substructure: &Substructure<'_>,
1622    mut f: F,
1623) -> P<Expr>
1624where
1625    F: FnMut(&ExtCtxt<'_>, CsFold<'_>) -> P<Expr>,
1626{
1627    match substructure.fields {
1628        EnumMatching(.., all_fields) | Struct(_, all_fields) => {
1629            if all_fields.is_empty() {
1630                return f(cx, CsFold::Fieldless);
1631            }
1632
1633            let (base_field, rest) = if use_foldl {
1634                all_fields.split_first().unwrap()
1635            } else {
1636                all_fields.split_last().unwrap()
1637            };
1638
1639            let base_expr = f(cx, CsFold::Single(base_field));
1640
1641            let op = |old, field: &FieldInfo| {
1642                let new = f(cx, CsFold::Single(field));
1643                f(cx, CsFold::Combine(field.span, old, new))
1644            };
1645
1646            if use_foldl {
1647                rest.iter().fold(base_expr, op)
1648            } else {
1649                rest.iter().rfold(base_expr, op)
1650            }
1651        }
1652        EnumDiscr(discr_field, match_expr) => {
1653            let discr_check_expr = f(cx, CsFold::Single(discr_field));
1654            if let Some(match_expr) = match_expr {
1655                if use_foldl {
1656                    f(cx, CsFold::Combine(trait_span, discr_check_expr, match_expr.clone()))
1657                } else {
1658                    f(cx, CsFold::Combine(trait_span, match_expr.clone(), discr_check_expr))
1659                }
1660            } else {
1661                discr_check_expr
1662            }
1663        }
1664        StaticEnum(..) | StaticStruct(..) => {
1665            cx.dcx().span_bug(trait_span, "static function in `derive`")
1666        }
1667        AllFieldlessEnum(..) => cx.dcx().span_bug(trait_span, "fieldless enum in `derive`"),
1668    }
1669}