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.
12 use ast::{MetaItem, Item, Expr};
14 use ext::base::ExtCtxt;
15 use ext::build::AstBuilder;
16 use ext::deriving::generic::*;
18 pub fn expand_deriving_ord(cx: &mut ExtCtxt,
21 in_items: ~[@Item]) -> ~[@Item] {
23 ($name:expr, $op:expr, $equal:expr) => {
26 generics: LifetimeBounds::empty(),
27 explicit_self: borrowed_explicit_self(),
28 args: ~[borrowed_self()],
29 ret_ty: Literal(Path::new(~["bool"])),
31 const_nonmatching: false,
32 combine_substructure: |cx, span, substr| cs_op($op, $equal, cx, span, substr)
37 let trait_def = TraitDef {
39 path: Path::new(~["std", "cmp", "Ord"]),
40 additional_bounds: ~[],
41 generics: LifetimeBounds::empty(),
43 md!("lt", true, false),
44 md!("le", true, true),
45 md!("gt", false, false),
46 md!("ge", false, true)
49 trait_def.expand(cx, mitem, in_items)
52 /// Strict inequality.
53 fn cs_op(less: bool, equal: bool, cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> @Expr {
54 let op = if less {ast::BiLt} else {ast::BiGt};
57 |cx, span, subexpr, self_f, other_fs| {
59 build up a series of chain ||'s and &&'s from the inside
60 out (hence foldr) to get lexical ordering, i.e. for op ==
64 self.f1 < other.f1 || (!(other.f1 < self.f1) &&
65 (self.f2 < other.f2 || (!(other.f2 < self.f2) &&
71 The optimiser should remove the redundancy. We explicitly
72 get use the binops to avoid auto-deref derefencing too many
73 layers of pointers, if the type includes pointers.
75 let other_f = match other_fs {
77 _ => cx.span_bug(span, "not exactly 2 arguments in `deriving(Ord)`")
80 let cmp = cx.expr_binary(span, op, self_f, other_f);
82 let not_cmp = cx.expr_unary(span, ast::UnNot,
83 cx.expr_binary(span, op, other_f, self_f));
85 let and = cx.expr_binary(span, ast::BiAnd, not_cmp, subexpr);
86 cx.expr_binary(span, ast::BiOr, cmp, and)
88 cx.expr_bool(span, equal),
90 // nonmatching enums, order by the order the variants are
101 _ => cx.span_bug(span, "not exactly 2 arguments in `deriving(Ord)`")