Skip to main content

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