]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/deriving/cmp/ord.rs
rollup merge of #21389: retep998/timer
[rust.git] / src / libsyntax / ext / deriving / cmp / ord.rs
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.
4 //
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.
10
11 pub use self::OrderingOp::*;
12
13 use ast;
14 use ast::{MetaItem, Item, Expr};
15 use codemap::Span;
16 use ext::base::ExtCtxt;
17 use ext::build::AstBuilder;
18 use ext::deriving::generic::*;
19 use ext::deriving::generic::ty::*;
20 use parse::token::InternedString;
21 use ptr::P;
22
23 pub fn expand_deriving_ord<F>(cx: &mut ExtCtxt,
24                               span: Span,
25                               mitem: &MetaItem,
26                               item: &Item,
27                               push: F) where
28     F: FnOnce(P<Item>),
29 {
30     macro_rules! md {
31         ($name:expr, $op:expr, $equal:expr) => { {
32             let inline = cx.meta_word(span, InternedString::new("inline"));
33             let attrs = vec!(cx.attribute(span, inline));
34             MethodDef {
35                 name: $name,
36                 generics: LifetimeBounds::empty(),
37                 explicit_self: borrowed_explicit_self(),
38                 args: vec!(borrowed_self()),
39                 ret_ty: Literal(Path::new(vec!("bool"))),
40                 attributes: attrs,
41                 combine_substructure: combine_substructure(box |cx, span, substr| {
42                     cs_op($op, $equal, cx, span, substr)
43                 })
44             }
45         } }
46     }
47
48     let ordering_ty = Literal(Path::new(vec!["std", "cmp", "Ordering"]));
49     let ret_ty = Literal(Path::new_(vec!["std", "option", "Option"],
50                                     None,
51                                     vec![box ordering_ty],
52                                     true));
53
54     let inline = cx.meta_word(span, InternedString::new("inline"));
55     let attrs = vec!(cx.attribute(span, inline));
56
57     let partial_cmp_def = MethodDef {
58         name: "partial_cmp",
59         generics: LifetimeBounds::empty(),
60         explicit_self: borrowed_explicit_self(),
61         args: vec![borrowed_self()],
62         ret_ty: ret_ty,
63         attributes: attrs,
64         combine_substructure: combine_substructure(box |cx, span, substr| {
65             cs_partial_cmp(cx, span, substr)
66         })
67     };
68
69     let trait_def = TraitDef {
70         span: span,
71         attributes: vec![],
72         path: Path::new(vec!["std", "cmp", "PartialOrd"]),
73         additional_bounds: vec![],
74         generics: LifetimeBounds::empty(),
75         methods: vec![
76             partial_cmp_def,
77             md!("lt", true, false),
78             md!("le", true, true),
79             md!("gt", false, false),
80             md!("ge", false, true)
81         ]
82     };
83     trait_def.expand(cx, mitem, item, push)
84 }
85
86 #[derive(Copy)]
87 pub enum OrderingOp {
88     PartialCmpOp, LtOp, LeOp, GtOp, GeOp,
89 }
90
91 pub fn some_ordering_collapsed(cx: &mut ExtCtxt,
92                                span: Span,
93                                op: OrderingOp,
94                                self_arg_tags: &[ast::Ident]) -> P<ast::Expr> {
95     let lft = cx.expr_ident(span, self_arg_tags[0]);
96     let rgt = cx.expr_addr_of(span, cx.expr_ident(span, self_arg_tags[1]));
97     let op_str = match op {
98         PartialCmpOp => "partial_cmp",
99         LtOp => "lt", LeOp => "le",
100         GtOp => "gt", GeOp => "ge",
101     };
102     cx.expr_method_call(span, lft, cx.ident_of(op_str), vec![rgt])
103 }
104
105 pub fn cs_partial_cmp(cx: &mut ExtCtxt, span: Span,
106               substr: &Substructure) -> P<Expr> {
107     let test_id = cx.ident_of("__test");
108     let ordering = cx.path_global(span,
109                                   vec!(cx.ident_of("std"),
110                                        cx.ident_of("cmp"),
111                                        cx.ident_of("Ordering"),
112                                        cx.ident_of("Equal")));
113     let ordering = cx.expr_path(ordering);
114     let equals_expr = cx.expr_some(span, ordering);
115
116     let partial_cmp_path = vec![
117         cx.ident_of("std"),
118         cx.ident_of("cmp"),
119         cx.ident_of("PartialOrd"),
120         cx.ident_of("partial_cmp"),
121     ];
122
123     /*
124     Builds:
125
126     let __test = ::std::cmp::PartialOrd::partial_cmp(&self_field1, &other_field1);
127     if __test == ::std::option::Option::Some(::std::cmp::Ordering::Equal) {
128         let __test = ::std::cmp::PartialOrd::partial_cmp(&self_field2, &other_field2);
129         if __test == ::std::option::Option::Some(::std::cmp::Ordering::Equal) {
130             ...
131         } else {
132             __test
133         }
134     } else {
135         __test
136     }
137
138     FIXME #6449: These `if`s could/should be `match`es.
139     */
140     cs_fold(
141         // foldr nests the if-elses correctly, leaving the first field
142         // as the outermost one, and the last as the innermost.
143         false,
144         |cx, span, old, self_f, other_fs| {
145             // let __test = new;
146             // if __test == Some(::std::cmp::Ordering::Equal) {
147             //    old
148             // } else {
149             //    __test
150             // }
151
152             let new = {
153                 let other_f = match other_fs {
154                     [ref o_f] => o_f,
155                     _ => cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`"),
156                 };
157
158                 let args = vec![
159                     cx.expr_addr_of(span, self_f),
160                     cx.expr_addr_of(span, other_f.clone()),
161                 ];
162
163                 cx.expr_call_global(span, partial_cmp_path.clone(), args)
164             };
165
166             let assign = cx.stmt_let(span, false, test_id, new);
167
168             let cond = cx.expr_binary(span, ast::BiEq,
169                                       cx.expr_ident(span, test_id),
170                                       equals_expr.clone());
171             let if_ = cx.expr_if(span,
172                                  cond,
173                                  old, Some(cx.expr_ident(span, test_id)));
174             cx.expr_block(cx.block(span, vec!(assign), Some(if_)))
175         },
176         equals_expr.clone(),
177         box |cx, span, (self_args, tag_tuple), _non_self_args| {
178             if self_args.len() != 2 {
179                 cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`")
180             } else {
181                 some_ordering_collapsed(cx, span, PartialCmpOp, tag_tuple)
182             }
183         },
184         cx, span, substr)
185 }
186
187 /// Strict inequality.
188 fn cs_op(less: bool, equal: bool, cx: &mut ExtCtxt,
189          span: Span, substr: &Substructure) -> P<Expr> {
190     let op = if less {ast::BiLt} else {ast::BiGt};
191     cs_fold(
192         false, // need foldr,
193         |cx, span, subexpr, self_f, other_fs| {
194             /*
195             build up a series of chain ||'s and &&'s from the inside
196             out (hence foldr) to get lexical ordering, i.e. for op ==
197             `ast::lt`
198
199             ```
200             self.f1 < other.f1 || (!(other.f1 < self.f1) &&
201                 (self.f2 < other.f2 || (!(other.f2 < self.f2) &&
202                     (false)
203                 ))
204             )
205             ```
206
207             The optimiser should remove the redundancy. We explicitly
208             get use the binops to avoid auto-deref dereferencing too many
209             layers of pointers, if the type includes pointers.
210             */
211             let other_f = match other_fs {
212                 [ref o_f] => o_f,
213                 _ => cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`")
214             };
215
216             let cmp = cx.expr_binary(span, op, self_f.clone(), other_f.clone());
217
218             let not_cmp = cx.expr_unary(span, ast::UnNot,
219                                         cx.expr_binary(span, op, other_f.clone(), self_f));
220
221             let and = cx.expr_binary(span, ast::BiAnd, not_cmp, subexpr);
222             cx.expr_binary(span, ast::BiOr, cmp, and)
223         },
224         cx.expr_bool(span, equal),
225         box |cx, span, (self_args, tag_tuple), _non_self_args| {
226             if self_args.len() != 2 {
227                 cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`")
228             } else {
229                 let op = match (less, equal) {
230                     (true,  true) => LeOp, (true,  false) => LtOp,
231                     (false, true) => GeOp, (false, false) => GtOp,
232                 };
233                 some_ordering_collapsed(cx, span, op, tag_tuple)
234             }
235         },
236         cx, span, substr)
237 }