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