Skip to main content

nounwind_macros/
lib.rs

1//! The underlying implementation of the `#[nounwind]` attribute macro.
2
3use proc_macro2::TokenStream;
4use quote::ToTokens;
5use syn::parse::{Parse, ParseStream};
6use syn::{parse_macro_input, parse_quote};
7
8struct Empty;
9impl Parse for Empty {
10    fn parse(_input: ParseStream) -> syn::Result<Self> {
11        Ok(Empty)
12    }
13}
14
15#[proc_macro_attribute]
16pub fn nounwind(
17    attr: proc_macro::TokenStream,
18    item: proc_macro::TokenStream,
19) -> proc_macro::TokenStream {
20    let _: Empty = parse_macro_input!(attr as Empty);
21    let input = parse_macro_input!(item as syn_mid::ItemFn);
22    do_nounwind(input)
23        .unwrap_or_else(syn::Error::into_compile_error)
24        .into()
25}
26
27fn do_nounwind(mut item: syn_mid::ItemFn) -> syn::Result<TokenStream> {
28    let old_block = std::mem::replace(
29        &mut item.block,
30        Box::new(parse_quote!({ compile_error!("dummy value") })),
31    );
32    item.block = Box::new(parse_quote!({
33        nounwind::abort_unwind(#[inline(always)] move || {
34            #old_block
35        })
36    }));
37    Ok(item.into_token_stream())
38}