]> git.lizzy.rs Git - rust.git/blob - src/librustc_allocator/expand.rs
Rename alloc::Void to alloc::Opaque
[rust.git] / src / librustc_allocator / expand.rs
1 // Copyright 2016 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 use rustc::middle::allocator::AllocatorKind;
12 use rustc_errors;
13 use syntax::abi::Abi;
14 use syntax::ast::{Crate, Attribute, LitKind, StrStyle};
15 use syntax::ast::{Unsafety, Constness, Generics, Mutability, Ty, Mac, Arg};
16 use syntax::ast::{self, Ident, Item, ItemKind, TyKind, VisibilityKind, Expr};
17 use syntax::attr;
18 use syntax::codemap::{dummy_spanned, respan};
19 use syntax::codemap::{ExpnInfo, NameAndSpan, MacroAttribute};
20 use syntax::ext::base::ExtCtxt;
21 use syntax::ext::base::Resolver;
22 use syntax::ext::build::AstBuilder;
23 use syntax::ext::expand::ExpansionConfig;
24 use syntax::ext::hygiene::{Mark, SyntaxContext};
25 use syntax::fold::{self, Folder};
26 use syntax::parse::ParseSess;
27 use syntax::ptr::P;
28 use syntax::symbol::Symbol;
29 use syntax::util::small_vector::SmallVector;
30 use syntax_pos::{Span, DUMMY_SP};
31
32 use {AllocatorMethod, AllocatorTy, ALLOCATOR_METHODS};
33
34 pub fn modify(sess: &ParseSess,
35               resolver: &mut Resolver,
36               krate: Crate,
37               handler: &rustc_errors::Handler) -> ast::Crate {
38     ExpandAllocatorDirectives {
39         handler,
40         sess,
41         resolver,
42         found: false,
43     }.fold_crate(krate)
44 }
45
46 struct ExpandAllocatorDirectives<'a> {
47     found: bool,
48     handler: &'a rustc_errors::Handler,
49     sess: &'a ParseSess,
50     resolver: &'a mut Resolver,
51 }
52
53 impl<'a> Folder for ExpandAllocatorDirectives<'a> {
54     fn fold_item(&mut self, item: P<Item>) -> SmallVector<P<Item>> {
55         let name = if attr::contains_name(&item.attrs, "global_allocator") {
56             "global_allocator"
57         } else {
58             return fold::noop_fold_item(item, self)
59         };
60         match item.node {
61             ItemKind::Static(..) => {}
62             _ => {
63                 self.handler.span_err(item.span, "allocators must be statics");
64                 return SmallVector::one(item)
65             }
66         }
67
68         if self.found {
69             self.handler.span_err(item.span, "cannot define more than one \
70                                               #[global_allocator]");
71             return SmallVector::one(item)
72         }
73         self.found = true;
74
75         let mark = Mark::fresh(Mark::root());
76         mark.set_expn_info(ExpnInfo {
77             call_site: DUMMY_SP,
78             callee: NameAndSpan {
79                 format: MacroAttribute(Symbol::intern(name)),
80                 span: None,
81                 allow_internal_unstable: true,
82                 allow_internal_unsafe: false,
83             }
84         });
85         let span = item.span.with_ctxt(SyntaxContext::empty().apply_mark(mark));
86         let ecfg = ExpansionConfig::default(name.to_string());
87         let mut f = AllocFnFactory {
88             span,
89             kind: AllocatorKind::Global,
90             global: item.ident,
91             core: Ident::from_str("core"),
92             cx: ExtCtxt::new(self.sess, ecfg, self.resolver),
93         };
94         let super_path = f.cx.path(f.span, vec![
95             Ident::from_str("super"),
96             f.global,
97         ]);
98         let mut items = vec![
99             f.cx.item_extern_crate(f.span, f.core),
100             f.cx.item_use_simple(
101                 f.span,
102                 respan(f.span.shrink_to_lo(), VisibilityKind::Inherited),
103                 super_path,
104             ),
105         ];
106         for method in ALLOCATOR_METHODS {
107             items.push(f.allocator_fn(method));
108         }
109         let name = f.kind.fn_name("allocator_abi");
110         let allocator_abi = Ident::with_empty_ctxt(Symbol::gensym(&name));
111         let module = f.cx.item_mod(span, span, allocator_abi, Vec::new(), items);
112         let module = f.cx.monotonic_expander().fold_item(module).pop().unwrap();
113
114         let mut ret = SmallVector::new();
115         ret.push(item);
116         ret.push(module);
117         return ret
118     }
119
120     fn fold_mac(&mut self, mac: Mac) -> Mac {
121         fold::noop_fold_mac(mac, self)
122     }
123 }
124
125 struct AllocFnFactory<'a> {
126     span: Span,
127     kind: AllocatorKind,
128     global: Ident,
129     core: Ident,
130     cx: ExtCtxt<'a>,
131 }
132
133 impl<'a> AllocFnFactory<'a> {
134     fn allocator_fn(&self, method: &AllocatorMethod) -> P<Item> {
135         let mut abi_args = Vec::new();
136         let mut i = 0;
137         let ref mut mk = || {
138             let name = Ident::from_str(&format!("arg{}", i));
139             i += 1;
140             name
141         };
142         let args = method.inputs.iter().map(|ty| {
143             self.arg_ty(ty, &mut abi_args, mk)
144         }).collect();
145         let result = self.call_allocator(method.name, args);
146         let (output_ty, output_expr) = self.ret_ty(&method.output, result);
147         let kind = ItemKind::Fn(self.cx.fn_decl(abi_args, ast::FunctionRetTy::Ty(output_ty)),
148                                 Unsafety::Unsafe,
149                                 dummy_spanned(Constness::NotConst),
150                                 Abi::Rust,
151                                 Generics::default(),
152                                 self.cx.block_expr(output_expr));
153         self.cx.item(self.span,
154                      Ident::from_str(&self.kind.fn_name(method.name)),
155                      self.attrs(),
156                      kind)
157     }
158
159     fn call_allocator(&self, method: &str, mut args: Vec<P<Expr>>) -> P<Expr> {
160         let method = self.cx.path(self.span, vec![
161             self.core,
162             Ident::from_str("alloc"),
163             Ident::from_str("GlobalAlloc"),
164             Ident::from_str(method),
165         ]);
166         let method = self.cx.expr_path(method);
167         let allocator = self.cx.path_ident(self.span, self.global);
168         let allocator = self.cx.expr_path(allocator);
169         let allocator = self.cx.expr_addr_of(self.span, allocator);
170         args.insert(0, allocator);
171
172         self.cx.expr_call(self.span, method, args)
173     }
174
175     fn attrs(&self) -> Vec<Attribute> {
176         let key = Symbol::intern("linkage");
177         let value = LitKind::Str(Symbol::intern("external"), StrStyle::Cooked);
178         let linkage = self.cx.meta_name_value(self.span, key, value);
179
180         let no_mangle = Symbol::intern("no_mangle");
181         let no_mangle = self.cx.meta_word(self.span, no_mangle);
182
183         let special = Symbol::intern("rustc_std_internal_symbol");
184         let special = self.cx.meta_word(self.span, special);
185         vec![
186             self.cx.attribute(self.span, linkage),
187             self.cx.attribute(self.span, no_mangle),
188             self.cx.attribute(self.span, special),
189         ]
190     }
191
192     fn arg_ty(&self,
193               ty: &AllocatorTy,
194               args: &mut Vec<Arg>,
195               ident: &mut FnMut() -> Ident) -> P<Expr> {
196         match *ty {
197             AllocatorTy::Layout => {
198                 let usize = self.cx.path_ident(self.span, Ident::from_str("usize"));
199                 let ty_usize = self.cx.ty_path(usize);
200                 let size = ident();
201                 let align = ident();
202                 args.push(self.cx.arg(self.span, size, ty_usize.clone()));
203                 args.push(self.cx.arg(self.span, align, ty_usize));
204
205                 let layout_new = self.cx.path(self.span, vec![
206                     self.core,
207                     Ident::from_str("alloc"),
208                     Ident::from_str("Layout"),
209                     Ident::from_str("from_size_align_unchecked"),
210                 ]);
211                 let layout_new = self.cx.expr_path(layout_new);
212                 let size = self.cx.expr_ident(self.span, size);
213                 let align = self.cx.expr_ident(self.span, align);
214                 let layout = self.cx.expr_call(self.span,
215                                                layout_new,
216                                                vec![size, align]);
217                 layout
218             }
219
220             AllocatorTy::Ptr => {
221                 let ident = ident();
222                 args.push(self.cx.arg(self.span, ident, self.ptr_u8()));
223                 let arg = self.cx.expr_ident(self.span, ident);
224                 self.cx.expr_cast(self.span, arg, self.ptr_opaque())
225             }
226
227             AllocatorTy::Usize => {
228                 let ident = ident();
229                 args.push(self.cx.arg(self.span, ident, self.usize()));
230                 self.cx.expr_ident(self.span, ident)
231             }
232
233             AllocatorTy::ResultPtr |
234             AllocatorTy::Bang |
235             AllocatorTy::Unit => {
236                 panic!("can't convert AllocatorTy to an argument")
237             }
238         }
239     }
240
241     fn ret_ty(&self, ty: &AllocatorTy, expr: P<Expr>) -> (P<Ty>, P<Expr>) {
242         match *ty {
243             AllocatorTy::ResultPtr => {
244                 // We're creating:
245                 //
246                 //      #expr as *mut u8
247
248                 let expr = self.cx.expr_cast(self.span, expr, self.ptr_u8());
249                 (self.ptr_u8(), expr)
250             }
251
252             AllocatorTy::Bang => {
253                 (self.cx.ty(self.span, TyKind::Never), expr)
254             }
255
256             AllocatorTy::Unit => {
257                 (self.cx.ty(self.span, TyKind::Tup(Vec::new())), expr)
258             }
259
260             AllocatorTy::Layout |
261             AllocatorTy::Usize |
262             AllocatorTy::Ptr => {
263                 panic!("can't convert AllocatorTy to an output")
264             }
265         }
266     }
267
268     fn usize(&self) -> P<Ty> {
269         let usize = self.cx.path_ident(self.span, Ident::from_str("usize"));
270         self.cx.ty_path(usize)
271     }
272
273     fn ptr_u8(&self) -> P<Ty> {
274         let u8 = self.cx.path_ident(self.span, Ident::from_str("u8"));
275         let ty_u8 = self.cx.ty_path(u8);
276         self.cx.ty_ptr(self.span, ty_u8, Mutability::Mutable)
277     }
278
279     fn ptr_opaque(&self) -> P<Ty> {
280         let opaque = self.cx.path(self.span, vec![
281             self.core,
282             Ident::from_str("alloc"),
283             Ident::from_str("Opaque"),
284         ]);
285         let ty_opaque = self.cx.ty_path(opaque);
286         self.cx.ty_ptr(self.span, ty_opaque, Mutability::Mutable)
287     }
288 }