]> git.lizzy.rs Git - rust.git/blob - src/librustc_builtin_macros/global_allocator.rs
Add 'src/tools/clippy/' from commit 'd2708873ef711ec8ab45df1e984ecf24a96cd369'
[rust.git] / src / librustc_builtin_macros / global_allocator.rs
1 use crate::util::check_builtin_macro_attribute;
2
3 use rustc_ast::ast::{self, Attribute, Expr, FnHeader, FnSig, Generics, Ident, Param};
4 use rustc_ast::ast::{ItemKind, Mutability, Stmt, Ty, TyKind, Unsafe};
5 use rustc_ast::expand::allocator::{
6     AllocatorKind, AllocatorMethod, AllocatorTy, ALLOCATOR_METHODS,
7 };
8 use rustc_ast::ptr::P;
9 use rustc_expand::base::{Annotatable, ExtCtxt};
10 use rustc_span::symbol::{kw, sym, Symbol};
11 use rustc_span::Span;
12
13 pub fn expand(
14     ecx: &mut ExtCtxt<'_>,
15     _span: Span,
16     meta_item: &ast::MetaItem,
17     item: Annotatable,
18 ) -> Vec<Annotatable> {
19     check_builtin_macro_attribute(ecx, meta_item, sym::global_allocator);
20
21     let not_static = |item: Annotatable| {
22         ecx.parse_sess.span_diagnostic.span_err(item.span(), "allocators must be statics");
23         vec![item]
24     };
25     let item = match item {
26         Annotatable::Item(item) => match item.kind {
27             ItemKind::Static(..) => item,
28             _ => return not_static(Annotatable::Item(item)),
29         },
30         _ => return not_static(item),
31     };
32
33     // Generate a bunch of new items using the AllocFnFactory
34     let span = ecx.with_def_site_ctxt(item.span);
35     let f = AllocFnFactory { span, kind: AllocatorKind::Global, global: item.ident, cx: ecx };
36
37     // Generate item statements for the allocator methods.
38     let stmts = ALLOCATOR_METHODS.iter().map(|method| f.allocator_fn(method)).collect();
39
40     // Generate anonymous constant serving as container for the allocator methods.
41     let const_ty = ecx.ty(span, TyKind::Tup(Vec::new()));
42     let const_body = ecx.expr_block(ecx.block(span, stmts));
43     let const_item = ecx.item_const(span, Ident::new(kw::Underscore, span), const_ty, const_body);
44
45     // Return the original item and the new methods.
46     vec![Annotatable::Item(item), Annotatable::Item(const_item)]
47 }
48
49 struct AllocFnFactory<'a, 'b> {
50     span: Span,
51     kind: AllocatorKind,
52     global: Ident,
53     cx: &'b ExtCtxt<'a>,
54 }
55
56 impl AllocFnFactory<'_, '_> {
57     fn allocator_fn(&self, method: &AllocatorMethod) -> Stmt {
58         let mut abi_args = Vec::new();
59         let mut i = 0;
60         let mut mk = || {
61             let name = self.cx.ident_of(&format!("arg{}", i), self.span);
62             i += 1;
63             name
64         };
65         let args = method.inputs.iter().map(|ty| self.arg_ty(ty, &mut abi_args, &mut mk)).collect();
66         let result = self.call_allocator(method.name, args);
67         let (output_ty, output_expr) = self.ret_ty(&method.output, result);
68         let decl = self.cx.fn_decl(abi_args, ast::FnRetTy::Ty(output_ty));
69         let header = FnHeader { unsafety: Unsafe::Yes(self.span), ..FnHeader::default() };
70         let sig = FnSig { decl, header };
71         let block = Some(self.cx.block_expr(output_expr));
72         let kind = ItemKind::Fn(ast::Defaultness::Final, sig, Generics::default(), block);
73         let item = self.cx.item(
74             self.span,
75             self.cx.ident_of(&self.kind.fn_name(method.name), self.span),
76             self.attrs(),
77             kind,
78         );
79         self.cx.stmt_item(self.span, item)
80     }
81
82     fn call_allocator(&self, method: &str, mut args: Vec<P<Expr>>) -> P<Expr> {
83         let method = self.cx.std_path(&[
84             Symbol::intern("alloc"),
85             Symbol::intern("GlobalAlloc"),
86             Symbol::intern(method),
87         ]);
88         let method = self.cx.expr_path(self.cx.path(self.span, method));
89         let allocator = self.cx.path_ident(self.span, self.global);
90         let allocator = self.cx.expr_path(allocator);
91         let allocator = self.cx.expr_addr_of(self.span, allocator);
92         args.insert(0, allocator);
93
94         self.cx.expr_call(self.span, method, args)
95     }
96
97     fn attrs(&self) -> Vec<Attribute> {
98         let special = sym::rustc_std_internal_symbol;
99         let special = self.cx.meta_word(self.span, special);
100         vec![self.cx.attribute(special)]
101     }
102
103     fn arg_ty(
104         &self,
105         ty: &AllocatorTy,
106         args: &mut Vec<Param>,
107         ident: &mut dyn FnMut() -> Ident,
108     ) -> P<Expr> {
109         match *ty {
110             AllocatorTy::Layout => {
111                 let usize = self.cx.path_ident(self.span, Ident::new(sym::usize, self.span));
112                 let ty_usize = self.cx.ty_path(usize);
113                 let size = ident();
114                 let align = ident();
115                 args.push(self.cx.param(self.span, size, ty_usize.clone()));
116                 args.push(self.cx.param(self.span, align, ty_usize));
117
118                 let layout_new = self.cx.std_path(&[
119                     Symbol::intern("alloc"),
120                     Symbol::intern("Layout"),
121                     Symbol::intern("from_size_align_unchecked"),
122                 ]);
123                 let layout_new = self.cx.expr_path(self.cx.path(self.span, layout_new));
124                 let size = self.cx.expr_ident(self.span, size);
125                 let align = self.cx.expr_ident(self.span, align);
126                 let layout = self.cx.expr_call(self.span, layout_new, vec![size, align]);
127                 layout
128             }
129
130             AllocatorTy::Ptr => {
131                 let ident = ident();
132                 args.push(self.cx.param(self.span, ident, self.ptr_u8()));
133                 let arg = self.cx.expr_ident(self.span, ident);
134                 self.cx.expr_cast(self.span, arg, self.ptr_u8())
135             }
136
137             AllocatorTy::Usize => {
138                 let ident = ident();
139                 args.push(self.cx.param(self.span, ident, self.usize()));
140                 self.cx.expr_ident(self.span, ident)
141             }
142
143             AllocatorTy::ResultPtr | AllocatorTy::Unit => {
144                 panic!("can't convert AllocatorTy to an argument")
145             }
146         }
147     }
148
149     fn ret_ty(&self, ty: &AllocatorTy, expr: P<Expr>) -> (P<Ty>, P<Expr>) {
150         match *ty {
151             AllocatorTy::ResultPtr => {
152                 // We're creating:
153                 //
154                 //      #expr as *mut u8
155
156                 let expr = self.cx.expr_cast(self.span, expr, self.ptr_u8());
157                 (self.ptr_u8(), expr)
158             }
159
160             AllocatorTy::Unit => (self.cx.ty(self.span, TyKind::Tup(Vec::new())), expr),
161
162             AllocatorTy::Layout | AllocatorTy::Usize | AllocatorTy::Ptr => {
163                 panic!("can't convert `AllocatorTy` to an output")
164             }
165         }
166     }
167
168     fn usize(&self) -> P<Ty> {
169         let usize = self.cx.path_ident(self.span, Ident::new(sym::usize, self.span));
170         self.cx.ty_path(usize)
171     }
172
173     fn ptr_u8(&self) -> P<Ty> {
174         let u8 = self.cx.path_ident(self.span, Ident::new(sym::u8, self.span));
175         let ty_u8 = self.cx.ty_path(u8);
176         self.cx.ty_ptr(self.span, ty_u8, Mutability::Mut)
177     }
178 }