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