rustc_builtin_macros/
alloc_error_handler.rs

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