wasmtime_versioned_export_macros/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//! This crate defines macros to easily define and use functions with a
//! versioned suffix, to facilitate using multiple versions of the same
//! crate that generate assembly.

use quote::ToTokens;

const VERSION: &str = env!("CARGO_PKG_VERSION");

fn version(value: impl std::fmt::Display) -> String {
    format!("{}_{}", value, VERSION.replace('.', "_"))
}

fn versioned_lit_str(value: impl std::fmt::Display) -> syn::LitStr {
    syn::LitStr::new(version(value).as_str(), proc_macro2::Span::call_site())
}

#[proc_macro_attribute]
pub fn versioned_export(
    _attr: proc_macro::TokenStream,
    item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    let mut function = syn::parse_macro_input!(item as syn::ItemFn);

    let export_name = versioned_lit_str(&function.sig.ident);
    function
        .attrs
        .push(syn::parse_quote! { #[export_name = #export_name] });

    function.to_token_stream().into()
}

#[proc_macro_attribute]
pub fn versioned_link(
    _attr: proc_macro::TokenStream,
    item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    let mut function = syn::parse_macro_input!(item as syn::ForeignItemFn);

    let link_name = versioned_lit_str(&function.sig.ident);
    function
        .attrs
        .push(syn::parse_quote! { #[link_name = #link_name] });

    function.to_token_stream().into()
}

#[proc_macro]
pub fn versioned_stringify_ident(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let ident = syn::parse_macro_input!(item as syn::Ident);

    versioned_lit_str(ident).to_token_stream().into()
}

#[proc_macro]
pub fn versioned_suffix(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
    if !item.is_empty() {
        return syn::Error::new(
            proc_macro2::Span::call_site(),
            "`versioned_suffix!` accepts no input",
        )
        .to_compile_error()
        .into();
    };

    versioned_lit_str("").to_token_stream().into()
}