Skip to main content

rustc_builtin_macros/deriving/cmp/
partial_ord.rs

1use rustc_ast::{ExprKind, ItemKind, MetaItem, PatKind, Safety, ast};
2use rustc_expand::base::{Annotatable, ExtCtxt};
3use rustc_span::{Ident, Span, sym};
4use thin_vec::thin_vec;
5
6use crate::deriving::generic::ty::*;
7use crate::deriving::generic::*;
8use crate::deriving::{path_std, pathvec};
9
10pub(crate) fn expand_deriving_partial_ord(
11    cx: &ExtCtxt<'_>,
12    span: Span,
13    mitem: &MetaItem,
14    item: &Annotatable,
15    push: &mut dyn FnMut(Annotatable),
16    is_const: bool,
17) {
18    let ordering_ty = Path(generic::ty::Path::new({
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [sym::cmp, sym::Ordering]))
    })path_std!(cmp::Ordering));
19    let ret_ty =
20        Path(Path::new_({
    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
            [sym::option, sym::Option]))
}pathvec!(option::Option), ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Box::new(ordering_ty)]))vec![Box::new(ordering_ty)], PathKind::Std));
21
22    // Order in which to perform matching
23    let discr_then_data = if let Annotatable::Item(item) = item
24        && let ItemKind::Enum(_, _, def) = &item.kind
25    {
26        let dataful: Vec<bool> = def.variants.iter().map(|v| !v.data.fields().is_empty()).collect();
27        match dataful.iter().filter(|&&b| b).count() {
28            // No data, placing the discriminant check first makes codegen simpler
29            0 => true,
30            1..=2 => false,
31            _ => (0..dataful.len() - 1).any(|i| {
32                if dataful[i]
33                    && let Some(idx) = dataful[i + 1..].iter().position(|v| *v)
34                {
35                    idx >= 2
36                } else {
37                    false
38                }
39            }),
40        }
41    } else {
42        true
43    };
44
45    let container_id = cx.current_expansion.id.expn_data().parent.expect_local();
46    let has_derive_ord = cx.resolver.has_derive_ord(container_id);
47    let default_substructure =
48        combine_substructure(|cx, span, substr| cs_partial_cmp(cx, span, substr, discr_then_data));
49    let simple_substructure = combine_substructure(|cx, span, _| {
50        cs_partial_cmp_simple(cx, span, cx.expr_ident(span, Ident::new(sym::other, span)))
51    });
52    let is_simple = match item {
53        Annotatable::Item(annitem) => match &annitem.kind {
54            // For unit structs/zero-variant enums, the default generated code is better.
55            ItemKind::Struct(.., ast::VariantData::Unit(..)) => false,
56            // Also for single fieldless variant enum
57            ItemKind::Enum(.., enum_def) if enum_def.variants.is_empty() => false,
58            ItemKind::Enum(.., enum_def)
59                if enum_def.variants.len() == 1
60                    && #[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(..)) =>
61            {
62                false
63            }
64            ItemKind::Struct(_, ast::Generics { params, .. }, _)
65            | ItemKind::Enum(_, ast::Generics { params, .. }, _)
66                if has_derive_ord
67                    && !params
68                        .iter()
69                        .any(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    ast::GenericParamKind::Type { .. } => true,
    _ => false,
}matches!(param.kind, ast::GenericParamKind::Type { .. })) =>
70            {
71                true
72            }
73            _ => false,
74        },
75        _ => false,
76    };
77
78    let partial_cmp_def = MethodDef {
79        name: sym::partial_cmp,
80        generics: Bounds::empty(),
81        explicit_self: true,
82        nonself_args: {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push((self_ref(), sym::other));
        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(),
                    [(self_ref(), sym::other)])))
    }
}smallvec![(self_ref(), sym::other)],
83        ret_ty,
84        attributes: {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(cx.attr_word(sym::inline, span));
    vec
}thin_vec![cx.attr_word(sym::inline, span)],
85        fieldless_variants_strategy: FieldlessVariantsStrategy::Unify,
86        combine_substructure: if is_simple { simple_substructure } else { default_substructure },
87    };
88
89    let trait_def = TraitDef {
90        span,
91        path: generic::ty::Path::new({
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [sym::cmp, sym::PartialOrd]))
    })path_std!(cmp::PartialOrd),
92        skip_path_as_bound: false,
93        needs_copy_as_bound_if_packed: true,
94        additional_bounds: ::smallvec::SmallVec::new()smallvec![],
95        supports_unions: false,
96        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],
97        associated_types: SmallVec::new(),
98        is_const,
99        safety: Safety::Default,
100        document: true,
101    };
102    trait_def.expand_ext(cx, mitem, item, push, is_simple)
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 cs_partial_cmp_simple(cx: &ExtCtxt<'_>, span: Span, other_expr: Box<ast::Expr>) -> BlockOrExpr {
110    let ord_cmp_path = cx.std_path(&[sym::cmp, sym::Ord, sym::cmp]);
111    let cmp_expr =
112        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]);
113    BlockOrExpr::new_expr(cx.expr_some(span, cmp_expr))
114}
115
116fn cs_partial_cmp(
117    cx: &ExtCtxt<'_>,
118    span: Span,
119    substr: &Substructure<'_>,
120    discr_then_data: bool,
121) -> BlockOrExpr {
122    let test_id = Ident::new(sym::cmp, span);
123    let equal_path = cx.path_global(span, cx.std_path(&[sym::cmp, sym::Ordering, sym::Equal]));
124    let partial_cmp_path = cx.std_path(&[sym::cmp, sym::PartialOrd, sym::partial_cmp]);
125
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 = cs_fold(
134        // foldr nests the if-elses correctly, leaving the first field
135        // as the outermost one, and the last as the innermost.
136        false,
137        cx,
138        span,
139        substr,
140        |cx, fold| match fold {
141            CsFold::Single(field) => {
142                let [other_expr] = &field.other_selflike_exprs[..] else {
143                    cx.dcx()
144                        .span_bug(field.span, "not exactly 2 arguments in `derive(PartialOrd)`");
145                };
146                let args = {
    let len = [(), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(field.self_expr.clone());
    vec.push(other_expr.clone());
    vec
}thin_vec![field.self_expr.clone(), other_expr.clone()];
147                cx.expr_call_global(field.span, partial_cmp_path.clone(), args)
148            }
149            CsFold::Combine(span, mut expr1, expr2) => {
150                // When the item is an enum, this expands to
151                // ```
152                // match (expr2) {
153                //     Some(Ordering::Equal) => expr1,
154                //     cmp => cmp
155                // }
156                // ```
157                // where `expr2` is `partial_cmp(self_discr, other_discr)`, and `expr1` is a `match`
158                // against the enum variants. This means that we begin by comparing the enum discriminants,
159                // before either inspecting their contents (if they match), or returning
160                // the `cmp::Ordering` of comparing the enum discriminants.
161                // ```
162                // match partial_cmp(self_discr, other_discr) {
163                //     Some(Ordering::Equal) => match (self, other)  {
164                //         (Self::A(self_0), Self::A(other_0)) => partial_cmp(self_0, other_0),
165                //         (Self::B(self_0), Self::B(other_0)) => partial_cmp(self_0, other_0),
166                //         _ => Some(Ordering::Equal)
167                //     }
168                //     cmp => cmp
169                // }
170                // ```
171                // If we have any certain enum layouts, flipping this results in better codegen
172                // ```
173                // match (self, other) {
174                //     (Self::A(self_0), Self::A(other_0)) => partial_cmp(self_0, other_0),
175                //     _ => partial_cmp(self_discr, other_discr)
176                // }
177                // ```
178                // Reference: https://github.com/rust-lang/rust/pull/103659#issuecomment-1328126354
179
180                if !discr_then_data
181                    && let ExprKind::Match(_, arms, _) = &mut expr1.kind
182                    && let Some(last) = arms.last_mut()
183                    && let PatKind::Wild = last.pat.kind
184                {
185                    last.body = Some(expr2);
186                    expr1
187                } else {
188                    let eq_arm = cx.arm(
189                        span,
190                        cx.pat_some(span, cx.pat_path(span, equal_path.clone())),
191                        expr1,
192                    );
193                    let neq_arm =
194                        cx.arm(span, cx.pat_ident(span, test_id), cx.expr_ident(span, test_id));
195                    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])
196                }
197            }
198            CsFold::Fieldless => cx.expr_some(span, cx.expr_path(equal_path.clone())),
199        },
200    );
201    BlockOrExpr::new_expr(expr)
202}