atagen

matrix-rust-sdk

public
Star0
Watch0
ssh://brewery@pls.lobotomise.me:33/atagen/matrix-rust-sdk.git
bindings/matrix-sdk-ffi-macros/src/lib.rsRust70 lines2.2 KB
1
// Copyright 2024 The Matrix.org Foundation C.I.C.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
use proc_macro::TokenStream;
16
use quote::quote;
17
use syn::{ImplItem, Item, TraitItem};
18
19
/// Attribute to specify the async runtime parameter for the `uniffi`
20
/// export macros if there any `async fn`s in the input.
21
#[proc_macro_attribute]
22
pub fn export(attr: TokenStream, item: TokenStream) -> TokenStream {
23
    let has_async_fn = |item| {
24
        if let Item::Fn(fun) = &item {
25
            if fun.sig.asyncness.is_some() {
26
                return true;
27
            }
28
        } else if let Item::Impl(blk) = &item {
29
            for item in &blk.items {
30
                if let ImplItem::Fn(fun) = item
31
                    && fun.sig.asyncness.is_some()
32
                {
33
                    return true;
34
                }
35
            }
36
        } else if let Item::Trait(blk) = &item {
37
            for item in &blk.items {
38
                if let TraitItem::Fn(fun) = item
39
                    && fun.sig.asyncness.is_some()
40
                {
41
                    return true;
42
                }
43
            }
44
        }
45
46
        false
47
    };
48
49
    let attr2 = proc_macro2::TokenStream::from(attr);
50
    let item2 = proc_macro2::TokenStream::from(item.clone());
51
52
    let res = match syn::parse(item) {
53
        Ok(item) => match has_async_fn(item) {
54
            true => {
55
                quote! {
56
                  #[cfg_attr(target_family = "wasm", uniffi::export(#attr2))]
57
                  #[cfg_attr(not(target_family = "wasm"), uniffi::export(async_runtime = "tokio", #attr2))]
58
                }
59
            }
60
            false => quote! { #[uniffi::export(#attr2)] },
61
        },
62
        Err(e) => e.into_compile_error(),
63
    };
64
65
    quote! {
66
        #res
67
        #item2
68
    }
69
    .into()
70
}