Skip to main content

rustc_builtin_macros/deriving/generic/
mod.rs

1//! Some code that abstracts away much of the boilerplate of writing
2//! `derive` instances for traits. Among other things it manages getting
3//! access to the fields of the 4 different sorts of structs and enum
4//! variants, as well as creating the method and impl ast instances.
5//!
6//! Supported features (fairly exhaustive):
7//!
8//! - Methods taking any number of parameters of any type, and returning
9//!   any type, other than vectors, bottom and closures.
10//! - Generating `impl`s for types with type parameters and lifetimes
11//!   (e.g., `Option<T>`), the parameters are automatically given the
12//!   current trait as a bound. (This includes separate type parameters
13//!   and lifetimes for methods.)
14//! - Additional bounds on the type parameters (`TraitDef.additional_bounds`)
15//!
16//! The most important thing for implementors is the `Substructure` and
17//! `SubstructureFields` objects. The latter groups 5 possibilities of the
18//! arguments:
19//!
20//! - `Struct`, when `Self` is a struct (including tuple structs, e.g
21//!   `struct T(i32, char)`).
22//! - `EnumMatching`, when `Self` is an enum and all the arguments are the
23//!   same variant of the enum (e.g., `Some(1)`, `Some(3)` and `Some(4)`)
24//! - `EnumDiscr` when `Self` is an enum, for comparing the enum discriminants.
25//! - `StaticEnum` and `StaticStruct` for static methods, where the type
26//!   being derived upon is either an enum or struct respectively. (Any
27//!   argument with type Self is just grouped among the non-self
28//!   arguments.)
29//!
30//! In the first two cases, the values from the corresponding fields in
31//! all the arguments are grouped together.
32//!
33//! The non-static cases have `Option<ident>` in several places associated
34//! with field `expr`s. This represents the name of the field it is
35//! associated with. It is only not `None` when the associated field has
36//! an identifier in the source code. For example, the `x`s in the
37//! following snippet
38//!
39//! ```rust
40//! struct A {
41//!     x: i32,
42//! }
43//!
44//! struct B(i32);
45//!
46//! enum C {
47//!     C0(i32),
48//!     C1 { x: i32 }
49//! }
50//! ```
51//!
52//! The `i32`s in `B` and `C0` don't have an identifier, so the
53//! `Option<ident>`s would be `None` for them.
54//!
55//! In the static cases, the structure is summarized, either into the just
56//! spans of the fields or a list of spans and the field idents (for tuple
57//! structs and record structs, respectively), or a list of these, for
58//! enums (one for each variant). For empty struct and empty enum
59//! variants, it is represented as a count of 0.
60//!
61//! # "`cs`" functions
62//!
63//! The `cs_...` functions ("combine substructure") are designed to
64//! make life easier by providing some pre-made recipes for common
65//! threads; mostly calling the function being derived on all the
66//! arguments and then combining them back together in some way (or
67//! letting the user chose that). They are not meant to be the only
68//! way to handle the structures that this code creates.
69//!
70//! # Examples
71//!
72//! The following simplified `PartialEq` is used for in-code examples:
73//!
74//! ```rust
75//! trait PartialEq {
76//!     fn eq(&self, other: &Self) -> bool;
77//! }
78//!
79//! impl PartialEq for i32 {
80//!     fn eq(&self, other: &i32) -> bool {
81//!         *self == *other
82//!     }
83//! }
84//! ```
85//!
86//! Some examples of the values of `SubstructureFields` follow, using the
87//! above `PartialEq`, `A`, `B` and `C`.
88//!
89//! ## Structs
90//!
91//! When generating the `expr` for the `A` impl, the `SubstructureFields` is
92//!
93//! ```text
94//! Struct(vec![FieldInfo {
95//!     span: <span of x>,
96//!     name: Some(<ident of x>),
97//!     self_: <expr for &self.x>,
98//!     other: vec![<expr for &other.x>],
99//! }])
100//! ```
101//!
102//! For the `B` impl, called with `B(a)` and `B(b)`,
103//!
104//! ```text
105//! Struct(vec![FieldInfo {
106//!     span: <span of i32>,
107//!     name: None,
108//!     self_: <expr for &a>,
109//!     other: vec![<expr for &b>],
110//! }])
111//! ```
112//!
113//! ## Enums
114//!
115//! When generating the `expr` for a call with `self == C0(a)` and `other
116//! == C0(b)`, the SubstructureFields is
117//!
118//! ```text
119//! EnumMatching(
120//!     0,
121//!     <ast::Variant for C0>,
122//!     vec![FieldInfo {
123//!         span: <span of i32>,
124//!         name: None,
125//!         self_: <expr for &a>,
126//!         other: vec![<expr for &b>],
127//!     }],
128//! )
129//! ```
130//!
131//! For `C1 {x}` and `C1 {x}`,
132//!
133//! ```text
134//! EnumMatching(
135//!     1,
136//!     <ast::Variant for C1>,
137//!     vec![FieldInfo {
138//!         span: <span of x>,
139//!         name: Some(<ident of x>),
140//!         self_: <expr for &self.x>,
141//!         other: vec![<expr for &other.x>],
142//!     }],
143//! )
144//! ```
145//!
146//! For the discriminants,
147//!
148//! ```text
149//! EnumDiscr(
150//!     &[<ident of self discriminant>, <ident of other discriminant>],
151//!     <expr to combine with>,
152//! )
153//! ```
154//!
155//! Note that this setup doesn't allow for the brute-force "match every variant
156//! against every other variant" approach, which is bad because it produces a
157//! quadratic amount of code (see #15375).
158//!
159//! ## Static
160//!
161//! A static method on the types above would result in,
162//!
163//! ```text
164//! StaticStruct(<ast::VariantData of A>, Named(vec![(<ident of x>, <span of x>)]))
165//!
166//! StaticStruct(<ast::VariantData of B>, Unnamed(vec![<span of x>]))
167//!
168//! StaticEnum(
169//!     <ast::EnumDef of C>,
170//!     vec![
171//!         (<ident of C0>, <span of C0>, Unnamed(vec![<span of i32>])),
172//!         (<ident of C1>, <span of C1>, Named(vec![(<ident of x>, <span of x>)])),
173//!     ],
174//! )
175//! ```
176
177use std::ops::Not;
178use std::vec;
179
180pub(crate) use SubstructureFields::*;
181pub(crate) use rustc_ast as ast;
182use rustc_ast::token::{IdentKind, LitKind, Token, TokenKind};
183use rustc_ast::tokenstream::{DelimSpan, Spacing, TokenTree};
184use rustc_ast::{
185    AttrArgs, DelimArgs, EnumDef, Expr, GenericArg, GenericParam, GenericParamKind, Generics,
186    Safety, SelfKind, VariantData,
187};
188use rustc_attr_ir::{Attribute, AttributeKind, ReprPacked};
189use rustc_attr_parsing::AttributeParser;
190use rustc_expand::base::ExtCtxt;
191use rustc_span::{Ident, Span, Symbol, kw, respan, sym};
192pub(crate) use smallvec::{SmallVec, smallvec};
193use thin_vec::{ThinVec, thin_vec};
194
195use crate::{deriving, diagnostics};
196
197pub(crate) struct TraitDef<'a> {
198    /// The span for the current #[derive(Foo)] header.
199    pub span: Span,
200
201    /// Path of the trait, including any type parameters
202    pub path: ast::Path,
203
204    /// Whether to skip adding the current trait as a bound to the type parameters of the type.
205    pub skip_path_as_bound: bool,
206
207    /// Whether `Copy` is needed as an additional bound on type parameters in a packed struct.
208    pub needs_copy_as_bound_if_packed: bool,
209
210    /// Additional bounds required of any type parameters of the type,
211    /// other than the current trait
212    pub additional_bounds: SmallVec<[ast::Path; 1]>,
213
214    /// Can this trait be derived for unions?
215    pub supports_unions: bool,
216
217    pub methods: SmallVec<[MethodDef<'a>; 1]>,
218
219    pub is_const: bool,
220
221    /// The safety of the `impl`.
222    pub safety: Safety,
223
224    /// Whether the added `impl` should appear in rustdoc output.
225    pub document: bool,
226}
227
228pub(crate) struct MethodDef<'a> {
229    /// name of the method
230    pub name: Symbol,
231    /// List of generics, e.g., `R: rand::Rng`
232    pub generics: Generics,
233
234    /// Is there is a `&self` argument? If not, it is a static function.
235    pub explicit_self: bool,
236
237    /// Arguments other than the self argument.
238    pub nonself_args: SmallVec<[(Box<ast::Ty>, Symbol); 1]>,
239
240    /// Whether this method has another arg of type `&self`.
241    pub has_other_selflike_arg: bool,
242
243    /// Returns type
244    pub ret_ty: Box<ast::Ty>,
245
246    pub attributes: ast::AttrVec,
247
248    pub fieldless_variants_strategy: FieldlessVariantsStrategy,
249
250    pub combine_substructure: CombineSubstructureFunc<'a>,
251}
252
253/// How to handle fieldless enum variants.
254#[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)]
255pub(crate) enum FieldlessVariantsStrategy {
256    /// Combine fieldless variants into a single match arm.
257    /// This assumes that relevant information has been handled
258    /// by looking at the enum's discriminant.
259    Unify,
260    /// Don't do anything special about fieldless variants. They are
261    /// handled like any other variant.
262    Default,
263    /// If all variants of the enum are fieldless, expand the special
264    /// `AllFieldLessEnum` substructure, so that the entire enum can be handled
265    /// at once.
266    SpecializeIfAllVariantsFieldless,
267}
268
269/// Summary of the relevant parts of a struct/enum field.
270pub(crate) struct FieldInfo {
271    pub span: Span,
272    /// None for tuple structs/normal enum variants, Some for normal
273    /// structs/struct enum variants.
274    pub name: Option<Ident>,
275    /// The expression corresponding to this field of `self`
276    /// (specifically, a reference to it).
277    pub self_expr: Box<Expr>,
278    /// The expression corresponding to a reference to this field in
279    /// the other selflike argument.
280    pub other_selflike_expr: Option<Box<Expr>>,
281    pub maybe_scalar: bool,
282}
283
284pub(crate) struct Substructure<'a> {
285    pub fields: SubstructureFields<'a>,
286    // FIXME: this is currently required to avoid issues with attribute macros after derives,
287    // such as https://github.com/rust-lang/rust/issues/163800.
288    // Ideally we would just use `Self` instead.
289    pub type_ident: Ident,
290}
291
292/// A summary of the possible sets of fields.
293pub(crate) enum SubstructureFields<'a> {
294    /// A non-static method where `Self` is a struct.
295    Struct(&'a ast::VariantData, Vec<FieldInfo>),
296
297    /// A non-static method handling the entire enum at once
298    /// (after it has been determined that none of the enum
299    /// variants has any fields).
300    AllFieldlessEnum(&'a ast::EnumDef),
301
302    /// Matching variants of the enum: ast::Variant,
303    /// fields: the field name is only non-`None` in the case of a struct
304    /// variant.
305    EnumMatching(&'a ast::Variant, Vec<FieldInfo>),
306
307    /// The discriminant of an enum. The field is the expression to combine the
308    /// discriminant expression with; it will be `None` if no match is necessary.
309    EnumDiscr(Option<Box<Expr>>),
310
311    /// A static method where `Self` is a struct.
312    StaticStruct(&'a ast::VariantData),
313
314    /// A static method where `Self` is an enum.
315    StaticEnum(&'a ast::EnumDef),
316}
317
318/// Combine the values of all the fields together. The last argument is
319/// all the fields of all the structures.
320pub(crate) type CombineSubstructureFunc<'a> =
321    Box<dyn Fn(&ExtCtxt<'_>, Span, Substructure<'_>) -> BlockOrExpr + 'a>;
322
323pub(crate) fn combine_substructure<'a>(
324    f: impl Fn(&ExtCtxt<'_>, Span, Substructure<'_>) -> BlockOrExpr + 'a,
325) -> CombineSubstructureFunc<'a> {
326    Box::new(f)
327}
328
329struct TypeParameter {
330    bound_generic_params: ThinVec<ast::GenericParam>,
331    ty: Box<ast::Ty>,
332}
333
334/// The code snippets built up for derived code are sometimes used as blocks
335/// (e.g. in a function body) and sometimes used as expressions (e.g. in a match
336/// arm). This structure avoids committing to either form until necessary,
337/// avoiding the insertion of any unnecessary blocks.
338///
339/// The statements come before the expression.
340pub(crate) struct BlockOrExpr(ThinVec<ast::Stmt>, Option<Box<Expr>>);
341
342impl BlockOrExpr {
343    pub(crate) fn new_stmts(stmts: ThinVec<ast::Stmt>) -> BlockOrExpr {
344        BlockOrExpr(stmts, None)
345    }
346
347    pub(crate) fn new_expr(expr: Box<Expr>) -> BlockOrExpr {
348        BlockOrExpr(ThinVec::new(), Some(expr))
349    }
350
351    pub(crate) fn new_mixed(stmts: ThinVec<ast::Stmt>, expr: Option<Box<Expr>>) -> BlockOrExpr {
352        BlockOrExpr(stmts, expr)
353    }
354
355    // Converts it into a block.
356    fn into_block(mut self, cx: &ExtCtxt<'_>, span: Span) -> Box<ast::Block> {
357        if let Some(expr) = self.1 {
358            self.0.push(cx.stmt_expr(expr));
359        }
360        cx.block(span, self.0)
361    }
362
363    // Converts it into an expression.
364    fn into_expr(self, cx: &ExtCtxt<'_>, span: Span) -> Box<Expr> {
365        if self.0.is_empty() {
366            match self.1 {
367                None => cx.expr_block(cx.block(span, ThinVec::new())),
368                Some(expr) => expr,
369            }
370        } else if let [stmt] = self.0.as_slice()
371            && let ast::StmtKind::Expr(expr) = &stmt.kind
372            && self.1.is_none()
373        {
374            // There's only a single statement expression. Pull it out.
375            expr.clone()
376        } else {
377            // Multiple statements and/or expressions.
378            cx.expr_block(self.into_block(cx, span))
379        }
380    }
381}
382
383/// This method helps to extract all the type parameters referenced from a
384/// type. For a type parameter `<T>`, it looks for either a `TyPath` that
385/// is not global and starts with `T`, or a `TyQPath`.
386/// Also include bound generic params from the input type.
387fn find_type_parameters(
388    ty: &ast::Ty,
389    ty_param_names: &[Symbol],
390    cx: &ExtCtxt<'_>,
391) -> Vec<TypeParameter> {
392    use rustc_ast::visit;
393
394    struct Visitor<'a, 'b> {
395        cx: &'a ExtCtxt<'b>,
396        ty_param_names: &'a [Symbol],
397        bound_generic_params_stack: ThinVec<ast::GenericParam>,
398        type_params: Vec<TypeParameter>,
399    }
400
401    impl<'a, 'b> visit::Visitor<'a> for Visitor<'a, 'b> {
402        fn visit_ty(&mut self, ty: &'a ast::Ty) {
403            let stack_len = self.bound_generic_params_stack.len();
404            if let ast::TyKind::FnPtr(fn_ptr) = &ty.kind
405                && !fn_ptr.generic_params.is_empty()
406            {
407                // Given a field `x: for<'a> fn(T::SomeType<'a>)`, we wan't to account for `'a` so
408                // that we generate `where for<'a> T::SomeType<'a>: ::core::clone::Clone`. #122622
409                self.bound_generic_params_stack.extend(fn_ptr.generic_params.iter().cloned());
410            }
411
412            if let ast::TyKind::Path(_, path) = &ty.kind
413                && let Some(segment) = path.segments.first()
414                && self.ty_param_names.contains(&segment.ident.name)
415            {
416                self.type_params.push(TypeParameter {
417                    bound_generic_params: self.bound_generic_params_stack.clone(),
418                    ty: Box::new(ty.clone()),
419                });
420            }
421
422            visit::walk_ty(self, ty);
423            self.bound_generic_params_stack.truncate(stack_len);
424        }
425
426        // Place bound generic params on a stack, to extract them when a type is encountered.
427        fn visit_poly_trait_ref(&mut self, trait_ref: &'a ast::PolyTraitRef) {
428            let stack_len = self.bound_generic_params_stack.len();
429            self.bound_generic_params_stack.extend(trait_ref.bound_generic_params.iter().cloned());
430
431            visit::walk_poly_trait_ref(self, trait_ref);
432
433            self.bound_generic_params_stack.truncate(stack_len);
434        }
435
436        fn visit_mac_call(&mut self, mac: &ast::MacCall) {
437            self.cx.dcx().emit_err(diagnostics::DeriveMacroCall { span: mac.span() });
438        }
439    }
440
441    let mut visitor = Visitor {
442        cx,
443        ty_param_names,
444        bound_generic_params_stack: ThinVec::new(),
445        type_params: Vec::new(),
446    };
447    visit::Visitor::visit_ty(&mut visitor, ty);
448
449    visitor.type_params
450}
451
452impl<'a> TraitDef<'a> {
453    pub(crate) fn expand(
454        self,
455        cx: &ExtCtxt<'_>,
456        item: &'a ast::Item,
457        push: &mut dyn FnMut(Box<ast::Item>),
458    ) {
459        self.expand_ext(cx, item, push, false);
460    }
461
462    pub(crate) fn expand_ext(
463        self,
464        cx: &ExtCtxt<'_>,
465        item: &'a ast::Item,
466        push: &mut dyn FnMut(Box<ast::Item>),
467        from_scratch: bool,
468    ) {
469        let span = self.span;
470        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!(
471            AttributeParser::parse_limited_sym(cx.sess, &item.attrs, &[sym::repr]),
472            Some(Attribute::Parsed(AttributeKind::Repr { reprs, .. })) if reprs.iter().any(|(x, _)| matches!(x, ReprPacked(..)))
473        );
474
475        let mut newitem = match &item.kind {
476            ast::ItemKind::Union(..) if !self.supports_unions => {
477                cx.dcx().emit_err(diagnostics::DeriveUnion { span });
478                return;
479            }
480            ast::ItemKind::Struct(ident, generics, struct_def)
481            | ast::ItemKind::Union(ident, generics, struct_def) => {
482                let fields = struct_def.fields().iter();
483                let methods = self.methods.iter().filter_map(|method_def| {
484                    let body = if from_scratch || method_def.is_static() {
485                        method_def.call_substructure_method(
486                            cx,
487                            span,
488                            StaticStruct(struct_def),
489                            *ident,
490                        )
491                    } else {
492                        method_def
493                            .expand_struct_method_body(cx, span, struct_def, is_packed, *ident)
494                    };
495
496                    method_def.create_method(cx, span, body)
497                });
498                self.create_derived_impl(cx, *ident, generics, fields, methods, is_packed)
499            }
500            ast::ItemKind::Enum(ident, generics, enum_def) => {
501                // We can skip generating the impl here, because `repr(packed)`
502                // enums cause an error later on and to prevent ICEs like #133025.
503                // This can only cause further compilation errors
504                // downstream in blatantly illegal code, so it is fine.
505                if is_packed {
506                    return;
507                }
508                let fields = enum_def.variants.iter().flat_map(|variant| variant.data.fields());
509                let methods = self.methods.iter().filter_map(|method_def| {
510                    let body = if from_scratch || method_def.is_static() {
511                        method_def.call_substructure_method(cx, span, StaticEnum(enum_def), *ident)
512                    } else {
513                        method_def.expand_enum_method_body(cx, span, enum_def, *ident)
514                    };
515
516                    method_def.create_method(cx, span, body)
517                });
518                self.create_derived_impl(cx, *ident, generics, fields, methods, is_packed)
519            }
520            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
521        };
522        // Keep the lint attributes of the previous item to control how the
523        // generated implementations are linted
524        newitem.attrs.extend(
525            item.attrs
526                .iter()
527                .filter(|a| {
528                    a.has_any_name(&[
529                        sym::allow,
530                        sym::warn,
531                        sym::deny,
532                        sym::forbid,
533                        sym::stable,
534                        sym::unstable,
535                    ])
536                })
537                .cloned(),
538        );
539        push(newitem);
540    }
541
542    /// Given that we are deriving a trait `DerivedTrait` for a type like:
543    ///
544    /// ```ignore (only-for-syntax-highlight)
545    /// struct Struct<'a, ..., 'z, A, B: DeclaredTrait, C, ..., Z>
546    /// where
547    ///     C: WhereTrait,
548    /// {
549    ///     a: A,
550    ///     b: B::Item,
551    ///     b1: <B as DeclaredTrait>::Item,
552    ///     c1: <C as WhereTrait>::Item,
553    ///     c2: Option<<C as WhereTrait>::Item>,
554    ///     ...
555    /// }
556    /// ```
557    ///
558    /// create an impl like:
559    ///
560    /// ```ignore (only-for-syntax-highlight)
561    /// impl<'a, ..., 'z, A, B: DeclaredTrait, C, ..., Z>
562    /// where
563    ///     C: WhereTrait,
564    ///     A: DerivedTrait + B1 + ... + BN,
565    ///     B: DerivedTrait + B1 + ... + BN,
566    ///     C: DerivedTrait + B1 + ... + BN,
567    ///     B::Item: DerivedTrait + B1 + ... + BN,
568    ///     <C as WhereTrait>::Item: DerivedTrait + B1 + ... + BN,
569    ///     ...
570    /// {
571    ///     ...
572    /// }
573    /// ```
574    ///
575    /// where B1, ..., BN are the bounds given by `bounds_paths`.'. Z is a phantom type, and
576    /// therefore does not get bound by the derived trait.
577    fn create_derived_impl(
578        &self,
579        cx: &ExtCtxt<'_>,
580        type_ident: Ident,
581        generics: &Generics,
582        fields: impl Iterator<Item = &'a ast::FieldDef>,
583        methods: impl Iterator<Item = Box<ast::AssocItem>>,
584        is_packed: bool,
585    ) -> Box<ast::Item> {
586        let mut where_clause = ast::WhereClause::default();
587        where_clause.span = generics.where_clause.span;
588        let ctxt = self.span.ctxt();
589
590        // Create the generic parameters
591        let params: ThinVec<_> = generics
592            .params
593            .iter()
594            .map(|param| match &param.kind {
595                GenericParamKind::Lifetime => param.clone(),
596                GenericParamKind::Type { .. } => {
597                    // Extra restrictions on the generics parameters to the
598                    // type being derived upon.
599                    let span = param.ident.span.with_ctxt(ctxt);
600                    let bounds: ThinVec<_> = self
601                        .additional_bounds
602                        .iter()
603                        .map(|p| cx.trait_bound(ast::Path { span, ..p.clone() }, self.is_const))
604                        .chain(
605                            // Add a bound for the current trait.
606                            self.skip_path_as_bound.not().then(|| {
607                                let mut trait_path = self.path.clone();
608                                trait_path.span = span;
609                                cx.trait_bound(trait_path, self.is_const)
610                            }),
611                        )
612                        .chain({
613                            // Add a `Copy` bound if required.
614                            if is_packed && self.needs_copy_as_bound_if_packed {
615                                let p = new_path(cx, span, { &[sym::marker, sym::Copy] }, ::alloc::vec::Vec::new())deriving::path_std!(cx, span, marker::Copy);
616                                Some(cx.trait_bound(p, self.is_const))
617                            } else {
618                                None
619                            }
620                        })
621                        .chain(
622                            // Also add in any bounds from the declaration.
623                            param.bounds.iter().cloned(),
624                        )
625                        .collect();
626
627                    cx.typaram(param.ident, bounds, None)
628                }
629                GenericParamKind::Const { ty, span, .. } => {
630                    let const_nodefault_kind = GenericParamKind::Const {
631                        ty: ty.clone(),
632                        span: span.with_ctxt(ctxt),
633
634                        // We can't have default values inside impl block
635                        default: None,
636                    };
637                    let mut param_clone = param.clone();
638                    param_clone.kind = const_nodefault_kind;
639                    param_clone
640                }
641            })
642            .map(|mut param| {
643                // Remove all attributes, because there might be helper attributes
644                // from other macros that will not be valid in the expanded implementation.
645                param.attrs.clear();
646                param
647            })
648            .collect();
649
650        // and similarly for where clauses
651        where_clause.predicates.extend(generics.where_clause.predicates.iter().map(|clause| {
652            ast::WherePredicate {
653                attrs: clause.attrs.clone(),
654                kind: clause.kind.clone(),
655                id: ast::DUMMY_NODE_ID,
656                span: clause.span.with_ctxt(ctxt),
657                is_placeholder: false,
658            }
659        }));
660
661        let ty_param_names: Vec<Symbol> = params
662            .iter()
663            .filter(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    ast::GenericParamKind::Type { .. } => true,
    _ => false,
}matches!(param.kind, ast::GenericParamKind::Type { .. }))
664            .map(|ty_param| ty_param.ident.name)
665            .collect();
666
667        if !ty_param_names.is_empty() {
668            for field in fields {
669                let field_ty_params = find_type_parameters(&field.ty, &ty_param_names, cx);
670
671                for field_ty_param in field_ty_params {
672                    // if we have already handled this type, skip it
673                    if let ast::TyKind::Path(_, p) = &field_ty_param.ty.kind
674                        && let [sole_segment] = &*p.segments
675                        && ty_param_names.contains(&sole_segment.ident.name)
676                    {
677                        continue;
678                    }
679                    let mut bounds: ThinVec<_> = self
680                        .additional_bounds
681                        .iter()
682                        .map(|p| cx.trait_bound(p.clone(), self.is_const))
683                        .collect();
684
685                    // Require the current trait.
686                    if !self.skip_path_as_bound {
687                        bounds.push(cx.trait_bound(self.path.clone(), self.is_const));
688                    }
689
690                    // Add a `Copy` bound if required.
691                    if is_packed && self.needs_copy_as_bound_if_packed {
692                        let p = new_path(cx, self.span, { &[sym::marker, sym::Copy] },
    ::alloc::vec::Vec::new())deriving::path_std!(cx, self.span, marker::Copy);
693                        bounds.push(cx.trait_bound(p, self.is_const));
694                    }
695
696                    if !bounds.is_empty() {
697                        let predicate = ast::WhereBoundPredicate {
698                            bound_generic_params: field_ty_param.bound_generic_params,
699                            bounded_ty: field_ty_param.ty,
700                            bounds,
701                        };
702
703                        let kind = ast::WherePredicateKind::BoundPredicate(predicate);
704                        let predicate = ast::WherePredicate {
705                            attrs: ThinVec::new(),
706                            kind,
707                            id: ast::DUMMY_NODE_ID,
708                            span: self.span,
709                            is_placeholder: false,
710                        };
711                        where_clause.predicates.push(predicate);
712                    }
713                }
714            }
715        }
716
717        let trait_generics = Generics { params, where_clause, span: generics.span.with_ctxt(ctxt) };
718
719        // Create the reference to the trait.
720        let trait_ref = cx.trait_ref(self.path.clone());
721
722        let self_params: Vec<_> = generics
723            .params
724            .iter()
725            .map(|param| generic_param_to_arg(cx, param, param.ident.span.with_ctxt(ctxt)))
726            .collect();
727
728        // Create the type of `self`.
729        let path =
730            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);
731        let self_type = cx.ty_path(path);
732
733        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),];
734
735        // Only add `rustc_const_unstable` attributes if `derive_const` is used within libcore/libstd,
736        // Other crates don't need stability attributes, so adding them is not useful, but libcore needs them
737        // on all const trait impls.
738        if self.is_const && cx.ecfg.features.staged_api() {
739            let rustc_const_unstable =
740                cx.path_ident(self.span, Ident::new(sym::rustc_const_unstable, self.span));
741
742            // #[rustc_const_unstable(feature = "derive_const", issue = "118304")]
743            attrs.push(
744                cx.attr_nested(
745                    rustc_ast::AttrItem {
746                        unsafety: Safety::Default,
747                        path: rustc_const_unstable,
748                        args: AttrArgs::Delimited(DelimArgs {
749                            dspan: DelimSpan::from_single(self.span),
750                            delim: rustc_ast::token::Delimiter::Parenthesis,
751                            tokens: [
752                                TokenKind::Ident(sym::feature, IdentKind::Normal),
753                                TokenKind::Eq,
754                                TokenKind::lit(LitKind::Str, sym::derive_const, None),
755                                TokenKind::Comma,
756                                TokenKind::Ident(sym::issue, IdentKind::Normal),
757                                TokenKind::Eq,
758                                TokenKind::lit(LitKind::Str, sym::derive_const_issue, None),
759                            ]
760                            .into_iter()
761                            .map(|kind| {
762                                TokenTree::Token(Token { kind, span: self.span }, Spacing::Alone)
763                            })
764                            .collect(),
765                        }),
766                        span: self.span,
767                    },
768                    self.span,
769                ),
770            )
771        }
772
773        if !self.document {
774            attrs.push(cx.attr_nested_word(sym::doc, sym::hidden, self.span));
775        }
776
777        cx.item_trait_impl(
778            self.span,
779            attrs,
780            trait_generics,
781            self.safety,
782            self.is_const,
783            trait_ref,
784            self_type,
785            methods.collect(),
786        )
787    }
788}
789
790impl<'a> MethodDef<'a> {
791    fn call_substructure_method(
792        &self,
793        cx: &ExtCtxt<'_>,
794        span: Span,
795        fields: SubstructureFields<'_>,
796        type_ident: Ident,
797    ) -> BlockOrExpr {
798        (self.combine_substructure)(cx, span, Substructure { fields, type_ident })
799    }
800
801    fn is_static(&self) -> bool {
802        !self.explicit_self
803    }
804
805    /// Expressions for `&self` and also any other
806    /// args with the same type (e.g. the `other` arg in `PartialEq::eq`).
807    fn get_selflike_args(&self, cx: &ExtCtxt<'_>, span: Span) -> ThinVec<Box<Expr>> {
808        if !self.explicit_self {
    ::core::panicking::panic("assertion failed: self.explicit_self")
};assert!(self.explicit_self);
809
810        let self_expr = cx.expr_self(span);
811        if self.has_other_selflike_arg {
812            {
    let len = [(), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(self_expr);
    vec.push(cx.expr_ident_sym(span, self.nonself_args[0].1));
    vec
}thin_vec![self_expr, cx.expr_ident_sym(span, self.nonself_args[0].1)]
813        } else {
814            {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(self_expr);
    vec
}thin_vec![self_expr]
815        }
816    }
817
818    fn create_method(
819        &self,
820        cx: &ExtCtxt<'_>,
821        span: Span,
822        body: BlockOrExpr,
823    ) -> Option<Box<ast::AssocItem>> {
824        // `assert_fields_are_eq` has an empty default implementation
825        if body.0.is_empty() && body.1.is_none() && self.name == sym::assert_fields_are_eq {
826            return None;
827        }
828        // Create the generics that aren't for `Self`.
829        let fn_generics = self.generics.clone();
830
831        let self_arg = self.explicit_self.then(|| {
832            let ident = Ident::new(kw::SelfLower, span);
833            ast::Param::from_self(
834                ast::AttrVec::default(),
835                respan(span, SelfKind::Region(None, ast::Mutability::Not)),
836                ident,
837            )
838        });
839        let args = self_arg
840            .into_iter()
841            .chain(self.nonself_args.iter().map(|(ty, name)| {
842                let ast_ty = ty.clone();
843                let ident = Ident::new(*name, span);
844                cx.param(span, ident, ast_ty)
845            }))
846            .collect();
847
848        let ret_type = if self.ret_ty.kind.is_unit() {
849            ast::FnRetTy::Default(span)
850        } else {
851            ast::FnRetTy::Ty(self.ret_ty.clone())
852        };
853
854        let method_ident = Ident::new(self.name, span);
855        let fn_decl = cx.fn_decl(args, ret_type);
856        let body_block = body.into_block(cx, span);
857
858        let trait_lo_sp = span.shrink_to_lo();
859
860        let sig = ast::FnSig { header: ast::FnHeader::default(), decl: fn_decl, span };
861        let defaultness = ast::Defaultness::Implicit;
862
863        // Create the method.
864        Some(Box::new(ast::AssocItem {
865            id: ast::DUMMY_NODE_ID,
866            attrs: self.attributes.clone(),
867            span,
868            vis: ast::Visibility { span: trait_lo_sp, kind: ast::VisibilityKind::Inherited },
869            kind: ast::AssocItemKind::Fn(Box::new(ast::Fn {
870                defaultness,
871                sig,
872                ident: method_ident,
873                generics: fn_generics,
874                contract: None,
875                body: Some(body_block),
876                define_opaque: None,
877                eii_impl: None,
878            })),
879            tokens: None,
880        }))
881    }
882
883    /// The normal case uses field access.
884    ///
885    /// ```
886    /// #[derive(PartialEq)]
887    /// # struct Dummy;
888    /// struct A { x: u8, y: u8 }
889    ///
890    /// // equivalent to:
891    /// impl PartialEq for A {
892    ///     fn eq(&self, other: &A) -> bool {
893    ///         self.x == other.x && self.y == other.y
894    ///     }
895    /// }
896    /// ```
897    ///
898    /// But if the struct is `repr(packed)`, we can't use something like
899    /// `&self.x` because that might cause an unaligned ref. So for any trait
900    /// method that takes a reference, we use a local block to force a copy.
901    /// This requires that the field impl `Copy`.
902    ///
903    /// ```rust,ignore (example)
904    /// # struct A { x: u8, y: u8 }
905    /// impl PartialEq for A {
906    ///     fn eq(&self, other: &A) -> bool {
907    ///         // Desugars to `{ self.x }.eq(&{ other.y }) && ...`
908    ///         { self.x } == { other.y } && { self.y } == { other.y }
909    ///     }
910    /// }
911    /// impl Hash for A {
912    ///     fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
913    ///         ::core::hash::Hash::hash(&{ self.x }, state);
914    ///         ::core::hash::Hash::hash(&{ self.y }, state);
915    ///     }
916    /// }
917    /// ```
918    fn expand_struct_method_body<'b>(
919        &self,
920        cx: &ExtCtxt<'_>,
921        span: Span,
922        struct_def: &'b VariantData,
923        is_packed: bool,
924        type_ident: Ident,
925    ) -> BlockOrExpr {
926        let selflike_args = self.get_selflike_args(cx, span);
927
928        let selflike_fields =
929            create_struct_field_access_fields(span, cx, &selflike_args, struct_def, is_packed);
930        self.call_substructure_method(cx, span, Struct(struct_def, selflike_fields), type_ident)
931    }
932
933    /// ```
934    /// #[derive(PartialEq)]
935    /// # struct Dummy;
936    /// enum A {
937    ///     A1,
938    ///     A2(i32)
939    /// }
940    /// ```
941    ///
942    /// is equivalent to:
943    ///
944    /// ```
945    /// #![feature(core_intrinsics)]
946    /// enum A {
947    ///     A1,
948    ///     A2(i32)
949    /// }
950    /// impl ::core::cmp::PartialEq for A {
951    ///     #[inline]
952    ///     fn eq(&self, other: &A) -> bool {
953    ///         let __self_discr = ::core::intrinsics::discriminant_value(self);
954    ///         let __arg1_discr = ::core::intrinsics::discriminant_value(other);
955    ///         __self_discr == __arg1_discr
956    ///             && match (self, other) {
957    ///                 (A::A2(__self_0), A::A2(__arg1_0)) => *__self_0 == *__arg1_0,
958    ///                 _ => true,
959    ///             }
960    ///     }
961    /// }
962    /// ```
963    ///
964    /// Creates a discriminant check combined with a match for a tuple of all
965    /// `selflike_args`, with an arm for each variant with fields, possibly an
966    /// arm for each fieldless variant (if `unify_fieldless_variants` is not
967    /// `Unify`), and possibly a default arm.
968    fn expand_enum_method_body<'b>(
969        &self,
970        cx: &ExtCtxt<'_>,
971        span: Span,
972        enum_def: &'b EnumDef,
973        type_ident: Ident,
974    ) -> BlockOrExpr {
975        let variants = &enum_def.variants;
976
977        // Traits that unify fieldless variants always use the discriminant(s).
978        let unify_fieldless_variants =
979            self.fieldless_variants_strategy == FieldlessVariantsStrategy::Unify;
980
981        // For zero-variant enum, this function body is unreachable. Generate
982        // `match *self {}`. This produces machine code identical to `unsafe {
983        // core::intrinsics::unreachable() }` while being safe and stable.
984        if variants.is_empty() {
985            let match_arg = cx.expr_deref(span, cx.expr_self(span));
986            let match_arms = ThinVec::new();
987            let expr = cx.expr_match(span, match_arg, match_arms);
988            return BlockOrExpr(ThinVec::new(), Some(expr));
989        }
990
991        let selflike_args = self.get_selflike_args(cx, span);
992
993        let prefixes: &[&str] = match selflike_args.len() {
994            1 => &["__self"],
995            2 => &["__self", "__arg1"],
996            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
997        };
998
999        // There are some special cases involving fieldless enums where no
1000        // match is necessary.
1001        let all_fieldless = variants.iter().all(|v| v.data.fields().is_empty());
1002        if all_fieldless {
1003            if variants.len() > 1 {
1004                match self.fieldless_variants_strategy {
1005                    FieldlessVariantsStrategy::Unify => {
1006                        // If the type is fieldless and the trait uses the discriminant and
1007                        // there are multiple variants, we need just an operation on
1008                        // the discriminant(s).
1009                        return self.call_substructure_method(
1010                            cx,
1011                            span,
1012                            EnumDiscr(None),
1013                            type_ident,
1014                        );
1015                    }
1016                    FieldlessVariantsStrategy::SpecializeIfAllVariantsFieldless => {
1017                        return self.call_substructure_method(
1018                            cx,
1019                            span,
1020                            AllFieldlessEnum(enum_def),
1021                            type_ident,
1022                        );
1023                    }
1024                    FieldlessVariantsStrategy::Default => (),
1025                }
1026            } else if let [variant] = variants.as_slice() {
1027                // If there is a single variant, we don't need an operation on
1028                // the discriminant(s). Just use the most degenerate result.
1029                return self.call_substructure_method(
1030                    cx,
1031                    span,
1032                    EnumMatching(variant, Vec::new()),
1033                    type_ident,
1034                );
1035            }
1036        }
1037
1038        // These arms are of the form:
1039        // (Variant1, Variant1, ...) => Body1
1040        // (Variant2, Variant2, ...) => Body2
1041        // ...
1042        // where each tuple has length = selflike_args.len()
1043        let mut match_arms: ThinVec<ast::Arm> = variants
1044            .iter()
1045            .filter(|&v| !(unify_fieldless_variants && v.data.fields().is_empty()))
1046            .map(|variant| {
1047                // A single arm has form (&VariantK, &VariantK, ...) => BodyK
1048                // (see "Final wrinkle" note below for why.)
1049
1050                let fields = create_struct_pattern_fields(span, cx, &variant.data, &prefixes);
1051
1052                let sp = variant.span.with_ctxt(span.ctxt());
1053                let variant_path =
1054                    cx.path(sp, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Ident::new(kw::SelfUpper, span), variant.ident]))vec![Ident::new(kw::SelfUpper, span), variant.ident]);
1055                let mut subpats =
1056                    create_struct_patterns(span, cx, variant_path, &variant.data, &prefixes);
1057
1058                // `(VariantK, VariantK, ...)` or just `VariantK`.
1059                let single_pat = if subpats.len() == 1 {
1060                    subpats.pop().unwrap()
1061                } else {
1062                    cx.pat_tuple(span, subpats)
1063                };
1064
1065                // For the BodyK, we need to delegate to our caller,
1066                // passing it an EnumMatching to indicate which case
1067                // we are in.
1068                //
1069                // Now, for some given VariantK, we have built up
1070                // expressions for referencing every field of every
1071                // Self arg, assuming all are instances of VariantK.
1072                // Build up code associated with such a case.
1073                let substructure = EnumMatching(variant, fields);
1074                let arm_expr = self
1075                    .call_substructure_method(cx, span, substructure, type_ident)
1076                    .into_expr(cx, span);
1077
1078                cx.arm(span, single_pat, arm_expr)
1079            })
1080            .collect();
1081
1082        // Add a default arm to the match, if necessary.
1083        let first_fieldless = variants.iter().find(|v| v.data.fields().is_empty());
1084        let default = match first_fieldless {
1085            Some(v) if unify_fieldless_variants => {
1086                // We need a default case that handles all the fieldless variants.
1087                Some(
1088                    self.call_substructure_method(
1089                        cx,
1090                        span,
1091                        EnumMatching(v, Vec::new()),
1092                        type_ident,
1093                    )
1094                    .into_expr(cx, span),
1095                )
1096            }
1097            _ if variants.len() > 1 && selflike_args.len() > 1 => {
1098                // Because we know that all the arguments will match if we reach
1099                // the match expression we add the unreachable intrinsic as the
1100                // result of the default which should help llvm in optimizing it.
1101                Some(deriving::call_unreachable(cx, span))
1102            }
1103            _ => None,
1104        };
1105        if let Some(arm) = default {
1106            match_arms.push(cx.arm(span, cx.pat_wild(span), arm));
1107        }
1108
1109        // Create a match expression with one arm per discriminant plus
1110        // possibly a default arm, e.g.:
1111        //      match (self, other) {
1112        //          (Variant1, Variant1, ...) => Body1
1113        //          (Variant2, Variant2, ...) => Body2,
1114        //          ...
1115        //          _ => ::core::intrinsics::unreachable(),
1116        //      }
1117        let get_match_expr = |mut selflike_args: ThinVec<Box<Expr>>| {
1118            let match_arg = if selflike_args.len() == 1 {
1119                selflike_args.pop().unwrap()
1120            } else {
1121                cx.expr_tuple(span, selflike_args)
1122            };
1123            cx.expr_match(span, match_arg, match_arms)
1124        };
1125
1126        // If the trait uses the discriminant and there are multiple variants, we need
1127        // to add a discriminant check operation before the match. Otherwise, the match
1128        // is enough.
1129        if unify_fieldless_variants && variants.len() > 1 {
1130            // Combine a discriminant check with the match.
1131            self.call_substructure_method(
1132                cx,
1133                span,
1134                EnumDiscr(Some(get_match_expr(selflike_args))),
1135                type_ident,
1136            )
1137        } else {
1138            BlockOrExpr(ThinVec::new(), Some(get_match_expr(selflike_args)))
1139        }
1140    }
1141}
1142
1143// general helper methods.
1144fn create_struct_patterns(
1145    span: Span,
1146    cx: &ExtCtxt<'_>,
1147    struct_path: ast::Path,
1148    struct_def: &VariantData,
1149    prefixes: &[&str],
1150) -> ThinVec<ast::Pat> {
1151    prefixes
1152        .iter()
1153        .map(|prefix| {
1154            let pieces_iter = struct_def.fields().iter().enumerate().map(|(i, struct_field)| {
1155                let ident = mk_pattern_ident(span, prefix, i);
1156                let path = ident.with_span_pos(struct_field.span);
1157                (struct_field.ident, cx.pat_ident(path.span, path))
1158            });
1159
1160            let struct_path = struct_path.clone();
1161            match *struct_def {
1162                VariantData::Struct { .. } => {
1163                    let field_pats = pieces_iter
1164                        .map(|(ident, pat)| ast::PatField {
1165                            ident: ident.expect("a braced struct with unnamed fields in `derive`"),
1166                            is_shorthand: false,
1167                            attrs: ast::AttrVec::new(),
1168                            id: ast::DUMMY_NODE_ID,
1169                            span: pat.span.with_ctxt(span.ctxt()),
1170                            pat: Box::new(pat),
1171                            is_placeholder: false,
1172                        })
1173                        .collect();
1174                    cx.pat_struct(span, struct_path, field_pats)
1175                }
1176                VariantData::Tuple(..) => {
1177                    let subpats = pieces_iter.map(|(_, subpat)| subpat).collect();
1178                    cx.pat_tuple_struct(span, struct_path, subpats)
1179                }
1180                VariantData::Unit(..) => cx.pat_path(span, struct_path),
1181            }
1182        })
1183        .collect()
1184}
1185
1186fn create_fields<F>(span: Span, struct_def: &VariantData, mk_exprs: F) -> Vec<FieldInfo>
1187where
1188    F: Fn(usize, &ast::FieldDef, Span) -> Vec<Box<Expr>>,
1189{
1190    struct_def
1191        .fields()
1192        .iter()
1193        .enumerate()
1194        .map(|(i, struct_field)| {
1195            // For this field, get an expr for each selflike_arg. E.g. for
1196            // `PartialEq::eq`, one for each of `&self` and `other`.
1197            let span = struct_field.span.with_ctxt(span.ctxt());
1198            let mut exprs: Vec<_> = mk_exprs(i, struct_field, span);
1199            let self_expr = exprs.remove(0);
1200            if true {
    if !(exprs.len() <= 1) {
        ::core::panicking::panic("assertion failed: exprs.len() <= 1")
    };
};debug_assert!(exprs.len() <= 1);
1201            FieldInfo {
1202                span,
1203                name: struct_field.ident,
1204                self_expr,
1205                other_selflike_expr: exprs.pop(),
1206                maybe_scalar: struct_field.ty.peel_refs().kind.maybe_scalar(),
1207            }
1208        })
1209        .collect()
1210}
1211
1212fn mk_pattern_ident(span: Span, prefix: &str, i: usize) -> Ident {
1213    Ident::from_str_and_span(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}_{1}", prefix, i))
    })format!("{prefix}_{i}"), span)
1214}
1215
1216fn create_struct_pattern_fields(
1217    span: Span,
1218    cx: &ExtCtxt<'_>,
1219    struct_def: &VariantData,
1220    prefixes: &[&str],
1221) -> Vec<FieldInfo> {
1222    create_fields(span, struct_def, |i, _struct_field, sp| {
1223        prefixes
1224            .iter()
1225            .map(|prefix| {
1226                let ident = mk_pattern_ident(span, prefix, i);
1227                cx.expr_path(cx.path_ident(sp, ident))
1228            })
1229            .collect()
1230    })
1231}
1232
1233fn create_struct_field_access_fields(
1234    span: Span,
1235    cx: &ExtCtxt<'_>,
1236    selflike_args: &[Box<Expr>],
1237    struct_def: &VariantData,
1238    is_packed: bool,
1239) -> Vec<FieldInfo> {
1240    create_fields(span, struct_def, |i, struct_field, sp| {
1241        selflike_args
1242            .iter()
1243            .map(|selflike_arg| {
1244                // Note: we must use `struct_field.span` rather than `sp` in the
1245                // `unwrap_or_else` case otherwise the hygiene is wrong and we get
1246                // "field `0` of struct `Point` is private" errors on tuple
1247                // structs.
1248                let mut field_expr = cx.expr(
1249                    sp,
1250                    ast::ExprKind::Field(
1251                        selflike_arg.clone(),
1252                        struct_field.ident.unwrap_or_else(|| {
1253                            Ident::from_str_and_span(&i.to_string(), struct_field.span)
1254                        }),
1255                    ),
1256                );
1257                if is_packed {
1258                    // Fields in packed structs are wrapped in a block, e.g. `&{self.0}`,
1259                    // causing a copy instead of a (potentially misaligned) reference.
1260                    field_expr = cx.expr_block(
1261                        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)]),
1262                    );
1263                }
1264                cx.expr_addr_of(sp, field_expr)
1265            })
1266            .collect()
1267    })
1268}
1269
1270pub(crate) fn generic_param_to_arg(cx: &ExtCtxt<'_>, p: &GenericParam, span: Span) -> GenericArg {
1271    match p.kind {
1272        GenericParamKind::Lifetime => GenericArg::Lifetime(cx.lifetime(span, p.ident)),
1273        GenericParamKind::Type { .. } => GenericArg::Type(cx.ty_ident(span, p.ident)),
1274        GenericParamKind::Const { .. } => GenericArg::Const(cx.const_ident(span, p.ident)),
1275    }
1276}
1277
1278pub(crate) fn generics_without_defaults(g: &Generics) -> Generics {
1279    Generics {
1280        params: g
1281            .params
1282            .iter()
1283            .map(|p| {
1284                let mut p = p.clone();
1285                match &mut p.kind {
1286                    ast::GenericParamKind::Const { default, .. } => *default = None,
1287                    ast::GenericParamKind::Type { default } => *default = None,
1288                    ast::GenericParamKind::Lifetime => {}
1289                };
1290                p.attrs.clear();
1291                p
1292            })
1293            .collect(),
1294        where_clause: g.where_clause.clone(),
1295        span: g.span,
1296    }
1297}