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