1use rustc_ast::expand::allocator::{
2 ALLOCATOR_METHODS, AllocatorMethod, AllocatorMethodInput, AllocatorTy, global_fn_name,
3};
4use rustc_ast::{
5 self as ast, AttrVec, Expr, Fn, FnHeader, FnSig, Generics, ItemKind, Mutability, Param, Safety,
6 Stmt, StmtKind, Ty, TyKind,
7};
8use rustc_expand::base::{Annotatable, ExtCtxt};
9use rustc_span::{Ident, Span, Symbol, kw, 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_ty = ecx.ty(ty_span, TyKind::Tup(ThinVec::new()));
57 let const_body = ast::ConstItemRhsKind::new_body(ecx.expr_block(ecx.block(span, stmts)));
58 let const_item = ecx.item_const(span, Ident::new(kw::Underscore, span), const_ty, const_body);
59 let const_item = if is_stmt {
60 Annotatable::Stmt(Box::new(ecx.stmt_item(span, const_item)))
61 } else {
62 Annotatable::Item(const_item)
63 };
64
65 ::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]
67}
68
69struct AllocFnFactory<'a, 'b> {
70 span: Span,
71 ty_span: Span,
72 global: Ident,
73 cx: &'a ExtCtxt<'b>,
74}
75
76impl AllocFnFactory<'_, '_> {
77 fn allocator_fn(&self, method: &AllocatorMethod) -> Stmt {
78 let mut abi_args = ThinVec::new();
79 let args = method.inputs.iter().map(|input| self.arg_ty(input, &mut abi_args)).collect();
80 let result = self.call_allocator(method.name, args);
81 let output_ty = self.ret_ty(&method.output);
82 let decl = self.cx.fn_decl(abi_args, ast::FnRetTy::Ty(output_ty));
83 let header = FnHeader { safety: Safety::Unsafe(self.span), ..FnHeader::default() };
84 let sig = FnSig { decl, header, span: self.span };
85 let body = Some(self.cx.block_expr(result));
86 let kind = ItemKind::Fn(Box::new(Fn {
87 defaultness: ast::Defaultness::Implicit,
88 sig,
89 ident: Ident::from_str_and_span(&global_fn_name(method.name), self.span),
90 generics: Generics::default(),
91 contract: None,
92 body,
93 define_opaque: None,
94 eii_impls: ThinVec::new(),
95 }));
96 let item = self.cx.item(self.span, self.attrs(method), kind);
97 self.cx.stmt_item(self.ty_span, item)
98 }
99
100 fn call_allocator(&self, method: Symbol, mut args: ThinVec<Box<Expr>>) -> Box<Expr> {
101 let method = self.cx.std_path(&[sym::alloc, sym::GlobalAlloc, method]);
102 let method = self.cx.expr_path(self.cx.path(self.ty_span, method));
103 let allocator = self.cx.path_ident(self.ty_span, self.global);
104 let allocator = self.cx.expr_path(allocator);
105 let allocator = self.cx.expr_addr_of(self.ty_span, allocator);
106 args.insert(0, allocator);
107
108 self.cx.expr_call(self.ty_span, method, args)
109 }
110
111 fn attrs(&self, method: &AllocatorMethod) -> AttrVec {
112 let alloc_attr = match method.name {
113 sym::alloc => sym::rustc_allocator,
114 sym::dealloc => sym::rustc_deallocator,
115 sym::realloc => sym::rustc_reallocator,
116 sym::alloc_zeroed => sym::rustc_allocator_zeroed,
117 _ => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("Unknown allocator method!")));
}unreachable!("Unknown allocator method!"),
118 };
119 {
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![
120 self.cx.attr_word(sym::rustc_std_internal_symbol, self.span),
121 self.cx.attr_word(alloc_attr, self.span)
122 ]
123 }
124
125 fn arg_ty(&self, input: &AllocatorMethodInput, args: &mut ThinVec<Param>) -> Box<Expr> {
126 match input.ty {
127 AllocatorTy::Layout => {
128 let size = Ident::from_str_and_span("size", self.span);
134 let align = Ident::from_str_and_span("align", self.span);
135
136 let usize = self.cx.path_ident(self.span, Ident::new(sym::usize, self.span));
137 let ty_usize = self.cx.ty_path(usize);
138 args.push(self.cx.param(self.span, size, ty_usize));
139 let ty_align = self.ptr_alignment();
140 args.push(self.cx.param(self.span, align, ty_align));
141
142 let layout_new = self.cx.std_path(&[
143 sym::alloc,
144 sym::Layout,
145 sym::from_size_alignment_unchecked,
146 ]);
147 let layout_new = self.cx.expr_path(self.cx.path(self.span, layout_new));
148 let size = self.cx.expr_ident(self.span, size);
149 let align = self.cx.expr_ident(self.span, align);
150 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]);
151 layout
152 }
153
154 AllocatorTy::Ptr => {
155 let ident = Ident::from_str_and_span(input.name, self.span);
156 args.push(self.cx.param(self.span, ident, self.ptr_u8()));
157 self.cx.expr_ident(self.span, ident)
158 }
159
160 AllocatorTy::Usize => {
161 let ident = Ident::from_str_and_span(input.name, self.span);
162 args.push(self.cx.param(self.span, ident, self.usize()));
163 self.cx.expr_ident(self.span, ident)
164 }
165
166 AllocatorTy::Never | AllocatorTy::ResultPtr | AllocatorTy::Unit => {
167 {
::core::panicking::panic_fmt(format_args!("can\'t convert AllocatorTy to an argument"));
}panic!("can't convert AllocatorTy to an argument")
168 }
169 }
170 }
171
172 fn ret_ty(&self, ty: &AllocatorTy) -> Box<Ty> {
173 match *ty {
174 AllocatorTy::ResultPtr => self.ptr_u8(),
175
176 AllocatorTy::Unit => self.cx.ty(self.span, TyKind::Tup(ThinVec::new())),
177
178 AllocatorTy::Layout | AllocatorTy::Never | AllocatorTy::Usize | AllocatorTy::Ptr => {
179 {
::core::panicking::panic_fmt(format_args!("can\'t convert `AllocatorTy` to an output"));
}panic!("can't convert `AllocatorTy` to an output")
180 }
181 }
182 }
183
184 fn usize(&self) -> Box<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_alignment(&self) -> Box<Ty> {
190 let path = self.cx.std_path(&[sym::mem, sym::Alignment]);
191 let path = self.cx.path(self.span, path);
192 self.cx.ty_path(path)
193 }
194
195 fn ptr_u8(&self) -> Box<Ty> {
196 let u8 = self.cx.path_ident(self.span, Ident::new(sym::u8, self.span));
197 let ty_u8 = self.cx.ty_path(u8);
198 self.cx.ty_ptr(self.span, ty_u8, Mutability::Mut)
199 }
200}