Skip to main content

rustc_builtin_macros/deriving/
partial_ord.rs

1use rustc_ast::{Expr, ItemKind, ast};
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, pathvec};
8
9pub(crate) fn expand_derive_partial_ord(
10    cx: &ExtCtxt<'_>,
11    span: Span,
12    item: &ast::Item,
13    push: &mut dyn FnMut(Box<ast::Item>),
14    is_const: bool,
15) {
16    let ordering_ty = cx.ty_path(cx.std_path(span, { &[sym::cmp, sym::Ordering] })path_std!(cx, span, cmp::Ordering));
17    let ret_ty = cx.ty_path(cx.std_path_all(
18        span,
19        { &[sym::option, sym::Option] }pathvec!(option::Option),
20        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [ast::GenericArg::Type(ordering_ty)]))vec![ast::GenericArg::Type(ordering_ty)],
21    ));
22
23    // Order in which to perform matching
24    let discr_then_data = discr_data_order(item);
25
26    let container_id = cx.current_expansion.id.expn_data().parent.expect_local();
27    let has_derive_ord = cx.resolver.has_derive_ord(container_id);
28    let is_simple = match &item.kind {
29        // For unit structs/zero-variant enums, the default generated code is better.
30        ItemKind::Struct(.., ast::VariantData::Unit(..)) => false,
31        // Also for single fieldless variant enum
32        ItemKind::Enum(.., enum_def) if enum_def.variants.is_empty() => false,
33        ItemKind::Enum(.., enum_def)
34            if enum_def.variants.len() == 1
35                && #[allow(non_exhaustive_omitted_patterns)] match enum_def.variants[0].data {
    ast::VariantData::Unit(..) => true,
    _ => false,
}matches!(enum_def.variants[0].data, ast::VariantData::Unit(..)) =>
36        {
37            false
38        }
39        ItemKind::Struct(_, ast::Generics { params, .. }, _)
40        | ItemKind::Enum(_, ast::Generics { params, .. }, _)
41            if has_derive_ord
42                && !params
43                    .iter()
44                    .any(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    ast::GenericParamKind::Type { .. } => true,
    _ => false,
}matches!(param.kind, ast::GenericParamKind::Type { .. })) =>
45        {
46            true
47        }
48        _ => false,
49    };
50
51    let partial_cmp_def = MethodDef {
52        name: sym::partial_cmp,
53        generics: cx.empty_generics(span),
54        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
}thin_vec![cx.param_self_ref(span), cx.param(span, sym::other, cx.ty_self_ref(span))],
55        ret_ty,
56        attributes: {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(cx.generated_attr(span, ast::GeneratedAttr::Inline));
    vec
}thin_vec![cx.generated_attr(span, ast::GeneratedAttr::Inline)],
57        body: if is_simple {
58            MethodBody::Directly(partial_cmp_simple_body(cx, span, cx.expr_name(span, sym::other)))
59        } else {
60            MethodBody::SubstructureFunc {
61                body_func: Box::new(|cx, span, substr| {
62                    partial_cmp_body(cx, span, substr, discr_then_data)
63                }),
64                strategy: FieldlessVariantsStrategy::Unify,
65                has_other_selflike_arg: true,
66            }
67        },
68    };
69
70    let trait_def = TraitDef {
71        span,
72        path: cx.std_path(span, { &[sym::cmp, sym::PartialOrd] })path_std!(cx, span, cmp::PartialOrd),
73        needs_copy_as_bound_if_packed: true,
74        additional_bounds: ::smallvec::SmallVec::new()smallvec![],
75        supports_unions: false,
76        methods: {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(partial_cmp_def);
        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(),
                    [partial_cmp_def])))
    }
}smallvec![partial_cmp_def],
77        is_const,
78        ..
79    };
80    trait_def.expand(cx, item, push);
81}
82
83pub(crate) fn discr_data_order(item: &ast::Item) -> bool {
84    if let ItemKind::Enum(_, _, def) = &item.kind {
85        let dataful: Vec<bool> = def.variants.iter().map(|v| !v.data.fields().is_empty()).collect();
86        match dataful.iter().filter(|&&b| b).count() {
87            // No data, placing the discriminant check first makes codegen simpler
88            0 => true,
89            1..=2 => false,
90            _ => (0..dataful.len() - 1).any(|i| {
91                if dataful[i]
92                    && let Some(idx) = dataful[i + 1..].iter().position(|v| *v)
93                {
94                    idx >= 2
95                } else {
96                    false
97                }
98            }),
99        }
100    } else {
101        true
102    }
103}
104
105// Special case for the type deriving both `PartialOrd` and `Ord`. Builds:
106// ```
107// Some(::core::cmp::Ord::cmp(self, other))
108// ```
109fn partial_cmp_simple_body(
110    cx: &ExtCtxt<'_>,
111    span: Span,
112    other_expr: Box<ast::Expr>,
113) -> BlockOrExpr {
114    let ord_cmp_path = cx.std_path(span, &[sym::cmp, sym::Ord, sym::cmp]);
115    let cmp_expr =
116        cx.expr_call_global(span, ord_cmp_path, {
    let len = [(), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(cx.expr_self(span));
    vec.push(other_expr);
    vec
}thin_vec![cx.expr_self(span), other_expr]);
117    BlockOrExpr::new_expr(cx.expr_some(span, cmp_expr))
118}
119
120fn partial_cmp_body(
121    cx: &ExtCtxt<'_>,
122    span: Span,
123    substr: Substructure<'_>,
124    discr_then_data: bool,
125) -> BlockOrExpr {
126    // Builds:
127    //
128    // match ::core::cmp::PartialOrd::partial_cmp(&self.x, &other.x) {
129    //     ::core::option::Option::Some(::core::cmp::Ordering::Equal) =>
130    //         ::core::cmp::PartialOrd::partial_cmp(&self.y, &other.y),
131    //     cmp => cmp,
132    // }
133    let expr = cmp_body(cx, span, substr, discr_then_data, OrdlikeDerive::PartialOrd);
134    BlockOrExpr::new_expr(expr)
135}
136
137#[derive(#[automatically_derived]impl ::core::marker::StructuralPartialEq for
    OrdlikeDerive {
}
#[automatically_derived]impl ::core::cmp::PartialEq for OrdlikeDerive {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
138pub(crate) enum OrdlikeDerive {
139    PartialOrd,
140    Ord,
141}
142
143pub(crate) fn cmp_body(
144    cx: &ExtCtxt<'_>,
145    span: Span,
146    substructure: Substructure<'_>,
147    discr_then_data: bool,
148    derive: OrdlikeDerive,
149) -> Box<Expr> {
150    let is_partial_ord = derive == OrdlikeDerive::PartialOrd;
151    let method_path = if is_partial_ord {
152        [sym::cmp, sym::PartialOrd, sym::partial_cmp]
153    } else {
154        [sym::cmp, sym::Ord, sym::cmp]
155    };
156    let equal_path = cx.std_path(span, &[sym::cmp, sym::Ordering, sym::Equal]);
157
158    // The combination of two field expressions. E.g. for `Ord::cmp` this
159    // is something like `<field1 comparison> && <field2 comparison>`.
160    let combine = |span, mut expr1: Box<Expr>, expr2| {
161        // For `PartialOrd` (`Ord` works the same but without the `Some` wrapping),
162        // when the item is an enum, this expands to
163        // ```
164        // match (expr2) {
165        //     Some(Ordering::Equal) => expr1,
166        //     cmp => cmp
167        // }
168        // ```
169        // where `expr2` is `partial_cmp(self_discr, other_discr)`, and `expr1` is a `match`
170        // against the enum variants. This means that we begin by comparing the enum discriminants,
171        // before either inspecting their contents (if they match), or returning
172        // the `cmp::Ordering` of comparing the enum discriminants.
173        // ```
174        // match partial_cmp(self_discr, other_discr) {
175        //     Some(Ordering::Equal) => match (self, other)  {
176        //         (Self::A(self_0), Self::A(other_0)) => partial_cmp(self_0, other_0),
177        //         (Self::B(self_0), Self::B(other_0)) => partial_cmp(self_0, other_0),
178        //         _ => Some(Ordering::Equal)
179        //     }
180        //     cmp => cmp
181        // }
182        // ```
183        // If we have any certain enum layouts, flipping this results in better codegen
184        // ```
185        // match (self, other) {
186        //     (Self::A(self_0), Self::A(other_0)) => partial_cmp(self_0, other_0),
187        //     _ => partial_cmp(self_discr, other_discr)
188        // }
189        // ```
190        // Reference: https://github.com/rust-lang/rust/pull/103659#issuecomment-1328126354
191
192        if !discr_then_data
193            && let ast::ExprKind::Match(_, arms, _) = &mut expr1.kind
194            && let Some(last) = arms.last_mut()
195            && let ast::PatKind::Wild = last.pat.kind
196        {
197            last.body = Some(expr2);
198            expr1
199        } else {
200            let eq_pat = cx.pat_path(span, equal_path.clone());
201            let eq_arm = cx.arm(
202                span,
203                if is_partial_ord { cx.pat_some(span, eq_pat) } else { eq_pat },
204                expr1,
205            );
206            let cmp = sym::cmp;
207            let neq_arm = cx.arm(span, cx.pat_name(span, cmp), cx.expr_name(span, cmp));
208            cx.expr_match(span, expr2, {
    let len = [(), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(eq_arm);
    vec.push(neq_arm);
    vec
}thin_vec![eq_arm, neq_arm])
209        }
210    };
211
212    match substructure {
213        EnumMatching(.., all_fields) | Struct(_, all_fields) => {
214            let op = |old, field: FieldInfo<'_>| {
215                // The basic case: a field expression for one or more selflike args. E.g.
216                // for `Ord::cmp` this is something like `Ord::cmp(&self.x, &other.x)`.
217                let other_expr =
218                    field.other_selflike_expr.expect("not exactly 2 arguments in `derive`");
219                let args = {
    let len = [(), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(field.self_expr);
    vec.push(other_expr);
    vec
}thin_vec![field.self_expr, other_expr];
220                let new =
221                    cx.expr_call_global(field.span, cx.std_path(field.span, &method_path), args);
222                match old {
223                    Some(old) => Some(combine(field.span, old, new)),
224                    None => Some(new),
225                }
226            };
227
228            all_fields.into_iter().rfold(None, op).unwrap_or_else(|| {
229                // The fallback case for a struct or enum variant with no fields.
230                let mut expr = cx.expr_path(equal_path);
231                if is_partial_ord {
232                    expr = cx.expr_some(span, expr)
233                };
234                expr
235            })
236        }
237        EnumDiscr(match_expr) => {
238            let self_expr = cx.expr_ref(span, call_discriminant_value(cx, span, kw::SelfLower));
239            let other_expr = cx.expr_ref(span, call_discriminant_value(cx, span, sym::other));
240            let args = {
    let len = [(), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(self_expr);
    vec.push(other_expr);
    vec
}thin_vec![self_expr, other_expr];
241            let discr_check_expr = cx.expr_call_global(span, cx.std_path(span, &method_path), args);
242            if let Some(match_expr) = match_expr {
243                combine(span, match_expr, discr_check_expr)
244            } else {
245                discr_check_expr
246            }
247        }
248    }
249}