1use rustc_ast::expand::allocator::{
2 ALLOCATOR_METHODS, AllocatorMethod, AllocatorMethodInput, AllocatorTy, global_fn_name,
3};
4use rustc_ast::{
5 self as ast, AttrVec, Expr, FnHeader, FnSig, Generics, ItemKind, Mutability, Param, Safety,
6 Stmt, StmtKind, Ty,
7};
8use rustc_expand::base::{Annotatable, ExtCtxt};
9use rustc_span::{Ident, Span, Symbol, sym};
10use thin_vec::{ThinVec, thin_vec};
11
12use crate::diagnostics;
13use crate::util::check_builtin_macro_attribute;
14
15pub(crate) fn expand(
16 ecx: &mut ExtCtxt<'_>,
17 _span: Span,
18 meta_item: &ast::MetaItem,
19 item: Annotatable,
20) -> Vec<Annotatable> {
21 check_builtin_macro_attribute(ecx, meta_item, sym::global_allocator);
22
23 let orig_item = item.clone();
24
25 let (item, ident, is_stmt, ty_span) = if let Annotatable::Item(item) = &item
28 && let ItemKind::Static(ast::StaticItem { ident, ty, .. }) = &item.kind
29 {
30 (item, *ident, 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(ast::StaticItem { ident, ty, .. }) = &item.kind
34 {
35 (item, *ident, true, ecx.with_def_site_ctxt(ty.span))
36 } else {
37 ecx.dcx().emit_err(diagnostics::AllocMustStatics { span: item.span() });
38 return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[orig_item]))vec![orig_item];
39 };
40
41 if let Some(attr) = item.attrs.iter().find(|x| x.has_name(sym::thread_local)) {
43 ecx.dcx()
44 .emit_err(diagnostics::AllocCannotThreadLocal { span: item.span, attr: attr.span });
45 return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[orig_item]))vec![orig_item];
46 }
47
48 let span = ecx.with_def_site_ctxt(item.span);
50 let f = AllocFnFactory { span, ty_span, global: ident, cx: ecx };
51
52 let stmts = ALLOCATOR_METHODS.iter().map(|method| f.allocator_fn(method)).collect();
54
55 let const_item = ecx.item_const_underscore(span, ecx.block(span, stmts));
57 let const_item = if is_stmt {
58 Annotatable::Stmt(Box::new(ecx.stmt_item(span, const_item)))
59 } else {
60 Annotatable::Item(const_item)
61 };
62
63 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[orig_item, const_item]))vec![orig_item, const_item]
65}
66
67struct AllocFnFactory<'a, 'b> {
68 span: Span,
69 ty_span: Span,
70 global: Ident,
71 cx: &'a ExtCtxt<'b>,
72}
73
74impl AllocFnFactory<'_, '_> {
75 fn allocator_fn(&self, method: &AllocatorMethod) -> Stmt {
76 let mut abi_args = ThinVec::new();
77 let args = method.inputs.iter().map(|input| self.arg_ty(input, &mut abi_args)).collect();
78 let result = self.call_allocator(method.name, args);
79 let output_ty = self.ret_ty(&method.output);
80 let decl = self.cx.fn_decl(abi_args, ast::FnRetTy::Ty(output_ty));
81 let header = FnHeader { safety: Safety::Unsafe(self.span), ..FnHeader::default() };
82 let sig = FnSig { decl, header, span: self.span };
83 let body = Some(self.cx.block_expr(result));
84 let kind = ItemKind::Fn(self.cx.item_fn(
85 sig,
86 Ident::from_str_and_span(&global_fn_name(method.name), self.span),
87 Generics::default(),
88 body,
89 ));
90 let item = self.cx.item(self.span, self.attrs(method), kind);
91 self.cx.stmt_item(self.ty_span, item)
92 }
93
94 fn call_allocator(&self, method: Symbol, mut args: ThinVec<Box<Expr>>) -> Box<Expr> {
95 let method = self.cx.std_path(self.ty_span, &[sym::alloc, sym::GlobalAlloc, method]);
96 let method = self.cx.expr_path(method);
97 let allocator = self.cx.path_ident(self.ty_span, self.global);
98 let allocator = self.cx.expr_path(allocator);
99 let allocator = self.cx.expr_addr_of(self.ty_span, allocator);
100 args.insert(0, allocator);
101
102 self.cx.expr_call(self.ty_span, method, args)
103 }
104
105 fn attrs(&self, method: &AllocatorMethod) -> AttrVec {
106 let alloc_attr = match method.name {
107 sym::alloc => sym::rustc_allocator,
108 sym::dealloc => sym::rustc_deallocator,
109 sym::realloc => sym::rustc_reallocator,
110 sym::alloc_zeroed => sym::rustc_allocator_zeroed,
111 _ => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("Unknown allocator method!")));
}unreachable!("Unknown allocator method!"),
112 };
113 {
let len = [(), ()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(self.cx.attr_word(sym::rustc_std_internal_symbol, self.span));
vec.push(self.cx.attr_word(alloc_attr, self.span));
vec
}thin_vec![
114 self.cx.attr_word(sym::rustc_std_internal_symbol, self.span),
115 self.cx.attr_word(alloc_attr, self.span)
116 ]
117 }
118
119 fn arg_ty(&self, input: &AllocatorMethodInput, args: &mut ThinVec<Param>) -> Box<Expr> {
120 match input.ty {
121 AllocatorTy::Layout => {
122 let ty_usize = self.usize();
129 args.push(self.cx.param(self.span, sym::size, ty_usize));
130 let ty_align = self.ptr_alignment();
131 args.push(self.cx.param(self.span, sym::align, ty_align));
132
133 let layout_new = self.cx.std_path(
134 self.span,
135 &[sym::alloc, sym::Layout, sym::from_size_alignment_unchecked],
136 );
137 let layout_new = self.cx.expr_path(layout_new);
138 let size = self.cx.expr_name(self.span, sym::size);
139 let align = self.cx.expr_name(self.span, sym::align);
140 let layout = self.cx.expr_call(self.span, layout_new, {
let len = [(), ()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(size);
vec.push(align);
vec
}thin_vec![size, align]);
141 layout
142 }
143
144 AllocatorTy::Ptr => {
145 let name = Symbol::intern(input.name);
146 args.push(self.cx.param(self.span, name, self.ptr_u8()));
147 self.cx.expr_name(self.span, name)
148 }
149
150 AllocatorTy::Usize => {
151 let name = Symbol::intern(input.name);
152 args.push(self.cx.param(self.span, name, self.usize()));
153 self.cx.expr_name(self.span, name)
154 }
155
156 AllocatorTy::Never | AllocatorTy::ResultPtr | AllocatorTy::Unit => {
157 {
::core::panicking::panic_fmt(format_args!("can\'t convert AllocatorTy to an argument"));
}panic!("can't convert AllocatorTy to an argument")
158 }
159 }
160 }
161
162 fn ret_ty(&self, ty: &AllocatorTy) -> Box<Ty> {
163 match *ty {
164 AllocatorTy::ResultPtr => self.ptr_u8(),
165
166 AllocatorTy::Unit => self.cx.ty_unit(self.span),
167
168 AllocatorTy::Layout | AllocatorTy::Never | AllocatorTy::Usize | AllocatorTy::Ptr => {
169 {
::core::panicking::panic_fmt(format_args!("can\'t convert `AllocatorTy` to an output"));
}panic!("can't convert `AllocatorTy` to an output")
170 }
171 }
172 }
173
174 fn usize(&self) -> Box<Ty> {
175 self.cx.ty_name(self.span, sym::usize)
176 }
177
178 fn ptr_alignment(&self) -> Box<Ty> {
179 let path = self.cx.std_path(self.span, &[sym::mem, sym::Alignment]);
180 self.cx.ty_path(path)
181 }
182
183 fn ptr_u8(&self) -> Box<Ty> {
184 let ty_u8 = self.cx.ty_name(self.span, sym::u8);
185 self.cx.ty_ptr(self.span, ty_u8, Mutability::Mut)
186 }
187}