ffi_gen_macro/
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
//! Macro for generating the rust api for a rust header file.
#![deny(missing_docs)]
use ffi_gen::{Abi, FfiGen};
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;

/// Selects an abi based on the compile target and uses ffigen to generate the rust api.
#[proc_macro]
pub fn ffi_gen(input: TokenStream) -> TokenStream {
    let input: TokenStream2 = input.into();
    (quote! {
        #[cfg_attr(all(target_family = "wasm", target_pointer_width = "32"), ffi_gen_macro::ffi_gen_wasm_32(#input))]
        #[cfg_attr(all(target_family = "wasm", target_pointer_width = "64"), ffi_gen_macro::ffi_gen_wasm_64(#input))]
        #[cfg_attr(all(not(target_family = "wasm"), target_pointer_width = "32"), ffi_gen_macro::ffi_gen_native_32(#input))]
        #[cfg_attr(all(not(target_family = "wasm"), target_pointer_width = "64"), ffi_gen_macro::ffi_gen_native_64(#input))]
        struct Api;
    })
    .into()
}

#[proc_macro_attribute]
#[doc(hidden)]
pub fn ffi_gen_wasm_32(input: TokenStream, _: TokenStream) -> TokenStream {
    inner_ffi_gen(input, Abi::Wasm32)
}

#[proc_macro_attribute]
#[doc(hidden)]
pub fn ffi_gen_wasm_64(input: TokenStream, _: TokenStream) -> TokenStream {
    inner_ffi_gen(input, Abi::Wasm64)
}

#[proc_macro_attribute]
#[doc(hidden)]
pub fn ffi_gen_native_32(input: TokenStream, _: TokenStream) -> TokenStream {
    inner_ffi_gen(input, Abi::Native32)
}

#[proc_macro_attribute]
#[doc(hidden)]
pub fn ffi_gen_native_64(input: TokenStream, _: TokenStream) -> TokenStream {
    inner_ffi_gen(input, Abi::Native64)
}

fn inner_ffi_gen(input: TokenStream, abi: Abi) -> TokenStream {
    let input = syn::parse_macro_input!(input as syn::LitStr);
    let ffigen = FfiGen::new(input.value()).unwrap();
    let rust = ffigen.generate_rust(abi).unwrap();
    rust.parse().unwrap()
}