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