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