matrix_sdk_ffi_macros/lib.rs
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
15use proc_macro::TokenStream;
16use quote::quote;
17use 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]
22pub 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 if fun.sig.asyncness.is_some() {
32 return true;
33 }
34 }
35 }
36 } else if let Item::Trait(blk) = &item {
37 for item in &blk.items {
38 if let TraitItem::Fn(fun) = item {
39 if fun.sig.asyncness.is_some() {
40 return true;
41 }
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 => quote! { #[uniffi::export(async_runtime = "tokio", #attr2)] },
55 false => quote! { #[uniffi::export(#attr2)] },
56 },
57 Err(e) => e.into_compile_error(),
58 };
59
60 quote! {
61 #res
62 #item2
63 }
64 .into()
65}