]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/deriving/cmp/partial_ord.rs
Auto merge of #34294 - alexandermerritt:book-nuls, r=steveklabnik
[rust.git] / src / libsyntax_ext / deriving / cmp / partial_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 deriving::generic::*;
14 use deriving::generic::ty::*;
15
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;
20 use syntax::ptr::P;
21 use syntax_pos::Span;
22
23 pub fn expand_deriving_partial_ord(cx: &mut ExtCtxt,
24                                    span: Span,
25                                    mitem: &MetaItem,
26                                    item: &Annotatable,
27                                    push: &mut FnMut(Annotatable))
28 {
29     macro_rules! md {
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));
33             MethodDef {
34                 name: $name,
35                 generics: LifetimeBounds::empty(),
36                 explicit_self: borrowed_explicit_self(),
37                 args: vec!(borrowed_self()),
38                 ret_ty: Literal(path_local!(bool)),
39                 attributes: attrs,
40                 is_unsafe: false,
41                 unify_fieldless_variants: true,
42                 combine_substructure: combine_substructure(Box::new(|cx, span, substr| {
43                     cs_op($op, $equal, cx, span, substr)
44                 }))
45             }
46         } }
47     }
48
49     let ordering_ty = Literal(path_std!(cx, core::cmp::Ordering));
50     let ret_ty = Literal(Path::new_(pathvec_std!(cx, core::option::Option),
51                                     None,
52                                     vec![Box::new(ordering_ty)],
53                                     true));
54
55     let inline = cx.meta_word(span, InternedString::new("inline"));
56     let attrs = vec!(cx.attribute(span, inline));
57
58     let partial_cmp_def = MethodDef {
59         name: "partial_cmp",
60         generics: LifetimeBounds::empty(),
61         explicit_self: borrowed_explicit_self(),
62         args: vec![borrowed_self()],
63         ret_ty: ret_ty,
64         attributes: attrs,
65         is_unsafe: false,
66         unify_fieldless_variants: true,
67         combine_substructure: combine_substructure(Box::new(|cx, span, substr| {
68             cs_partial_cmp(cx, span, substr)
69         }))
70     };
71
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) {
76         vec![partial_cmp_def]
77     } else {
78         vec![
79             partial_cmp_def,
80             md!("lt", true, false),
81             md!("le", true, true),
82             md!("gt", false, false),
83             md!("ge", false, true)
84         ]
85     };
86
87     let trait_def = TraitDef {
88         span: span,
89         attributes: vec![],
90         path: path_std!(cx, core::cmp::PartialOrd),
91         additional_bounds: vec![],
92         generics: LifetimeBounds::empty(),
93         is_unsafe: false,
94         methods: methods,
95         associated_types: Vec::new(),
96     };
97     trait_def.expand(cx, mitem, item, push)
98 }
99
100 #[derive(Copy, Clone)]
101 pub enum OrderingOp {
102     PartialCmpOp, LtOp, LeOp, GtOp, GeOp,
103 }
104
105 pub fn some_ordering_collapsed(cx: &mut ExtCtxt,
106                                span: Span,
107                                op: OrderingOp,
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",
115     };
116     cx.expr_method_call(span, lft, cx.ident_of(op_str), vec![rgt])
117 }
118
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);
126
127     let partial_cmp_path = cx.std_path(&["cmp", "PartialOrd", "partial_cmp"]);
128
129     /*
130     Builds:
131
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) => {
136                     ...
137                 }
138                 __cmp => __cmp
139             },
140         __cmp => __cmp
141     }
142     */
143     cs_fold(
144         // foldr nests the if-elses correctly, leaving the first field
145         // as the outermost one, and the last as the innermost.
146         false,
147         |cx, span, old, self_f, other_fs| {
148             // match new {
149             //     Some(::std::cmp::Ordering::Equal) => old,
150             //     __cmp => __cmp
151             // }
152
153             let new = {
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)`"),
157                 };
158
159                 let args = vec![
160                     cx.expr_addr_of(span, self_f),
161                     cx.expr_addr_of(span, other_f.clone()),
162                 ];
163
164                 cx.expr_call_global(span, partial_cmp_path.clone(), args)
165             };
166
167             let eq_arm = cx.arm(span,
168                                 vec![cx.pat_some(span,
169                                                  cx.pat_enum(span,
170                                                              ordering.clone(),
171                                                              vec![]))],
172                                 old);
173             let neq_arm = cx.arm(span,
174                                  vec![cx.pat_ident(span, test_id)],
175                                  cx.expr_ident(span, test_id));
176
177             cx.expr_match(span, new, vec![eq_arm, neq_arm])
178         },
179         equals_expr.clone(),
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)`")
183             } else {
184                 some_ordering_collapsed(cx, span, PartialCmpOp, tag_tuple)
185             }
186         }),
187         cx, span, substr)
188 }
189
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 };
194     cs_fold(
195         false, // need foldr,
196         |cx, span, subexpr, self_f, other_fs| {
197             /*
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 ==
200             `ast::lt`
201
202             ```
203             self.f1 < other.f1 || (!(other.f1 < self.f1) &&
204                 (self.f2 < other.f2 || (!(other.f2 < self.f2) &&
205                     (false)
206                 ))
207             )
208             ```
209
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.
213             */
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)`")
217             };
218
219             let cmp = cx.expr_binary(span, op, self_f.clone(), other_f.clone());
220
221             let not_cmp = cx.expr_unary(span, ast::UnOp::Not,
222                                         cx.expr_binary(span, op, other_f.clone(), self_f));
223
224             let and = cx.expr_binary(span, BinOpKind::And, not_cmp, subexpr);
225             cx.expr_binary(span, BinOpKind::Or, cmp, and)
226         },
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)`")
231             } else {
232                 let op = match (less, equal) {
233                     (true,  true) => LeOp, (true,  false) => LtOp,
234                     (false, true) => GeOp, (false, false) => GtOp,
235                 };
236                 some_ordering_collapsed(cx, span, op, tag_tuple)
237             }
238         }),
239         cx, span, substr)
240 }