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