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