Skip to main content

rustc_builtin_macros/deriving/generic/
mod.rs

1use std::ops::Not;
2
3pub(crate) use Substructure::*;
4pub(crate) use rustc_ast as ast;
5use rustc_ast::{EnumDef, Expr, GenericParamKind, Generics, Param, Safety, VariantData};
6use rustc_attr_ir::{Attribute, AttributeKind, ReprPacked};
7use rustc_attr_parsing::AttributeParser;
8use rustc_expand::base::ExtCtxt;
9use rustc_span::{Ident, Span, Symbol, kw, sym};
10pub(crate) use smallvec::{SmallVec, smallvec};
11use thin_vec::{ThinVec, thin_vec};
12
13use crate::util::generic_param_to_arg;
14use crate::{deriving, diagnostics};
15
16pub(crate) struct TraitDef<'a> {
17    /// The span for the current #[derive(Foo)] header.
18    pub span: Span,
19
20    /// Path of the trait, including any type parameters
21    pub path: ast::Path,
22
23    /// Whether to skip adding the current trait as a bound to the type parameters of the type.
24    pub skip_path_as_bound: bool = false,
25
26    /// Whether `Copy` is needed as an additional bound on type parameters in a packed struct.
27    pub needs_copy_as_bound_if_packed: bool,
28
29    /// Additional bounds required of any type parameters of the type,
30    /// other than the current trait
31    pub additional_bounds: SmallVec<[ast::Path; 1]>,
32
33    /// Can this trait be derived for unions?
34    pub supports_unions: bool,
35
36    pub methods: SmallVec<[MethodDef<'a>; 1]>,
37
38    pub is_const: bool,
39
40    /// The safety of the `impl`.
41    pub safety: Safety = Safety::Default,
42
43    /// Whether the added `impl` should appear in rustdoc output.
44    pub document: bool = true,
45}
46
47pub(crate) struct MethodDef<'a> {
48    /// name of the method
49    pub name: Symbol,
50    /// List of generics, e.g., `R: rand::Rng`
51    pub generics: Generics,
52
53    pub args: ThinVec<Param>,
54
55    /// Returns type
56    pub ret_ty: Box<ast::Ty>,
57
58    pub attributes: ast::AttrVec,
59
60    pub body: MethodBody<'a>,
61}
62
63/// How to handle fieldless enum variants.
64#[derive(#[automatically_derived]impl ::core::marker::StructuralPartialEq for
    FieldlessVariantsStrategy {
}
#[automatically_derived]impl ::core::cmp::PartialEq for
    FieldlessVariantsStrategy {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
65pub(crate) enum FieldlessVariantsStrategy {
66    /// Combine fieldless variants into a single match arm.
67    /// This assumes that relevant information has been handled
68    /// by looking at the enum's discriminant.
69    Unify,
70    /// Don't do anything special about fieldless variants. They are
71    /// handled like any other variant.
72    Default,
73}
74
75/// Summary of the relevant parts of a struct/enum field.
76pub(crate) struct FieldInfo<'a> {
77    pub span: Span,
78    /// The expression corresponding to this field of `self`
79    /// (specifically, a reference to it).
80    pub self_expr: Box<Expr>,
81    /// The expression corresponding to a reference to this field in
82    /// the other selflike argument.
83    pub other_selflike_expr: Option<Box<Expr>>,
84    pub def: &'a ast::FieldDef,
85}
86
87/// A helper that makes the code for several derive macros easier to write
88/// as they all have a similar base structure.
89pub(crate) enum Substructure<'a> {
90    /// A non-static method where `Self` is a struct, including tuple structs.
91    Struct(&'a ast::VariantData, Vec<FieldInfo<'a>>),
92
93    /// Matching variants of the enum: ast::Variant, fields.
94    /// Created when `Self` is an enum and all the arguments are the
95    /// same variant of the enum.
96    EnumMatching(&'a ast::Variant, Vec<FieldInfo<'a>>),
97
98    /// The discriminant of an enum. The field is the expression to combine the
99    /// discriminant expression with; it will be `None` if no match is necessary.
100    EnumDiscr(Option<Box<Expr>>),
101}
102
103pub(crate) enum MethodBody<'a> {
104    /// See the documentation on [`Substructure`] for when this is used.
105    SubstructureFunc {
106        body_func: Box<dyn Fn(&ExtCtxt<'_>, Span, Substructure<'_>) -> BlockOrExpr + 'a>,
107        strategy: FieldlessVariantsStrategy,
108        has_other_selflike_arg: bool,
109    },
110    /// The common case.
111    /// If you are adding a new macro, you most likely want to use this.
112    Directly(BlockOrExpr),
113}
114
115struct TypeParameter {
116    bound_generic_params: ThinVec<ast::GenericParam>,
117    ty: Box<ast::Ty>,
118}
119
120/// The code snippets built up for derived code are sometimes used as blocks
121/// (e.g. in a function body) and sometimes used as expressions (e.g. in a match
122/// arm). This structure avoids committing to either form until necessary,
123/// avoiding the insertion of any unnecessary blocks.
124///
125/// The statements come before the expression.
126pub(crate) struct BlockOrExpr(ThinVec<ast::Stmt>, Option<Box<Expr>>);
127
128impl BlockOrExpr {
129    pub(crate) fn new_stmts(stmts: ThinVec<ast::Stmt>) -> BlockOrExpr {
130        BlockOrExpr(stmts, None)
131    }
132
133    pub(crate) fn new_expr(expr: Box<Expr>) -> BlockOrExpr {
134        BlockOrExpr(ThinVec::new(), Some(expr))
135    }
136
137    pub(crate) fn new_mixed(stmts: ThinVec<ast::Stmt>, expr: Option<Box<Expr>>) -> BlockOrExpr {
138        BlockOrExpr(stmts, expr)
139    }
140
141    // Converts it into a block.
142    fn into_block(mut self, cx: &ExtCtxt<'_>, span: Span) -> Box<ast::Block> {
143        if let Some(expr) = self.1 {
144            self.0.push(cx.stmt_expr(expr));
145        }
146        cx.block(span, self.0)
147    }
148
149    // Converts it into an expression.
150    fn into_expr(self, cx: &ExtCtxt<'_>, span: Span) -> Box<Expr> {
151        if self.0.is_empty() {
152            match self.1 {
153                None => cx.expr_block(cx.block(span, ThinVec::new())),
154                Some(expr) => expr,
155            }
156        } else if let [stmt] = self.0.as_slice()
157            && let ast::StmtKind::Expr(expr) = &stmt.kind
158            && self.1.is_none()
159        {
160            // There's only a single statement expression. Pull it out.
161            expr.clone()
162        } else {
163            // Multiple statements and/or expressions.
164            cx.expr_block(self.into_block(cx, span))
165        }
166    }
167
168    fn take(&mut self) -> BlockOrExpr {
169        std::mem::replace(self, BlockOrExpr::new_stmts(ThinVec::new()))
170    }
171}
172
173/// This method helps to extract all the type parameters referenced from a
174/// type. For a type parameter `<T>`, it looks for either a `TyPath` that
175/// is not global and starts with `T`, or a `TyQPath`.
176/// Also include bound generic params from the input type.
177fn find_type_parameters(
178    ty: &ast::Ty,
179    ty_param_names: &[Symbol],
180    cx: &ExtCtxt<'_>,
181) -> Vec<TypeParameter> {
182    use rustc_ast::visit;
183
184    struct Visitor<'a, 'b> {
185        cx: &'a ExtCtxt<'b>,
186        ty_param_names: &'a [Symbol],
187        bound_generic_params_stack: ThinVec<ast::GenericParam>,
188        type_params: Vec<TypeParameter>,
189    }
190
191    impl<'a, 'b> visit::Visitor<'a> for Visitor<'a, 'b> {
192        fn visit_ty(&mut self, ty: &'a ast::Ty) {
193            let stack_len = self.bound_generic_params_stack.len();
194            if let ast::TyKind::FnPtr(fn_ptr) = &ty.kind
195                && !fn_ptr.generic_params.is_empty()
196            {
197                // Given a field `x: for<'a> fn(T::SomeType<'a>)`, we wan't to account for `'a` so
198                // that we generate `where for<'a> T::SomeType<'a>: ::core::clone::Clone`. #122622
199                self.bound_generic_params_stack.extend(fn_ptr.generic_params.iter().cloned());
200            }
201
202            if let ast::TyKind::Path(_, path) = &ty.kind
203                && let Some(segment) = path.segments.first()
204                && self.ty_param_names.contains(&segment.ident.name)
205            {
206                self.type_params.push(TypeParameter {
207                    bound_generic_params: self.bound_generic_params_stack.clone(),
208                    ty: Box::new(ty.clone()),
209                });
210            }
211
212            visit::walk_ty(self, ty);
213            self.bound_generic_params_stack.truncate(stack_len);
214        }
215
216        // Place bound generic params on a stack, to extract them when a type is encountered.
217        fn visit_poly_trait_ref(&mut self, trait_ref: &'a ast::PolyTraitRef) {
218            let stack_len = self.bound_generic_params_stack.len();
219            self.bound_generic_params_stack.extend(trait_ref.bound_generic_params.iter().cloned());
220
221            visit::walk_poly_trait_ref(self, trait_ref);
222
223            self.bound_generic_params_stack.truncate(stack_len);
224        }
225
226        fn visit_mac_call(&mut self, mac: &ast::MacCall) {
227            self.cx.dcx().emit_err(diagnostics::DeriveMacroCall { span: mac.span() });
228        }
229    }
230
231    let mut visitor = Visitor {
232        cx,
233        ty_param_names,
234        bound_generic_params_stack: ThinVec::new(),
235        type_params: Vec::new(),
236    };
237    visit::Visitor::visit_ty(&mut visitor, ty);
238
239    visitor.type_params
240}
241
242impl<'a> TraitDef<'a> {
243    pub(crate) fn expand(
244        self,
245        cx: &ExtCtxt<'_>,
246        item: &'a ast::Item,
247        push: &mut dyn FnMut(Box<ast::Item>),
248    ) {
249        let span = self.span;
250        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!(
251            AttributeParser::parse_limited_sym(cx.sess, &item.attrs, &[sym::repr]),
252            Some(Attribute::Parsed(AttributeKind::Repr { reprs, .. })) if reprs.iter().any(|(x, _)| matches!(x, ReprPacked(..)))
253        );
254
255        let fields: Box<dyn Iterator<Item = &ast::FieldDef>>;
256        let methods;
257        let (ident, generics) = match &item.kind {
258            ast::ItemKind::Union(..) if !self.supports_unions => {
259                cx.dcx().emit_err(diagnostics::DeriveUnion { span });
260                return;
261            }
262            ast::ItemKind::Struct(ident, generics, struct_def)
263            | ast::ItemKind::Union(ident, generics, struct_def) => {
264                fields = Box::new(struct_def.fields().iter());
265                methods = self
266                    .methods
267                    .into_iter()
268                    .filter_map(|mut method_def| {
269                        let body = if let MethodBody::Directly(body) = &mut method_def.body {
270                            body.take()
271                        } else {
272                            method_def.expand_struct_method_body(cx, span, struct_def, is_packed)
273                        };
274
275                        method_def.create_method(cx, span, body)
276                    })
277                    .collect();
278                (ident, generics)
279            }
280            ast::ItemKind::Enum(ident, generics, enum_def) => {
281                // We can skip generating the impl here, because `repr(packed)`
282                // enums cause an error later on and to prevent ICEs like #133025.
283                // This can only cause further compilation errors
284                // downstream in blatantly illegal code, so it is fine.
285                if is_packed {
286                    return;
287                }
288                fields =
289                    Box::new(enum_def.variants.iter().flat_map(|variant| variant.data.fields()));
290                methods = self
291                    .methods
292                    .into_iter()
293                    .filter_map(|mut method_def| {
294                        let body = if let MethodBody::Directly(body) = &mut method_def.body {
295                            body.take()
296                        } else {
297                            method_def.expand_enum_method_body(cx, span, enum_def)
298                        };
299
300                        method_def.create_method(cx, span, body)
301                    })
302                    .collect();
303                (ident, generics)
304            }
305            _ => ::core::panicking::unreachable_default_msg()unreachable!(),
306        };
307        let mut where_clause = ast::WhereClause::default();
308        where_clause.span = generics.where_clause.span;
309        let ctxt = self.span.ctxt();
310
311        let mut ty_param_names = Vec::with_capacity(generics.params.len());
312        let mut self_params = Vec::with_capacity(generics.params.len());
313        // Create the generic parameters
314        let params: ThinVec<_> = generics
315            .params
316            .iter()
317            .map(|param| match &param.kind {
318                GenericParamKind::Lifetime => param.clone(),
319                GenericParamKind::Type { .. } => {
320                    // Extra restrictions on the generics parameters to the
321                    // type being derived upon.
322                    let span = param.ident.span.with_ctxt(ctxt);
323                    let bounds: ThinVec<_> = self
324                        .additional_bounds
325                        .iter()
326                        .map(|p| cx.trait_bound(ast::Path { span, ..p.clone() }, self.is_const))
327                        .chain(
328                            // Add a bound for the current trait.
329                            self.skip_path_as_bound.not().then(|| {
330                                let mut trait_path = self.path.clone();
331                                trait_path.span = span;
332                                cx.trait_bound(trait_path, self.is_const)
333                            }),
334                        )
335                        .chain({
336                            // Add a `Copy` bound if required.
337                            if is_packed && self.needs_copy_as_bound_if_packed {
338                                let p = cx.std_path(span, { &[sym::marker, sym::Copy] })deriving::path_std!(cx, span, marker::Copy);
339                                Some(cx.trait_bound(p, self.is_const))
340                            } else {
341                                None
342                            }
343                        })
344                        .chain(
345                            // Also add in any bounds from the declaration.
346                            param.bounds.iter().cloned(),
347                        )
348                        .collect();
349
350                    ty_param_names.push(param.ident.name);
351                    cx.typaram(param.ident, bounds, None)
352                }
353                GenericParamKind::Const { ty, span, .. } => {
354                    let const_nodefault_kind = GenericParamKind::Const {
355                        ty: ty.clone(),
356                        span: span.with_ctxt(ctxt),
357
358                        // We can't have default values inside impl block
359                        default: None,
360                    };
361                    let mut param_clone = param.clone();
362                    param_clone.kind = const_nodefault_kind;
363                    param_clone
364                }
365            })
366            .map(|mut param| {
367                // Remove all attributes, because there might be helper attributes
368                // from other macros that will not be valid in the expanded implementation.
369                param.attrs.clear();
370                self_params.push(generic_param_to_arg(
371                    cx,
372                    &param,
373                    param.ident.span.with_ctxt(ctxt),
374                ));
375                param
376            })
377            .collect();
378
379        // and similarly for where clauses
380        where_clause.predicates.extend(generics.where_clause.predicates.iter().map(|clause| {
381            ast::WherePredicate {
382                attrs: clause.attrs.clone(),
383                kind: clause.kind.clone(),
384                id: ast::DUMMY_NODE_ID,
385                span: clause.span.with_ctxt(ctxt),
386                is_placeholder: false,
387            }
388        }));
389
390        if !ty_param_names.is_empty() {
391            for field in fields {
392                let field_ty_params = find_type_parameters(&field.ty, &ty_param_names, cx);
393
394                for field_ty_param in field_ty_params {
395                    // if we have already handled this type, skip it
396                    if let ast::TyKind::Path(_, p) = &field_ty_param.ty.kind
397                        && let [sole_segment] = &*p.segments
398                        && ty_param_names.contains(&sole_segment.ident.name)
399                    {
400                        continue;
401                    }
402                    let mut bounds: ThinVec<_> = self
403                        .additional_bounds
404                        .iter()
405                        .map(|p| cx.trait_bound(p.clone(), self.is_const))
406                        .collect();
407
408                    // Require the current trait.
409                    if !self.skip_path_as_bound {
410                        bounds.push(cx.trait_bound(self.path.clone(), self.is_const));
411                    }
412
413                    // Add a `Copy` bound if required.
414                    if is_packed && self.needs_copy_as_bound_if_packed {
415                        let p = cx.std_path(self.span, { &[sym::marker, sym::Copy] })deriving::path_std!(cx, self.span, marker::Copy);
416                        bounds.push(cx.trait_bound(p, self.is_const));
417                    }
418
419                    if !bounds.is_empty() {
420                        let predicate = ast::WhereBoundPredicate {
421                            bound_generic_params: field_ty_param.bound_generic_params,
422                            bounded_ty: field_ty_param.ty,
423                            bounds,
424                        };
425
426                        let kind = ast::WherePredicateKind::BoundPredicate(predicate);
427                        let predicate = ast::WherePredicate {
428                            attrs: ThinVec::new(),
429                            kind,
430                            id: ast::DUMMY_NODE_ID,
431                            span: self.span,
432                            is_placeholder: false,
433                        };
434                        where_clause.predicates.push(predicate);
435                    }
436                }
437            }
438        }
439
440        let trait_generics = Generics { params, where_clause, span: generics.span.with_ctxt(ctxt) };
441
442        // Create the reference to the trait.
443        let trait_ref = cx.trait_ref(self.path);
444
445        // Create the type of `self`.
446        let path = cx.path_all(ident.span.with_ctxt(ctxt), &[*ident], self_params);
447        let self_type = cx.ty_path(path);
448
449        let mut attrs =
450            {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(cx.generated_attr(self.span,
            ast::GeneratedAttr::AutomaticallyDerived));
    vec
}thin_vec![cx.generated_attr(self.span, ast::GeneratedAttr::AutomaticallyDerived)];
451
452        // Only add `rustc_const_unstable` attributes if `derive_const` is used within libcore/libstd,
453        // Other crates don't need stability attributes, so adding them is not useful, but libcore needs them
454        // on all const trait impls.
455        if self.is_const && cx.ecfg.features.staged_api() {
456            attrs.push(cx.generated_attr(self.span, ast::GeneratedAttr::RustcConstUnstableDerived));
457        }
458
459        if !self.document {
460            attrs.push(cx.generated_attr(self.span, ast::GeneratedAttr::DocHidden));
461        }
462
463        let mut newitem = cx.item_trait_impl(
464            self.span,
465            attrs,
466            trait_generics,
467            self.safety,
468            self.is_const,
469            trait_ref,
470            self_type,
471            methods,
472        );
473        // Keep the lint attributes of the previous item to control how the
474        // generated implementations are linted
475        newitem.attrs.extend(
476            item.attrs
477                .iter()
478                .filter(|a| {
479                    a.has_any_name(&[
480                        sym::allow,
481                        sym::warn,
482                        sym::deny,
483                        sym::forbid,
484                        sym::stable,
485                        sym::unstable,
486                    ])
487                })
488                .cloned(),
489        );
490        push(newitem);
491    }
492}
493
494impl<'a> MethodDef<'a> {
495    fn create_method(
496        self,
497        cx: &ExtCtxt<'_>,
498        span: Span,
499        body: BlockOrExpr,
500    ) -> Option<Box<ast::AssocItem>> {
501        // `assert_fields_are_eq` has an empty default implementation
502        if body.0.is_empty() && body.1.is_none() && self.name == sym::assert_fields_are_eq {
503            return None;
504        }
505
506        let ret_type = if self.ret_ty.kind.is_unit() {
507            ast::FnRetTy::Default(span)
508        } else {
509            ast::FnRetTy::Ty(self.ret_ty)
510        };
511
512        let method_ident = Ident::new(self.name, span);
513        let fn_decl = cx.fn_decl(self.args, ret_type);
514        let body_block = body.into_block(cx, span);
515
516        let trait_lo_sp = span.shrink_to_lo();
517
518        let sig = ast::FnSig { header: ast::FnHeader::default(), decl: fn_decl, span };
519
520        // Create the method.
521        Some(Box::new(ast::AssocItem {
522            id: ast::DUMMY_NODE_ID,
523            attrs: self.attributes,
524            span,
525            vis: ast::Visibility { span: trait_lo_sp, kind: ast::VisibilityKind::Inherited },
526            kind: ast::AssocItemKind::Fn(cx.item_fn(
527                sig,
528                method_ident,
529                self.generics,
530                Some(body_block),
531            )),
532            tokens: None,
533        }))
534    }
535
536    /// The normal case uses field access.
537    ///
538    /// ```
539    /// #[derive(PartialEq)]
540    /// # struct Dummy;
541    /// struct A { x: u8, y: u8 }
542    ///
543    /// // equivalent to:
544    /// impl PartialEq for A {
545    ///     fn eq(&self, other: &A) -> bool {
546    ///         self.x == other.x && self.y == other.y
547    ///     }
548    /// }
549    /// ```
550    ///
551    /// But if the struct is `repr(packed)`, we can't use something like
552    /// `&self.x` because that might cause an unaligned ref. So for any trait
553    /// method that takes a reference, we use a local block to force a copy.
554    /// This requires that the field impl `Copy`.
555    ///
556    /// ```rust,ignore (example)
557    /// # struct A { x: u8, y: u8 }
558    /// impl PartialEq for A {
559    ///     fn eq(&self, other: &A) -> bool {
560    ///         // Desugars to `{ self.x }.eq(&{ other.y }) && ...`
561    ///         { self.x } == { other.y } && { self.y } == { other.y }
562    ///     }
563    /// }
564    /// impl Hash for A {
565    ///     fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
566    ///         ::core::hash::Hash::hash(&{ self.x }, state);
567    ///         ::core::hash::Hash::hash(&{ self.y }, state);
568    ///     }
569    /// }
570    /// ```
571    fn expand_struct_method_body<'b>(
572        &self,
573        cx: &ExtCtxt<'_>,
574        span: Span,
575        struct_def: &'b VariantData,
576        is_packed: bool,
577    ) -> BlockOrExpr {
578        let MethodBody::SubstructureFunc { body_func, has_other_selflike_arg, .. } = &self.body
579        else {
580            ::core::panicking::unreachable_default_msg()unreachable!()
581        };
582        let selflike_fields = struct_def
583            .fields()
584            .iter()
585            .enumerate()
586            .map(|(i, struct_field)| {
587                // For this field, get an expr for each selflike_arg. E.g. for
588                // `PartialEq::eq`, one for each of `&self` and `other`.
589                let field_span = struct_field.span.with_ctxt(span.ctxt());
590                let expr_for_selflike_arg = |selflike_arg| {
591                    // Note: we must use `struct_field.span` rather than `sp` in the
592                    // `unwrap_or_else` case otherwise the hygiene is wrong and we get
593                    // "field `0` of struct `Point` is private" errors on tuple
594                    // structs.
595                    let mut field_expr = cx.expr(
596                        field_span,
597                        ast::ExprKind::Field(
598                            selflike_arg,
599                            struct_field
600                                .ident
601                                .unwrap_or_else(|| Ident::new(sym::integer(i), struct_field.span)),
602                        ),
603                    );
604                    if is_packed {
605                        // Fields in packed structs are wrapped in a block, e.g. `&{self.0}`,
606                        // causing a copy instead of a (potentially misaligned) reference.
607                        field_expr = cx.expr_block(
608                            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)]),
609                        );
610                    }
611                    cx.expr_ref(field_span, field_expr)
612                };
613
614                let self_expr = expr_for_selflike_arg(cx.expr_self(span));
615                let other_selflike_expr = has_other_selflike_arg
616                    .then(|| expr_for_selflike_arg(cx.expr_name(span, sym::other)));
617                FieldInfo { span: field_span, self_expr, other_selflike_expr, def: struct_field }
618            })
619            .collect();
620
621        body_func(cx, span, Struct(struct_def, selflike_fields))
622    }
623
624    /// ```
625    /// #[derive(PartialEq)]
626    /// # struct Dummy;
627    /// enum A {
628    ///     A1,
629    ///     A2(i32)
630    /// }
631    /// ```
632    ///
633    /// is equivalent to:
634    ///
635    /// ```
636    /// #![feature(core_intrinsics)]
637    /// enum A {
638    ///     A1,
639    ///     A2(i32)
640    /// }
641    /// impl ::core::cmp::PartialEq for A {
642    ///     #[inline]
643    ///     fn eq(&self, other: &A) -> bool {
644    ///         ::core::intrinsics::discriminant_value(self) == ::core::intrinsics::discriminant_value(other)
645    ///             && match (self, other) {
646    ///                 (A::A2(__self_0), A::A2(__arg1_0)) => *__self_0 == *__arg1_0,
647    ///                 _ => true,
648    ///             }
649    ///     }
650    /// }
651    /// ```
652    ///
653    /// Creates a discriminant check combined with a match for a tuple of all
654    /// `selflike_args`, with an arm for each variant with fields, possibly an
655    /// arm for each fieldless variant (if `unify_fieldless_variants` is not
656    /// `Unify`), and possibly a default arm.
657    fn expand_enum_method_body<'b>(
658        &self,
659        cx: &ExtCtxt<'_>,
660        span: Span,
661        enum_def: &'b EnumDef,
662    ) -> BlockOrExpr {
663        let variants = &enum_def.variants;
664
665        // There are some special cases involving fieldless enums where no
666        // match is necessary.
667        let all_fieldless = variants.iter().all(|v| v.data.fields().is_empty());
668        let MethodBody::SubstructureFunc { body_func, strategy, has_other_selflike_arg } =
669            &self.body
670        else {
671            ::core::panicking::unreachable_default_msg()unreachable!()
672        };
673        // Traits that unify fieldless variants always use the discriminant(s).
674        let unify_fieldless_variants = *strategy == FieldlessVariantsStrategy::Unify;
675
676        match variants.as_slice() {
677            [] => {
678                // For zero-variant enum, this function body is unreachable. Generate
679                // `match *self {}`. This produces machine code identical to `unsafe {
680                // core::intrinsics::unreachable() }` while being safe and stable.
681                let match_arg = cx.expr_deref(span, cx.expr_self(span));
682                let expr = cx.expr_match(span, match_arg, ThinVec::new());
683                return BlockOrExpr::new_expr(expr);
684            }
685            [variant] if all_fieldless => {
686                // If there is a single variant, we don't need an operation on
687                // the discriminant(s). Just use the most degenerate result.
688                return body_func(cx, span, EnumMatching(variant, Vec::new()));
689            }
690            _ if all_fieldless && unify_fieldless_variants => {
691                // If the type is fieldless and the trait uses the discriminant and
692                // there are multiple variants, we need just an operation on
693                // the discriminant(s).
694                return body_func(cx, span, EnumDiscr(None));
695            }
696            _ => (),
697        }
698
699        // These arms are of the form:
700        // (Variant1, Variant1) => Body1
701        // (Variant2, Variant2) => Body2
702        // ...
703        // where each tuple has length 2 if `has_other_selflike_arg` and 1 otherwise
704        let mut match_arms: ThinVec<ast::Arm> = variants
705            .iter()
706            .filter(|&v| !(unify_fieldless_variants && v.data.fields().is_empty()))
707            .map(|variant| {
708                // A single arm has form (&VariantK, &VariantK) => BodyK
709                // (see "Final wrinkle" note below for why.)
710                let variant_span = variant.span.with_ctxt(span.ctxt());
711                let pat_for_field = |prefix| {
712                    let pieces_iter =
713                        variant.data.fields().iter().enumerate().map(|(i, struct_field)| {
714                            let name = Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}_{1}", prefix, i))
    })format!("{prefix}_{i}"));
715                            (
716                                struct_field.ident,
717                                cx.pat_name(struct_field.span.with_ctxt(span.ctxt()), name),
718                            )
719                        });
720
721                    let struct_path =
722                        cx.path(variant_span, &[Ident::new(kw::SelfUpper, span), variant.ident]);
723
724                    match variant.data {
725                        VariantData::Struct { .. } => {
726                            let field_pats = pieces_iter
727                                .map(|(ident, pat)| ast::PatField {
728                                    ident: ident
729                                        .expect("a braced struct with unnamed fields in `derive`"),
730                                    is_shorthand: false,
731                                    attrs: ast::AttrVec::new(),
732                                    id: ast::DUMMY_NODE_ID,
733                                    span: pat.span,
734                                    pat: Box::new(pat),
735                                    is_placeholder: false,
736                                })
737                                .collect();
738                            cx.pat_struct(span, struct_path, field_pats)
739                        }
740                        VariantData::Tuple(..) => {
741                            let subpats = pieces_iter.map(|(_, subpat)| subpat).collect();
742                            cx.pat_tuple_struct(span, struct_path, subpats)
743                        }
744                        VariantData::Unit(..) => cx.pat_path(span, struct_path),
745                    }
746                };
747
748                // `(VariantK, VariantK)` or just `VariantK`.
749                let single_pat = if *has_other_selflike_arg {
750                    cx.pat_tuple(span, {
    let len = [(), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(pat_for_field("__self"));
    vec.push(pat_for_field("__arg1"));
    vec
}thin_vec![pat_for_field("__self"), pat_for_field("__arg1"),])
751                } else {
752                    pat_for_field("__self")
753                };
754
755                let fields = variant
756                    .data
757                    .fields()
758                    .iter()
759                    .enumerate()
760                    .map(|(i, struct_field)| {
761                        // For this field, get an expr for each selflike_arg. E.g. for
762                        // `PartialEq::eq`, one for each of `&self` and `other`.
763                        let span = struct_field.span.with_ctxt(span.ctxt());
764                        let expr_for_field =
765                            |prefix| cx.expr_name(span, Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}_{1}", prefix, i))
    })format!("{prefix}_{i}")));
766
767                        let self_expr = expr_for_field("__self");
768                        let other_selflike_expr =
769                            has_other_selflike_arg.then(|| expr_for_field("__arg1"));
770                        FieldInfo { span, self_expr, other_selflike_expr, def: struct_field }
771                    })
772                    .collect();
773                // For the BodyK, we need to delegate to our caller,
774                // passing it an EnumMatching to indicate which case
775                // we are in.
776                //
777                // Now, for some given VariantK, we have built up
778                // expressions for referencing every field of every
779                // Self arg, assuming all are instances of VariantK.
780                // Build up code associated with such a case.
781                let arm_expr =
782                    body_func(cx, span, EnumMatching(variant, fields)).into_expr(cx, span);
783
784                cx.arm(span, single_pat, arm_expr)
785            })
786            .collect();
787
788        // Add a default arm to the match, if necessary.
789        let first_fieldless = variants.iter().find(|v| v.data.fields().is_empty());
790        let default = match first_fieldless {
791            Some(v) if unify_fieldless_variants => {
792                // We need a default case that handles all the fieldless variants.
793                Some(body_func(cx, span, EnumMatching(v, Vec::new())).into_expr(cx, span))
794            }
795            _ if variants.len() > 1 && *has_other_selflike_arg => {
796                // Because we know that all the arguments will match if we reach
797                // the match expression we add the unreachable intrinsic as the
798                // result of the default which should help llvm in optimizing it.
799                Some(deriving::call_unreachable(cx, span))
800            }
801            _ => None,
802        };
803        if let Some(arm) = default {
804            match_arms.push(cx.arm(span, cx.pat_wild(span), arm));
805        }
806
807        // Create a match expression with one arm per discriminant plus
808        // possibly a default arm, e.g.:
809        //      match (self, other) {
810        //          (Variant1, Variant1) => Body1
811        //          (Variant2, Variant2) => Body2,
812        //          ...
813        //          _ => ::core::intrinsics::unreachable(),
814        //      }
815
816        let self_expr = cx.expr_self(span);
817        let match_arg = if *has_other_selflike_arg {
818            cx.expr_tuple(span, {
    let len = [(), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(self_expr);
    vec.push(cx.expr_name(span, sym::other));
    vec
}thin_vec![self_expr, cx.expr_name(span, sym::other)])
819        } else {
820            self_expr
821        };
822        let match_expr = cx.expr_match(span, match_arg, match_arms);
823
824        // If the trait uses the discriminant and there are multiple variants, we need
825        // to add a discriminant check operation before the match. Otherwise, the match
826        // is enough.
827        if unify_fieldless_variants && variants.len() > 1 {
828            // Combine a discriminant check with the match.
829            body_func(cx, span, EnumDiscr(Some(match_expr)))
830        } else {
831            BlockOrExpr::new_expr(match_expr)
832        }
833    }
834}
835
836pub(crate) fn generics_without_defaults(g: &Generics) -> Generics {
837    Generics {
838        params: g
839            .params
840            .iter()
841            .map(|p| {
842                let mut p = p.clone();
843                match &mut p.kind {
844                    ast::GenericParamKind::Const { default, .. } => *default = None,
845                    ast::GenericParamKind::Type { default } => *default = None,
846                    ast::GenericParamKind::Lifetime => {}
847                };
848                p.attrs.clear();
849                p
850            })
851            .collect(),
852        where_clause: g.where_clause.clone(),
853        span: g.span,
854    }
855}