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;
178
179pub(crate) use Substructure::*;
180pub(crate) use rustc_ast as ast;
181use rustc_ast::{
182 EnumDef, Expr, GenericArg, GenericParam, GenericParamKind, Generics, Safety, VariantData,
183};
184use rustc_attr_ir::{Attribute, AttributeKind, ReprPacked};
185use rustc_attr_parsing::AttributeParser;
186use rustc_expand::base::ExtCtxt;
187use rustc_span::{Ident, Span, Symbol, kw, sym};
188pub(crate) use smallvec::{SmallVec, smallvec};
189use thin_vec::{ThinVec, thin_vec};
190
191use crate::{deriving, diagnostics};
192
193pub(crate) struct TraitDef<'a> {
194 /// The span for the current #[derive(Foo)] header.
195 pub span: Span,
196
197 /// Path of the trait, including any type parameters
198 pub path: ast::Path,
199
200 /// Whether to skip adding the current trait as a bound to the type parameters of the type.
201 pub skip_path_as_bound: bool = false,
202
203 /// Whether `Copy` is needed as an additional bound on type parameters in a packed struct.
204 pub needs_copy_as_bound_if_packed: bool,
205
206 /// Additional bounds required of any type parameters of the type,
207 /// other than the current trait
208 pub additional_bounds: SmallVec<[ast::Path; 1]>,
209
210 /// Can this trait be derived for unions?
211 pub supports_unions: bool,
212
213 pub methods: SmallVec<[MethodDef<'a>; 1]>,
214
215 pub is_const: bool,
216
217 /// The safety of the `impl`.
218 pub safety: Safety = Safety::Default,
219
220 /// Whether the added `impl` should appear in rustdoc output.
221 pub document: bool = true,
222}
223
224pub(crate) struct MethodDef<'a> {
225 /// name of the method
226 pub name: Symbol,
227 /// List of generics, e.g., `R: rand::Rng`
228 pub generics: Generics,
229
230 /// Is there is a `&self` argument? If not, it is a static function.
231 pub explicit_self: bool,
232
233 /// Arguments other than the self argument.
234 pub nonself_args: SmallVec<[(Box<ast::Ty>, Symbol); 1]>,
235
236 /// Whether this method has another arg of type `&self`.
237 pub has_other_selflike_arg: bool,
238
239 /// Returns type
240 pub ret_ty: Box<ast::Ty>,
241
242 pub attributes: ast::AttrVec,
243
244 pub fieldless_variants_strategy: FieldlessVariantsStrategy,
245
246 pub combine_substructure: CombineSubstructureFunc<'a>,
247}
248
249/// How to handle fieldless enum variants.
250#[derive(PartialEq)]
251pub(crate) enum FieldlessVariantsStrategy {
252 /// Combine fieldless variants into a single match arm.
253 /// This assumes that relevant information has been handled
254 /// by looking at the enum's discriminant.
255 Unify,
256 /// Don't do anything special about fieldless variants. They are
257 /// handled like any other variant.
258 Default,
259}
260
261/// Summary of the relevant parts of a struct/enum field.
262pub(crate) struct FieldInfo {
263 pub span: Span,
264 /// None for tuple structs/normal enum variants, Some for normal
265 /// structs/struct enum variants.
266 pub name: Option<Ident>,
267 /// The expression corresponding to this field of `self`
268 /// (specifically, a reference to it).
269 pub self_expr: Box<Expr>,
270 /// The expression corresponding to a reference to this field in
271 /// the other selflike argument.
272 pub other_selflike_expr: Option<Box<Expr>>,
273 pub maybe_scalar: bool,
274}
275
276/// A summary of the possible sets of fields.
277pub(crate) enum Substructure<'a> {
278 /// A non-static method where `Self` is a struct.
279 Struct(&'a ast::VariantData, Vec<FieldInfo>),
280
281 /// Matching variants of the enum: ast::Variant,
282 /// fields: the field name is only non-`None` in the case of a struct
283 /// variant.
284 EnumMatching(&'a ast::Variant, Vec<FieldInfo>),
285
286 /// The discriminant of an enum. The field is the expression to combine the
287 /// discriminant expression with; it will be `None` if no match is necessary.
288 EnumDiscr(Option<Box<Expr>>),
289
290 /// A static method where `Self` is a struct.
291 StaticStruct(&'a ast::VariantData),
292
293 /// A static method where `Self` is an enum.
294 StaticEnum(&'a ast::EnumDef),
295}
296
297/// Combine the values of all the fields together. The last argument is
298/// all the fields of all the structures.
299pub(crate) type CombineSubstructureFunc<'a> =
300 Box<dyn Fn(&ExtCtxt<'_>, Span, Substructure<'_>) -> BlockOrExpr + 'a>;
301
302pub(crate) fn combine_substructure<'a>(
303 f: impl Fn(&ExtCtxt<'_>, Span, Substructure<'_>) -> BlockOrExpr + 'a,
304) -> CombineSubstructureFunc<'a> {
305 Box::new(f)
306}
307
308struct TypeParameter {
309 bound_generic_params: ThinVec<ast::GenericParam>,
310 ty: Box<ast::Ty>,
311}
312
313/// The code snippets built up for derived code are sometimes used as blocks
314/// (e.g. in a function body) and sometimes used as expressions (e.g. in a match
315/// arm). This structure avoids committing to either form until necessary,
316/// avoiding the insertion of any unnecessary blocks.
317///
318/// The statements come before the expression.
319pub(crate) struct BlockOrExpr(ThinVec<ast::Stmt>, Option<Box<Expr>>);
320
321impl BlockOrExpr {
322 pub(crate) fn new_stmts(stmts: ThinVec<ast::Stmt>) -> BlockOrExpr {
323 BlockOrExpr(stmts, None)
324 }
325
326 pub(crate) fn new_expr(expr: Box<Expr>) -> BlockOrExpr {
327 BlockOrExpr(ThinVec::new(), Some(expr))
328 }
329
330 pub(crate) fn new_mixed(stmts: ThinVec<ast::Stmt>, expr: Option<Box<Expr>>) -> BlockOrExpr {
331 BlockOrExpr(stmts, expr)
332 }
333
334 // Converts it into a block.
335 fn into_block(mut self, cx: &ExtCtxt<'_>, span: Span) -> Box<ast::Block> {
336 if let Some(expr) = self.1 {
337 self.0.push(cx.stmt_expr(expr));
338 }
339 cx.block(span, self.0)
340 }
341
342 // Converts it into an expression.
343 fn into_expr(self, cx: &ExtCtxt<'_>, span: Span) -> Box<Expr> {
344 if self.0.is_empty() {
345 match self.1 {
346 None => cx.expr_block(cx.block(span, ThinVec::new())),
347 Some(expr) => expr,
348 }
349 } else if let [stmt] = self.0.as_slice()
350 && let ast::StmtKind::Expr(expr) = &stmt.kind
351 && self.1.is_none()
352 {
353 // There's only a single statement expression. Pull it out.
354 expr.clone()
355 } else {
356 // Multiple statements and/or expressions.
357 cx.expr_block(self.into_block(cx, span))
358 }
359 }
360}
361
362/// This method helps to extract all the type parameters referenced from a
363/// type. For a type parameter `<T>`, it looks for either a `TyPath` that
364/// is not global and starts with `T`, or a `TyQPath`.
365/// Also include bound generic params from the input type.
366fn find_type_parameters(
367 ty: &ast::Ty,
368 ty_param_names: &[Symbol],
369 cx: &ExtCtxt<'_>,
370) -> Vec<TypeParameter> {
371 use rustc_ast::visit;
372
373 struct Visitor<'a, 'b> {
374 cx: &'a ExtCtxt<'b>,
375 ty_param_names: &'a [Symbol],
376 bound_generic_params_stack: ThinVec<ast::GenericParam>,
377 type_params: Vec<TypeParameter>,
378 }
379
380 impl<'a, 'b> visit::Visitor<'a> for Visitor<'a, 'b> {
381 fn visit_ty(&mut self, ty: &'a ast::Ty) {
382 let stack_len = self.bound_generic_params_stack.len();
383 if let ast::TyKind::FnPtr(fn_ptr) = &ty.kind
384 && !fn_ptr.generic_params.is_empty()
385 {
386 // Given a field `x: for<'a> fn(T::SomeType<'a>)`, we wan't to account for `'a` so
387 // that we generate `where for<'a> T::SomeType<'a>: ::core::clone::Clone`. #122622
388 self.bound_generic_params_stack.extend(fn_ptr.generic_params.iter().cloned());
389 }
390
391 if let ast::TyKind::Path(_, path) = &ty.kind
392 && let Some(segment) = path.segments.first()
393 && self.ty_param_names.contains(&segment.ident.name)
394 {
395 self.type_params.push(TypeParameter {
396 bound_generic_params: self.bound_generic_params_stack.clone(),
397 ty: Box::new(ty.clone()),
398 });
399 }
400
401 visit::walk_ty(self, ty);
402 self.bound_generic_params_stack.truncate(stack_len);
403 }
404
405 // Place bound generic params on a stack, to extract them when a type is encountered.
406 fn visit_poly_trait_ref(&mut self, trait_ref: &'a ast::PolyTraitRef) {
407 let stack_len = self.bound_generic_params_stack.len();
408 self.bound_generic_params_stack.extend(trait_ref.bound_generic_params.iter().cloned());
409
410 visit::walk_poly_trait_ref(self, trait_ref);
411
412 self.bound_generic_params_stack.truncate(stack_len);
413 }
414
415 fn visit_mac_call(&mut self, mac: &ast::MacCall) {
416 self.cx.dcx().emit_err(diagnostics::DeriveMacroCall { span: mac.span() });
417 }
418 }
419
420 let mut visitor = Visitor {
421 cx,
422 ty_param_names,
423 bound_generic_params_stack: ThinVec::new(),
424 type_params: Vec::new(),
425 };
426 visit::Visitor::visit_ty(&mut visitor, ty);
427
428 visitor.type_params
429}
430
431impl<'a> TraitDef<'a> {
432 pub(crate) fn expand(
433 self,
434 cx: &ExtCtxt<'_>,
435 item: &'a ast::Item,
436 push: &mut dyn FnMut(Box<ast::Item>),
437 ) {
438 self.expand_ext(cx, item, push, false);
439 }
440
441 pub(crate) fn expand_ext(
442 self,
443 cx: &ExtCtxt<'_>,
444 item: &'a ast::Item,
445 push: &mut dyn FnMut(Box<ast::Item>),
446 from_scratch: bool,
447 ) {
448 let span = self.span;
449 let is_packed = matches!(
450 AttributeParser::parse_limited_sym(cx.sess, &item.attrs, &[sym::repr]),
451 Some(Attribute::Parsed(AttributeKind::Repr { reprs, .. })) if reprs.iter().any(|(x, _)| matches!(x, ReprPacked(..)))
452 );
453
454 let mut newitem = match &item.kind {
455 ast::ItemKind::Union(..) if !self.supports_unions => {
456 cx.dcx().emit_err(diagnostics::DeriveUnion { span });
457 return;
458 }
459 ast::ItemKind::Struct(ident, generics, struct_def)
460 | ast::ItemKind::Union(ident, generics, struct_def) => {
461 let fields = struct_def.fields().iter();
462 let methods = self.methods.iter().filter_map(|method_def| {
463 let body = if from_scratch || method_def.is_static() {
464 method_def.call_substructure_method(cx, span, StaticStruct(struct_def))
465 } else {
466 method_def.expand_struct_method_body(cx, span, struct_def, is_packed)
467 };
468
469 method_def.create_method(cx, span, body)
470 });
471 self.create_derived_impl(cx, *ident, generics, fields, methods, is_packed)
472 }
473 ast::ItemKind::Enum(ident, generics, enum_def) => {
474 // We can skip generating the impl here, because `repr(packed)`
475 // enums cause an error later on and to prevent ICEs like #133025.
476 // This can only cause further compilation errors
477 // downstream in blatantly illegal code, so it is fine.
478 if is_packed {
479 return;
480 }
481 let fields = enum_def.variants.iter().flat_map(|variant| variant.data.fields());
482 let methods = self.methods.iter().filter_map(|method_def| {
483 let body = if from_scratch || method_def.is_static() {
484 method_def.call_substructure_method(cx, span, StaticEnum(enum_def))
485 } else {
486 method_def.expand_enum_method_body(cx, span, enum_def)
487 };
488
489 method_def.create_method(cx, span, body)
490 });
491 self.create_derived_impl(cx, *ident, generics, fields, methods, is_packed)
492 }
493 _ => unreachable!(),
494 };
495 // Keep the lint attributes of the previous item to control how the
496 // generated implementations are linted
497 newitem.attrs.extend(
498 item.attrs
499 .iter()
500 .filter(|a| {
501 a.has_any_name(&[
502 sym::allow,
503 sym::warn,
504 sym::deny,
505 sym::forbid,
506 sym::stable,
507 sym::unstable,
508 ])
509 })
510 .cloned(),
511 );
512 push(newitem);
513 }
514
515 /// Given that we are deriving a trait `DerivedTrait` for a type like:
516 ///
517 /// ```ignore (only-for-syntax-highlight)
518 /// struct Struct<'a, ..., 'z, A, B: DeclaredTrait, C, ..., Z>
519 /// where
520 /// C: WhereTrait,
521 /// {
522 /// a: A,
523 /// b: B::Item,
524 /// b1: <B as DeclaredTrait>::Item,
525 /// c1: <C as WhereTrait>::Item,
526 /// c2: Option<<C as WhereTrait>::Item>,
527 /// ...
528 /// }
529 /// ```
530 ///
531 /// create an impl like:
532 ///
533 /// ```ignore (only-for-syntax-highlight)
534 /// impl<'a, ..., 'z, A, B: DeclaredTrait, C, ..., Z>
535 /// where
536 /// C: WhereTrait,
537 /// A: DerivedTrait + B1 + ... + BN,
538 /// B: DerivedTrait + B1 + ... + BN,
539 /// C: DerivedTrait + B1 + ... + BN,
540 /// B::Item: DerivedTrait + B1 + ... + BN,
541 /// <C as WhereTrait>::Item: DerivedTrait + B1 + ... + BN,
542 /// ...
543 /// {
544 /// ...
545 /// }
546 /// ```
547 ///
548 /// where B1, ..., BN are the bounds given by `bounds_paths`.'. Z is a phantom type, and
549 /// therefore does not get bound by the derived trait.
550 fn create_derived_impl(
551 &self,
552 cx: &ExtCtxt<'_>,
553 type_ident: Ident,
554 generics: &Generics,
555 fields: impl Iterator<Item = &'a ast::FieldDef>,
556 methods: impl Iterator<Item = Box<ast::AssocItem>>,
557 is_packed: bool,
558 ) -> Box<ast::Item> {
559 let mut where_clause = ast::WhereClause::default();
560 where_clause.span = generics.where_clause.span;
561 let ctxt = self.span.ctxt();
562
563 // Create the generic parameters
564 let params: ThinVec<_> = generics
565 .params
566 .iter()
567 .map(|param| match ¶m.kind {
568 GenericParamKind::Lifetime => param.clone(),
569 GenericParamKind::Type { .. } => {
570 // Extra restrictions on the generics parameters to the
571 // type being derived upon.
572 let span = param.ident.span.with_ctxt(ctxt);
573 let bounds: ThinVec<_> = self
574 .additional_bounds
575 .iter()
576 .map(|p| cx.trait_bound(ast::Path { span, ..p.clone() }, self.is_const))
577 .chain(
578 // Add a bound for the current trait.
579 self.skip_path_as_bound.not().then(|| {
580 let mut trait_path = self.path.clone();
581 trait_path.span = span;
582 cx.trait_bound(trait_path, self.is_const)
583 }),
584 )
585 .chain({
586 // Add a `Copy` bound if required.
587 if is_packed && self.needs_copy_as_bound_if_packed {
588 let p = deriving::path_std!(cx, span, marker::Copy);
589 Some(cx.trait_bound(p, self.is_const))
590 } else {
591 None
592 }
593 })
594 .chain(
595 // Also add in any bounds from the declaration.
596 param.bounds.iter().cloned(),
597 )
598 .collect();
599
600 cx.typaram(param.ident, bounds, None)
601 }
602 GenericParamKind::Const { ty, span, .. } => {
603 let const_nodefault_kind = GenericParamKind::Const {
604 ty: ty.clone(),
605 span: span.with_ctxt(ctxt),
606
607 // We can't have default values inside impl block
608 default: None,
609 };
610 let mut param_clone = param.clone();
611 param_clone.kind = const_nodefault_kind;
612 param_clone
613 }
614 })
615 .map(|mut param| {
616 // Remove all attributes, because there might be helper attributes
617 // from other macros that will not be valid in the expanded implementation.
618 param.attrs.clear();
619 param
620 })
621 .collect();
622
623 // and similarly for where clauses
624 where_clause.predicates.extend(generics.where_clause.predicates.iter().map(|clause| {
625 ast::WherePredicate {
626 attrs: clause.attrs.clone(),
627 kind: clause.kind.clone(),
628 id: ast::DUMMY_NODE_ID,
629 span: clause.span.with_ctxt(ctxt),
630 is_placeholder: false,
631 }
632 }));
633
634 let ty_param_names: Vec<Symbol> = params
635 .iter()
636 .filter(|param| matches!(param.kind, ast::GenericParamKind::Type { .. }))
637 .map(|ty_param| ty_param.ident.name)
638 .collect();
639
640 if !ty_param_names.is_empty() {
641 for field in fields {
642 let field_ty_params = find_type_parameters(&field.ty, &ty_param_names, cx);
643
644 for field_ty_param in field_ty_params {
645 // if we have already handled this type, skip it
646 if let ast::TyKind::Path(_, p) = &field_ty_param.ty.kind
647 && let [sole_segment] = &*p.segments
648 && ty_param_names.contains(&sole_segment.ident.name)
649 {
650 continue;
651 }
652 let mut bounds: ThinVec<_> = self
653 .additional_bounds
654 .iter()
655 .map(|p| cx.trait_bound(p.clone(), self.is_const))
656 .collect();
657
658 // Require the current trait.
659 if !self.skip_path_as_bound {
660 bounds.push(cx.trait_bound(self.path.clone(), self.is_const));
661 }
662
663 // Add a `Copy` bound if required.
664 if is_packed && self.needs_copy_as_bound_if_packed {
665 let p = deriving::path_std!(cx, self.span, marker::Copy);
666 bounds.push(cx.trait_bound(p, self.is_const));
667 }
668
669 if !bounds.is_empty() {
670 let predicate = ast::WhereBoundPredicate {
671 bound_generic_params: field_ty_param.bound_generic_params,
672 bounded_ty: field_ty_param.ty,
673 bounds,
674 };
675
676 let kind = ast::WherePredicateKind::BoundPredicate(predicate);
677 let predicate = ast::WherePredicate {
678 attrs: ThinVec::new(),
679 kind,
680 id: ast::DUMMY_NODE_ID,
681 span: self.span,
682 is_placeholder: false,
683 };
684 where_clause.predicates.push(predicate);
685 }
686 }
687 }
688 }
689
690 let trait_generics = Generics { params, where_clause, span: generics.span.with_ctxt(ctxt) };
691
692 // Create the reference to the trait.
693 let trait_ref = cx.trait_ref(self.path.clone());
694
695 let self_params: Vec<_> = generics
696 .params
697 .iter()
698 .map(|param| generic_param_to_arg(cx, param, param.ident.span.with_ctxt(ctxt)))
699 .collect();
700
701 // Create the type of `self`.
702 let path = cx.path_all(type_ident.span.with_ctxt(ctxt), &[type_ident], self_params);
703 let self_type = cx.ty_path(path);
704
705 let mut attrs =
706 thin_vec![cx.generated_attr(self.span, ast::GeneratedAttr::AutomaticallyDerived)];
707
708 // Only add `rustc_const_unstable` attributes if `derive_const` is used within libcore/libstd,
709 // Other crates don't need stability attributes, so adding them is not useful, but libcore needs them
710 // on all const trait impls.
711 if self.is_const && cx.ecfg.features.staged_api() {
712 attrs.push(cx.generated_attr(self.span, ast::GeneratedAttr::RustcConstUnstableDerived));
713 }
714
715 if !self.document {
716 attrs.push(cx.generated_attr(self.span, ast::GeneratedAttr::DocHidden));
717 }
718
719 cx.item_trait_impl(
720 self.span,
721 attrs,
722 trait_generics,
723 self.safety,
724 self.is_const,
725 trait_ref,
726 self_type,
727 methods.collect(),
728 )
729 }
730}
731
732impl<'a> MethodDef<'a> {
733 fn call_substructure_method(
734 &self,
735 cx: &ExtCtxt<'_>,
736 span: Span,
737 fields: Substructure<'_>,
738 ) -> BlockOrExpr {
739 (self.combine_substructure)(cx, span, fields)
740 }
741
742 fn is_static(&self) -> bool {
743 !self.explicit_self
744 }
745
746 fn create_method(
747 &self,
748 cx: &ExtCtxt<'_>,
749 span: Span,
750 body: BlockOrExpr,
751 ) -> Option<Box<ast::AssocItem>> {
752 // `assert_fields_are_eq` has an empty default implementation
753 if body.0.is_empty() && body.1.is_none() && self.name == sym::assert_fields_are_eq {
754 return None;
755 }
756
757 let self_arg = self.explicit_self.then(|| {
758 let infer_ty = cx.ty(span, ast::TyKind::ImplicitSelf);
759 let ty = cx.ty_ref(span, infer_ty, None, ast::Mutability::Not);
760 (ty, kw::SelfLower)
761 });
762 let args = self_arg
763 .into_iter()
764 .chain(self.nonself_args.iter().cloned())
765 .map(|(ty, name)| cx.param(span, name, ty))
766 .collect();
767
768 let ret_type = if self.ret_ty.kind.is_unit() {
769 ast::FnRetTy::Default(span)
770 } else {
771 ast::FnRetTy::Ty(self.ret_ty.clone())
772 };
773
774 let method_ident = Ident::new(self.name, span);
775 let fn_decl = cx.fn_decl(args, ret_type);
776 let body_block = body.into_block(cx, span);
777
778 let trait_lo_sp = span.shrink_to_lo();
779
780 let sig = ast::FnSig { header: ast::FnHeader::default(), decl: fn_decl, span };
781
782 // Create the method.
783 Some(Box::new(ast::AssocItem {
784 id: ast::DUMMY_NODE_ID,
785 attrs: self.attributes.clone(),
786 span,
787 vis: ast::Visibility { span: trait_lo_sp, kind: ast::VisibilityKind::Inherited },
788 kind: ast::AssocItemKind::Fn(cx.item_fn(
789 sig,
790 method_ident,
791 self.generics.clone(),
792 Some(body_block),
793 )),
794 tokens: None,
795 }))
796 }
797
798 /// The normal case uses field access.
799 ///
800 /// ```
801 /// #[derive(PartialEq)]
802 /// # struct Dummy;
803 /// struct A { x: u8, y: u8 }
804 ///
805 /// // equivalent to:
806 /// impl PartialEq for A {
807 /// fn eq(&self, other: &A) -> bool {
808 /// self.x == other.x && self.y == other.y
809 /// }
810 /// }
811 /// ```
812 ///
813 /// But if the struct is `repr(packed)`, we can't use something like
814 /// `&self.x` because that might cause an unaligned ref. So for any trait
815 /// method that takes a reference, we use a local block to force a copy.
816 /// This requires that the field impl `Copy`.
817 ///
818 /// ```rust,ignore (example)
819 /// # struct A { x: u8, y: u8 }
820 /// impl PartialEq for A {
821 /// fn eq(&self, other: &A) -> bool {
822 /// // Desugars to `{ self.x }.eq(&{ other.y }) && ...`
823 /// { self.x } == { other.y } && { self.y } == { other.y }
824 /// }
825 /// }
826 /// impl Hash for A {
827 /// fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
828 /// ::core::hash::Hash::hash(&{ self.x }, state);
829 /// ::core::hash::Hash::hash(&{ self.y }, state);
830 /// }
831 /// }
832 /// ```
833 fn expand_struct_method_body<'b>(
834 &self,
835 cx: &ExtCtxt<'_>,
836 span: Span,
837 struct_def: &'b VariantData,
838 is_packed: bool,
839 ) -> BlockOrExpr {
840 let self_expr = cx.expr_self(span);
841 let selflike_args = if self.has_other_selflike_arg {
842 &[self_expr, cx.expr_name(span, self.nonself_args[0].1)][..]
843 } else {
844 &[self_expr]
845 };
846
847 let selflike_fields =
848 create_struct_field_access_fields(span, cx, selflike_args, struct_def, is_packed);
849 self.call_substructure_method(cx, span, Struct(struct_def, selflike_fields))
850 }
851
852 /// ```
853 /// #[derive(PartialEq)]
854 /// # struct Dummy;
855 /// enum A {
856 /// A1,
857 /// A2(i32)
858 /// }
859 /// ```
860 ///
861 /// is equivalent to:
862 ///
863 /// ```
864 /// #![feature(core_intrinsics)]
865 /// enum A {
866 /// A1,
867 /// A2(i32)
868 /// }
869 /// impl ::core::cmp::PartialEq for A {
870 /// #[inline]
871 /// fn eq(&self, other: &A) -> bool {
872 /// let __self_discr = ::core::intrinsics::discriminant_value(self);
873 /// let __arg1_discr = ::core::intrinsics::discriminant_value(other);
874 /// __self_discr == __arg1_discr
875 /// && match (self, other) {
876 /// (A::A2(__self_0), A::A2(__arg1_0)) => *__self_0 == *__arg1_0,
877 /// _ => true,
878 /// }
879 /// }
880 /// }
881 /// ```
882 ///
883 /// Creates a discriminant check combined with a match for a tuple of all
884 /// `selflike_args`, with an arm for each variant with fields, possibly an
885 /// arm for each fieldless variant (if `unify_fieldless_variants` is not
886 /// `Unify`), and possibly a default arm.
887 fn expand_enum_method_body<'b>(
888 &self,
889 cx: &ExtCtxt<'_>,
890 span: Span,
891 enum_def: &'b EnumDef,
892 ) -> BlockOrExpr {
893 let variants = &enum_def.variants;
894
895 // For zero-variant enum, this function body is unreachable. Generate
896 // `match *self {}`. This produces machine code identical to `unsafe {
897 // core::intrinsics::unreachable() }` while being safe and stable.
898 if variants.is_empty() {
899 let match_arg = cx.expr_deref(span, cx.expr_self(span));
900 let match_arms = ThinVec::new();
901 let expr = cx.expr_match(span, match_arg, match_arms);
902 return BlockOrExpr(ThinVec::new(), Some(expr));
903 }
904
905 // There are some special cases involving fieldless enums where no
906 // match is necessary.
907 let all_fieldless = variants.iter().all(|v| v.data.fields().is_empty());
908 if all_fieldless {
909 if variants.len() > 1 {
910 match self.fieldless_variants_strategy {
911 FieldlessVariantsStrategy::Unify => {
912 // If the type is fieldless and the trait uses the discriminant and
913 // there are multiple variants, we need just an operation on
914 // the discriminant(s).
915 return self.call_substructure_method(cx, span, EnumDiscr(None));
916 }
917 FieldlessVariantsStrategy::Default => (),
918 }
919 } else if let [variant] = variants.as_slice() {
920 // If there is a single variant, we don't need an operation on
921 // the discriminant(s). Just use the most degenerate result.
922 return self.call_substructure_method(cx, span, EnumMatching(variant, Vec::new()));
923 }
924 }
925
926 // Traits that unify fieldless variants always use the discriminant(s).
927 let unify_fieldless_variants =
928 self.fieldless_variants_strategy == FieldlessVariantsStrategy::Unify;
929
930 let prefixes: &[&str] =
931 if self.has_other_selflike_arg { &["__self", "__arg1"] } else { &["__self"] };
932
933 // These arms are of the form:
934 // (Variant1, Variant1, ...) => Body1
935 // (Variant2, Variant2, ...) => Body2
936 // ...
937 // where each tuple has length = selflike_args.len()
938 let mut match_arms: ThinVec<ast::Arm> = variants
939 .iter()
940 .filter(|&v| !(unify_fieldless_variants && v.data.fields().is_empty()))
941 .map(|variant| {
942 // A single arm has form (&VariantK, &VariantK, ...) => BodyK
943 // (see "Final wrinkle" note below for why.)
944
945 let fields = create_struct_pattern_fields(span, cx, &variant.data, &prefixes);
946
947 let sp = variant.span.with_ctxt(span.ctxt());
948 let variant_path = cx.path(sp, &[Ident::new(kw::SelfUpper, span), variant.ident]);
949 let mut subpats =
950 create_struct_patterns(span, cx, variant_path, &variant.data, &prefixes);
951
952 // `(VariantK, VariantK, ...)` or just `VariantK`.
953 let single_pat = if subpats.len() == 1 {
954 subpats.pop().unwrap()
955 } else {
956 cx.pat_tuple(span, subpats)
957 };
958
959 // For the BodyK, we need to delegate to our caller,
960 // passing it an EnumMatching to indicate which case
961 // we are in.
962 //
963 // Now, for some given VariantK, we have built up
964 // expressions for referencing every field of every
965 // Self arg, assuming all are instances of VariantK.
966 // Build up code associated with such a case.
967 let arm_expr = self
968 .call_substructure_method(cx, span, EnumMatching(variant, fields))
969 .into_expr(cx, span);
970
971 cx.arm(span, single_pat, arm_expr)
972 })
973 .collect();
974
975 // Add a default arm to the match, if necessary.
976 let first_fieldless = variants.iter().find(|v| v.data.fields().is_empty());
977 let default = match first_fieldless {
978 Some(v) if unify_fieldless_variants => {
979 // We need a default case that handles all the fieldless variants.
980 Some(
981 self.call_substructure_method(cx, span, EnumMatching(v, Vec::new()))
982 .into_expr(cx, span),
983 )
984 }
985 _ if variants.len() > 1 && self.has_other_selflike_arg => {
986 // Because we know that all the arguments will match if we reach
987 // the match expression we add the unreachable intrinsic as the
988 // result of the default which should help llvm in optimizing it.
989 Some(deriving::call_unreachable(cx, span))
990 }
991 _ => None,
992 };
993 if let Some(arm) = default {
994 match_arms.push(cx.arm(span, cx.pat_wild(span), arm));
995 }
996
997 // Create a match expression with one arm per discriminant plus
998 // possibly a default arm, e.g.:
999 // match (self, other) {
1000 // (Variant1, Variant1) => Body1
1001 // (Variant2, Variant2) => Body2,
1002 // ...
1003 // _ => ::core::intrinsics::unreachable(),
1004 // }
1005
1006 let self_expr = cx.expr_self(span);
1007 let match_arg = if self.has_other_selflike_arg {
1008 cx.expr_tuple(span, thin_vec![self_expr, cx.expr_name(span, self.nonself_args[0].1)])
1009 } else {
1010 self_expr
1011 };
1012 let match_expr = cx.expr_match(span, match_arg, match_arms);
1013
1014 // If the trait uses the discriminant and there are multiple variants, we need
1015 // to add a discriminant check operation before the match. Otherwise, the match
1016 // is enough.
1017 if unify_fieldless_variants && variants.len() > 1 {
1018 // Combine a discriminant check with the match.
1019 self.call_substructure_method(cx, span, EnumDiscr(Some(match_expr)))
1020 } else {
1021 BlockOrExpr(ThinVec::new(), Some(match_expr))
1022 }
1023 }
1024}
1025
1026// general helper methods.
1027fn create_struct_patterns(
1028 span: Span,
1029 cx: &ExtCtxt<'_>,
1030 struct_path: ast::Path,
1031 struct_def: &VariantData,
1032 prefixes: &[&str],
1033) -> ThinVec<ast::Pat> {
1034 prefixes
1035 .iter()
1036 .map(|prefix| {
1037 let pieces_iter = struct_def.fields().iter().enumerate().map(|(i, struct_field)| {
1038 let ident = Symbol::intern(&format!("{prefix}_{i}"));
1039 (struct_field.ident, cx.pat_name(struct_field.span.with_ctxt(span.ctxt()), ident))
1040 });
1041
1042 let struct_path = struct_path.clone();
1043 match *struct_def {
1044 VariantData::Struct { .. } => {
1045 let field_pats = pieces_iter
1046 .map(|(ident, pat)| ast::PatField {
1047 ident: ident.expect("a braced struct with unnamed fields in `derive`"),
1048 is_shorthand: false,
1049 attrs: ast::AttrVec::new(),
1050 id: ast::DUMMY_NODE_ID,
1051 span: pat.span.with_ctxt(span.ctxt()),
1052 pat: Box::new(pat),
1053 is_placeholder: false,
1054 })
1055 .collect();
1056 cx.pat_struct(span, struct_path, field_pats)
1057 }
1058 VariantData::Tuple(..) => {
1059 let subpats = pieces_iter.map(|(_, subpat)| subpat).collect();
1060 cx.pat_tuple_struct(span, struct_path, subpats)
1061 }
1062 VariantData::Unit(..) => cx.pat_path(span, struct_path),
1063 }
1064 })
1065 .collect()
1066}
1067
1068fn create_fields<F>(span: Span, struct_def: &VariantData, mk_exprs: F) -> Vec<FieldInfo>
1069where
1070 F: Fn(usize, &ast::FieldDef, Span) -> Vec<Box<Expr>>,
1071{
1072 struct_def
1073 .fields()
1074 .iter()
1075 .enumerate()
1076 .map(|(i, struct_field)| {
1077 // For this field, get an expr for each selflike_arg. E.g. for
1078 // `PartialEq::eq`, one for each of `&self` and `other`.
1079 let span = struct_field.span.with_ctxt(span.ctxt());
1080 let mut exprs: Vec<_> = mk_exprs(i, struct_field, span);
1081 let self_expr = exprs.remove(0);
1082 debug_assert!(exprs.len() <= 1);
1083 FieldInfo {
1084 span,
1085 name: struct_field.ident,
1086 self_expr,
1087 other_selflike_expr: exprs.pop(),
1088 maybe_scalar: struct_field.ty.peel_refs().kind.maybe_scalar(),
1089 }
1090 })
1091 .collect()
1092}
1093
1094fn create_struct_pattern_fields(
1095 span: Span,
1096 cx: &ExtCtxt<'_>,
1097 struct_def: &VariantData,
1098 prefixes: &[&str],
1099) -> Vec<FieldInfo> {
1100 create_fields(span, struct_def, |i, _struct_field, sp| {
1101 prefixes
1102 .iter()
1103 .map(|prefix| cx.expr_name(sp, Symbol::intern(&format!("{prefix}_{i}"))))
1104 .collect()
1105 })
1106}
1107
1108fn create_struct_field_access_fields(
1109 span: Span,
1110 cx: &ExtCtxt<'_>,
1111 selflike_args: &[Box<Expr>],
1112 struct_def: &VariantData,
1113 is_packed: bool,
1114) -> Vec<FieldInfo> {
1115 create_fields(span, struct_def, |i, struct_field, sp| {
1116 selflike_args
1117 .iter()
1118 .map(|selflike_arg| {
1119 // Note: we must use `struct_field.span` rather than `sp` in the
1120 // `unwrap_or_else` case otherwise the hygiene is wrong and we get
1121 // "field `0` of struct `Point` is private" errors on tuple
1122 // structs.
1123 let mut field_expr = cx.expr(
1124 sp,
1125 ast::ExprKind::Field(
1126 selflike_arg.clone(),
1127 struct_field
1128 .ident
1129 .unwrap_or_else(|| Ident::new(sym::integer(i), struct_field.span)),
1130 ),
1131 );
1132 if is_packed {
1133 // Fields in packed structs are wrapped in a block, e.g. `&{self.0}`,
1134 // causing a copy instead of a (potentially misaligned) reference.
1135 field_expr = cx.expr_block(
1136 cx.block(struct_field.span, thin_vec![cx.stmt_expr(field_expr)]),
1137 );
1138 }
1139 cx.expr_addr_of(sp, field_expr)
1140 })
1141 .collect()
1142 })
1143}
1144
1145pub(crate) fn generic_param_to_arg(cx: &ExtCtxt<'_>, p: &GenericParam, span: Span) -> GenericArg {
1146 match p.kind {
1147 GenericParamKind::Lifetime => GenericArg::Lifetime(cx.lifetime(span, p.ident)),
1148 GenericParamKind::Type { .. } => GenericArg::Type(cx.ty_ident(span, p.ident)),
1149 GenericParamKind::Const { .. } => GenericArg::Const(cx.const_ident(span, p.ident)),
1150 }
1151}
1152
1153pub(crate) fn generics_without_defaults(g: &Generics) -> Generics {
1154 Generics {
1155 params: g
1156 .params
1157 .iter()
1158 .map(|p| {
1159 let mut p = p.clone();
1160 match &mut p.kind {
1161 ast::GenericParamKind::Const { default, .. } => *default = None,
1162 ast::GenericParamKind::Type { default } => *default = None,
1163 ast::GenericParamKind::Lifetime => {}
1164 };
1165 p.attrs.clear();
1166 p
1167 })
1168 .collect(),
1169 where_clause: g.where_clause.clone(),
1170 span: g.span,
1171 }
1172}