1use rustc_ast::{BinOpKind, BorrowKind, Expr, ExprKind, Mutability};
2use rustc_expand::base::ExtCtxt;
3use rustc_span::{Span, kw, sym};
4use thin_vec::thin_vec;
56use crate::deriving::generic::*;
7use crate::deriving::{call_discriminant_value, path_std};
89/// Expands a `#[derive(PartialEq)]` attribute into an implementation for the
10/// target item.
11pub(crate) fn expand_derive_partial_eq(
12 cx: &ExtCtxt<'_>,
13 span: Span,
14 item: &ast::Item,
15 push: &mut dyn FnMut(Box<ast::Item>),
16 is_const: bool,
17) {
18let structural_trait_def = TraitDef {
19span,
20 path: cx.std_path(span, { &[sym::marker, sym::StructuralPartialEq] })path_std!(cx, span, marker::StructuralPartialEq),
21 skip_path_as_bound: true, // crucial!
22needs_copy_as_bound_if_packed: false,
23// The `StructuralPartialEq` impl must have the *same* bounds as the `PartialEq` impl,
24 // or it will apply in situations where it should not, such as in the bug
25 // <https://github.com/rust-lang/rust/issues/147714>.
26 additional_bounds: {
let count = 0usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push(cx.std_path(span, { &[sym::cmp, sym::PartialEq] }));
vec
} else {
::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[cx.std_path(span, { &[sym::cmp, sym::PartialEq] })])))
}
}smallvec![path_std!(cx, span, cmp::PartialEq)],
27// We really don't support unions, but that's already checked by the impl generated below;
28 // a second check here would lead to redundant error messages.
29supports_unions: true,
30 methods: SmallVec::new(),
31 is_const: false,
32 ..
33 };
34structural_trait_def.expand(cx, item, push);
3536// No need to generate `ne`, the default suffices, and not generating it is
37 // faster.
38let methods = {
let count = 0usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push(MethodDef {
name: sym::eq,
generics: cx.empty_generics(span),
args: {
let len = [(), ()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(cx.param_self_ref(span));
vec.push(cx.param(span, sym::other, cx.ty_self_ref(span)));
vec
},
ret_ty: cx.ty_name(span, sym::bool),
attributes: {
let len = [()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(cx.generated_attr(span,
ast::GeneratedAttr::Inline));
vec
},
body: MethodBody::SubstructureFunc {
body_func: Box::new(partial_eq_body),
strategy: FieldlessVariantsStrategy::Unify,
has_other_selflike_arg: true,
},
});
vec
} else {
::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[MethodDef {
name: sym::eq,
generics: cx.empty_generics(span),
args: {
let len = [(), ()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(cx.param_self_ref(span));
vec.push(cx.param(span, sym::other, cx.ty_self_ref(span)));
vec
},
ret_ty: cx.ty_name(span, sym::bool),
attributes: {
let len = [()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(cx.generated_attr(span,
ast::GeneratedAttr::Inline));
vec
},
body: MethodBody::SubstructureFunc {
body_func: Box::new(partial_eq_body),
strategy: FieldlessVariantsStrategy::Unify,
has_other_selflike_arg: true,
},
}])))
}
}smallvec![MethodDef {
39 name: sym::eq,
40 generics: cx.empty_generics(span),
41 args: thin_vec![cx.param_self_ref(span), cx.param(span, sym::other, cx.ty_self_ref(span))],
42 ret_ty: cx.ty_name(span, sym::bool),
43 attributes: thin_vec![cx.generated_attr(span, ast::GeneratedAttr::Inline)],
44 body: MethodBody::SubstructureFunc {
45 body_func: Box::new(partial_eq_body),
46 strategy: FieldlessVariantsStrategy::Unify,
47 has_other_selflike_arg: true,
48 },
49 }];
5051let trait_def = TraitDef {
52span,
53 path: cx.std_path(span, { &[sym::cmp, sym::PartialEq] })path_std!(cx, span, cmp::PartialEq),
54 needs_copy_as_bound_if_packed: true,
55 additional_bounds: SmallVec::new(),
56 supports_unions: false,
57methods,
58is_const,
59 ..
60 };
61trait_def.expand(cx, item, push)
62}
6364/// Generates the equality expression for a struct or enum variant when deriving
65/// `PartialEq`.
66///
67/// This function generates an expression that checks if all fields of a struct
68/// or enum variant are equal.
69/// - Scalar fields are compared first for efficiency, followed by compound
70/// fields.
71/// - If there are no fields, returns `true` (fieldless types are always equal).
72///
73/// Whether a field is considered "scalar" is determined by comparing the symbol
74/// of its type to a set of known scalar type symbols (e.g., `i32`, `u8`, etc).
75/// This check is based on the type's symbol.
76///
77/// ### Example 1
78/// ```
79/// #[derive(PartialEq)]
80/// struct i32;
81///
82/// // Here, `field_2` is of type `i32`, but since it's a user-defined type (not
83/// // the primitive), it will not be treated as scalar. The function will still
84/// // check equality of `field_2` first because the symbol matches `i32`.
85/// #[derive(PartialEq)]
86/// struct Struct {
87/// field_1: &'static str,
88/// field_2: i32,
89/// }
90/// ```
91///
92/// ### Example 2
93/// ```
94/// mod ty {
95/// pub type i32 = i32;
96/// }
97///
98/// // Here, `field_2` is of type `ty::i32`, which is a type alias for `i32`.
99/// // However, the function will not reorder the fields because the symbol for
100/// // `ty::i32` does not match the symbol for the primitive `i32`
101/// // ("ty::i32" != "i32").
102/// #[derive(PartialEq)]
103/// struct Struct {
104/// field_1: &'static str,
105/// field_2: ty::i32,
106/// }
107/// ```
108///
109/// For enums, the discriminant is compared first, then the rest of the fields.
110fn partial_eq_body(cx: &ExtCtxt<'_>, span: Span, substructure: Substructure<'_>) -> BlockOrExpr {
111BlockOrExpr::new_expr(match substructure {
112EnumMatching(.., fields) | Struct(.., fields) => {
113let combine = move |acc, field: &FieldInfo<'_>| {
114let rhs = field115 .other_selflike_expr
116 .as_ref()
117 .expect("not exactly 2 arguments in `derive(PartialEq)`");
118119let rhs = cx.expr_binary(
120field.span,
121 BinOpKind::Eq,
122wrap_block_expr(cx, peel_refs(&field.self_expr)),
123wrap_block_expr(cx, peel_refs(rhs)),
124 );
125match acc {
126// Combine the previous comparison with the current field
127 // using logical AND.
128Some(lhs) => Some(cx.expr_binary(field.span, BinOpKind::And, lhs, rhs)),
129// Start the chain with the first field's comparison.
130None => Some(rhs),
131 }
132 };
133134let maybe_scalar = |field: &FieldInfo<'_>| field.def.ty.peel_refs().kind.maybe_scalar();
135// First compare scalar fields, then compound fields, combining all
136 // with logical AND.
137fields138 .iter()
139 .filter(|field| maybe_scalar(field))
140 .chain(fields.iter().filter(|field| !maybe_scalar(field)))
141 .fold(None, combine)
142// If there are no fields, treat as always equal.
143.unwrap_or_else(|| cx.expr_bool(span, true))
144 }
145EnumDiscr(match_expr) => {
146let self_expr = call_discriminant_value(cx, span, kw::SelfLower);
147let other_selflike_expr = call_discriminant_value(cx, span, sym::other);
148let lhs = cx.expr_binary(span, BinOpKind::Eq, self_expr, other_selflike_expr);
149let Some(match_expr) = match_exprelse {
150return BlockOrExpr::new_expr(lhs);
151 };
152// Compare the discriminant first (cheaper), then the rest of the
153 // fields.
154cx.expr_binary(span, BinOpKind::And, lhs, match_expr)
155 }
156 })
157}
158159/// Removes all leading immutable references from an expression.
160///
161/// This is used to strip away any number of leading `&` from an expression
162/// (e.g., `&&&T` becomes `T`). Only removes immutable references; mutable
163/// references are preserved.
164fn peel_refs(mut expr: &Box<Expr>) -> Box<Expr> {
165while let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, inner) = &expr.kind {
166 expr = inner;
167 }
168expr.clone()
169}
170171/// Wraps a block expression in parentheses to ensure valid AST in macro
172/// expansion output.
173///
174/// If the given expression is a block, it is wrapped in parentheses; otherwise,
175/// it is returned unchanged.
176fn wrap_block_expr(cx: &ExtCtxt<'_>, expr: Box<Expr>) -> Box<Expr> {
177if #[allow(non_exhaustive_omitted_patterns)] match &expr.kind {
ExprKind::Block(..) => true,
_ => false,
}matches!(&expr.kind, ExprKind::Block(..)) {
178return cx.expr_paren(expr.span, expr);
179 }
180expr181}