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