Debian Codegraph @

third_party/rust/uniffi_bindgen/src/interface/callbacks.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 //! # Callback Interface definitions for a `ComponentInterface`.
6 //!
7 //! This module converts callback interface definitions from UDL into structures that
8 //! can be added to a `ComponentInterface`. A declaration in the UDL like this:
9 //!
10 //! ```
11 //! # let ci = uniffi_bindgen::interface::ComponentInterface::from_webidl(r##"
12 //! # namespace example {};
13 //! callback interface Example {
14 //! string hello();
15 //! };
16 //! # "##, "crate_name")?;
17 //! # Ok::<(), anyhow::Error>(())
18 //! ```
19 //!
20 //! Will result in a [`CallbackInterface`] member being added to the resulting
21 //! [`crate::ComponentInterface`]:
22 //!
23 //! ```
24 //! # let ci = uniffi_bindgen::interface::ComponentInterface::from_webidl(r##"
25 //! # namespace example {};
26 //! # callback interface Example {
27 //! # string hello();
28 //! # };
29 //! # "##, "crate_name")?;
30 //! let callback = ci.get_callback_interface_definition("Example").unwrap();
31 //! assert_eq!(callback.name(), "Example");
32 //! assert_eq!(callback.methods()[0].name(), "hello");
33 //! # Ok::<(), anyhow::Error>(())
34 //! ```
35
36 use std::iter;
37
38 use heck::ToUpperCamelCase;
39 use uniffi_meta::Checksum;
40
41 use super::ffi::{FfiArgument, FfiCallbackFunction, FfiField, FfiFunction, FfiStruct, FfiType};
42 use super::object::Method;
43 use super::{AsType, Callable, Type, TypeIterator};
44
45 #[derive(Debug, Clone, Checksum)]
46 pub struct CallbackInterface {
47 pub(super) name: String,
48 pub(super) module_path: String,
49 pub(super) methods: Vec<Method>,
50 // We don't include the FFIFunc in the hash calculation, because:
51 // - it is entirely determined by the other fields,
52 // so excluding it is safe.
53 // - its `name` property includes a checksum derived from the very
54 // hash value we're trying to calculate here, so excluding it
55 // avoids a weird circular dependency in the calculation.
56 #[checksum_ignore]
57 pub(super) ffi_init_callback: FfiFunction,
58 #[checksum_ignore]
59 pub(super) docstring: Option<String>,
60 }
61
62 impl CallbackInterface {
63 pub fn name(&self) -> &str {
64 &self.name
65 }
66
67 pub fn module_path(&self) -> &str {
68 &self.module_path
69 }
70
71 pub fn methods(&self) -> Vec<&Method> {
72 self.methods.iter().collect()
73 }
74
75 pub fn ffi_init_callback(&self) -> &FfiFunction {
76 &self.ffi_init_callback
77 }
78
79 pub(super) fn derive_ffi_funcs(&mut self) {
80 self.ffi_init_callback =
81 FfiFunction::callback_init(&self.module_path, &self.name, vtable_name(&self.name));
82 }
83
84 /// FfiCallbacks to define for our methods.
85 pub fn ffi_callbacks(&self) -> Vec<FfiCallbackFunction> {
86 ffi_callbacks(&self.name, &self.methods)
87 }
88
89 /// The VTable FFI type
90 pub fn vtable(&self) -> FfiType {
91 FfiType::Struct(vtable_name(&self.name))
92 }
93
94 /// the VTable struct to define.
95 pub fn vtable_definition(&self) -> FfiStruct {
96 vtable_struct(&self.name, &self.methods)
97 }
98
99 /// Vec of (ffi_callback, method) pairs
100 pub fn vtable_methods(&self) -> Vec<(FfiCallbackFunction, Method)> {
101 self.methods
102 .iter()
103 .enumerate()
104 .map(|(i, method)| (method_ffi_callback(&self.name, method, i), method.clone()))
105 .collect()
106 }
107
108 pub fn iter_types(&self) -> TypeIterator<'_> {
109 Box::new(self.methods.iter().flat_map(Method::iter_types))
110 }
111
112 pub fn docstring(&self) -> Option<&str> {
113 self.docstring.as_deref()
114 }
115
116 pub fn has_async_method(&self) -> bool {
117 self.methods.iter().any(Method::is_async)
118 }
119 }
120
121 impl AsType for CallbackInterface {
122 fn as_type(&self) -> Type {
123 Type::CallbackInterface {
124 name: self.name.clone(),
125 module_path: self.module_path.clone(),
126 }
127 }
128 }
129
130 impl TryFrom<uniffi_meta::CallbackInterfaceMetadata> for CallbackInterface {
131 type Error = anyhow::Error;
132
133 fn try_from(meta: uniffi_meta::CallbackInterfaceMetadata) -> anyhow::Result<Self> {
134 Ok(Self {
135 name: meta.name,
136 module_path: meta.module_path,
137 methods: Default::default(),
138 ffi_init_callback: Default::default(),
139 docstring: meta.docstring.clone(),
140 })
141 }
142 }
143
144 /// [FfiCallbackFunction] functions for the methods of a callback/trait interface
145 pub fn ffi_callbacks(trait_name: &str, methods: &[Method]) -> Vec<FfiCallbackFunction> {
146 methods
147 .iter()
148 .enumerate()
149 .map(|(i, method)| method_ffi_callback(trait_name, method, i))
150 .collect()
151 }
152
153 pub fn method_ffi_callback(trait_name: &str, method: &Method, index: usize) -> FfiCallbackFunction {
154 if !method.is_async() {
155 FfiCallbackFunction {
156 name: method_ffi_callback_name(trait_name, index),
157 arguments: iter::once(FfiArgument::new("uniffi_handle", FfiType::UInt64))
158 .chain(method.arguments().into_iter().map(Into::into))
159 .chain(iter::once(match method.return_type() {
160 Some(t) => {
161 FfiArgument::new("uniffi_out_return", FfiType::from(t).mut_reference())
162 }
163 None => FfiArgument::new("uniffi_out_return", FfiType::VoidPointer),
164 }))
165 .collect(),
166 has_rust_call_status_arg: true,
167 return_type: None,
168 }
169 } else {
170 let completion_callback =
171 ffi_foreign_future_complete(method.return_type().map(FfiType::from));
172 FfiCallbackFunction {
173 name: method_ffi_callback_name(trait_name, index),
174 arguments: iter::once(FfiArgument::new("uniffi_handle", FfiType::UInt64))
175 .chain(method.arguments().into_iter().map(Into::into))
176 .chain([
177 FfiArgument::new(
178 "uniffi_future_callback",
179 FfiType::Callback(completion_callback.name),
180 ),
181 FfiArgument::new("uniffi_callback_data", FfiType::UInt64),
182 FfiArgument::new(
183 "uniffi_out_return",
184 FfiType::Struct("ForeignFuture".to_owned()).mut_reference(),
185 ),
186 ])
187 .collect(),
188 has_rust_call_status_arg: false,
189 return_type: None,
190 }
191 }
192 }
193
194 /// Result struct to pass to the completion callback for async methods
195 pub fn foreign_future_ffi_result_struct(return_ffi_type: Option<FfiType>) -> FfiStruct {
196 let return_type_name =
197 FfiType::return_type_name(return_ffi_type.as_ref()).to_upper_camel_case();
198 FfiStruct {
199 name: format!("ForeignFutureStruct{return_type_name}"),
200 fields: match return_ffi_type {
201 Some(return_ffi_type) => vec![
202 FfiField::new("return_value", return_ffi_type),
203 FfiField::new("call_status", FfiType::RustCallStatus),
204 ],
205 None => vec![
206 // In Rust, `return_value` is `()` -- a ZST.
207 // ZSTs are not valid in `C`, but they also take up 0 space.
208 // Skip the `return_value` field to make the layout correct.
209 FfiField::new("call_status", FfiType::RustCallStatus),
210 ],
211 },
212 }
213 }
214
215 /// Definition for callback functions to complete an async callback interface method
216 pub fn ffi_foreign_future_complete(return_ffi_type: Option<FfiType>) -> FfiCallbackFunction {
217 let return_type_name =
218 FfiType::return_type_name(return_ffi_type.as_ref()).to_upper_camel_case();
219 FfiCallbackFunction {
220 name: format!("ForeignFutureComplete{return_type_name}"),
221 arguments: vec![
222 FfiArgument::new("callback_data", FfiType::UInt64),
223 FfiArgument::new(
224 "result",
225 FfiType::Struct(format!("ForeignFutureStruct{return_type_name}")),
226 ),
227 ],
228 return_type: None,
229 has_rust_call_status_arg: false,
230 }
231 }
232
233 /// [FfiStruct] for a callback/trait interface VTable
234 ///
235 /// This struct has a FfiCallbackFunction field for each method, plus extra fields for special
236 /// methods
237 pub fn vtable_struct(trait_name: &str, methods: &[Method]) -> FfiStruct {
238 FfiStruct {
239 name: vtable_name(trait_name),
240 fields: methods
241 .iter()
242 .enumerate()
243 .map(|(i, method)| {
244 FfiField::new(
245 method.name(),
246 FfiType::Callback(format!("CallbackInterface{trait_name}Method{i}")),
247 )
248 })
249 .chain([FfiField::new(
250 "uniffi_free",
251 FfiType::Callback("CallbackInterfaceFree".to_owned()),
252 )])
253 .collect(),
254 }
255 }
256
257 pub fn method_ffi_callback_name(trait_name: &str, index: usize) -> String {
258 format!("CallbackInterface{trait_name}Method{index}")
259 }
260
261 pub fn vtable_name(trait_name: &str) -> String {
262 format!("VTableCallbackInterface{trait_name}")
263 }
264
265 #[cfg(test)]
266 mod test {
267 use super::super::ComponentInterface;
268
269 #[test]
270 fn test_empty_interface() {
271 const UDL: &str = r#"
272 namespace test{};
273 // Weird, but allowed.
274 callback interface Testing {};
275 "#;
276 let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap();
277 assert_eq!(ci.callback_interface_definitions().len(), 1);
278 assert_eq!(
279 ci.get_callback_interface_definition("Testing")
280 .unwrap()
281 .methods()
282 .len(),
283 0
284 );
285 }
286
287 #[test]
288 fn test_multiple_interfaces() {
289 const UDL: &str = r#"
290 namespace test{};
291 callback interface One {
292 void one();
293 };
294 callback interface Two {
295 u32 two();
296 u64 too();
297 };
298 "#;
299 let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap();
300 assert_eq!(ci.callback_interface_definitions().len(), 2);
301
302 let callbacks_one = ci.get_callback_interface_definition("One").unwrap();
303 assert_eq!(callbacks_one.methods().len(), 1);
304 assert_eq!(callbacks_one.methods()[0].name(), "one");
305
306 let callbacks_two = ci.get_callback_interface_definition("Two").unwrap();
307 assert_eq!(callbacks_two.methods().len(), 2);
308 assert_eq!(callbacks_two.methods()[0].name(), "two");
309 assert_eq!(callbacks_two.methods()[1].name(), "too");
310 }
311
312 #[test]
313 fn test_docstring_callback_interface() {
314 const UDL: &str = r#"
315 namespace test{};
316 /// informative docstring
317 callback interface Testing { };
318 "#;
319 let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap();
320 assert_eq!(
321 ci.get_callback_interface_definition("Testing")
322 .unwrap()
323 .docstring()
324 .unwrap(),
325 "informative docstring"
326 );
327 }
328 }