rustc_builtin_macros/
global_allocator.rs

1use rustc_ast::expand::allocator::{
2    ALLOCATOR_METHODS, AllocatorMethod, AllocatorMethodInput, AllocatorTy, global_fn_name,
3};
4use rustc_ast::ptr::P;
5use rustc_ast::{
6    self as ast, AttrVec, Expr, Fn, FnHeader, FnSig, Generics, ItemKind, Mutability, Param, Safety,
7    Stmt, StmtKind, Ty, TyKind,
8};
9use rustc_expand::base::{Annotatable, ExtCtxt};
10use rustc_span::{Ident, Span, Symbol, kw, sym};
11use thin_vec::{ThinVec, thin_vec};
12
13use crate::errors;
14use crate::util::check_builtin_macro_attribute;
15
16pub(crate) fn expand(
17    ecx: &mut ExtCtxt<'_>,
18    _span: Span,
19    meta_item: &ast::MetaItem,
20    item: Annotatable,
21) -> Vec<Annotatable> {
22    check_builtin_macro_attribute(ecx, meta_item, sym::global_allocator);
23
24    let orig_item = item.clone();
25
26    // Allow using `#[global_allocator]` on an item statement
27    // FIXME - if we get deref patterns, use them to reduce duplication here
28    let (item, is_stmt, ty_span) = if let Annotatable::Item(item) = &item
29        && let ItemKind::Static(box ast::StaticItem { ty, .. }) = &item.kind
30    {
31        (item, false, ecx.with_def_site_ctxt(ty.span))
32    } else if let Annotatable::Stmt(stmt) = &item
33        && let StmtKind::Item(item) = &stmt.kind
34        && let ItemKind::Static(box ast::StaticItem { ty, .. }) = &item.kind
35    {
36        (item, true, ecx.with_def_site_ctxt(ty.span))
37    } else {
38        ecx.dcx().emit_err(errors::AllocMustStatics { span: item.span() });
39        return vec![orig_item];
40    };
41
42    // Generate a bunch of new items using the AllocFnFactory
43    let span = ecx.with_def_site_ctxt(item.span);
44    let f = AllocFnFactory { span, ty_span, 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(ThinVec::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
63struct AllocFnFactory<'a, 'b> {
64    span: Span,
65    ty_span: Span,
66    global: Ident,
67    cx: &'a ExtCtxt<'b>,
68}
69
70impl AllocFnFactory<'_, '_> {
71    fn allocator_fn(&self, method: &AllocatorMethod) -> Stmt {
72        let mut abi_args = ThinVec::new();
73        let args = method.inputs.iter().map(|input| self.arg_ty(input, &mut abi_args)).collect();
74        let result = self.call_allocator(method.name, args);
75        let output_ty = self.ret_ty(&method.output);
76        let decl = self.cx.fn_decl(abi_args, ast::FnRetTy::Ty(output_ty));
77        let header = FnHeader { safety: Safety::Unsafe(self.span), ..FnHeader::default() };
78        let sig = FnSig { decl, header, span: self.span };
79        let body = Some(self.cx.block_expr(result));
80        let kind = ItemKind::Fn(Box::new(Fn {
81            defaultness: ast::Defaultness::Final,
82            sig,
83            generics: Generics::default(),
84            contract: None,
85            body,
86            define_opaque: None,
87        }));
88        let item = self.cx.item(
89            self.span,
90            Ident::from_str_and_span(&global_fn_name(method.name), self.span),
91            self.attrs(),
92            kind,
93        );
94        self.cx.stmt_item(self.ty_span, item)
95    }
96
97    fn call_allocator(&self, method: Symbol, mut args: ThinVec<P<Expr>>) -> P<Expr> {
98        let method = self.cx.std_path(&[sym::alloc, sym::GlobalAlloc, method]);
99        let method = self.cx.expr_path(self.cx.path(self.ty_span, method));
100        let allocator = self.cx.path_ident(self.ty_span, self.global);
101        let allocator = self.cx.expr_path(allocator);
102        let allocator = self.cx.expr_addr_of(self.ty_span, allocator);
103        args.insert(0, allocator);
104
105        self.cx.expr_call(self.ty_span, method, args)
106    }
107
108    fn attrs(&self) -> AttrVec {
109        thin_vec![self.cx.attr_word(sym::rustc_std_internal_symbol, self.span)]
110    }
111
112    fn arg_ty(&self, input: &AllocatorMethodInput, args: &mut ThinVec<Param>) -> P<Expr> {
113        match input.ty {
114            AllocatorTy::Layout => {
115                // If an allocator method is ever introduced having multiple
116                // Layout arguments, these argument names need to be
117                // disambiguated somehow. Currently the generated code would
118                // fail to compile with "identifier is bound more than once in
119                // this parameter list".
120                let size = Ident::from_str_and_span("size", self.span);
121                let align = Ident::from_str_and_span("align", self.span);
122
123                let usize = self.cx.path_ident(self.span, Ident::new(sym::usize, self.span));
124                let ty_usize = self.cx.ty_path(usize);
125                args.push(self.cx.param(self.span, size, ty_usize.clone()));
126                args.push(self.cx.param(self.span, align, ty_usize));
127
128                let layout_new =
129                    self.cx.std_path(&[sym::alloc, sym::Layout, sym::from_size_align_unchecked]);
130                let layout_new = self.cx.expr_path(self.cx.path(self.span, layout_new));
131                let size = self.cx.expr_ident(self.span, size);
132                let align = self.cx.expr_ident(self.span, align);
133                let layout = self.cx.expr_call(self.span, layout_new, thin_vec![size, align]);
134                layout
135            }
136
137            AllocatorTy::Ptr => {
138                let ident = Ident::from_str_and_span(input.name, self.span);
139                args.push(self.cx.param(self.span, ident, self.ptr_u8()));
140                self.cx.expr_ident(self.span, ident)
141            }
142
143            AllocatorTy::Usize => {
144                let ident = Ident::from_str_and_span(input.name, self.span);
145                args.push(self.cx.param(self.span, ident, self.usize()));
146                self.cx.expr_ident(self.span, ident)
147            }
148
149            AllocatorTy::ResultPtr | AllocatorTy::Unit => {
150                panic!("can't convert AllocatorTy to an argument")
151            }
152        }
153    }
154
155    fn ret_ty(&self, ty: &AllocatorTy) -> P<Ty> {
156        match *ty {
157            AllocatorTy::ResultPtr => self.ptr_u8(),
158
159            AllocatorTy::Unit => self.cx.ty(self.span, TyKind::Tup(ThinVec::new())),
160
161            AllocatorTy::Layout | AllocatorTy::Usize | AllocatorTy::Ptr => {
162                panic!("can't convert `AllocatorTy` to an output")
163            }
164        }
165    }
166
167    fn usize(&self) -> P<Ty> {
168        let usize = self.cx.path_ident(self.span, Ident::new(sym::usize, self.span));
169        self.cx.ty_path(usize)
170    }
171
172    fn ptr_u8(&self) -> P<Ty> {
173        let u8 = self.cx.path_ident(self.span, Ident::new(sym::u8, self.span));
174        let ty_u8 = self.cx.ty_path(u8);
175        self.cx.ty_ptr(self.span, ty_u8, Mutability::Mut)
176    }
177}