rustc_builtin_macros/deriving/
partial_ord.rs1use 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 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 ItemKind::Struct(.., ast::VariantData::Unit(..)) => false,
31 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 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
105fn 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 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 let combine = |span, mut expr1: Box<Expr>, expr2| {
161 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 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 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}