3 use crate::deriving::{path_local, pathvec_std, path_std};
4 use crate::deriving::generic::*;
5 use crate::deriving::generic::ty::*;
7 use syntax::ast::{self, BinOpKind, Expr, MetaItem};
8 use syntax_expand::base::{Annotatable, ExtCtxt};
10 use syntax::symbol::{sym, Symbol};
13 pub fn expand_deriving_partial_ord(cx: &mut ExtCtxt<'_>,
17 push: &mut dyn FnMut(Annotatable)) {
19 ($name:expr, $op:expr, $equal:expr) => { {
20 let inline = cx.meta_word(span, sym::inline);
21 let attrs = vec![cx.attribute(inline)];
24 generics: LifetimeBounds::empty(),
25 explicit_self: borrowed_explicit_self(),
26 args: vec![(borrowed_self(), "other")],
27 ret_ty: Literal(path_local!(bool)),
30 unify_fieldless_variants: true,
31 combine_substructure: combine_substructure(Box::new(|cx, span, substr| {
32 cs_op($op, $equal, cx, span, substr)
38 let ordering_ty = Literal(path_std!(cx, cmp::Ordering));
39 let ret_ty = Literal(Path::new_(pathvec_std!(cx, option::Option),
41 vec![Box::new(ordering_ty)],
44 let inline = cx.meta_word(span, sym::inline);
45 let attrs = vec![cx.attribute(inline)];
47 let partial_cmp_def = MethodDef {
49 generics: LifetimeBounds::empty(),
50 explicit_self: borrowed_explicit_self(),
51 args: vec![(borrowed_self(), "other")],
55 unify_fieldless_variants: true,
56 combine_substructure: combine_substructure(Box::new(|cx, span, substr| {
57 cs_partial_cmp(cx, span, substr)
61 // avoid defining extra methods if we can
62 // c-like enums, enums without any fields and structs without fields
63 // can safely define only `partial_cmp`.
64 let methods = if is_type_without_fields(item) {
68 md!("lt", true, false),
69 md!("le", true, true),
70 md!("gt", false, false),
71 md!("ge", false, true)]
74 let trait_def = TraitDef {
77 path: path_std!(cx, cmp::PartialOrd),
78 additional_bounds: vec![],
79 generics: LifetimeBounds::empty(),
81 supports_unions: false,
83 associated_types: Vec::new(),
85 trait_def.expand(cx, mitem, item, push)
88 #[derive(Copy, Clone)]
97 pub fn some_ordering_collapsed(
101 self_arg_tags: &[ast::Ident],
103 let lft = cx.expr_ident(span, self_arg_tags[0]);
104 let rgt = cx.expr_addr_of(span, cx.expr_ident(span, self_arg_tags[1]));
105 let op_str = match op {
106 PartialCmpOp => "partial_cmp",
112 cx.expr_method_call(span, lft, cx.ident_of(op_str, span), vec![rgt])
115 pub fn cs_partial_cmp(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_>) -> P<Expr> {
116 let test_id = ast::Ident::new(sym::cmp, span);
117 let ordering = cx.path_global(span, cx.std_path(&[sym::cmp, sym::Ordering, sym::Equal]));
118 let ordering_expr = cx.expr_path(ordering.clone());
119 let equals_expr = cx.expr_some(span, ordering_expr);
121 let partial_cmp_path = cx.std_path(&[sym::cmp, sym::PartialOrd, sym::partial_cmp]);
125 // match ::std::cmp::PartialOrd::partial_cmp(&self_field1, &other_field1) {
126 // ::std::option::Option::Some(::std::cmp::Ordering::Equal) =>
127 // match ::std::cmp::PartialOrd::partial_cmp(&self_field2, &other_field2) {
128 // ::std::option::Option::Some(::std::cmp::Ordering::Equal) => {
136 cs_fold(// foldr nests the if-elses correctly, leaving the first field
137 // as the outermost one, and the last as the innermost.
139 |cx, span, old, self_f, other_fs| {
141 // Some(::std::cmp::Ordering::Equal) => old,
146 let other_f = match other_fs {
150 "not exactly 2 arguments in `derive(PartialOrd)`")
155 cx.expr_addr_of(span, self_f),
156 cx.expr_addr_of(span, other_f.clone()),
159 cx.expr_call_global(span, partial_cmp_path.clone(), args)
162 let eq_arm = cx.arm(span,
163 cx.pat_some(span, cx.pat_path(span, ordering.clone())),
165 let neq_arm = cx.arm(span,
166 cx.pat_ident(span, test_id),
167 cx.expr_ident(span, test_id));
169 cx.expr_match(span, new, vec![eq_arm, neq_arm])
172 Box::new(|cx, span, (self_args, tag_tuple), _non_self_args| {
173 if self_args.len() != 2 {
174 cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`")
176 some_ordering_collapsed(cx, span, PartialCmpOp, tag_tuple)
184 /// Strict inequality.
187 cx: &mut ExtCtxt<'_>,
189 substr: &Substructure<'_>) -> P<Expr> {
190 let ordering_path = |cx: &mut ExtCtxt<'_>, name: &str| {
191 cx.expr_path(cx.path_global(
192 span, cx.std_path(&[sym::cmp, sym::Ordering, Symbol::intern(name)])))
195 let par_cmp = |cx: &mut ExtCtxt<'_>, span, self_f: P<Expr>, other_fs: &[P<Expr>], default| {
196 let other_f = match other_fs {
198 _ => cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`"),
201 // `PartialOrd::partial_cmp(self.fi, other.fi)`
202 let cmp_path = cx.expr_path(cx.path_global(span, cx.std_path(&[sym::cmp,
204 sym::partial_cmp])));
205 let cmp = cx.expr_call(span,
207 vec![cx.expr_addr_of(span, self_f),
208 cx.expr_addr_of(span, other_f.clone())]);
210 let default = ordering_path(cx, default);
211 // `Option::unwrap_or(_, Ordering::Equal)`
212 let unwrap_path = cx.expr_path(cx.path_global(span, cx.std_path(&[sym::option,
215 cx.expr_call(span, unwrap_path, vec![cmp, default])
218 let fold = cs_fold1(false, // need foldr
219 |cx, span, subexpr, self_f, other_fs| {
220 // build up a series of `partial_cmp`s from the inside
221 // out (hence foldr) to get lexical ordering, i.e., for op ==
225 // Ordering::then_with(
226 // Option::unwrap_or(
227 // PartialOrd::partial_cmp(self.f1, other.f1), Ordering::Equal)
229 // Option::unwrap_or(
230 // PartialOrd::partial_cmp(self.f2, other.f2), Ordering::Greater)
240 // Ordering::then_with(
241 // Option::unwrap_or(
242 // PartialOrd::partial_cmp(self.f1, other.f1), Ordering::Equal)
244 // Option::unwrap_or(
245 // PartialOrd::partial_cmp(self.f2, other.f2), Ordering::Greater)
248 // != Ordering::Greater
251 // The optimiser should remove the redundancy. We explicitly
252 // get use the binops to avoid auto-deref dereferencing too many
253 // layers of pointers, if the type includes pointers.
255 // `Option::unwrap_or(PartialOrd::partial_cmp(self.fi, other.fi), Ordering::Equal)`
256 let par_cmp = par_cmp(cx, span, self_f, other_fs, "Equal");
258 // `Ordering::then_with(Option::unwrap_or(..), ..)`
259 let then_with_path = cx.expr_path(cx.path_global(span,
260 cx.std_path(&[sym::cmp,
263 cx.expr_call(span, then_with_path, vec![par_cmp, cx.lambda0(span, subexpr)])
267 Some((span, self_f, other_fs)) => {
268 let opposite = if less { "Greater" } else { "Less" };
269 par_cmp(cx, span, self_f, other_fs, opposite)
271 None => cx.expr_bool(span, inclusive)
274 Box::new(|cx, span, (self_args, tag_tuple), _non_self_args| {
275 if self_args.len() != 2 {
276 cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`")
278 let op = match (less, inclusive) {
279 (false, false) => GtOp,
280 (false, true) => GeOp,
281 (true, false) => LtOp,
282 (true, true) => LeOp,
284 some_ordering_collapsed(cx, span, op, tag_tuple)
291 match *substr.fields {
292 EnumMatching(.., ref all_fields) |
293 Struct(.., ref all_fields) if !all_fields.is_empty() => {
294 let ordering = ordering_path(cx, if less ^ inclusive { "Less" } else { "Greater" });
295 let comp_op = if inclusive { BinOpKind::Ne } else { BinOpKind::Eq };
297 cx.expr_binary(span, comp_op, fold, ordering)