1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::OrderingOp::*;
13 use deriving::{path_local, pathvec_std, path_std};
14 use deriving::generic::*;
15 use deriving::generic::ty::*;
17 use syntax::ast::{self, BinOpKind, Expr, MetaItem};
18 use syntax::ext::base::{Annotatable, ExtCtxt};
19 use syntax::ext::build::AstBuilder;
21 use syntax::symbol::Symbol;
24 pub fn expand_deriving_partial_ord(cx: &mut ExtCtxt,
28 push: &mut dyn FnMut(Annotatable)) {
30 ($name:expr, $op:expr, $equal:expr) => { {
31 let inline = cx.meta_word(span, Symbol::intern("inline"));
32 let attrs = vec![cx.attribute(span, inline)];
35 generics: LifetimeBounds::empty(),
36 explicit_self: borrowed_explicit_self(),
37 args: vec![(borrowed_self(), "other")],
38 ret_ty: Literal(path_local!(bool)),
41 unify_fieldless_variants: true,
42 combine_substructure: combine_substructure(Box::new(|cx, span, substr| {
43 cs_op($op, $equal, cx, span, substr)
49 let ordering_ty = Literal(path_std!(cx, cmp::Ordering));
50 let ret_ty = Literal(Path::new_(pathvec_std!(cx, option::Option),
52 vec![Box::new(ordering_ty)],
55 let inline = cx.meta_word(span, Symbol::intern("inline"));
56 let attrs = vec![cx.attribute(span, inline)];
58 let partial_cmp_def = MethodDef {
60 generics: LifetimeBounds::empty(),
61 explicit_self: borrowed_explicit_self(),
62 args: vec![(borrowed_self(), "other")],
66 unify_fieldless_variants: true,
67 combine_substructure: combine_substructure(Box::new(|cx, span, substr| {
68 cs_partial_cmp(cx, span, substr)
72 // avoid defining extra methods if we can
73 // c-like enums, enums without any fields and structs without fields
74 // can safely define only `partial_cmp`.
75 let methods = if is_type_without_fields(item) {
79 md!("lt", true, false),
80 md!("le", true, true),
81 md!("gt", false, false),
82 md!("ge", false, true)]
85 let trait_def = TraitDef {
88 path: path_std!(cx, cmp::PartialOrd),
89 additional_bounds: vec![],
90 generics: LifetimeBounds::empty(),
92 supports_unions: false,
94 associated_types: Vec::new(),
96 trait_def.expand(cx, mitem, item, push)
99 #[derive(Copy, Clone)]
100 pub enum OrderingOp {
108 pub fn some_ordering_collapsed(cx: &mut ExtCtxt,
111 self_arg_tags: &[ast::Ident])
113 let lft = cx.expr_ident(span, self_arg_tags[0]);
114 let rgt = cx.expr_addr_of(span, cx.expr_ident(span, self_arg_tags[1]));
115 let op_str = match op {
116 PartialCmpOp => "partial_cmp",
122 cx.expr_method_call(span, lft, cx.ident_of(op_str), vec![rgt])
125 pub fn cs_partial_cmp(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> {
126 let test_id = cx.ident_of("cmp").gensym();
127 let ordering = cx.path_global(span, cx.std_path(&["cmp", "Ordering", "Equal"]));
128 let ordering_expr = cx.expr_path(ordering.clone());
129 let equals_expr = cx.expr_some(span, ordering_expr);
131 let partial_cmp_path = cx.std_path(&["cmp", "PartialOrd", "partial_cmp"]);
135 // match ::std::cmp::PartialOrd::partial_cmp(&self_field1, &other_field1) {
136 // ::std::option::Option::Some(::std::cmp::Ordering::Equal) =>
137 // match ::std::cmp::PartialOrd::partial_cmp(&self_field2, &other_field2) {
138 // ::std::option::Option::Some(::std::cmp::Ordering::Equal) => {
146 cs_fold(// foldr nests the if-elses correctly, leaving the first field
147 // as the outermost one, and the last as the innermost.
149 |cx, span, old, self_f, other_fs| {
151 // Some(::std::cmp::Ordering::Equal) => old,
156 let other_f = match (other_fs.len(), other_fs.get(0)) {
157 (1, Some(o_f)) => o_f,
160 "not exactly 2 arguments in `derive(PartialOrd)`")
165 cx.expr_addr_of(span, self_f),
166 cx.expr_addr_of(span, other_f.clone()),
169 cx.expr_call_global(span, partial_cmp_path.clone(), args)
172 let eq_arm = cx.arm(span,
173 vec![cx.pat_some(span, cx.pat_path(span, ordering.clone()))],
175 let neq_arm = cx.arm(span,
176 vec![cx.pat_ident(span, test_id)],
177 cx.expr_ident(span, test_id));
179 cx.expr_match(span, new, vec![eq_arm, neq_arm])
182 Box::new(|cx, span, (self_args, tag_tuple), _non_self_args| {
183 if self_args.len() != 2 {
184 cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`")
186 some_ordering_collapsed(cx, span, PartialCmpOp, tag_tuple)
194 /// Strict inequality.
199 substr: &Substructure) -> P<Expr> {
200 let ordering_path = |cx: &mut ExtCtxt, name: &str| {
201 cx.expr_path(cx.path_global(span, cx.std_path(&["cmp", "Ordering", name])))
204 let par_cmp = |cx: &mut ExtCtxt, span, self_f: P<Expr>, other_fs: &[P<Expr>], default| {
205 let other_f = match (other_fs.len(), other_fs.get(0)) {
206 (1, Some(o_f)) => o_f,
207 _ => cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`"),
210 // `PartialOrd::partial_cmp(self.fi, other.fi)`
211 let cmp_path = cx.expr_path(cx.path_global(span, cx.std_path(&["cmp",
214 let cmp = cx.expr_call(span,
216 vec![cx.expr_addr_of(span, self_f),
217 cx.expr_addr_of(span, other_f.clone())]);
219 let default = ordering_path(cx, default);
220 // `Option::unwrap_or(_, Ordering::Equal)`
221 let unwrap_path = cx.expr_path(cx.path_global(span, cx.std_path(&["option",
224 cx.expr_call(span, unwrap_path, vec![cmp, default])
227 let fold = cs_fold1(false, // need foldr
228 |cx, span, subexpr, self_f, other_fs| {
229 // build up a series of `partial_cmp`s from the inside
230 // out (hence foldr) to get lexical ordering, i.e., for op ==
234 // Ordering::then_with(
235 // Option::unwrap_or(
236 // PartialOrd::partial_cmp(self.f1, other.f1), Ordering::Equal)
238 // Option::unwrap_or(
239 // PartialOrd::partial_cmp(self.f2, other.f2), Ordering::Greater)
249 // Ordering::then_with(
250 // Option::unwrap_or(
251 // PartialOrd::partial_cmp(self.f1, other.f1), Ordering::Equal)
253 // Option::unwrap_or(
254 // PartialOrd::partial_cmp(self.f2, other.f2), Ordering::Greater)
257 // != Ordering::Greater
260 // The optimiser should remove the redundancy. We explicitly
261 // get use the binops to avoid auto-deref dereferencing too many
262 // layers of pointers, if the type includes pointers.
264 // `Option::unwrap_or(PartialOrd::partial_cmp(self.fi, other.fi), Ordering::Equal)`
265 let par_cmp = par_cmp(cx, span, self_f, other_fs, "Equal");
267 // `Ordering::then_with(Option::unwrap_or(..), ..)`
268 let then_with_path = cx.expr_path(cx.path_global(span,
272 cx.expr_call(span, then_with_path, vec![par_cmp, cx.lambda0(span, subexpr)])
276 Some((span, self_f, other_fs)) => {
277 let opposite = if less { "Greater" } else { "Less" };
278 par_cmp(cx, span, self_f, other_fs, opposite)
280 None => cx.expr_bool(span, inclusive)
283 Box::new(|cx, span, (self_args, tag_tuple), _non_self_args| {
284 if self_args.len() != 2 {
285 cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`")
287 let op = match (less, inclusive) {
288 (false, false) => GtOp,
289 (false, true) => GeOp,
290 (true, false) => LtOp,
291 (true, true) => LeOp,
293 some_ordering_collapsed(cx, span, op, tag_tuple)
300 match *substr.fields {
301 EnumMatching(.., ref all_fields) |
302 Struct(.., ref all_fields) if !all_fields.is_empty() => {
303 let ordering = ordering_path(cx, if less ^ inclusive { "Less" } else { "Greater" });
304 let comp_op = if inclusive { BinOpKind::Ne } else { BinOpKind::Eq };
306 cx.expr_binary(span, comp_op, fold, ordering)