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