Debian Codegraph @

third_party/rust/uniffi_macros/src/export/trait_interface.rs

raw
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 proc_macro2::{Ident, Span, TokenStream};
6 use quote::{quote, quote_spanned};
7
8 use uniffi_meta::ObjectImpl;
9
10 use crate::{
11 export::{
12 attributes::ExportTraitArgs, callback_interface, gen_method_scaffolding, item::ImplItem,
13 },
14 ffiops,
15 object::interface_meta_static_var,
16 util::{ident_to_string, tagged_impl_header},
17 };
18
19 pub(super) fn gen_trait_scaffolding(
20 mod_path: &str,
21 args: ExportTraitArgs,
22 self_ident: Ident,
23 items: Vec<ImplItem>,
24 udl_mode: bool,
25 with_foreign: bool,
26 docstring: String,
27 ) -> syn::Result<TokenStream> {
28 if let Some(rt) = args.async_runtime {
29 return Err(syn::Error::new_spanned(rt, "not supported for traits"));
30 }
31 let trait_name = ident_to_string(&self_ident);
32 let trait_impl = with_foreign.then(|| {
33 callback_interface::trait_impl(mod_path, &self_ident, &items)
34 .unwrap_or_else(|e| e.into_compile_error())
35 });
36
37 let clone_fn_ident = Ident::new(
38 &uniffi_meta::clone_fn_symbol_name(mod_path, &trait_name),
39 Span::call_site(),
40 );
41 let free_fn_ident = Ident::new(
42 &uniffi_meta::free_fn_symbol_name(mod_path, &trait_name),
43 Span::call_site(),
44 );
45
46 let helper_fn_tokens = quote! {
47 #[doc(hidden)]
48 #[unsafe(no_mangle)]
49 /// Clone a pointer to this object type
50 ///
51 /// Safety: Only pass pointers returned by a UniFFI call. Do not pass pointers that were
52 /// passed to the free function.
53 pub unsafe extern "C" fn #clone_fn_ident(
54 ptr: *const ::std::ffi::c_void,
55 call_status: &mut ::uniffi::RustCallStatus
56 ) -> *const ::std::ffi::c_void {
57 ::uniffi::deps::trace!("clonining trait: {} ({:?})", #trait_name, ptr);
58 ::uniffi::rust_call(call_status, || {
59 let ptr = ptr as *mut ::std::sync::Arc<dyn #self_ident>;
60 let arc: ::std::sync::Arc<_> = unsafe { ::std::clone::Clone::clone(&*ptr) };
61 ::std::result::Result::Ok(
62 ::std::boxed::Box::into_raw(
63 ::std::boxed::Box::new(arc),
64 ) as *const ::std::ffi::c_void
65 )
66 })
67 }
68
69 #[doc(hidden)]
70 #[unsafe(no_mangle)]
71 /// Free a pointer to this object type
72 ///
73 /// Safety: Only pass pointers returned by a UniFFI call. Do not pass pointers that were
74 /// passed to the free function.
75 ///
76 /// Note: clippy doesn't complain about this being unsafe, but it definitely is since it
77 /// calls `Box::from_raw`.
78 pub unsafe extern "C" fn #free_fn_ident(
79 ptr: *const ::std::ffi::c_void,
80 call_status: &mut ::uniffi::RustCallStatus
81 ) {
82 ::uniffi::deps::trace!("freeing trait: {} ({:?})", #trait_name, ptr);
83 ::uniffi::rust_call(call_status, || {
84 ::std::assert!(!ptr.is_null());
85 ::std::mem::drop(unsafe {
86 ::std::boxed::Box::from_raw(
87 ptr as *mut ::std::sync::Arc<dyn #self_ident>,
88 )
89 });
90 ::std::result::Result::Ok(())
91 });
92 }
93 };
94
95 let impl_tokens: TokenStream = items
96 .into_iter()
97 .map(|item| match item {
98 ImplItem::Method(sig) => gen_method_scaffolding(sig, None, udl_mode),
99 _ => unreachable!("traits have no constructors"),
100 })
101 .collect::<syn::Result<_>>()?;
102
103 let meta_static_var = (!udl_mode).then(|| {
104 let imp = if with_foreign {
105 ObjectImpl::CallbackTrait
106 } else {
107 ObjectImpl::Trait
108 };
109 interface_meta_static_var(&self_ident, imp, mod_path, docstring.as_str())
110 .unwrap_or_else(syn::Error::into_compile_error)
111 });
112 let ffi_converter_tokens = ffi_converter(mod_path, &self_ident, with_foreign);
113
114 Ok(quote_spanned! { self_ident.span() =>
115 #meta_static_var
116 #helper_fn_tokens
117 #trait_impl
118 #impl_tokens
119 #ffi_converter_tokens
120 })
121 }
122
123 pub(crate) fn ffi_converter(
124 mod_path: &str,
125 trait_ident: &Ident,
126 with_foreign: bool,
127 ) -> TokenStream {
128 // TODO: support defining remote trait interfaces
129 let remote = false;
130 let impl_spec = tagged_impl_header("FfiConverterArc", &quote! { dyn #trait_ident }, remote);
131 let lift_ref_impl_spec = tagged_impl_header("LiftRef", &quote! { dyn #trait_ident }, remote);
132 let trait_name = ident_to_string(trait_ident);
133 let try_lift = if with_foreign {
134 let trait_impl_ident = callback_interface::trait_impl_ident(&trait_name);
135 quote! {
136 fn try_lift(v: Self::FfiType) -> ::uniffi::deps::anyhow::Result<::std::sync::Arc<Self>> {
137 ::std::result::Result::Ok(::std::sync::Arc::new(<#trait_impl_ident>::new(v as u64)))
138 }
139 }
140 } else {
141 quote! {
142 fn try_lift(v: Self::FfiType) -> ::uniffi::deps::anyhow::Result<::std::sync::Arc<Self>> {
143 unsafe {
144 ::std::result::Result::Ok(
145 *::std::boxed::Box::from_raw(v as *mut ::std::sync::Arc<Self>),
146 )
147 }
148 }
149 }
150 };
151 let metadata_code = if with_foreign {
152 quote! { ::uniffi::metadata::codes::TYPE_CALLBACK_TRAIT_INTERFACE }
153 } else {
154 quote! { ::uniffi::metadata::codes::TYPE_TRAIT_INTERFACE }
155 };
156 let lower_self = ffiops::lower(quote! { ::std::sync::Arc<Self> });
157 let try_lift_self = ffiops::try_lift(quote! { ::std::sync::Arc<Self> });
158
159 quote! {
160 // All traits must be `Sync + Send`. The generated scaffolding will fail to compile
161 // if they are not, but unfortunately it fails with an unactionably obscure error message.
162 // By asserting the requirement explicitly, we help Rust produce a more scrutable error message
163 // and thus help the user debug why the requirement isn't being met.
164 ::uniffi::deps::static_assertions::assert_impl_all!(
165 dyn #trait_ident: ::core::marker::Sync, ::core::marker::Send
166 );
167
168 unsafe #impl_spec {
169 type FfiType = *const ::std::os::raw::c_void;
170
171 fn lower(obj: ::std::sync::Arc<Self>) -> Self::FfiType {
172 ::std::boxed::Box::into_raw(::std::boxed::Box::new(obj)) as *const ::std::os::raw::c_void
173 }
174
175 #try_lift
176
177 fn write(obj: ::std::sync::Arc<Self>, buf: &mut ::std::vec::Vec<u8>) {
178 ::uniffi::deps::static_assertions::const_assert!(::std::mem::size_of::<*const ::std::ffi::c_void>() <= 8);
179 ::uniffi::deps::bytes::BufMut::put_u64(
180 buf,
181 #lower_self(obj) as ::std::primitive::u64,
182 );
183 }
184
185 fn try_read(buf: &mut &[u8]) -> ::uniffi::Result<::std::sync::Arc<Self>> {
186 ::uniffi::deps::static_assertions::const_assert!(::std::mem::size_of::<*const ::std::ffi::c_void>() <= 8);
187 ::uniffi::check_remaining(buf, 8)?;
188 #try_lift_self(::uniffi::deps::bytes::Buf::get_u64(buf) as Self::FfiType)
189 }
190
191 const TYPE_ID_META: ::uniffi::MetadataBuffer = ::uniffi::MetadataBuffer::from_code(#metadata_code)
192 .concat_str(#mod_path)
193 .concat_str(#trait_name);
194 }
195
196 unsafe #lift_ref_impl_spec {
197 type LiftType = ::std::sync::Arc<dyn #trait_ident>;
198 }
199 }
200 }