Skip to main content

rustc_builtin_macros/deriving/
partial_eq.rs

1use rustc_ast::{BinOpKind, BorrowKind, Expr, ExprKind, Mutability};
2use rustc_expand::base::ExtCtxt;
3use rustc_span::{Span, kw, sym};
4use thin_vec::thin_vec;
5
6use crate::deriving::generic::*;
7use crate::deriving::{call_discriminant_value, path_std};
8
9/// 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) {
18    let structural_trait_def = TraitDef {
19        span,
20        path: cx.std_path(span, { &[sym::marker, sym::StructuralPartialEq] })path_std!(cx, span, marker::StructuralPartialEq),
21        skip_path_as_bound: true, // crucial!
22        needs_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.
29        supports_unions: true,
30        methods: SmallVec::new(),
31        is_const: false,
32        ..
33    };
34    structural_trait_def.expand(cx, item, push);
35
36    // No need to generate `ne`, the default suffices, and not generating it is
37    // faster.
38    let 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    }];
50
51    let trait_def = TraitDef {
52        span,
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,
57        methods,
58        is_const,
59        ..
60    };
61    trait_def.expand(cx, item, push)
62}
63
64/// 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 {
111    BlockOrExpr::new_expr(match substructure {
112        EnumMatching(.., fields) | Struct(.., fields) => {
113            let combine = move |acc, field: &FieldInfo<'_>| {
114                let rhs = field
115                    .other_selflike_expr
116                    .as_ref()
117                    .expect("not exactly 2 arguments in `derive(PartialEq)`");
118
119                let rhs = cx.expr_binary(
120                    field.span,
121                    BinOpKind::Eq,
122                    wrap_block_expr(cx, peel_refs(&field.self_expr)),
123                    wrap_block_expr(cx, peel_refs(rhs)),
124                );
125                match acc {
126                    // Combine the previous comparison with the current field
127                    // using logical AND.
128                    Some(lhs) => Some(cx.expr_binary(field.span, BinOpKind::And, lhs, rhs)),
129                    // Start the chain with the first field's comparison.
130                    None => Some(rhs),
131                }
132            };
133
134            let 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.
137            fields
138                .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        }
145        EnumDiscr(match_expr) => {
146            let self_expr = call_discriminant_value(cx, span, kw::SelfLower);
147            let other_selflike_expr = call_discriminant_value(cx, span, sym::other);
148            let lhs = cx.expr_binary(span, BinOpKind::Eq, self_expr, other_selflike_expr);
149            let Some(match_expr) = match_expr else {
150                return BlockOrExpr::new_expr(lhs);
151            };
152            // Compare the discriminant first (cheaper), then the rest of the
153            // fields.
154            cx.expr_binary(span, BinOpKind::And, lhs, match_expr)
155        }
156    })
157}
158
159/// 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> {
165    while let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, inner) = &expr.kind {
166        expr = inner;
167    }
168    expr.clone()
169}
170
171/// 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> {
177    if #[allow(non_exhaustive_omitted_patterns)] match &expr.kind {
    ExprKind::Block(..) => true,
    _ => false,
}matches!(&expr.kind, ExprKind::Block(..)) {
178        return cx.expr_paren(expr.span, expr);
179    }
180    expr
181}