| 1 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 |
|
| 5 |
use crate::{ |
| 6 |
export::ImplItem, |
| 7 |
ffiops, |
| 8 |
fnsig::{FnKind, FnSignature, ReceiverArg}, |
| 9 |
util::{ |
| 10 |
create_metadata_items, derive_ffi_traits, ident_to_string, mod_path, tagged_impl_header, |
| 11 |
}, |
| 12 |
}; |
| 13 |
use proc_macro2::{Span, TokenStream}; |
| 14 |
use quote::{format_ident, quote}; |
| 15 |
use std::iter; |
| 16 |
use syn::Ident; |
| 17 |
|
| 18 |
/// Generate a trait impl that calls foreign callbacks |
| 19 |
/// |
| 20 |
/// This generates: |
| 21 |
/// * A `repr(C)` VTable struct where each field is the FFI function for the trait method. |
| 22 |
/// * A FFI function for foreign code to set their VTable for the interface |
| 23 |
/// * An implementation of the trait using that VTable |
| 24 |
pub(super) fn trait_impl( |
| 25 |
mod_path: &str, |
| 26 |
trait_ident: &Ident, |
| 27 |
items: &[ImplItem], |
| 28 |
) -> syn::Result<TokenStream> { |
| 29 |
let trait_name = ident_to_string(trait_ident); |
| 30 |
let trait_impl_ident = trait_impl_ident(&trait_name); |
| 31 |
let vtable_type = format_ident!("UniFfiTraitVtable{trait_name}"); |
| 32 |
let vtable_cell = format_ident!("UNIFFI_TRAIT_CELL_{}", trait_name.to_uppercase()); |
| 33 |
let init_ident = Ident::new( |
| 34 |
&uniffi_meta::init_callback_vtable_fn_symbol_name(mod_path, &trait_name), |
| 35 |
Span::call_site(), |
| 36 |
); |
| 37 |
let methods = items |
| 38 |
.iter() |
| 39 |
.map(|item| match item { |
| 40 |
ImplItem::Constructor(sig) => Err(syn::Error::new( |
| 41 |
sig.span, |
| 42 |
"Constructors not allowed in trait interfaces", |
| 43 |
)), |
| 44 |
ImplItem::Method(sig) => Ok(sig), |
| 45 |
}) |
| 46 |
.collect::<syn::Result<Vec<_>>>()?; |
| 47 |
|
| 48 |
let vtable_fields = methods.iter().map(|sig| { |
| 49 |
let ident = &sig.ident; |
| 50 |
let param_names = sig.scaffolding_param_names(); |
| 51 |
let param_types = sig.scaffolding_param_types(); |
| 52 |
let lift_return_type = ffiops::lift_return_type(&sig.return_ty); |
| 53 |
if !sig.is_async { |
| 54 |
quote! { |
| 55 |
pub #ident: extern "C" fn( |
| 56 |
uniffi_handle: u64, |
| 57 |
#(#param_names: #param_types,)* |
| 58 |
uniffi_out_return: &mut #lift_return_type, |
| 59 |
uniffi_out_call_status: &mut ::uniffi::RustCallStatus, |
| 60 |
), |
| 61 |
} |
| 62 |
} else { |
| 63 |
quote! { |
| 64 |
pub #ident: extern "C" fn( |
| 65 |
uniffi_handle: u64, |
| 66 |
#(#param_names: #param_types,)* |
| 67 |
uniffi_future_callback: ::uniffi::ForeignFutureCallback<#lift_return_type>, |
| 68 |
uniffi_callback_data: u64, |
| 69 |
uniffi_out_return: &mut ::uniffi::ForeignFuture, |
| 70 |
), |
| 71 |
} |
| 72 |
} |
| 73 |
}); |
| 74 |
|
| 75 |
let trait_impl_methods = methods |
| 76 |
.iter() |
| 77 |
.map(|sig| gen_method_impl(sig, &vtable_cell)) |
| 78 |
.collect::<syn::Result<Vec<_>>>()?; |
| 79 |
let has_async_method = methods.iter().any(|m| m.is_async); |
| 80 |
let impl_attributes = has_async_method.then(|| quote! { #[::async_trait::async_trait] }); |
| 81 |
|
| 82 |
Ok(quote! { |
| 83 |
#[allow(missing_docs)] |
| 84 |
pub struct #vtable_type { |
| 85 |
#(#vtable_fields)* |
| 86 |
pub uniffi_free: extern "C" fn(handle: u64), |
| 87 |
} |
| 88 |
|
| 89 |
static #vtable_cell: ::uniffi::UniffiForeignPointerCell::<#vtable_type> = ::uniffi::UniffiForeignPointerCell::<#vtable_type>::new(); |
| 90 |
|
| 91 |
#[allow(missing_docs)] |
| 92 |
#[unsafe(no_mangle)] |
| 93 |
pub extern "C" fn #init_ident(vtable: ::std::ptr::NonNull<#vtable_type>) { |
| 94 |
#vtable_cell.set(vtable); |
| 95 |
} |
| 96 |
|
| 97 |
#[derive(Debug)] |
| 98 |
struct #trait_impl_ident { |
| 99 |
handle: u64, |
| 100 |
} |
| 101 |
|
| 102 |
impl #trait_impl_ident { |
| 103 |
fn new(handle: u64) -> Self { |
| 104 |
Self { handle } |
| 105 |
} |
| 106 |
} |
| 107 |
|
| 108 |
::uniffi::deps::static_assertions::assert_impl_all!(#trait_impl_ident: ::core::marker::Send); |
| 109 |
|
| 110 |
#impl_attributes |
| 111 |
impl #trait_ident for #trait_impl_ident { |
| 112 |
#(#trait_impl_methods)* |
| 113 |
} |
| 114 |
|
| 115 |
impl ::std::ops::Drop for #trait_impl_ident { |
| 116 |
fn drop(&mut self) { |
| 117 |
let vtable = #vtable_cell.get(); |
| 118 |
(vtable.uniffi_free)(self.handle); |
| 119 |
} |
| 120 |
} |
| 121 |
}) |
| 122 |
} |
| 123 |
|
| 124 |
pub fn trait_impl_ident(trait_name: &str) -> Ident { |
| 125 |
Ident::new( |
| 126 |
&format!("UniFFICallbackHandler{trait_name}"), |
| 127 |
Span::call_site(), |
| 128 |
) |
| 129 |
} |
| 130 |
|
| 131 |
pub fn ffi_converter_callback_interface_impl( |
| 132 |
trait_ident: &Ident, |
| 133 |
trait_impl_ident: &Ident, |
| 134 |
) -> TokenStream { |
| 135 |
// TODO: support remote callback interfaces |
| 136 |
let remote = false; |
| 137 |
let trait_name = ident_to_string(trait_ident); |
| 138 |
let dyn_trait = quote! { dyn #trait_ident }; |
| 139 |
let box_dyn_trait = quote! { ::std::boxed::Box<#dyn_trait> }; |
| 140 |
let lift_impl_spec = tagged_impl_header("Lift", &box_dyn_trait, remote); |
| 141 |
let type_id_impl_spec = tagged_impl_header("TypeId", &box_dyn_trait, remote); |
| 142 |
let derive_ffi_traits = derive_ffi_traits(&box_dyn_trait, remote, &["LiftRef", "LiftReturn"]); |
| 143 |
let mod_path = match mod_path() { |
| 144 |
Ok(p) => p, |
| 145 |
Err(e) => return e.into_compile_error(), |
| 146 |
}; |
| 147 |
let try_lift_self = ffiops::try_lift(quote! { Self }); |
| 148 |
|
| 149 |
quote! { |
| 150 |
#[doc(hidden)] |
| 151 |
#[automatically_derived] |
| 152 |
unsafe #lift_impl_spec { |
| 153 |
type FfiType = u64; |
| 154 |
|
| 155 |
fn try_lift(v: Self::FfiType) -> ::uniffi::deps::anyhow::Result<Self> { |
| 156 |
::std::result::Result::Ok(::std::boxed::Box::new(<#trait_impl_ident>::new(v))) |
| 157 |
} |
| 158 |
|
| 159 |
fn try_read(buf: &mut &[u8]) -> ::uniffi::deps::anyhow::Result<Self> { |
| 160 |
use ::uniffi::deps::bytes::Buf; |
| 161 |
::uniffi::check_remaining(buf, 8)?; |
| 162 |
#try_lift_self(buf.get_u64()) |
| 163 |
} |
| 164 |
} |
| 165 |
|
| 166 |
#[doc(hidden)] |
| 167 |
#[automatically_derived] |
| 168 |
#type_id_impl_spec { |
| 169 |
const TYPE_ID_META: ::uniffi::MetadataBuffer = ::uniffi::MetadataBuffer::from_code( |
| 170 |
::uniffi::metadata::codes::TYPE_CALLBACK_INTERFACE, |
| 171 |
) |
| 172 |
.concat_str(#mod_path) |
| 173 |
.concat_str(#trait_name); |
| 174 |
} |
| 175 |
|
| 176 |
#derive_ffi_traits |
| 177 |
} |
| 178 |
} |
| 179 |
|
| 180 |
/// Generate a single method for [trait_impl]. This implements a trait method by invoking a |
| 181 |
/// foreign-supplied callback. |
| 182 |
fn gen_method_impl(sig: &FnSignature, vtable_cell: &Ident) -> syn::Result<TokenStream> { |
| 183 |
let FnSignature { |
| 184 |
ident, |
| 185 |
is_async, |
| 186 |
return_ty, |
| 187 |
kind, |
| 188 |
receiver, |
| 189 |
name, |
| 190 |
span, |
| 191 |
.. |
| 192 |
} = sig; |
| 193 |
|
| 194 |
if !matches!(kind, FnKind::TraitMethod { .. }) { |
| 195 |
return Err(syn::Error::new( |
| 196 |
*span, |
| 197 |
format!( |
| 198 |
"Internal UniFFI error: Unexpected function kind for callback interface {name}: {kind:?}", |
| 199 |
), |
| 200 |
)); |
| 201 |
} |
| 202 |
|
| 203 |
let self_param = match receiver { |
| 204 |
Some(ReceiverArg::Ref) => quote! { &self }, |
| 205 |
Some(ReceiverArg::Arc) => quote! { self: Arc<Self> }, |
| 206 |
None => { |
| 207 |
return Err(syn::Error::new( |
| 208 |
*span, |
| 209 |
"callback interface methods must take &self as their first argument", |
| 210 |
)); |
| 211 |
} |
| 212 |
}; |
| 213 |
|
| 214 |
let params = sig.params(); |
| 215 |
let lower_exprs = sig.args.iter().map(|a| { |
| 216 |
let lower = ffiops::lower(&a.ty); |
| 217 |
let ident = &a.ident; |
| 218 |
quote! { #lower(#ident) } |
| 219 |
}); |
| 220 |
|
| 221 |
let lift_return_type = ffiops::lift_return_type(&sig.return_ty); |
| 222 |
let lift_foreign_return = ffiops::lift_foreign_return(&sig.return_ty); |
| 223 |
|
| 224 |
if !is_async { |
| 225 |
Ok(quote! { |
| 226 |
fn #ident(#self_param, #(#params),*) -> #return_ty { |
| 227 |
let vtable = #vtable_cell.get(); |
| 228 |
let mut uniffi_call_status: ::uniffi::RustCallStatus = ::std::default::Default::default(); |
| 229 |
let mut uniffi_return_value: #lift_return_type = ::uniffi::FfiDefault::ffi_default(); |
| 230 |
(vtable.#ident)(self.handle, #(#lower_exprs,)* &mut uniffi_return_value, &mut uniffi_call_status); |
| 231 |
#lift_foreign_return(uniffi_return_value, uniffi_call_status) |
| 232 |
} |
| 233 |
}) |
| 234 |
} else { |
| 235 |
Ok(quote! { |
| 236 |
async fn #ident(#self_param, #(#params),*) -> #return_ty { |
| 237 |
let vtable = #vtable_cell.get(); |
| 238 |
::uniffi::foreign_async_call::<_, #return_ty, crate::UniFfiTag>(move |uniffi_future_callback, uniffi_future_callback_data| { |
| 239 |
let mut uniffi_foreign_future: ::uniffi::ForeignFuture = ::uniffi::FfiDefault::ffi_default(); |
| 240 |
(vtable.#ident)(self.handle, #(#lower_exprs,)* uniffi_future_callback, uniffi_future_callback_data, &mut uniffi_foreign_future); |
| 241 |
uniffi_foreign_future |
| 242 |
}).await |
| 243 |
} |
| 244 |
}) |
| 245 |
} |
| 246 |
} |
| 247 |
|
| 248 |
pub(super) fn metadata_items( |
| 249 |
self_ident: &Ident, |
| 250 |
items: &[ImplItem], |
| 251 |
module_path: &str, |
| 252 |
docstring: String, |
| 253 |
) -> syn::Result<Vec<TokenStream>> { |
| 254 |
let trait_name = ident_to_string(self_ident); |
| 255 |
let callback_interface_items = create_metadata_items( |
| 256 |
"callback_interface", |
| 257 |
&trait_name, |
| 258 |
quote! { |
| 259 |
::uniffi::MetadataBuffer::from_code(::uniffi::metadata::codes::CALLBACK_INTERFACE) |
| 260 |
.concat_str(#module_path) |
| 261 |
.concat_str(#trait_name) |
| 262 |
.concat_long_str(#docstring) |
| 263 |
}, |
| 264 |
None, |
| 265 |
); |
| 266 |
|
| 267 |
iter::once(Ok(callback_interface_items)) |
| 268 |
.chain(items.iter().map(|item| match item { |
| 269 |
ImplItem::Method(sig) => sig.metadata_items(), |
| 270 |
_ => unreachable!("traits have no constructors"), |
| 271 |
})) |
| 272 |
.collect() |
| 273 |
} |