2 use rustc::middle::allocator::AllocatorKind;
3 use smallvec::{smallvec, SmallVec};
6 self, Arg, Attribute, Crate, Expr, FnHeader, Generics, Ident, Item, ItemKind,
7 Mac, Mod, Mutability, Ty, TyKind, Unsafety, VisibilityKind,
11 respan, ExpnInfo, MacroAttribute,
14 base::{ExtCtxt, Resolver},
16 expand::ExpansionConfig,
17 hygiene::{Mark, SyntaxContext},
19 mut_visit::{self, MutVisitor},
22 symbol::{kw, sym, Symbol}
26 use crate::{AllocatorMethod, AllocatorTy, ALLOCATOR_METHODS};
30 resolver: &mut dyn Resolver,
33 handler: &rustc_errors::Handler,
35 ExpandAllocatorDirectives {
40 crate_name: Some(crate_name),
41 in_submod: -1, // -1 to account for the "root" module
45 struct ExpandAllocatorDirectives<'a> {
47 handler: &'a rustc_errors::Handler,
49 resolver: &'a mut dyn Resolver,
50 crate_name: Option<String>,
52 // For now, we disallow `global_allocator` in submodules because hygiene is hard. Keep track of
53 // whether we are in a submodule or not. If `in_submod > 0` we are in a submodule.
57 impl MutVisitor for ExpandAllocatorDirectives<'_> {
58 fn flat_map_item(&mut self, item: P<Item>) -> SmallVec<[P<Item>; 1]> {
59 debug!("in submodule {}", self.in_submod);
61 let name = if attr::contains_name(&item.attrs, sym::global_allocator) {
64 return mut_visit::noop_flat_map_item(item, self);
67 ItemKind::Static(..) => {}
70 .span_err(item.span, "allocators must be statics");
71 return smallvec![item];
75 if self.in_submod > 0 {
77 .span_err(item.span, "`global_allocator` cannot be used in submodules");
78 return smallvec![item];
83 .span_err(item.span, "cannot define more than one #[global_allocator]");
84 return smallvec![item];
88 // Create a fresh Mark for the new macro expansion we are about to do
89 let mark = Mark::fresh(Mark::root());
90 mark.set_expn_info(ExpnInfo {
91 call_site: item.span, // use the call site of the static
93 format: MacroAttribute(Symbol::intern(name)),
94 allow_internal_unstable: Some(vec![
95 Symbol::intern("rustc_attrs"),
97 allow_internal_unsafe: false,
98 local_inner_macros: false,
99 edition: self.sess.edition,
102 // Tie the span to the macro expansion info we just created
103 let span = item.span.with_ctxt(SyntaxContext::empty().apply_mark(mark));
105 // Create an expansion config
106 let ecfg = ExpansionConfig::default(self.crate_name.take().unwrap());
108 // Generate a bunch of new items using the AllocFnFactory
109 let mut f = AllocFnFactory {
111 kind: AllocatorKind::Global,
113 core: Ident::with_empty_ctxt(sym::core),
114 cx: ExtCtxt::new(self.sess, ecfg, self.resolver),
117 // We will generate a new submodule. To `use` the static from that module, we need to get
118 // the `super::...` path.
119 let super_path = f.cx.path(f.span, vec![Ident::with_empty_ctxt(kw::Super), f.global]);
121 // Generate the items in the submodule
122 let mut items = vec![
123 // import `core` to use allocators
124 f.cx.item_extern_crate(f.span, f.core),
125 // `use` the `global_allocator` in `super`
126 f.cx.item_use_simple(
128 respan(f.span.shrink_to_lo(), VisibilityKind::Inherited),
133 // Add the allocator methods to the submodule
137 .map(|method| f.allocator_fn(method)),
140 // Generate the submodule itself
141 let name = f.kind.fn_name("allocator_abi");
142 let allocator_abi = Ident::from_str(&name).gensym();
143 let module = f.cx.item_mod(span, span, allocator_abi, Vec::new(), items);
144 let module = f.cx.monotonic_expander().flat_map_item(module).pop().unwrap();
146 // Return the item and new submodule
147 smallvec![item, module]
150 // If we enter a submodule, take note.
151 fn visit_mod(&mut self, m: &mut Mod) {
152 debug!("enter submodule");
154 mut_visit::noop_visit_mod(m, self);
156 debug!("exit submodule");
159 // `visit_mac` is disabled by default. Enable it here.
160 fn visit_mac(&mut self, mac: &mut Mac) {
161 mut_visit::noop_visit_mac(mac, self)
165 struct AllocFnFactory<'a> {
173 impl AllocFnFactory<'_> {
174 fn allocator_fn(&self, method: &AllocatorMethod) -> P<Item> {
175 let mut abi_args = Vec::new();
177 let ref mut mk = || {
178 let name = Ident::from_str(&format!("arg{}", i));
185 .map(|ty| self.arg_ty(ty, &mut abi_args, mk))
187 let result = self.call_allocator(method.name, args);
188 let (output_ty, output_expr) = self.ret_ty(&method.output, result);
189 let kind = ItemKind::Fn(
190 self.cx.fn_decl(abi_args, ast::FunctionRetTy::Ty(output_ty)),
192 unsafety: Unsafety::Unsafe,
193 ..FnHeader::default()
196 self.cx.block_expr(output_expr),
200 Ident::from_str(&self.kind.fn_name(method.name)),
206 fn call_allocator(&self, method: &str, mut args: Vec<P<Expr>>) -> P<Expr> {
207 let method = self.cx.path(
211 Ident::from_str("alloc"),
212 Ident::from_str("GlobalAlloc"),
213 Ident::from_str(method),
216 let method = self.cx.expr_path(method);
217 let allocator = self.cx.path_ident(self.span, self.global);
218 let allocator = self.cx.expr_path(allocator);
219 let allocator = self.cx.expr_addr_of(self.span, allocator);
220 args.insert(0, allocator);
222 self.cx.expr_call(self.span, method, args)
225 fn attrs(&self) -> Vec<Attribute> {
226 let special = Symbol::intern("rustc_std_internal_symbol");
227 let special = self.cx.meta_word(self.span, special);
228 vec![self.cx.attribute(self.span, special)]
235 ident: &mut dyn FnMut() -> Ident,
238 AllocatorTy::Layout => {
239 let usize = self.cx.path_ident(self.span, Ident::with_empty_ctxt(sym::usize));
240 let ty_usize = self.cx.ty_path(usize);
243 args.push(self.cx.arg(self.span, size, ty_usize.clone()));
244 args.push(self.cx.arg(self.span, align, ty_usize));
246 let layout_new = self.cx.path(
250 Ident::from_str("alloc"),
251 Ident::from_str("Layout"),
252 Ident::from_str("from_size_align_unchecked"),
255 let layout_new = self.cx.expr_path(layout_new);
256 let size = self.cx.expr_ident(self.span, size);
257 let align = self.cx.expr_ident(self.span, align);
258 let layout = self.cx.expr_call(self.span, layout_new, vec![size, align]);
262 AllocatorTy::Ptr => {
264 args.push(self.cx.arg(self.span, ident, self.ptr_u8()));
265 let arg = self.cx.expr_ident(self.span, ident);
266 self.cx.expr_cast(self.span, arg, self.ptr_u8())
269 AllocatorTy::Usize => {
271 args.push(self.cx.arg(self.span, ident, self.usize()));
272 self.cx.expr_ident(self.span, ident)
275 AllocatorTy::ResultPtr | AllocatorTy::Unit => {
276 panic!("can't convert AllocatorTy to an argument")
281 fn ret_ty(&self, ty: &AllocatorTy, expr: P<Expr>) -> (P<Ty>, P<Expr>) {
283 AllocatorTy::ResultPtr => {
288 let expr = self.cx.expr_cast(self.span, expr, self.ptr_u8());
289 (self.ptr_u8(), expr)
292 AllocatorTy::Unit => (self.cx.ty(self.span, TyKind::Tup(Vec::new())), expr),
294 AllocatorTy::Layout | AllocatorTy::Usize | AllocatorTy::Ptr => {
295 panic!("can't convert AllocatorTy to an output")
300 fn usize(&self) -> P<Ty> {
301 let usize = self.cx.path_ident(self.span, Ident::with_empty_ctxt(sym::usize));
302 self.cx.ty_path(usize)
305 fn ptr_u8(&self) -> P<Ty> {
306 let u8 = self.cx.path_ident(self.span, Ident::with_empty_ctxt(sym::u8));
307 let ty_u8 = self.cx.ty_path(u8);
308 self.cx.ty_ptr(self.span, ty_u8, Mutability::Mutable)