| 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 |
//! # Function definitions for a `ComponentInterface`. |
| 6 |
//! |
| 7 |
//! This module converts function 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 |
//! string hello(); |
| 14 |
//! }; |
| 15 |
//! # "##, "crate_name")?; |
| 16 |
//! # Ok::<(), anyhow::Error>(()) |
| 17 |
//! ``` |
| 18 |
//! |
| 19 |
//! Will result in a [`Function`] member being added to the resulting [`crate::ComponentInterface`]: |
| 20 |
//! |
| 21 |
//! ``` |
| 22 |
//! # use uniffi_bindgen::interface::Type; |
| 23 |
//! # let ci = uniffi_bindgen::interface::ComponentInterface::from_webidl(r##" |
| 24 |
//! # namespace example { |
| 25 |
//! # string hello(); |
| 26 |
//! # }; |
| 27 |
//! # "##, "crate_name")?; |
| 28 |
//! let func = ci.get_function_definition("hello").unwrap(); |
| 29 |
//! assert_eq!(func.name(), "hello"); |
| 30 |
//! assert!(matches!(func.return_type(), Some(Type::String))); |
| 31 |
//! assert_eq!(func.arguments().len(), 0); |
| 32 |
//! # Ok::<(), anyhow::Error>(()) |
| 33 |
//! ``` |
| 34 |
|
| 35 |
use anyhow::Result; |
| 36 |
use uniffi_meta::Checksum; |
| 37 |
|
| 38 |
use super::ffi::{FfiArgument, FfiFunction, FfiType}; |
| 39 |
use super::{AsType, ComponentInterface, Literal, ObjectImpl, Type, TypeIterator}; |
| 40 |
|
| 41 |
/// Represents a standalone function. |
| 42 |
/// |
| 43 |
/// Each `Function` corresponds to a standalone function in the rust module, |
| 44 |
/// and has a corresponding standalone function in the foreign language bindings. |
| 45 |
/// |
| 46 |
/// In the FFI, this will be a standalone function with appropriately lowered types. |
| 47 |
#[derive(Debug, Clone, Checksum)] |
| 48 |
pub struct Function { |
| 49 |
pub(super) name: String, |
| 50 |
pub(super) module_path: String, |
| 51 |
pub(super) is_async: bool, |
| 52 |
pub(super) arguments: Vec<Argument>, |
| 53 |
pub(super) return_type: Option<Type>, |
| 54 |
// We don't include the FFIFunc in the hash calculation, because: |
| 55 |
// - it is entirely determined by the other fields, |
| 56 |
// so excluding it is safe. |
| 57 |
// - its `name` property includes a checksum derived from the very |
| 58 |
// hash value we're trying to calculate here, so excluding it |
| 59 |
// avoids a weird circular dependency in the calculation. |
| 60 |
#[checksum_ignore] |
| 61 |
pub(super) ffi_func: FfiFunction, |
| 62 |
#[checksum_ignore] |
| 63 |
pub(super) docstring: Option<String>, |
| 64 |
pub(super) throws: Option<Type>, |
| 65 |
pub(super) checksum_fn_name: String, |
| 66 |
// Force a checksum value, or we'll fallback to the trait. |
| 67 |
#[checksum_ignore] |
| 68 |
pub(super) checksum: Option<u16>, |
| 69 |
} |
| 70 |
|
| 71 |
impl Function { |
| 72 |
pub fn name(&self) -> &str { |
| 73 |
&self.name |
| 74 |
} |
| 75 |
|
| 76 |
// Note: Don't recalculate the checksum. In order to have consistent checksums, |
| 77 |
// we use the Rust names as input. |
| 78 |
pub fn rename(&mut self, new_name: String) { |
| 79 |
self.name = new_name; |
| 80 |
} |
| 81 |
|
| 82 |
pub fn is_async(&self) -> bool { |
| 83 |
self.is_async |
| 84 |
} |
| 85 |
|
| 86 |
pub fn arguments(&self) -> Vec<&Argument> { |
| 87 |
self.arguments.iter().collect() |
| 88 |
} |
| 89 |
|
| 90 |
pub fn full_arguments(&self) -> Vec<Argument> { |
| 91 |
self.arguments.to_vec() |
| 92 |
} |
| 93 |
|
| 94 |
pub fn return_type(&self) -> Option<&Type> { |
| 95 |
self.return_type.as_ref() |
| 96 |
} |
| 97 |
|
| 98 |
pub fn ffi_func(&self) -> &FfiFunction { |
| 99 |
&self.ffi_func |
| 100 |
} |
| 101 |
|
| 102 |
pub fn checksum_fn_name(&self) -> &str { |
| 103 |
&self.checksum_fn_name |
| 104 |
} |
| 105 |
|
| 106 |
pub fn checksum(&self) -> u16 { |
| 107 |
self.checksum.unwrap_or_else(|| uniffi_meta::checksum(self)) |
| 108 |
} |
| 109 |
|
| 110 |
pub fn throws(&self) -> bool { |
| 111 |
self.throws.is_some() |
| 112 |
} |
| 113 |
|
| 114 |
pub fn throws_name(&self) -> Option<&str> { |
| 115 |
super::throws_name(&self.throws) |
| 116 |
} |
| 117 |
|
| 118 |
pub fn throws_type(&self) -> Option<&Type> { |
| 119 |
self.throws.as_ref() |
| 120 |
} |
| 121 |
|
| 122 |
pub fn derive_ffi_func(&mut self) -> Result<()> { |
| 123 |
assert!(!self.ffi_func.name.is_empty()); |
| 124 |
self.ffi_func.init( |
| 125 |
self.return_type.as_ref().map(Into::into), |
| 126 |
self.arguments.iter().map(Into::into), |
| 127 |
); |
| 128 |
Ok(()) |
| 129 |
} |
| 130 |
|
| 131 |
pub fn docstring(&self) -> Option<&str> { |
| 132 |
self.docstring.as_deref() |
| 133 |
} |
| 134 |
} |
| 135 |
|
| 136 |
impl From<uniffi_meta::FnParamMetadata> for Argument { |
| 137 |
fn from(meta: uniffi_meta::FnParamMetadata) -> Self { |
| 138 |
Argument { |
| 139 |
name: meta.name, |
| 140 |
type_: meta.ty, |
| 141 |
by_ref: meta.by_ref, |
| 142 |
optional: meta.optional, |
| 143 |
default: meta.default, |
| 144 |
} |
| 145 |
} |
| 146 |
} |
| 147 |
|
| 148 |
impl From<uniffi_meta::FnMetadata> for Function { |
| 149 |
fn from(meta: uniffi_meta::FnMetadata) -> Self { |
| 150 |
let ffi_name = meta.ffi_symbol_name(); |
| 151 |
let checksum_fn_name = meta.checksum_symbol_name(); |
| 152 |
let is_async = meta.is_async; |
| 153 |
let return_type = meta.return_type; |
| 154 |
let arguments = meta.inputs.into_iter().map(Into::into).collect(); |
| 155 |
|
| 156 |
let ffi_func = FfiFunction { |
| 157 |
name: ffi_name, |
| 158 |
is_async, |
| 159 |
..FfiFunction::default() |
| 160 |
}; |
| 161 |
|
| 162 |
Self { |
| 163 |
name: meta.name, |
| 164 |
module_path: meta.module_path, |
| 165 |
is_async, |
| 166 |
arguments, |
| 167 |
return_type, |
| 168 |
ffi_func, |
| 169 |
docstring: meta.docstring.clone(), |
| 170 |
throws: meta.throws, |
| 171 |
checksum_fn_name, |
| 172 |
checksum: meta.checksum, |
| 173 |
} |
| 174 |
} |
| 175 |
} |
| 176 |
|
| 177 |
/// Represents an argument to a function/constructor/method call. |
| 178 |
/// |
| 179 |
/// Each argument has a name and a type, along with some optional metadata. |
| 180 |
#[derive(Debug, Clone, Checksum)] |
| 181 |
pub struct Argument { |
| 182 |
pub(super) name: String, |
| 183 |
pub(super) type_: Type, |
| 184 |
pub(super) by_ref: bool, |
| 185 |
pub(super) optional: bool, |
| 186 |
pub(super) default: Option<Literal>, |
| 187 |
} |
| 188 |
|
| 189 |
impl Argument { |
| 190 |
pub fn name(&self) -> &str { |
| 191 |
&self.name |
| 192 |
} |
| 193 |
|
| 194 |
pub fn rename(&mut self, new_name: String) { |
| 195 |
self.name = new_name; |
| 196 |
} |
| 197 |
|
| 198 |
pub fn by_ref(&self) -> bool { |
| 199 |
self.by_ref |
| 200 |
} |
| 201 |
|
| 202 |
pub fn is_trait_ref(&self) -> bool { |
| 203 |
matches!(&self.type_, Type::Object { imp, .. } if *imp == ObjectImpl::Trait) |
| 204 |
} |
| 205 |
|
| 206 |
pub fn default_value(&self) -> Option<&Literal> { |
| 207 |
self.default.as_ref() |
| 208 |
} |
| 209 |
|
| 210 |
pub fn iter_types(&self) -> TypeIterator<'_> { |
| 211 |
self.type_.iter_types() |
| 212 |
} |
| 213 |
} |
| 214 |
|
| 215 |
impl AsType for Argument { |
| 216 |
fn as_type(&self) -> Type { |
| 217 |
self.type_.clone() |
| 218 |
} |
| 219 |
} |
| 220 |
|
| 221 |
impl From<&Argument> for FfiArgument { |
| 222 |
fn from(a: &Argument) -> FfiArgument { |
| 223 |
FfiArgument { |
| 224 |
name: a.name.clone(), |
| 225 |
type_: (&a.type_).into(), |
| 226 |
} |
| 227 |
} |
| 228 |
} |
| 229 |
|
| 230 |
/// Combines the return and throws type of a function/method |
| 231 |
#[derive(Debug, PartialOrd, Ord, PartialEq, Eq)] |
| 232 |
pub struct ResultType<'a> { |
| 233 |
pub return_type: Option<&'a Type>, |
| 234 |
pub throws_type: Option<&'a Type>, |
| 235 |
} |
| 236 |
|
| 237 |
impl ResultType<'_> { |
| 238 |
/// Get the `T` parameters for the `FutureCallback<T>` for this ResultType |
| 239 |
pub fn future_callback_param(&self) -> FfiType { |
| 240 |
match self.return_type { |
| 241 |
Some(t) => t.into(), |
| 242 |
None => FfiType::UInt8, |
| 243 |
} |
| 244 |
} |
| 245 |
} |
| 246 |
|
| 247 |
/// Implemented by function-like types (Function, Method, Constructor) |
| 248 |
pub trait Callable { |
| 249 |
fn arguments(&self) -> Vec<&Argument>; |
| 250 |
fn return_type(&self) -> Option<&Type>; |
| 251 |
fn throws_type(&self) -> Option<&Type>; |
| 252 |
fn is_async(&self) -> bool; |
| 253 |
fn docstring(&self) -> Option<&str>; |
| 254 |
fn takes_self(&self) -> bool { |
| 255 |
false |
| 256 |
} |
| 257 |
fn result_type(&self) -> ResultType<'_> { |
| 258 |
ResultType { |
| 259 |
return_type: self.return_type(), |
| 260 |
throws_type: self.throws_type(), |
| 261 |
} |
| 262 |
} |
| 263 |
|
| 264 |
fn iter_types(&self) -> TypeIterator<'_> { |
| 265 |
let types: Vec<&Type> = self |
| 266 |
.arguments() |
| 267 |
.iter() |
| 268 |
.flat_map(|a| a.iter_types()) |
| 269 |
.chain(self.return_type().iter().flat_map(|t| t.iter_types())) |
| 270 |
.chain(self.throws_type().iter().flat_map(|t| t.iter_types())) |
| 271 |
.collect(); |
| 272 |
Box::new(types.into_iter()) |
| 273 |
} |
| 274 |
|
| 275 |
// Scaffolding function |
| 276 |
fn ffi_func(&self) -> &FfiFunction; |
| 277 |
|
| 278 |
// Quick way to get the rust future scaffolding function that corresponds to our return type. |
| 279 |
|
| 280 |
fn ffi_rust_future_poll(&self, ci: &ComponentInterface) -> String { |
| 281 |
ci.ffi_rust_future_poll(self.return_type().map(Into::into)) |
| 282 |
.name() |
| 283 |
.to_owned() |
| 284 |
} |
| 285 |
|
| 286 |
fn ffi_rust_future_cancel(&self, ci: &ComponentInterface) -> String { |
| 287 |
ci.ffi_rust_future_cancel(self.return_type().map(Into::into)) |
| 288 |
.name() |
| 289 |
.to_owned() |
| 290 |
} |
| 291 |
|
| 292 |
fn ffi_rust_future_complete(&self, ci: &ComponentInterface) -> String { |
| 293 |
ci.ffi_rust_future_complete(self.return_type().map(Into::into)) |
| 294 |
.name() |
| 295 |
.to_owned() |
| 296 |
} |
| 297 |
|
| 298 |
fn ffi_rust_future_free(&self, ci: &ComponentInterface) -> String { |
| 299 |
ci.ffi_rust_future_free(self.return_type().map(Into::into)) |
| 300 |
.name() |
| 301 |
.to_owned() |
| 302 |
} |
| 303 |
} |
| 304 |
|
| 305 |
impl Callable for Function { |
| 306 |
fn arguments(&self) -> Vec<&Argument> { |
| 307 |
self.arguments() |
| 308 |
} |
| 309 |
|
| 310 |
fn return_type(&self) -> Option<&Type> { |
| 311 |
self.return_type() |
| 312 |
} |
| 313 |
|
| 314 |
fn throws_type(&self) -> Option<&Type> { |
| 315 |
self.throws_type() |
| 316 |
} |
| 317 |
|
| 318 |
fn docstring(&self) -> Option<&str> { |
| 319 |
self.docstring() |
| 320 |
} |
| 321 |
|
| 322 |
fn is_async(&self) -> bool { |
| 323 |
self.is_async |
| 324 |
} |
| 325 |
|
| 326 |
fn ffi_func(&self) -> &FfiFunction { |
| 327 |
&self.ffi_func |
| 328 |
} |
| 329 |
} |
| 330 |
|
| 331 |
// Needed because Askama likes to add extra refs to variables |
| 332 |
impl<T: Callable> Callable for &T { |
| 333 |
fn arguments(&self) -> Vec<&Argument> { |
| 334 |
(*self).arguments() |
| 335 |
} |
| 336 |
|
| 337 |
fn return_type(&self) -> Option<&Type> { |
| 338 |
(*self).return_type() |
| 339 |
} |
| 340 |
|
| 341 |
fn throws_type(&self) -> Option<&Type> { |
| 342 |
(*self).throws_type() |
| 343 |
} |
| 344 |
|
| 345 |
fn is_async(&self) -> bool { |
| 346 |
(*self).is_async() |
| 347 |
} |
| 348 |
|
| 349 |
fn docstring(&self) -> Option<&str> { |
| 350 |
(*self).docstring() |
| 351 |
} |
| 352 |
|
| 353 |
fn ffi_func(&self) -> &FfiFunction { |
| 354 |
(*self).ffi_func() |
| 355 |
} |
| 356 |
|
| 357 |
fn takes_self(&self) -> bool { |
| 358 |
(*self).takes_self() |
| 359 |
} |
| 360 |
} |
| 361 |
|
| 362 |
#[cfg(test)] |
| 363 |
mod test { |
| 364 |
use super::super::ComponentInterface; |
| 365 |
use super::*; |
| 366 |
|
| 367 |
#[test] |
| 368 |
fn test_minimal_and_rich_function() -> Result<()> { |
| 369 |
let ci = ComponentInterface::from_webidl( |
| 370 |
r#" |
| 371 |
namespace test { |
| 372 |
void minimal(); |
| 373 |
[Throws=TestError] |
| 374 |
sequence<string?> rich(u32 arg1, TestDict arg2); |
| 375 |
}; |
| 376 |
[Error] |
| 377 |
enum TestError { "err" }; |
| 378 |
dictionary TestDict { |
| 379 |
u32 field; |
| 380 |
}; |
| 381 |
"#, |
| 382 |
"crate_name", |
| 383 |
)?; |
| 384 |
|
| 385 |
let func1 = ci.get_function_definition("minimal").unwrap(); |
| 386 |
assert_eq!(func1.name(), "minimal"); |
| 387 |
assert!(func1.return_type().is_none()); |
| 388 |
assert!(func1.throws_type().is_none()); |
| 389 |
assert_eq!(func1.arguments().len(), 0); |
| 390 |
|
| 391 |
let func2 = ci.get_function_definition("rich").unwrap(); |
| 392 |
assert_eq!(func2.name(), "rich"); |
| 393 |
assert_eq!( |
| 394 |
func2.return_type().unwrap(), |
| 395 |
&Type::Sequence { |
| 396 |
inner_type: Box::new(Type::Optional { |
| 397 |
inner_type: Box::new(Type::String) |
| 398 |
}) |
| 399 |
} |
| 400 |
); |
| 401 |
assert!( |
| 402 |
matches!(func2.throws_type(), Some(Type::Enum { name, .. }) if name == "TestError" && ci.is_name_used_as_error(name)) |
| 403 |
); |
| 404 |
assert_eq!(func2.arguments().len(), 2); |
| 405 |
assert_eq!(func2.arguments()[0].name(), "arg1"); |
| 406 |
assert_eq!(func2.arguments()[0].as_type(), Type::UInt32); |
| 407 |
assert_eq!(func2.arguments()[1].name(), "arg2"); |
| 408 |
assert!( |
| 409 |
matches!(func2.arguments()[1].as_type(), Type::Record { name, .. } if name == "TestDict") |
| 410 |
); |
| 411 |
Ok(()) |
| 412 |
} |
| 413 |
|
| 414 |
#[test] |
| 415 |
fn test_docstring_function() { |
| 416 |
const UDL: &str = r#" |
| 417 |
namespace test { |
| 418 |
/// informative docstring |
| 419 |
void testing(); |
| 420 |
}; |
| 421 |
"#; |
| 422 |
let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap(); |
| 423 |
assert_eq!( |
| 424 |
ci.get_function_definition("testing") |
| 425 |
.unwrap() |
| 426 |
.docstring() |
| 427 |
.unwrap(), |
| 428 |
"informative docstring" |
| 429 |
); |
| 430 |
} |
| 431 |
|
| 432 |
#[test] |
| 433 |
fn test_iter_types() { |
| 434 |
let f = Function { |
| 435 |
name: "fn".to_string(), |
| 436 |
module_path: "fn".to_string(), |
| 437 |
is_async: false, |
| 438 |
arguments: vec![Argument { |
| 439 |
name: "a".to_string(), |
| 440 |
type_: Type::Int32, |
| 441 |
by_ref: false, |
| 442 |
optional: true, |
| 443 |
default: None, |
| 444 |
}], |
| 445 |
return_type: Some(Type::Int64), |
| 446 |
ffi_func: FfiFunction::default(), |
| 447 |
docstring: None, |
| 448 |
throws: Some(Type::Int8), |
| 449 |
checksum_fn_name: "".to_string(), |
| 450 |
checksum: None, |
| 451 |
}; |
| 452 |
assert!(f.iter_types().any(|t| matches!(t, Type::Int32))); |
| 453 |
assert!(f.iter_types().any(|t| matches!(t, Type::Int64))); |
| 454 |
assert!(f.iter_types().any(|t| matches!(t, Type::Int8))); |
| 455 |
} |
| 456 |
} |