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::generic::*;
14 use deriving::generic::ty::*;
16 use syntax::ast::{MetaItem, Expr, BinOpKind, self};
17 use syntax::ext::base::{ExtCtxt, Annotatable};
18 use syntax::ext::build::AstBuilder;
19 use syntax::parse::token::InternedString;
23 pub fn expand_deriving_partial_ord(cx: &mut ExtCtxt,
27 push: &mut FnMut(Annotatable))
30 ($name:expr, $op:expr, $equal:expr) => { {
31 let inline = cx.meta_word(span, InternedString::new("inline"));
32 let attrs = vec!(cx.attribute(span, inline));
35 generics: LifetimeBounds::empty(),
36 explicit_self: borrowed_explicit_self(),
37 args: vec!(borrowed_self()),
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, core::cmp::Ordering));
50 let ret_ty = Literal(Path::new_(pathvec_std!(cx, core::option::Option),
52 vec![Box::new(ordering_ty)],
55 let inline = cx.meta_word(span, InternedString::new("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()],
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) {
80 md!("lt", true, false),
81 md!("le", true, true),
82 md!("gt", false, false),
83 md!("ge", false, true)
87 let trait_def = TraitDef {
90 path: path_std!(cx, core::cmp::PartialOrd),
91 additional_bounds: vec![],
92 generics: LifetimeBounds::empty(),
95 associated_types: Vec::new(),
97 trait_def.expand(cx, mitem, item, push)
100 #[derive(Copy, Clone)]
101 pub enum OrderingOp {
102 PartialCmpOp, LtOp, LeOp, GtOp, GeOp,
105 pub fn some_ordering_collapsed(cx: &mut ExtCtxt,
108 self_arg_tags: &[ast::Ident]) -> P<ast::Expr> {
109 let lft = cx.expr_ident(span, self_arg_tags[0]);
110 let rgt = cx.expr_addr_of(span, cx.expr_ident(span, self_arg_tags[1]));
111 let op_str = match op {
112 PartialCmpOp => "partial_cmp",
113 LtOp => "lt", LeOp => "le",
114 GtOp => "gt", GeOp => "ge",
116 cx.expr_method_call(span, lft, cx.ident_of(op_str), vec![rgt])
119 pub fn cs_partial_cmp(cx: &mut ExtCtxt, span: Span,
120 substr: &Substructure) -> P<Expr> {
121 let test_id = cx.ident_of("__cmp");
122 let ordering = cx.path_global(span,
123 cx.std_path(&["cmp", "Ordering", "Equal"]));
124 let ordering_expr = cx.expr_path(ordering.clone());
125 let equals_expr = cx.expr_some(span, ordering_expr);
127 let partial_cmp_path = cx.std_path(&["cmp", "PartialOrd", "partial_cmp"]);
132 match ::std::cmp::PartialOrd::partial_cmp(&self_field1, &other_field1) {
133 ::std::option::Option::Some(::std::cmp::Ordering::Equal) =>
134 match ::std::cmp::PartialOrd::partial_cmp(&self_field2, &other_field2) {
135 ::std::option::Option::Some(::std::cmp::Ordering::Equal) => {
144 // foldr nests the if-elses correctly, leaving the first field
145 // as the outermost one, and the last as the innermost.
147 |cx, span, old, self_f, other_fs| {
149 // Some(::std::cmp::Ordering::Equal) => old,
154 let other_f = match (other_fs.len(), other_fs.get(0)) {
155 (1, Some(o_f)) => o_f,
156 _ => cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`"),
160 cx.expr_addr_of(span, self_f),
161 cx.expr_addr_of(span, other_f.clone()),
164 cx.expr_call_global(span, partial_cmp_path.clone(), args)
167 let eq_arm = cx.arm(span,
168 vec![cx.pat_some(span,
173 let neq_arm = cx.arm(span,
174 vec![cx.pat_ident(span, test_id)],
175 cx.expr_ident(span, test_id));
177 cx.expr_match(span, new, vec![eq_arm, neq_arm])
180 Box::new(|cx, span, (self_args, tag_tuple), _non_self_args| {
181 if self_args.len() != 2 {
182 cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`")
184 some_ordering_collapsed(cx, span, PartialCmpOp, tag_tuple)
190 /// Strict inequality.
191 fn cs_op(less: bool, equal: bool, cx: &mut ExtCtxt,
192 span: Span, substr: &Substructure) -> P<Expr> {
193 let op = if less { BinOpKind::Lt } else { BinOpKind::Gt };
195 false, // need foldr,
196 |cx, span, subexpr, self_f, other_fs| {
198 build up a series of chain ||'s and &&'s from the inside
199 out (hence foldr) to get lexical ordering, i.e. for op ==
203 self.f1 < other.f1 || (!(other.f1 < self.f1) &&
204 (self.f2 < other.f2 || (!(other.f2 < self.f2) &&
210 The optimiser should remove the redundancy. We explicitly
211 get use the binops to avoid auto-deref dereferencing too many
212 layers of pointers, if the type includes pointers.
214 let other_f = match (other_fs.len(), other_fs.get(0)) {
215 (1, Some(o_f)) => o_f,
216 _ => cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`")
219 let cmp = cx.expr_binary(span, op, self_f.clone(), other_f.clone());
221 let not_cmp = cx.expr_unary(span, ast::UnOp::Not,
222 cx.expr_binary(span, op, other_f.clone(), self_f));
224 let and = cx.expr_binary(span, BinOpKind::And, not_cmp, subexpr);
225 cx.expr_binary(span, BinOpKind::Or, cmp, and)
227 cx.expr_bool(span, equal),
228 Box::new(|cx, span, (self_args, tag_tuple), _non_self_args| {
229 if self_args.len() != 2 {
230 cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`")
232 let op = match (less, equal) {
233 (true, true) => LeOp, (true, false) => LtOp,
234 (false, true) => GeOp, (false, false) => GtOp,
236 some_ordering_collapsed(cx, span, op, tag_tuple)