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.
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.
11 use rustc::middle::allocator::AllocatorKind;
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};
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;
28 use syntax::symbol::Symbol;
29 use syntax::util::small_vector::SmallVector;
30 use syntax_pos::{Span, DUMMY_SP};
32 use {AllocatorMethod, AllocatorTy, ALLOCATOR_METHODS};
34 pub fn modify(sess: &ParseSess,
35 resolver: &mut Resolver,
37 handler: &rustc_errors::Handler) -> ast::Crate {
38 ExpandAllocatorDirectives {
46 struct ExpandAllocatorDirectives<'a> {
48 handler: &'a rustc_errors::Handler,
50 resolver: &'a mut Resolver,
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") {
58 return fold::noop_fold_item(item, self)
61 ItemKind::Static(..) => {}
63 self.handler.span_err(item.span, "allocators must be statics");
64 return SmallVector::one(item)
69 self.handler.span_err(item.span, "cannot define more than one \
70 #[global_allocator]");
71 return SmallVector::one(item)
75 let mark = Mark::fresh(Mark::root());
76 mark.set_expn_info(ExpnInfo {
79 format: MacroAttribute(Symbol::intern(name)),
81 allow_internal_unstable: true,
82 allow_internal_unsafe: false,
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 {
89 kind: AllocatorKind::Global,
91 core: Ident::from_str("core"),
92 cx: ExtCtxt::new(self.sess, ecfg, self.resolver),
94 let super_path = f.cx.path(f.span, vec![
95 Ident::from_str("super"),
99 f.cx.item_extern_crate(f.span, f.core),
100 f.cx.item_use_simple(
102 respan(f.span.shrink_to_lo(), VisibilityKind::Inherited),
106 for method in ALLOCATOR_METHODS {
107 items.push(f.allocator_fn(method));
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();
114 let mut ret = SmallVector::new();
120 fn fold_mac(&mut self, mac: Mac) -> Mac {
121 fold::noop_fold_mac(mac, self)
125 struct AllocFnFactory<'a> {
133 impl<'a> AllocFnFactory<'a> {
134 fn allocator_fn(&self, method: &AllocatorMethod) -> P<Item> {
135 let mut abi_args = Vec::new();
137 let ref mut mk = || {
138 let name = Ident::from_str(&format!("arg{}", i));
142 let args = method.inputs.iter().map(|ty| {
143 self.arg_ty(ty, &mut abi_args, mk)
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)),
149 dummy_spanned(Constness::NotConst),
152 self.cx.block_expr(output_expr));
153 self.cx.item(self.span,
154 Ident::from_str(&self.kind.fn_name(method.name)),
159 fn call_allocator(&self, method: &str, mut args: Vec<P<Expr>>) -> P<Expr> {
160 let method = self.cx.path(self.span, vec![
162 Ident::from_str("alloc"),
163 Ident::from_str("GlobalAlloc"),
164 Ident::from_str(method),
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);
172 self.cx.expr_call(self.span, method, args)
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);
180 let no_mangle = Symbol::intern("no_mangle");
181 let no_mangle = self.cx.meta_word(self.span, no_mangle);
183 let special = Symbol::intern("rustc_std_internal_symbol");
184 let special = self.cx.meta_word(self.span, special);
186 self.cx.attribute(self.span, linkage),
187 self.cx.attribute(self.span, no_mangle),
188 self.cx.attribute(self.span, special),
195 ident: &mut FnMut() -> Ident) -> P<Expr> {
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);
202 args.push(self.cx.arg(self.span, size, ty_usize.clone()));
203 args.push(self.cx.arg(self.span, align, ty_usize));
205 let layout_new = self.cx.path(self.span, vec![
207 Ident::from_str("alloc"),
208 Ident::from_str("Layout"),
209 Ident::from_str("from_size_align_unchecked"),
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,
220 AllocatorTy::Ptr => {
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())
227 AllocatorTy::Usize => {
229 args.push(self.cx.arg(self.span, ident, self.usize()));
230 self.cx.expr_ident(self.span, ident)
233 AllocatorTy::ResultPtr |
235 AllocatorTy::Unit => {
236 panic!("can't convert AllocatorTy to an argument")
241 fn ret_ty(&self, ty: &AllocatorTy, expr: P<Expr>) -> (P<Ty>, P<Expr>) {
243 AllocatorTy::ResultPtr => {
248 let expr = self.cx.expr_cast(self.span, expr, self.ptr_u8());
249 (self.ptr_u8(), expr)
252 AllocatorTy::Bang => {
253 (self.cx.ty(self.span, TyKind::Never), expr)
256 AllocatorTy::Unit => {
257 (self.cx.ty(self.span, TyKind::Tup(Vec::new())), expr)
260 AllocatorTy::Layout |
262 AllocatorTy::Ptr => {
263 panic!("can't convert AllocatorTy to an output")
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)
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)
279 fn ptr_opaque(&self) -> P<Ty> {
280 let opaque = self.cx.path(self.span, vec![
282 Ident::from_str("alloc"),
283 Ident::from_str("Opaque"),
285 let ty_opaque = self.cx.ty_path(opaque);
286 self.cx.ty_ptr(self.span, ty_opaque, Mutability::Mutable)