Debian Codegraph @

third_party/rust/uniffi_macros/src/object.rs

raw
1 use proc_macro2::{Ident, Span, TokenStream};
2 use quote::quote;
3 use syn::DeriveInput;
4
5 use crate::{
6 ffiops,
7 util::{create_metadata_items, extract_docstring, ident_to_string, mod_path},
8 DeriveOptions,
9 };
10 use uniffi_meta::ObjectImpl;
11
12 /// Stores parsed data from the Derive Input for the struct/enum.
13 struct ObjectItem {
14 ident: Ident,
15 docstring: String,
16 }
17
18 impl ObjectItem {
19 fn new(input: DeriveInput) -> syn::Result<Self> {
20 Ok(Self {
21 ident: input.ident,
22 docstring: extract_docstring(&input.attrs)?,
23 })
24 }
25
26 fn ident(&self) -> &Ident {
27 &self.ident
28 }
29
30 fn name(&self) -> String {
31 ident_to_string(&self.ident)
32 }
33
34 fn docstring(&self) -> &str {
35 self.docstring.as_str()
36 }
37 }
38
39 pub fn expand_object(input: DeriveInput, options: DeriveOptions) -> syn::Result<TokenStream> {
40 let module_path = mod_path()?;
41 let object = ObjectItem::new(input)?;
42 let name = object.name();
43 let ident = object.ident();
44 let clone_fn_ident = Ident::new(
45 &uniffi_meta::clone_fn_symbol_name(&module_path, &name),
46 Span::call_site(),
47 );
48 let free_fn_ident = Ident::new(
49 &uniffi_meta::free_fn_symbol_name(&module_path, &name),
50 Span::call_site(),
51 );
52 let meta_static_var = options.generate_metadata.then(|| {
53 interface_meta_static_var(
54 object.ident(),
55 ObjectImpl::Struct,
56 &module_path,
57 object.docstring(),
58 )
59 .unwrap_or_else(syn::Error::into_compile_error)
60 });
61 let interface_impl = interface_impl(&object, &options);
62
63 Ok(quote! {
64 #[doc(hidden)]
65 #[unsafe(no_mangle)]
66 pub unsafe extern "C" fn #clone_fn_ident(
67 ptr: *const ::std::ffi::c_void,
68 call_status: &mut ::uniffi::RustCallStatus
69 ) -> *const ::std::ffi::c_void {
70 ::uniffi::deps::trace!("clone: {} ({:?})", #name, ptr);
71 ::uniffi::rust_call(call_status, || {
72 unsafe { ::std::sync::Arc::increment_strong_count(ptr) };
73 ::std::result::Result::Ok(ptr)
74 })
75 }
76
77 #[doc(hidden)]
78 #[unsafe(no_mangle)]
79 pub unsafe extern "C" fn #free_fn_ident(
80 ptr: *const ::std::ffi::c_void,
81 call_status: &mut ::uniffi::RustCallStatus
82 ) {
83 ::uniffi::deps::trace!("free: {} ({:?})", #name, ptr);
84 ::uniffi::rust_call(call_status, || {
85 assert!(!ptr.is_null());
86 let ptr = ptr.cast::<#ident>();
87 unsafe {
88 ::std::sync::Arc::decrement_strong_count(ptr);
89 }
90 ::std::result::Result::Ok(())
91 });
92 }
93
94 #interface_impl
95 #meta_static_var
96 })
97 }
98
99 fn wasm_single_threaded_annotation() -> TokenStream {
100 #[cfg(feature = "wasm-unstable-single-threaded")]
101 {
102 quote! {
103 #[cfg(not(target_arch = "wasm32"))]
104 }
105 }
106 #[cfg(not(feature = "wasm-unstable-single-threaded"))]
107 {
108 TokenStream::default()
109 }
110 }
111
112 fn interface_impl(object: &ObjectItem, options: &DeriveOptions) -> TokenStream {
113 let name = object.name();
114 let ident = object.ident();
115 let impl_spec = options.ffi_impl_header("FfiConverterArc", ident);
116 let lower_return_impl_spec = options.ffi_impl_header("LowerReturn", ident);
117 let lower_error_impl_spec = options.ffi_impl_header("LowerError", ident);
118 let type_id_impl_spec = options.ffi_impl_header("TypeId", ident);
119 let lift_ref_impl_spec = options.ffi_impl_header("LiftRef", ident);
120 let mod_path = match mod_path() {
121 Ok(p) => p,
122 Err(e) => return e.into_compile_error(),
123 };
124 let arc_self_type = quote! { ::std::sync::Arc<Self> };
125 let lower_arc = ffiops::lower(&arc_self_type);
126 let type_id_meta_arc = ffiops::type_id_meta(&arc_self_type);
127 let try_lift_arc = ffiops::try_lift(&arc_self_type);
128 let lower_return_type_arc = ffiops::lower_return_type(&arc_self_type);
129 let lower_return_arc = ffiops::lower_return(&arc_self_type);
130 let lower_error_arc = ffiops::lower_error(&arc_self_type);
131 let single_threaded_annotation = wasm_single_threaded_annotation();
132
133 quote! {
134 // All Object structs must be `Sync + Send`. The generated scaffolding will fail to compile
135 // if they are not, but unfortunately it fails with an unactionably obscure error message.
136 // By asserting the requirement explicitly, we help Rust produce a more scrutable error message
137 // and thus help the user debug why the requirement isn't being met.
138 #single_threaded_annotation
139 ::uniffi::deps::static_assertions::assert_impl_all!(
140 #ident: ::core::marker::Sync, ::core::marker::Send
141 );
142
143 #[doc(hidden)]
144 #[automatically_derived]
145 /// Support for passing reference-counted shared objects via the FFI.
146 ///
147 /// To avoid dealing with complex lifetime semantics over the FFI, any data passed
148 /// by reference must be encapsulated in an `Arc`, and must be safe to share
149 /// across threads.
150 unsafe #impl_spec {
151 // Don't use a pointer to <T> as that requires a `pub <T>`
152 type FfiType = *const ::std::os::raw::c_void;
153
154 /// When lowering, we have an owned `Arc` and we transfer that ownership
155 /// to the foreign-language code, "leaking" it out of Rust's ownership system
156 /// as a raw pointer. This works safely because we have unique ownership of `self`.
157 /// The foreign-language code is responsible for freeing this by calling the
158 /// `ffi_object_free` FFI function provided by the corresponding UniFFI type.
159 ///
160 /// Safety: when freeing the resulting pointer, the foreign-language code must
161 /// call the destructor function specific to the type `T`. Calling the destructor
162 /// function for other types may lead to undefined behaviour.
163 fn lower(obj: ::std::sync::Arc<Self>) -> Self::FfiType {
164 let ptr = ::std::sync::Arc::into_raw(obj) as Self::FfiType;
165 ::uniffi::deps::trace!("lower: {} ({:?})", #name, ptr);
166 ptr
167 }
168
169 /// When lifting, we receive an owned `Arc` that the foreign language code cloned.
170 fn try_lift(v: Self::FfiType) -> ::uniffi::Result<::std::sync::Arc<Self>> {
171 ::uniffi::deps::trace!("lift: {} ({:?})", #name, v);
172 let v = v as *const #ident;
173 ::std::result::Result::Ok(unsafe { ::std::sync::Arc::<Self>::from_raw(v) })
174 }
175
176 /// When writing as a field of a complex structure, make a clone and transfer ownership
177 /// of it to the foreign-language code by writing its pointer into the buffer.
178 /// The foreign-language code is responsible for freeing this by calling the
179 /// `ffi_object_free` FFI function provided by the corresponding UniFFI type.
180 ///
181 /// Safety: when freeing the resulting pointer, the foreign-language code must
182 /// call the destructor function specific to the type `T`. Calling the destructor
183 /// function for other types may lead to undefined behaviour.
184 fn write(obj: ::std::sync::Arc<Self>, buf: &mut ::std::vec::Vec<u8>) {
185 ::uniffi::deps::static_assertions::const_assert!(::std::mem::size_of::<*const ::std::ffi::c_void>() <= 8);
186 ::uniffi::deps::bytes::BufMut::put_u64(buf, #lower_arc(obj) as ::std::primitive::u64);
187 }
188
189 /// When reading as a field of a complex structure, we receive a "borrow" of the `Arc`
190 /// that is owned by the foreign-language code, and make a clone for our own use.
191 ///
192 /// Safety: the buffer must contain a pointer previously obtained by calling
193 /// the `lower()` or `write()` method of this impl.
194 fn try_read(buf: &mut &[u8]) -> ::uniffi::Result<::std::sync::Arc<Self>> {
195 ::uniffi::deps::static_assertions::const_assert!(::std::mem::size_of::<*const ::std::ffi::c_void>() <= 8);
196 ::uniffi::check_remaining(buf, 8)?;
197 #try_lift_arc(::uniffi::deps::bytes::Buf::get_u64(buf) as Self::FfiType)
198 }
199
200 const TYPE_ID_META: ::uniffi::MetadataBuffer = ::uniffi::MetadataBuffer::from_code(::uniffi::metadata::codes::TYPE_INTERFACE)
201 .concat_str(#mod_path)
202 .concat_str(#name);
203 }
204
205 unsafe #lower_return_impl_spec {
206 type ReturnType = #lower_return_type_arc;
207
208 fn lower_return(obj: Self) -> ::std::result::Result<Self::ReturnType, ::uniffi::RustCallError> {
209 #lower_return_arc(::std::sync::Arc::new(obj))
210 }
211 }
212
213 unsafe #lower_error_impl_spec {
214 fn lower_error(obj: Self) -> ::uniffi::RustBuffer {
215 #lower_error_arc(::std::sync::Arc::new(obj))
216 }
217 }
218
219 unsafe #lift_ref_impl_spec {
220 type LiftType = ::std::sync::Arc<Self>;
221 }
222
223 #type_id_impl_spec {
224 const TYPE_ID_META: ::uniffi::MetadataBuffer = #type_id_meta_arc;
225 }
226 }
227 }
228
229 pub(crate) fn interface_meta_static_var(
230 ident: &Ident,
231 imp: ObjectImpl,
232 module_path: &str,
233 docstring: &str,
234 ) -> syn::Result<TokenStream> {
235 let name = ident_to_string(ident);
236 let code = match imp {
237 ObjectImpl::Struct => quote! { ::uniffi::metadata::codes::INTERFACE },
238 ObjectImpl::Trait => quote! { ::uniffi::metadata::codes::TRAIT_INTERFACE },
239 ObjectImpl::CallbackTrait => quote! { ::uniffi::metadata::codes::CALLBACK_TRAIT_INTERFACE },
240 };
241
242 Ok(create_metadata_items(
243 "interface",
244 &name,
245 quote! {
246 ::uniffi::MetadataBuffer::from_code(#code)
247 .concat_str(#module_path)
248 .concat_str(#name)
249 .concat_long_str(#docstring)
250 },
251 None,
252 ))
253 }