]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/deriving/cmp/partial_ord.rs
Rollup merge of #35917 - jseyfried:remove_attr_ext_traits, r=nrc
[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::{self, BinOpKind, Expr, MetaItem};
17 use syntax::ext::base::{Annotatable, ExtCtxt};
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     macro_rules! md {
29         ($name:expr, $op:expr, $equal:expr) => { {
30             let inline = cx.meta_word(span, InternedString::new("inline"));
31             let attrs = vec!(cx.attribute(span, inline));
32             MethodDef {
33                 name: $name,
34                 generics: LifetimeBounds::empty(),
35                 explicit_self: borrowed_explicit_self(),
36                 args: vec!(borrowed_self()),
37                 ret_ty: Literal(path_local!(bool)),
38                 attributes: attrs,
39                 is_unsafe: false,
40                 unify_fieldless_variants: true,
41                 combine_substructure: combine_substructure(Box::new(|cx, span, substr| {
42                     cs_op($op, $equal, cx, span, substr)
43                 }))
44             }
45         } }
46     }
47
48     let ordering_ty = Literal(path_std!(cx, core::cmp::Ordering));
49     let ret_ty = Literal(Path::new_(pathvec_std!(cx, core::option::Option),
50                                     None,
51                                     vec![Box::new(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         is_unsafe: false,
65         unify_fieldless_variants: true,
66         combine_substructure: combine_substructure(Box::new(|cx, span, substr| {
67             cs_partial_cmp(cx, span, substr)
68         })),
69     };
70
71     // avoid defining extra methods if we can
72     // c-like enums, enums without any fields and structs without fields
73     // can safely define only `partial_cmp`.
74     let methods = if is_type_without_fields(item) {
75         vec![partial_cmp_def]
76     } else {
77         vec![partial_cmp_def,
78              md!("lt", true, false),
79              md!("le", true, true),
80              md!("gt", false, false),
81              md!("ge", false, true)]
82     };
83
84     let trait_def = TraitDef {
85         span: span,
86         attributes: vec![],
87         path: path_std!(cx, core::cmp::PartialOrd),
88         additional_bounds: vec![],
89         generics: LifetimeBounds::empty(),
90         is_unsafe: false,
91         methods: methods,
92         associated_types: Vec::new(),
93     };
94     trait_def.expand(cx, mitem, item, push)
95 }
96
97 #[derive(Copy, Clone)]
98 pub enum OrderingOp {
99     PartialCmpOp,
100     LtOp,
101     LeOp,
102     GtOp,
103     GeOp,
104 }
105
106 pub fn some_ordering_collapsed(cx: &mut ExtCtxt,
107                                span: Span,
108                                op: OrderingOp,
109                                self_arg_tags: &[ast::Ident])
110                                -> P<ast::Expr> {
111     let lft = cx.expr_ident(span, self_arg_tags[0]);
112     let rgt = cx.expr_addr_of(span, cx.expr_ident(span, self_arg_tags[1]));
113     let op_str = match op {
114         PartialCmpOp => "partial_cmp",
115         LtOp => "lt",
116         LeOp => "le",
117         GtOp => "gt",
118         GeOp => "ge",
119     };
120     cx.expr_method_call(span, lft, cx.ident_of(op_str), vec![rgt])
121 }
122
123 pub fn cs_partial_cmp(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> {
124     let test_id = cx.ident_of("__cmp");
125     let ordering = cx.path_global(span, cx.std_path(&["cmp", "Ordering", "Equal"]));
126     let ordering_expr = cx.expr_path(ordering.clone());
127     let equals_expr = cx.expr_some(span, ordering_expr);
128
129     let partial_cmp_path = cx.std_path(&["cmp", "PartialOrd", "partial_cmp"]);
130
131     // Builds:
132     //
133     // match ::std::cmp::PartialOrd::partial_cmp(&self_field1, &other_field1) {
134     // ::std::option::Option::Some(::std::cmp::Ordering::Equal) =>
135     // match ::std::cmp::PartialOrd::partial_cmp(&self_field2, &other_field2) {
136     // ::std::option::Option::Some(::std::cmp::Ordering::Equal) => {
137     // ...
138     // }
139     // __cmp => __cmp
140     // },
141     // __cmp => __cmp
142     // }
143     //
144     cs_fold(// 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, cx.pat_path(span, ordering.clone()))],
169                             old);
170         let neq_arm = cx.arm(span,
171                              vec![cx.pat_ident(span, test_id)],
172                              cx.expr_ident(span, test_id));
173
174         cx.expr_match(span, new, vec![eq_arm, neq_arm])
175     },
176             equals_expr.clone(),
177             Box::new(|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,
185             span,
186             substr)
187 }
188
189 /// Strict inequality.
190 fn cs_op(less: bool, equal: bool, cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> {
191     let op = if less { BinOpKind::Lt } else { BinOpKind::Gt };
192     cs_fold(false, // need foldr,
193             |cx, span, subexpr, self_f, other_fs| {
194         // build up a series of chain ||'s and &&'s from the inside
195         // out (hence foldr) to get lexical ordering, i.e. for op ==
196         // `ast::lt`
197         //
198         // ```
199         // self.f1 < other.f1 || (!(other.f1 < self.f1) &&
200         // (self.f2 < other.f2 || (!(other.f2 < self.f2) &&
201         // (false)
202         // ))
203         // )
204         // ```
205         //
206         // The optimiser should remove the redundancy. We explicitly
207         // get use the binops to avoid auto-deref dereferencing too many
208         // layers of pointers, if the type includes pointers.
209         //
210         let other_f = match (other_fs.len(), other_fs.get(0)) {
211             (1, Some(o_f)) => o_f,
212             _ => cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`"),
213         };
214
215         let cmp = cx.expr_binary(span, op, self_f.clone(), other_f.clone());
216
217         let not_cmp = cx.expr_unary(span,
218                                     ast::UnOp::Not,
219                                     cx.expr_binary(span, op, other_f.clone(), self_f));
220
221         let and = cx.expr_binary(span, BinOpKind::And, not_cmp, subexpr);
222         cx.expr_binary(span, BinOpKind::Or, cmp, and)
223     },
224             cx.expr_bool(span, equal),
225             Box::new(|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,
231                 (true, false) => LtOp,
232                 (false, true) => GeOp,
233                 (false, false) => GtOp,
234             };
235             some_ordering_collapsed(cx, span, op, tag_tuple)
236         }
237     }),
238             cx,
239             span,
240             substr)
241 }