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