Skip to main content

rustc_builtin_macros/deriving/
partial_ord.rs

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