rustc_builtin_macros/
alloc_error_handler.rs

1use rustc_ast::{
2    self as ast, Fn, FnHeader, FnSig, Generics, ItemKind, Safety, Stmt, StmtKind, TyKind,
3};
4use rustc_expand::base::{Annotatable, ExtCtxt};
5use rustc_span::{Ident, Span, kw, sym};
6use thin_vec::{ThinVec, thin_vec};
7
8use crate::errors;
9use crate::util::check_builtin_macro_attribute;
10
11pub(crate) fn expand(
12    ecx: &mut ExtCtxt<'_>,
13    _span: Span,
14    meta_item: &ast::MetaItem,
15    item: Annotatable,
16) -> Vec<Annotatable> {
17    check_builtin_macro_attribute(ecx, meta_item, sym::alloc_error_handler);
18
19    let orig_item = item.clone();
20
21    // Allow using `#[alloc_error_handler]` on an item statement
22    // FIXME - if we get deref patterns, use them to reduce duplication here
23    let (item, ident, is_stmt, sig_span) = if let Annotatable::Item(item) = &item
24        && let ItemKind::Fn(fn_kind) = &item.kind
25    {
26        (item, fn_kind.ident, false, ecx.with_def_site_ctxt(fn_kind.sig.span))
27    } else if let Annotatable::Stmt(stmt) = &item
28        && let StmtKind::Item(item) = &stmt.kind
29        && let ItemKind::Fn(fn_kind) = &item.kind
30    {
31        (item, fn_kind.ident, true, ecx.with_def_site_ctxt(fn_kind.sig.span))
32    } else {
33        ecx.dcx().emit_err(errors::AllocErrorMustBeFn { span: item.span() });
34        return vec![orig_item];
35    };
36
37    // Generate a bunch of new items using the AllocFnFactory
38    let span = ecx.with_def_site_ctxt(item.span);
39
40    // Generate item statements for the allocator methods.
41    let stmts = thin_vec![generate_handler(ecx, ident, span, sig_span)];
42
43    // Generate anonymous constant serving as container for the allocator methods.
44    let const_ty = ecx.ty(sig_span, TyKind::Tup(ThinVec::new()));
45    let const_body = ecx.expr_block(ecx.block(span, stmts));
46    let const_item = ecx.item_const(span, Ident::new(kw::Underscore, span), const_ty, const_body);
47    let const_item = if is_stmt {
48        Annotatable::Stmt(Box::new(ecx.stmt_item(span, const_item)))
49    } else {
50        Annotatable::Item(const_item)
51    };
52
53    // Return the original item and the new methods.
54    vec![orig_item, const_item]
55}
56
57// #[rustc_std_internal_symbol]
58// unsafe fn __rg_oom(size: usize, align: usize) -> ! {
59//     handler(core::alloc::Layout::from_size_align_unchecked(size, align))
60// }
61fn generate_handler(cx: &ExtCtxt<'_>, handler: Ident, span: Span, sig_span: Span) -> Stmt {
62    let usize = cx.path_ident(span, Ident::new(sym::usize, span));
63    let ty_usize = cx.ty_path(usize);
64    let size = Ident::new(sym::size, span);
65    let align = Ident::new(sym::align, span);
66
67    let layout_new = cx.std_path(&[sym::alloc, sym::Layout, sym::from_size_align_unchecked]);
68    let layout_new = cx.expr_path(cx.path(span, layout_new));
69    let layout = cx.expr_call(
70        span,
71        layout_new,
72        thin_vec![cx.expr_ident(span, size), cx.expr_ident(span, align)],
73    );
74
75    let call = cx.expr_call_ident(sig_span, handler, thin_vec![layout]);
76
77    let never = ast::FnRetTy::Ty(cx.ty(span, TyKind::Never));
78    let params = thin_vec![cx.param(span, size, ty_usize.clone()), cx.param(span, align, ty_usize)];
79    let decl = cx.fn_decl(params, never);
80    let header = FnHeader { safety: Safety::Unsafe(span), ..FnHeader::default() };
81    let sig = FnSig { decl, header, span };
82
83    let body = Some(cx.block_expr(call));
84    let kind = ItemKind::Fn(Box::new(Fn {
85        defaultness: ast::Defaultness::Final,
86        sig,
87        ident: Ident::from_str_and_span("__rg_oom", span),
88        generics: Generics::default(),
89        contract: None,
90        body,
91        define_opaque: None,
92    }));
93
94    let attrs = thin_vec![cx.attr_word(sym::rustc_std_internal_symbol, span)];
95
96    let item = cx.item(span, attrs, kind);
97    cx.stmt_item(sig_span, item)
98}