]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/global_allocator.rs
Rollup merge of #65994 - estebank:where-bound, r=nikomatsakis
[rust.git] / src / libsyntax_ext / global_allocator.rs
1 use crate::util::check_builtin_macro_attribute;
2
3 use syntax::ast::{ItemKind, Mutability, Stmt, Ty, TyKind, Unsafety};
4 use syntax::ast::{self, Param, Attribute, Expr, FnSig, FnHeader, Generics, Ident};
5 use syntax::expand::allocator::{AllocatorKind, AllocatorMethod, AllocatorTy, ALLOCATOR_METHODS};
6 use syntax::ptr::P;
7 use syntax::symbol::{kw, sym, Symbol};
8 use syntax_expand::base::{Annotatable, ExtCtxt};
9 use syntax_pos::Span;
10
11 pub fn expand(
12     ecx: &mut ExtCtxt<'_>,
13     _span: Span,
14     meta_item: &ast::MetaItem,
15     item: Annotatable,
16 ) -> Vec<Annotatable> {
17     check_builtin_macro_attribute(ecx, meta_item, sym::global_allocator);
18
19     let not_static = |item: Annotatable| {
20         ecx.parse_sess.span_diagnostic.span_err(item.span(), "allocators must be statics");
21         vec![item]
22     };
23     let item = match item {
24         Annotatable::Item(item) => match item.kind {
25             ItemKind::Static(..) => item,
26             _ => return not_static(Annotatable::Item(item)),
27         }
28         _ => return not_static(item),
29     };
30
31     // Generate a bunch of new items using the AllocFnFactory
32     let span = ecx.with_def_site_ctxt(item.span);
33     let f = AllocFnFactory {
34         span,
35         kind: AllocatorKind::Global,
36         global: item.ident,
37         cx: ecx,
38     };
39
40     // Generate item statements for the allocator methods.
41     let stmts = ALLOCATOR_METHODS.iter().map(|method| f.allocator_fn(method)).collect();
42
43     // Generate anonymous constant serving as container for the allocator methods.
44     let const_ty = ecx.ty(span, TyKind::Tup(Vec::new()));
45     let const_body = ecx.expr_block(ecx.block(span, stmts));
46     let const_item =
47         ecx.item_const(span, Ident::new(kw::Underscore, span), const_ty, const_body);
48
49     // Return the original item and the new methods.
50     vec![Annotatable::Item(item), Annotatable::Item(const_item)]
51 }
52
53 struct AllocFnFactory<'a, 'b> {
54     span: Span,
55     kind: AllocatorKind,
56     global: Ident,
57     cx: &'b ExtCtxt<'a>,
58 }
59
60 impl AllocFnFactory<'_, '_> {
61     fn allocator_fn(&self, method: &AllocatorMethod) -> Stmt {
62         let mut abi_args = Vec::new();
63         let mut i = 0;
64         let ref mut mk = || {
65             let name = self.cx.ident_of(&format!("arg{}", i), self.span);
66             i += 1;
67             name
68         };
69         let args = method
70             .inputs
71             .iter()
72             .map(|ty| self.arg_ty(ty, &mut abi_args, mk))
73             .collect();
74         let result = self.call_allocator(method.name, args);
75         let (output_ty, output_expr) = self.ret_ty(&method.output, result);
76         let decl = self.cx.fn_decl(abi_args, ast::FunctionRetTy::Ty(output_ty));
77         let header = FnHeader { unsafety: Unsafety::Unsafe, ..FnHeader::default() };
78         let sig = FnSig { decl, header };
79         let kind = ItemKind::Fn(sig, Generics::default(), self.cx.block_expr(output_expr));
80         let item = self.cx.item(
81             self.span,
82             self.cx.ident_of(&self.kind.fn_name(method.name), self.span),
83             self.attrs(),
84             kind,
85         );
86         self.cx.stmt_item(self.span, item)
87     }
88
89     fn call_allocator(&self, method: &str, mut args: Vec<P<Expr>>) -> P<Expr> {
90         let method = self.cx.std_path(&[
91             Symbol::intern("alloc"),
92             Symbol::intern("GlobalAlloc"),
93             Symbol::intern(method),
94         ]);
95         let method = self.cx.expr_path(self.cx.path(self.span, method));
96         let allocator = self.cx.path_ident(self.span, self.global);
97         let allocator = self.cx.expr_path(allocator);
98         let allocator = self.cx.expr_addr_of(self.span, allocator);
99         args.insert(0, allocator);
100
101         self.cx.expr_call(self.span, method, args)
102     }
103
104     fn attrs(&self) -> Vec<Attribute> {
105         let special = sym::rustc_std_internal_symbol;
106         let special = self.cx.meta_word(self.span, special);
107         vec![self.cx.attribute(special)]
108     }
109
110     fn arg_ty(
111         &self,
112         ty: &AllocatorTy,
113         args: &mut Vec<Param>,
114         ident: &mut dyn FnMut() -> Ident,
115     ) -> P<Expr> {
116         match *ty {
117             AllocatorTy::Layout => {
118                 let usize = self.cx.path_ident(self.span, Ident::new(sym::usize, self.span));
119                 let ty_usize = self.cx.ty_path(usize);
120                 let size = ident();
121                 let align = ident();
122                 args.push(self.cx.param(self.span, size, ty_usize.clone()));
123                 args.push(self.cx.param(self.span, align, ty_usize));
124
125                 let layout_new = self.cx.std_path(&[
126                     Symbol::intern("alloc"),
127                     Symbol::intern("Layout"),
128                     Symbol::intern("from_size_align_unchecked"),
129                 ]);
130                 let layout_new = self.cx.expr_path(self.cx.path(self.span, layout_new));
131                 let size = self.cx.expr_ident(self.span, size);
132                 let align = self.cx.expr_ident(self.span, align);
133                 let layout = self.cx.expr_call(self.span, layout_new, vec![size, align]);
134                 layout
135             }
136
137             AllocatorTy::Ptr => {
138                 let ident = ident();
139                 args.push(self.cx.param(self.span, ident, self.ptr_u8()));
140                 let arg = self.cx.expr_ident(self.span, ident);
141                 self.cx.expr_cast(self.span, arg, self.ptr_u8())
142             }
143
144             AllocatorTy::Usize => {
145                 let ident = ident();
146                 args.push(self.cx.param(self.span, ident, self.usize()));
147                 self.cx.expr_ident(self.span, ident)
148             }
149
150             AllocatorTy::ResultPtr | AllocatorTy::Unit => {
151                 panic!("can't convert AllocatorTy to an argument")
152             }
153         }
154     }
155
156     fn ret_ty(&self, ty: &AllocatorTy, expr: P<Expr>) -> (P<Ty>, P<Expr>) {
157         match *ty {
158             AllocatorTy::ResultPtr => {
159                 // We're creating:
160                 //
161                 //      #expr as *mut u8
162
163                 let expr = self.cx.expr_cast(self.span, expr, self.ptr_u8());
164                 (self.ptr_u8(), expr)
165             }
166
167             AllocatorTy::Unit => (self.cx.ty(self.span, TyKind::Tup(Vec::new())), expr),
168
169             AllocatorTy::Layout | AllocatorTy::Usize | AllocatorTy::Ptr => {
170                 panic!("can't convert `AllocatorTy` to an output")
171             }
172         }
173     }
174
175     fn usize(&self) -> P<Ty> {
176         let usize = self.cx.path_ident(self.span, Ident::new(sym::usize, self.span));
177         self.cx.ty_path(usize)
178     }
179
180     fn ptr_u8(&self) -> P<Ty> {
181         let u8 = self.cx.path_ident(self.span, Ident::new(sym::u8, self.span));
182         let ty_u8 = self.cx.ty_path(u8);
183         self.cx.ty_ptr(self.span, ty_u8, Mutability::Mutable)
184     }
185 }