1 use crate::util::check_builtin_macro_attribute;
3 use rustc_ast::expand::allocator::{
4 AllocatorKind, AllocatorMethod, AllocatorTy, ALLOCATOR_METHODS,
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};
12 use thin_vec::thin_vec;
15 ecx: &mut ExtCtxt<'_>,
17 meta_item: &ast::MetaItem,
19 ) -> Vec<Annotatable> {
20 check_builtin_macro_attribute(ecx, meta_item, sym::global_allocator);
22 let orig_item = item.clone();
24 ecx.sess.parse_sess.span_diagnostic.span_err(item.span(), "allocators must be statics");
25 vec![orig_item.clone()]
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(),
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(),
40 _ => return not_static(),
42 _ => return not_static(),
45 // Generate a bunch of new items using the AllocFnFactory
46 let span = ecx.with_def_site_ctxt(item.span);
48 AllocFnFactory { span, ty_span, kind: AllocatorKind::Global, global: item.ident, cx: ecx };
50 // Generate item statements for the allocator methods.
51 let stmts = ALLOCATOR_METHODS.iter().map(|method| f.allocator_fn(method)).collect();
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)))
60 Annotatable::Item(const_item)
63 // Return the original item and the new methods.
64 vec![orig_item, const_item]
67 struct AllocFnFactory<'a, 'b> {
75 impl AllocFnFactory<'_, '_> {
76 fn allocator_fn(&self, method: &AllocatorMethod) -> Stmt {
77 let mut abi_args = Vec::new();
80 let name = Ident::from_str_and_span(&format!("arg{}", i), self.span);
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,
94 generics: Generics::default(),
97 let item = self.cx.item(
99 Ident::from_str_and_span(&self.kind.fn_name(method.name), self.span),
103 self.cx.stmt_item(self.ty_span, item)
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);
114 self.cx.expr_call(self.ty_span, method, args)
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)]
126 args: &mut Vec<Param>,
127 ident: &mut dyn FnMut() -> Ident,
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);
135 args.push(self.cx.param(self.span, size, ty_usize.clone()));
136 args.push(self.cx.param(self.span, align, ty_usize));
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]);
147 AllocatorTy::Ptr => {
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())
154 AllocatorTy::Usize => {
156 args.push(self.cx.param(self.span, ident, self.usize()));
157 self.cx.expr_ident(self.span, ident)
160 AllocatorTy::ResultPtr | AllocatorTy::Unit => {
161 panic!("can't convert AllocatorTy to an argument")
166 fn ret_ty(&self, ty: &AllocatorTy, expr: P<Expr>) -> (P<Ty>, P<Expr>) {
168 AllocatorTy::ResultPtr => {
173 let expr = self.cx.expr_cast(self.span, expr, self.ptr_u8());
174 (self.ptr_u8(), expr)
177 AllocatorTy::Unit => (self.cx.ty(self.span, TyKind::Tup(Vec::new())), expr),
179 AllocatorTy::Layout | AllocatorTy::Usize | AllocatorTy::Ptr => {
180 panic!("can't convert `AllocatorTy` to an output")
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)
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)