]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/deriving/generic/ty.rs
fa284f4ab0e17bb7623aca19a56f05af614bbafd
[rust.git] / src / libsyntax_ext / deriving / generic / ty.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 //! A mini version of ast::Ty, which is easier to use, and features an explicit `Self` type to use
12 //! when specifying impls to be derived.
13
14 pub use self::PtrTy::*;
15 pub use self::Ty::*;
16
17 use syntax::ast;
18 use syntax::ast::{Expr, GenericParamKind, Generics, Ident, SelfKind, GenericArg};
19 use syntax::ext::base::ExtCtxt;
20 use syntax::ext::build::AstBuilder;
21 use syntax::source_map::{respan, DUMMY_SP};
22 use syntax::ptr::P;
23 use syntax_pos::Span;
24 use syntax_pos::symbol::keywords;
25
26 /// The types of pointers
27 #[derive(Clone)]
28 pub enum PtrTy<'a> {
29     /// &'lifetime mut
30     Borrowed(Option<&'a str>, ast::Mutability),
31     /// *mut
32     Raw(ast::Mutability),
33 }
34
35 /// A path, e.g. `::std::option::Option::<i32>` (global). Has support
36 /// for type parameters and a lifetime.
37 #[derive(Clone)]
38 pub struct Path<'a> {
39     path: Vec<&'a str>,
40     lifetime: Option<&'a str>,
41     params: Vec<Box<Ty<'a>>>,
42     kind: PathKind,
43 }
44
45 #[derive(Clone)]
46 pub enum PathKind {
47     Local,
48     Global,
49     Std,
50 }
51
52 impl<'a> Path<'a> {
53     pub fn new<'r>(path: Vec<&'r str>) -> Path<'r> {
54         Path::new_(path, None, Vec::new(), PathKind::Std)
55     }
56     pub fn new_local<'r>(path: &'r str) -> Path<'r> {
57         Path::new_(vec![path], None, Vec::new(), PathKind::Local)
58     }
59     pub fn new_<'r>(path: Vec<&'r str>,
60                     lifetime: Option<&'r str>,
61                     params: Vec<Box<Ty<'r>>>,
62                     kind: PathKind)
63                     -> Path<'r> {
64         Path {
65             path,
66             lifetime,
67             params,
68             kind,
69         }
70     }
71
72     pub fn to_ty(&self,
73                  cx: &ExtCtxt,
74                  span: Span,
75                  self_ty: Ident,
76                  self_generics: &Generics)
77                  -> P<ast::Ty> {
78         cx.ty_path(self.to_path(cx, span, self_ty, self_generics))
79     }
80     pub fn to_path(&self,
81                    cx: &ExtCtxt,
82                    span: Span,
83                    self_ty: Ident,
84                    self_generics: &Generics)
85                    -> ast::Path {
86         let mut idents = self.path.iter().map(|s| cx.ident_of(*s)).collect();
87         let lt = mk_lifetimes(cx, span, &self.lifetime);
88         let tys: Vec<P<ast::Ty>> =
89             self.params.iter().map(|t| t.to_ty(cx, span, self_ty, self_generics)).collect();
90         let params = lt.into_iter()
91                        .map(|lt| GenericArg::Lifetime(lt))
92                        .chain(tys.into_iter().map(|ty| GenericArg::Type(ty)))
93                        .collect();
94
95         match self.kind {
96             PathKind::Global => cx.path_all(span, true, idents, params, Vec::new()),
97             PathKind::Local => cx.path_all(span, false, idents, params, Vec::new()),
98             PathKind::Std => {
99                 let def_site = DUMMY_SP.apply_mark(cx.current_expansion.mark);
100                 idents.insert(0, Ident::new(keywords::DollarCrate.name(), def_site));
101                 cx.path_all(span, false, idents, params, Vec::new())
102             }
103         }
104
105     }
106 }
107
108 /// A type. Supports pointers, Self, and literals
109 #[derive(Clone)]
110 pub enum Ty<'a> {
111     Self_,
112     /// &/Box/ Ty
113     Ptr(Box<Ty<'a>>, PtrTy<'a>),
114     /// mod::mod::Type<[lifetime], [Params...]>, including a plain type
115     /// parameter, and things like `i32`
116     Literal(Path<'a>),
117     /// includes unit
118     Tuple(Vec<Ty<'a>>),
119 }
120
121 pub fn borrowed_ptrty<'r>() -> PtrTy<'r> {
122     Borrowed(None, ast::Mutability::Immutable)
123 }
124 pub fn borrowed<'r>(ty: Box<Ty<'r>>) -> Ty<'r> {
125     Ptr(ty, borrowed_ptrty())
126 }
127
128 pub fn borrowed_explicit_self<'r>() -> Option<Option<PtrTy<'r>>> {
129     Some(Some(borrowed_ptrty()))
130 }
131
132 pub fn borrowed_self<'r>() -> Ty<'r> {
133     borrowed(Box::new(Self_))
134 }
135
136 pub fn nil_ty<'r>() -> Ty<'r> {
137     Tuple(Vec::new())
138 }
139
140 fn mk_lifetime(cx: &ExtCtxt, span: Span, lt: &Option<&str>) -> Option<ast::Lifetime> {
141     lt.map(|s|
142         cx.lifetime(span, Ident::from_str(s))
143     )
144 }
145
146 fn mk_lifetimes(cx: &ExtCtxt, span: Span, lt: &Option<&str>) -> Vec<ast::Lifetime> {
147     mk_lifetime(cx, span, lt).into_iter().collect()
148 }
149
150 impl<'a> Ty<'a> {
151     pub fn to_ty(&self,
152                  cx: &ExtCtxt,
153                  span: Span,
154                  self_ty: Ident,
155                  self_generics: &Generics)
156                  -> P<ast::Ty> {
157         match *self {
158             Ptr(ref ty, ref ptr) => {
159                 let raw_ty = ty.to_ty(cx, span, self_ty, self_generics);
160                 match *ptr {
161                     Borrowed(ref lt, mutbl) => {
162                         let lt = mk_lifetime(cx, span, lt);
163                         cx.ty_rptr(span, raw_ty, lt, mutbl)
164                     }
165                     Raw(mutbl) => cx.ty_ptr(span, raw_ty, mutbl),
166                 }
167             }
168             Literal(ref p) => p.to_ty(cx, span, self_ty, self_generics),
169             Self_ => cx.ty_path(self.to_path(cx, span, self_ty, self_generics)),
170             Tuple(ref fields) => {
171                 let ty = ast::TyKind::Tup(fields.iter()
172                     .map(|f| f.to_ty(cx, span, self_ty, self_generics))
173                     .collect());
174                 cx.ty(span, ty)
175             }
176         }
177     }
178
179     pub fn to_path(&self,
180                    cx: &ExtCtxt,
181                    span: Span,
182                    self_ty: Ident,
183                    generics: &Generics)
184                    -> ast::Path {
185         match *self {
186             Self_ => {
187                 let params: Vec<_> = generics.params.iter().map(|param| match param.kind {
188                     GenericParamKind::Lifetime { .. } => {
189                         GenericArg::Lifetime(ast::Lifetime { id: param.id, ident: param.ident })
190                     }
191                     GenericParamKind::Type { .. } => {
192                         GenericArg::Type(cx.ty_ident(span, param.ident))
193                     }
194                 }).collect();
195
196                 cx.path_all(span, false, vec![self_ty], params, vec![])
197             }
198             Literal(ref p) => p.to_path(cx, span, self_ty, generics),
199             Ptr(..) => cx.span_bug(span, "pointer in a path in generic `derive`"),
200             Tuple(..) => cx.span_bug(span, "tuple in a path in generic `derive`"),
201         }
202     }
203 }
204
205
206 fn mk_ty_param(cx: &ExtCtxt,
207                span: Span,
208                name: &str,
209                attrs: &[ast::Attribute],
210                bounds: &[Path],
211                self_ident: Ident,
212                self_generics: &Generics)
213                -> ast::GenericParam {
214     let bounds = bounds.iter()
215         .map(|b| {
216             let path = b.to_path(cx, span, self_ident, self_generics);
217             cx.trait_bound(path)
218         })
219         .collect();
220     cx.typaram(span, cx.ident_of(name), attrs.to_owned(), bounds, None)
221 }
222
223 fn mk_generics(params: Vec<ast::GenericParam>, span: Span) -> Generics {
224     Generics {
225         params,
226         where_clause: ast::WhereClause {
227             id: ast::DUMMY_NODE_ID,
228             predicates: Vec::new(),
229             span,
230         },
231         span,
232     }
233 }
234
235 /// Lifetimes and bounds on type parameters
236 #[derive(Clone)]
237 pub struct LifetimeBounds<'a> {
238     pub lifetimes: Vec<(&'a str, Vec<&'a str>)>,
239     pub bounds: Vec<(&'a str, Vec<Path<'a>>)>,
240 }
241
242 impl<'a> LifetimeBounds<'a> {
243     pub fn empty() -> LifetimeBounds<'a> {
244         LifetimeBounds {
245             lifetimes: Vec::new(),
246             bounds: Vec::new(),
247         }
248     }
249     pub fn to_generics(&self,
250                        cx: &ExtCtxt,
251                        span: Span,
252                        self_ty: Ident,
253                        self_generics: &Generics)
254                        -> Generics {
255         let generic_params = self.lifetimes
256             .iter()
257             .map(|&(lt, ref bounds)| {
258                 let bounds = bounds.iter()
259                     .map(|b| ast::GenericBound::Outlives(cx.lifetime(span, Ident::from_str(b))));
260                 cx.lifetime_def(span, Ident::from_str(lt), vec![], bounds.collect())
261             })
262             .chain(self.bounds
263                 .iter()
264                 .map(|t| {
265                     let (name, ref bounds) = *t;
266                     mk_ty_param(cx, span, name, &[], &bounds, self_ty, self_generics)
267                 })
268             )
269             .collect();
270
271         mk_generics(generic_params, span)
272     }
273 }
274
275 pub fn get_explicit_self(cx: &ExtCtxt,
276                          span: Span,
277                          self_ptr: &Option<PtrTy>)
278                          -> (P<Expr>, ast::ExplicitSelf) {
279     // this constructs a fresh `self` path
280     let self_path = cx.expr_self(span);
281     match *self_ptr {
282         None => (self_path, respan(span, SelfKind::Value(ast::Mutability::Immutable))),
283         Some(ref ptr) => {
284             let self_ty =
285                 respan(span,
286                        match *ptr {
287                            Borrowed(ref lt, mutbl) => {
288                                let lt = lt.map(|s| cx.lifetime(span, Ident::from_str(s)));
289                                SelfKind::Region(lt, mutbl)
290                            }
291                            Raw(_) => {
292                                cx.span_bug(span, "attempted to use *self in deriving definition")
293                            }
294                        });
295             let self_expr = cx.expr_deref(span, self_path);
296             (self_expr, self_ty)
297         }
298     }
299 }