| 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 |
//! # Component Interface Definition. |
| 6 |
//! |
| 7 |
//! This module provides an abstract representation of the interface provided by a UniFFI Rust Component, |
| 8 |
//! in high-level terms suitable for translation into target consumer languages such as Kotlin |
| 9 |
//! and Swift. It also provides facilities for parsing a WebIDL interface definition file into such a |
| 10 |
//! representation. |
| 11 |
//! |
| 12 |
//! The entrypoint to this crate is the `ComponentInterface` struct, which holds a complete definition |
| 13 |
//! of the interface provided by a component, in two parts: |
| 14 |
//! |
| 15 |
//! * The high-level consumer API, in terms of objects and records and methods and so-on |
| 16 |
//! * The low-level FFI contract through which the foreign language code can call into Rust. |
| 17 |
//! |
| 18 |
//! That's really the key concept of this crate so it's worth repeating: a `ComponentInterface` completely |
| 19 |
//! defines the shape and semantics of an interface between the Rust-based implementation of a component |
| 20 |
//! and its foreign language consumers, including details like: |
| 21 |
//! |
| 22 |
//! * The names of all symbols in the compiled object file |
| 23 |
//! * The type and arity of all exported functions |
| 24 |
//! * The layout and conventions used for all arguments and return types |
| 25 |
//! |
| 26 |
//! If you have a dynamic library compiled from a Rust Component using this crate, and a foreign |
| 27 |
//! language binding generated from the same `ComponentInterface` using the same version of this |
| 28 |
//! module, then there should be no opportunities for them to disagree on how the two sides should |
| 29 |
//! interact. |
| 30 |
//! |
| 31 |
//! General and incomplete TODO list for this thing: |
| 32 |
//! |
| 33 |
//! * It should prevent user error and the possibility of generating bad code by doing (at least) |
| 34 |
//! the following checks: |
| 35 |
//! * No duplicate names (types, methods, args, etc) |
| 36 |
//! * No shadowing of builtin names, or names we use in code generation |
| 37 |
//! |
| 38 |
//! We expect that if the user actually does one of these things, then they *should* get a compile |
| 39 |
//! error when trying to build the component, because the codegen will be invalid. But we can't |
| 40 |
//! guarantee that there's not some edge-case where it produces valid-but-incorrect code. |
| 41 |
//! |
| 42 |
//! * There is a *lot* of cloning going on, in the spirit of "first make it work". There's probably |
| 43 |
//! a good opportunity here for e.g. interned strings, but we're nowhere near the point were we need |
| 44 |
//! that kind of optimization just yet. |
| 45 |
//! |
| 46 |
//! * Error messages and general developer experience leave a lot to be desired. |
| 47 |
|
| 48 |
use std::{ |
| 49 |
collections::{btree_map::Entry, BTreeMap, BTreeSet, HashSet}, |
| 50 |
iter, |
| 51 |
}; |
| 52 |
|
| 53 |
use anyhow::{anyhow, bail, ensure, Context, Result}; |
| 54 |
|
| 55 |
pub mod universe; |
| 56 |
pub use uniffi_meta::{AsType, EnumShape, ObjectImpl, Type}; |
| 57 |
use universe::{TypeIterator, TypeUniverse}; |
| 58 |
|
| 59 |
mod callbacks; |
| 60 |
pub use callbacks::CallbackInterface; |
| 61 |
mod enum_; |
| 62 |
pub use enum_::{Enum, Variant}; |
| 63 |
mod function; |
| 64 |
pub use function::{Argument, Callable, Function, ResultType}; |
| 65 |
mod object; |
| 66 |
pub use object::{Constructor, Method, Object, UniffiTrait}; |
| 67 |
mod record; |
| 68 |
pub use record::{Field, Record}; |
| 69 |
|
| 70 |
pub mod ffi; |
| 71 |
mod visit_mut; |
| 72 |
pub use ffi::{ |
| 73 |
FfiArgument, FfiCallbackFunction, FfiDefinition, FfiField, FfiFunction, FfiStruct, FfiType, |
| 74 |
}; |
| 75 |
pub use uniffi_meta::Radix; |
| 76 |
use uniffi_meta::{ |
| 77 |
ConstructorMetadata, LiteralMetadata, NamespaceMetadata, ObjectMetadata, |
| 78 |
ObjectTraitImplMetadata, TraitMethodMetadata, UniffiTraitMetadata, UNIFFI_CONTRACT_VERSION, |
| 79 |
}; |
| 80 |
pub type Literal = LiteralMetadata; |
| 81 |
|
| 82 |
/// The main public interface for this module, representing the complete details of an interface exposed |
| 83 |
/// by a rust component and the details of consuming it via an extern-C FFI layer. |
| 84 |
#[derive(Clone, Debug, Default)] |
| 85 |
pub struct ComponentInterface { |
| 86 |
/// All of the types used in the interface. |
| 87 |
// We can't checksum `self.types`, but its contents are implied by the other fields |
| 88 |
// anyway, so it's safe to ignore it. |
| 89 |
pub(super) types: TypeUniverse, |
| 90 |
/// The high-level API provided by the component. |
| 91 |
enums: BTreeMap<String, Enum>, |
| 92 |
records: BTreeMap<String, Record>, |
| 93 |
functions: Vec<Function>, |
| 94 |
objects: Vec<Object>, |
| 95 |
callback_interfaces: Vec<CallbackInterface>, |
| 96 |
// Type names which were seen used as an error. |
| 97 |
errors: HashSet<String>, |
| 98 |
// Types which were seen used as callback interface error. |
| 99 |
callback_interface_throws_types: BTreeSet<Type>, |
| 100 |
// A mapping from an external module path to the external namespace. |
| 101 |
crate_to_namespace: BTreeMap<String, NamespaceMetadata>, |
| 102 |
} |
| 103 |
|
| 104 |
impl ComponentInterface { |
| 105 |
pub fn new(crate_name: &str) -> Self { |
| 106 |
assert!(!crate_name.is_empty()); |
| 107 |
Self { |
| 108 |
types: TypeUniverse::new(NamespaceMetadata { |
| 109 |
crate_name: crate_name.to_string(), |
| 110 |
..Default::default() |
| 111 |
}), |
| 112 |
..Default::default() |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
/// Parse a `ComponentInterface` from a string containing a WebIDL definition. |
| 117 |
pub fn from_webidl(idl: &str, module_path: &str) -> Result<Self> { |
| 118 |
ensure!( |
| 119 |
!module_path.is_empty(), |
| 120 |
"you must specify a valid crate name" |
| 121 |
); |
| 122 |
let group = uniffi_udl::parse_udl(idl, module_path)?; |
| 123 |
Self::from_metadata(group) |
| 124 |
} |
| 125 |
|
| 126 |
/// Create a `ComponentInterface` from a `MetadataGroup` |
| 127 |
/// Public so that external binding generators can use it. |
| 128 |
pub fn from_metadata(group: uniffi_meta::MetadataGroup) -> Result<Self> { |
| 129 |
let mut ci = Self { |
| 130 |
types: TypeUniverse::new(group.namespace.clone()), |
| 131 |
..Default::default() |
| 132 |
}; |
| 133 |
ci.add_metadata(group)?; |
| 134 |
Ok(ci) |
| 135 |
} |
| 136 |
|
| 137 |
/// Add a metadata group to a `ComponentInterface`. |
| 138 |
pub fn add_metadata(&mut self, group: uniffi_meta::MetadataGroup) -> Result<()> { |
| 139 |
if self.types.namespace.name.is_empty() { |
| 140 |
self.types.namespace = group.namespace.clone(); |
| 141 |
} else if self.types.namespace != group.namespace { |
| 142 |
bail!( |
| 143 |
"Namespace mismatch: {:?} - {:?}", |
| 144 |
group.namespace, |
| 145 |
self.types.namespace |
| 146 |
); |
| 147 |
} |
| 148 |
|
| 149 |
if group.namespace_docstring.is_some() { |
| 150 |
self.types.namespace_docstring = group.namespace_docstring.clone(); |
| 151 |
} |
| 152 |
|
| 153 |
// Unconditionally add the String type, which is used by the panic handling |
| 154 |
self.types.add_known_type(&Type::String)?; |
| 155 |
crate::macro_metadata::add_group_to_ci(self, group)?; |
| 156 |
Ok(()) |
| 157 |
} |
| 158 |
|
| 159 |
pub fn set_crate_to_namespace_map(&mut self, namespaces: BTreeMap<String, NamespaceMetadata>) { |
| 160 |
assert_eq!( |
| 161 |
namespaces.get(self.crate_name()).unwrap().name, |
| 162 |
self.namespace() |
| 163 |
); |
| 164 |
self.crate_to_namespace = namespaces |
| 165 |
} |
| 166 |
|
| 167 |
/// The string namespace within which this API should be presented to the caller. |
| 168 |
/// |
| 169 |
/// This string would typically be used to prefix function names in the FFI, to build |
| 170 |
/// a package or module name for the foreign language, etc. |
| 171 |
pub fn namespace(&self) -> &str { |
| 172 |
&self.types.namespace.name |
| 173 |
} |
| 174 |
|
| 175 |
pub fn namespace_docstring(&self) -> Option<&str> { |
| 176 |
self.types.namespace_docstring.as_deref() |
| 177 |
} |
| 178 |
|
| 179 |
/// The crate this interfaces lives in. |
| 180 |
pub fn crate_name(&self) -> &str { |
| 181 |
&self.types.namespace.crate_name |
| 182 |
} |
| 183 |
|
| 184 |
pub fn uniffi_contract_version(&self) -> u32 { |
| 185 |
// This is set by the scripts in the version-mismatch fixture |
| 186 |
let force_version = std::env::var("UNIFFI_FORCE_CONTRACT_VERSION"); |
| 187 |
match force_version { |
| 188 |
Ok(v) if !v.is_empty() => v.parse().unwrap(), |
| 189 |
_ => UNIFFI_CONTRACT_VERSION, |
| 190 |
} |
| 191 |
} |
| 192 |
|
| 193 |
/// Get the definitions for every Enum type in the interface. |
| 194 |
pub fn enum_definitions(&self) -> impl Iterator<Item = &Enum> { |
| 195 |
self.enums.values() |
| 196 |
} |
| 197 |
|
| 198 |
/// Get an Enum definition by name, or None if no such Enum is defined. |
| 199 |
pub fn get_enum_definition(&self, name: &str) -> Option<&Enum> { |
| 200 |
self.enums.get(name) |
| 201 |
} |
| 202 |
|
| 203 |
/// Get the definitions for every Record type in the interface. |
| 204 |
pub fn record_definitions(&self) -> impl Iterator<Item = &Record> { |
| 205 |
self.records.values() |
| 206 |
} |
| 207 |
|
| 208 |
/// Get a Record definition by name, or None if no such Record is defined. |
| 209 |
pub fn get_record_definition(&self, name: &str) -> Option<&Record> { |
| 210 |
self.records.get(name) |
| 211 |
} |
| 212 |
|
| 213 |
/// Get the definitions for every Function in the interface. |
| 214 |
pub fn function_definitions(&self) -> &[Function] { |
| 215 |
&self.functions |
| 216 |
} |
| 217 |
|
| 218 |
/// Get a Function definition by name, or None if no such Function is defined. |
| 219 |
pub fn get_function_definition(&self, name: &str) -> Option<&Function> { |
| 220 |
// TODO: probably we could store these internally in a HashMap to make this easier? |
| 221 |
self.functions.iter().find(|f| f.name == name) |
| 222 |
} |
| 223 |
|
| 224 |
/// Returns `true` if we have any objects in this interface. |
| 225 |
pub fn has_object_definitions(&self) -> bool { |
| 226 |
!self.objects.is_empty() |
| 227 |
} |
| 228 |
|
| 229 |
/// Get the definitions for every Object type in the interface. |
| 230 |
pub fn object_definitions(&self) -> &[Object] { |
| 231 |
&self.objects |
| 232 |
} |
| 233 |
|
| 234 |
/// Get an Object definition by name, or None if no such Object is defined. |
| 235 |
pub fn get_object_definition(&self, name: &str) -> Option<&Object> { |
| 236 |
// TODO: probably we could store these internally in a HashMap to make this easier? |
| 237 |
self.objects.iter().find(|o| o.name == name) |
| 238 |
} |
| 239 |
|
| 240 |
fn callback_interface_callback_definitions( |
| 241 |
&self, |
| 242 |
) -> impl IntoIterator<Item = FfiCallbackFunction> + '_ { |
| 243 |
self.callback_interfaces |
| 244 |
.iter() |
| 245 |
.flat_map(|cbi| cbi.ffi_callbacks()) |
| 246 |
.chain(self.objects.iter().flat_map(|o| o.ffi_callbacks())) |
| 247 |
} |
| 248 |
|
| 249 |
/// Get the definitions for callback FFI functions |
| 250 |
/// |
| 251 |
/// These are defined by the foreign code and invoked by Rust. |
| 252 |
fn callback_interface_vtable_definitions(&self) -> impl IntoIterator<Item = FfiStruct> + '_ { |
| 253 |
self.callback_interface_definitions() |
| 254 |
.iter() |
| 255 |
.map(|cbi| cbi.vtable_definition()) |
| 256 |
.chain( |
| 257 |
self.object_definitions() |
| 258 |
.iter() |
| 259 |
.flat_map(|o| o.vtable_definition()), |
| 260 |
) |
| 261 |
} |
| 262 |
|
| 263 |
/// Get the definitions for every Callback Interface type in the interface. |
| 264 |
pub fn callback_interface_definitions(&self) -> &[CallbackInterface] { |
| 265 |
&self.callback_interfaces |
| 266 |
} |
| 267 |
|
| 268 |
/// Get a Callback interface definition by name, or None if no such interface is defined. |
| 269 |
pub fn get_callback_interface_definition(&self, name: &str) -> Option<&CallbackInterface> { |
| 270 |
// TODO: probably we could store these internally in a HashMap to make this easier? |
| 271 |
self.callback_interfaces.iter().find(|o| o.name == name) |
| 272 |
} |
| 273 |
|
| 274 |
/// Get the definitions for every Callback Interface type in the interface. |
| 275 |
pub fn has_async_callback_interface_definition(&self) -> bool { |
| 276 |
self.callback_interfaces |
| 277 |
.iter() |
| 278 |
.any(|cbi| cbi.has_async_method()) |
| 279 |
|| self |
| 280 |
.objects |
| 281 |
.iter() |
| 282 |
.any(|o| o.has_callback_interface() && o.has_async_method()) |
| 283 |
} |
| 284 |
|
| 285 |
pub fn has_callback_definitions(&self) -> bool { |
| 286 |
!self.callback_interface_definitions().is_empty() |
| 287 |
|| self |
| 288 |
.object_definitions() |
| 289 |
.iter() |
| 290 |
.any(|o| o.has_callback_interface()) |
| 291 |
} |
| 292 |
|
| 293 |
/// Get the definitions for every Method type in the interface. |
| 294 |
pub fn iter_callables(&self) -> impl Iterator<Item = &dyn Callable> { |
| 295 |
// Each of the `as &dyn Callable` casts is a trivial cast, but it seems like the clearest |
| 296 |
// way to express the logic in the current Rust |
| 297 |
#[allow(trivial_casts)] |
| 298 |
self.function_definitions() |
| 299 |
.iter() |
| 300 |
.map(|f| f as &dyn Callable) |
| 301 |
.chain(self.objects.iter().flat_map(|o| { |
| 302 |
o.constructors() |
| 303 |
.into_iter() |
| 304 |
.map(|c| c as &dyn Callable) |
| 305 |
.chain(o.methods().into_iter().map(|m| m as &dyn Callable)) |
| 306 |
})) |
| 307 |
} |
| 308 |
|
| 309 |
/// Should we generate read (and lift) functions for errors? |
| 310 |
/// |
| 311 |
/// This is a workaround for the fact that lower/write can't be generated for some errors, |
| 312 |
/// specifically errors that are defined as flat in the UDL, but actually have fields in the |
| 313 |
/// Rust source. |
| 314 |
pub fn should_generate_error_read(&self, e: &Enum) -> bool { |
| 315 |
// We can and should always generate read() methods for fielded errors |
| 316 |
let fielded = !e.is_flat(); |
| 317 |
// For flat errors, we should only generate read() methods if we need them to support |
| 318 |
// callback interface errors |
| 319 |
let used_in_foreign_interface = self |
| 320 |
.callback_interface_definitions() |
| 321 |
.iter() |
| 322 |
.flat_map(|cb| cb.methods()) |
| 323 |
.chain( |
| 324 |
self.object_definitions() |
| 325 |
.iter() |
| 326 |
.filter(|o| o.has_callback_interface()) |
| 327 |
.flat_map(|o| o.methods()), |
| 328 |
) |
| 329 |
.any(|m| m.throws_type() == Some(&e.as_type())); |
| 330 |
|
| 331 |
self.is_name_used_as_error(&e.name) && (fielded || used_in_foreign_interface) |
| 332 |
} |
| 333 |
|
| 334 |
/// Iterate over all known local types in the interface. |
| 335 |
pub fn iter_local_types(&self) -> impl Iterator<Item = &Type> { |
| 336 |
self.types.iter_local_types() |
| 337 |
} |
| 338 |
|
| 339 |
/// Get details about all `Type`s defined in external crates. |
| 340 |
pub fn iter_external_types(&self) -> impl Iterator<Item = &Type> { |
| 341 |
self.types.iter_external_types() |
| 342 |
} |
| 343 |
|
| 344 |
// Keep only the local types in an iterator of types. |
| 345 |
pub fn filter_local_types<'a>( |
| 346 |
&'a self, |
| 347 |
types: impl Iterator<Item = &'a Type>, |
| 348 |
) -> impl Iterator<Item = &'a Type> { |
| 349 |
self.types.filter_local_types(types) |
| 350 |
} |
| 351 |
|
| 352 |
pub fn is_external(&self, t: &Type) -> bool { |
| 353 |
self.types.is_external(t) |
| 354 |
} |
| 355 |
|
| 356 |
/// Get a specific type |
| 357 |
pub fn get_type(&self, name: &str) -> Option<Type> { |
| 358 |
self.types.get_type_definition(name) |
| 359 |
} |
| 360 |
|
| 361 |
pub fn namespace_for_type(&self, ty: &Type) -> Result<&str> { |
| 362 |
let mod_path = ty |
| 363 |
.module_path() |
| 364 |
.ok_or_else(|| anyhow!("type {ty:?} has no module path"))?; |
| 365 |
self.namespace_for_module_path(mod_path) |
| 366 |
} |
| 367 |
|
| 368 |
pub fn namespace_for_module_path(&self, module_path: &str) -> Result<&str> { |
| 369 |
self.crate_to_namespace |
| 370 |
.get(module_path) |
| 371 |
.map(|n| n.name.as_ref()) |
| 372 |
// incase not library mode and we've not been told |
| 373 |
.or_else(|| (module_path == self.crate_name()).then(|| self.namespace())) |
| 374 |
.ok_or_else(|| anyhow!("unresolved module path {module_path}")) |
| 375 |
} |
| 376 |
|
| 377 |
/// Iterate over all types contained in the given item. |
| 378 |
/// |
| 379 |
/// This method uses `iter_types` to iterate over the types contained within the given type, |
| 380 |
/// but additionally recurses into the definition of user-defined types like records and enums |
| 381 |
/// to yield the types that *they* contain. |
| 382 |
fn iter_types_in_item<'a>(&'a self, item: &'a Type) -> impl Iterator<Item = &'a Type> + 'a { |
| 383 |
RecursiveTypeIterator::new(self, item) |
| 384 |
} |
| 385 |
|
| 386 |
/// Check whether the given item contains any (possibly nested) Type::Object references. |
| 387 |
/// |
| 388 |
/// This is important to know in language bindings that cannot integrate object types |
| 389 |
/// tightly with the host GC, and hence need to perform manual destruction of objects. |
| 390 |
pub fn item_contains_object_references(&self, item: &Type) -> bool { |
| 391 |
self.iter_types_in_item(item) |
| 392 |
.any(|t| matches!(t, Type::Object { .. })) |
| 393 |
} |
| 394 |
|
| 395 |
/// Check whether the given item contains any (possibly nested) unsigned types |
| 396 |
pub fn item_contains_unsigned_types(&self, item: &Type) -> bool { |
| 397 |
self.iter_types_in_item(item) |
| 398 |
.any(|t| matches!(t, Type::UInt8 | Type::UInt16 | Type::UInt32 | Type::UInt64)) |
| 399 |
} |
| 400 |
|
| 401 |
/// Check whether the interface contains any optional types |
| 402 |
pub fn contains_optional_types(&self) -> bool { |
| 403 |
self.types |
| 404 |
.iter_local_types() |
| 405 |
.any(|t| matches!(t, Type::Optional { .. })) |
| 406 |
} |
| 407 |
|
| 408 |
/// Check whether the interface contains any sequence types |
| 409 |
pub fn contains_sequence_types(&self) -> bool { |
| 410 |
self.types |
| 411 |
.iter_local_types() |
| 412 |
.any(|t| matches!(t, Type::Sequence { .. })) |
| 413 |
} |
| 414 |
|
| 415 |
/// Check whether the interface contains any map types |
| 416 |
pub fn contains_map_types(&self) -> bool { |
| 417 |
self.types |
| 418 |
.iter_local_types() |
| 419 |
.any(|t| matches!(t, Type::Map { .. })) |
| 420 |
} |
| 421 |
|
| 422 |
/// Check whether the interface contains any object types |
| 423 |
pub fn contains_object_types(&self) -> bool { |
| 424 |
self.types |
| 425 |
.iter_local_types() |
| 426 |
.any(|t| matches!(t, Type::Object { .. })) |
| 427 |
} |
| 428 |
|
| 429 |
// The namespace to use in crate-level FFI function definitions. Not used as the ffi |
| 430 |
// namespace for types - each type has its own `module_path` which is used for them. |
| 431 |
fn ffi_namespace(&self) -> &str { |
| 432 |
&self.types.namespace.crate_name |
| 433 |
} |
| 434 |
|
| 435 |
/// Builtin FFI function to get the current contract version |
| 436 |
/// This is needed so that the foreign language bindings can check that they are using the same |
| 437 |
/// ABI as the scaffolding |
| 438 |
pub fn ffi_uniffi_contract_version(&self) -> FfiFunction { |
| 439 |
FfiFunction { |
| 440 |
name: format!("ffi_{}_uniffi_contract_version", self.ffi_namespace()), |
| 441 |
is_async: false, |
| 442 |
arguments: vec![], |
| 443 |
return_type: Some(FfiType::UInt32), |
| 444 |
has_rust_call_status_arg: false, |
| 445 |
is_object_free_function: false, |
| 446 |
} |
| 447 |
} |
| 448 |
|
| 449 |
/// Builtin FFI function for allocating a new `RustBuffer`. |
| 450 |
/// This is needed so that the foreign language bindings can create buffers in which to pass |
| 451 |
/// complex data types across the FFI. |
| 452 |
pub fn ffi_rustbuffer_alloc(&self) -> FfiFunction { |
| 453 |
FfiFunction { |
| 454 |
name: format!("ffi_{}_rustbuffer_alloc", self.ffi_namespace()), |
| 455 |
is_async: false, |
| 456 |
arguments: vec![FfiArgument { |
| 457 |
name: "size".to_string(), |
| 458 |
type_: FfiType::UInt64, |
| 459 |
}], |
| 460 |
return_type: Some(FfiType::RustBuffer(None)), |
| 461 |
has_rust_call_status_arg: true, |
| 462 |
is_object_free_function: false, |
| 463 |
} |
| 464 |
} |
| 465 |
|
| 466 |
/// Builtin FFI function for copying foreign-owned bytes |
| 467 |
/// This is needed so that the foreign language bindings can create buffers in which to pass |
| 468 |
/// complex data types across the FFI. |
| 469 |
pub fn ffi_rustbuffer_from_bytes(&self) -> FfiFunction { |
| 470 |
FfiFunction { |
| 471 |
name: format!("ffi_{}_rustbuffer_from_bytes", self.ffi_namespace()), |
| 472 |
is_async: false, |
| 473 |
arguments: vec![FfiArgument { |
| 474 |
name: "bytes".to_string(), |
| 475 |
type_: FfiType::ForeignBytes, |
| 476 |
}], |
| 477 |
return_type: Some(FfiType::RustBuffer(None)), |
| 478 |
has_rust_call_status_arg: true, |
| 479 |
is_object_free_function: false, |
| 480 |
} |
| 481 |
} |
| 482 |
|
| 483 |
/// Builtin FFI function for freeing a `RustBuffer`. |
| 484 |
/// This is needed so that the foreign language bindings can free buffers in which they received |
| 485 |
/// complex data types returned across the FFI. |
| 486 |
pub fn ffi_rustbuffer_free(&self) -> FfiFunction { |
| 487 |
FfiFunction { |
| 488 |
name: format!("ffi_{}_rustbuffer_free", self.ffi_namespace()), |
| 489 |
is_async: false, |
| 490 |
arguments: vec![FfiArgument { |
| 491 |
name: "buf".to_string(), |
| 492 |
type_: FfiType::RustBuffer(None), |
| 493 |
}], |
| 494 |
return_type: None, |
| 495 |
has_rust_call_status_arg: true, |
| 496 |
is_object_free_function: false, |
| 497 |
} |
| 498 |
} |
| 499 |
|
| 500 |
/// Builtin FFI function for reserving extra space in a `RustBuffer`. |
| 501 |
/// This is needed so that the foreign language bindings can grow buffers used for passing |
| 502 |
/// complex data types across the FFI. |
| 503 |
pub fn ffi_rustbuffer_reserve(&self) -> FfiFunction { |
| 504 |
FfiFunction { |
| 505 |
name: format!("ffi_{}_rustbuffer_reserve", self.ffi_namespace()), |
| 506 |
is_async: false, |
| 507 |
arguments: vec![ |
| 508 |
FfiArgument { |
| 509 |
name: "buf".to_string(), |
| 510 |
type_: FfiType::RustBuffer(None), |
| 511 |
}, |
| 512 |
FfiArgument { |
| 513 |
name: "additional".to_string(), |
| 514 |
type_: FfiType::UInt64, |
| 515 |
}, |
| 516 |
], |
| 517 |
return_type: Some(FfiType::RustBuffer(None)), |
| 518 |
has_rust_call_status_arg: true, |
| 519 |
is_object_free_function: false, |
| 520 |
} |
| 521 |
} |
| 522 |
|
| 523 |
/// Builtin FFI function to poll a Rust future. |
| 524 |
pub fn ffi_rust_future_poll(&self, return_ffi_type: Option<FfiType>) -> FfiFunction { |
| 525 |
FfiFunction { |
| 526 |
name: self.rust_future_ffi_fn_name("rust_future_poll", return_ffi_type), |
| 527 |
is_async: false, |
| 528 |
arguments: vec![ |
| 529 |
FfiArgument { |
| 530 |
name: "handle".to_owned(), |
| 531 |
type_: FfiType::Handle, |
| 532 |
}, |
| 533 |
FfiArgument { |
| 534 |
name: "callback".to_owned(), |
| 535 |
type_: FfiType::Callback("RustFutureContinuationCallback".to_owned()), |
| 536 |
}, |
| 537 |
FfiArgument { |
| 538 |
name: "callback_data".to_owned(), |
| 539 |
type_: FfiType::Handle, |
| 540 |
}, |
| 541 |
], |
| 542 |
return_type: None, |
| 543 |
has_rust_call_status_arg: false, |
| 544 |
is_object_free_function: false, |
| 545 |
} |
| 546 |
} |
| 547 |
|
| 548 |
/// Builtin FFI function to complete a Rust future and get it's result. |
| 549 |
/// |
| 550 |
/// We generate one of these for each FFI return type. |
| 551 |
pub fn ffi_rust_future_complete(&self, return_ffi_type: Option<FfiType>) -> FfiFunction { |
| 552 |
FfiFunction { |
| 553 |
name: self.rust_future_ffi_fn_name("rust_future_complete", return_ffi_type.clone()), |
| 554 |
is_async: false, |
| 555 |
arguments: vec![FfiArgument { |
| 556 |
name: "handle".to_owned(), |
| 557 |
type_: FfiType::Handle, |
| 558 |
}], |
| 559 |
return_type: return_ffi_type, |
| 560 |
has_rust_call_status_arg: true, |
| 561 |
is_object_free_function: false, |
| 562 |
} |
| 563 |
} |
| 564 |
|
| 565 |
/// Builtin FFI function for cancelling a Rust Future |
| 566 |
pub fn ffi_rust_future_cancel(&self, return_ffi_type: Option<FfiType>) -> FfiFunction { |
| 567 |
FfiFunction { |
| 568 |
name: self.rust_future_ffi_fn_name("rust_future_cancel", return_ffi_type), |
| 569 |
is_async: false, |
| 570 |
arguments: vec![FfiArgument { |
| 571 |
name: "handle".to_owned(), |
| 572 |
type_: FfiType::Handle, |
| 573 |
}], |
| 574 |
return_type: None, |
| 575 |
has_rust_call_status_arg: false, |
| 576 |
is_object_free_function: false, |
| 577 |
} |
| 578 |
} |
| 579 |
|
| 580 |
/// Builtin FFI function for freeing a Rust Future |
| 581 |
pub fn ffi_rust_future_free(&self, return_ffi_type: Option<FfiType>) -> FfiFunction { |
| 582 |
FfiFunction { |
| 583 |
name: self.rust_future_ffi_fn_name("rust_future_free", return_ffi_type), |
| 584 |
is_async: false, |
| 585 |
arguments: vec![FfiArgument { |
| 586 |
name: "handle".to_owned(), |
| 587 |
type_: FfiType::Handle, |
| 588 |
}], |
| 589 |
return_type: None, |
| 590 |
has_rust_call_status_arg: false, |
| 591 |
is_object_free_function: false, |
| 592 |
} |
| 593 |
} |
| 594 |
|
| 595 |
fn rust_future_ffi_fn_name(&self, base_name: &str, return_ffi_type: Option<FfiType>) -> String { |
| 596 |
let namespace = self.ffi_namespace(); |
| 597 |
let return_type_name = FfiType::return_type_name(return_ffi_type.as_ref()); |
| 598 |
format!("ffi_{namespace}_{base_name}_{return_type_name}") |
| 599 |
} |
| 600 |
|
| 601 |
/// Does this interface contain async functions? |
| 602 |
pub fn has_async_fns(&self) -> bool { |
| 603 |
self.iter_ffi_function_definitions().any(|f| f.is_async()) |
| 604 |
|| self |
| 605 |
.callback_interfaces |
| 606 |
.iter() |
| 607 |
.any(CallbackInterface::has_async_method) |
| 608 |
} |
| 609 |
|
| 610 |
/// Iterate over `T` parameters of the `FutureCallback<T>` callbacks in this interface |
| 611 |
pub fn iter_future_callback_params(&self) -> impl Iterator<Item = FfiType> { |
| 612 |
let unique_results = self |
| 613 |
.iter_callables() |
| 614 |
.map(|c| c.result_type().future_callback_param()) |
| 615 |
.collect::<BTreeSet<_>>(); |
| 616 |
unique_results.into_iter() |
| 617 |
} |
| 618 |
|
| 619 |
/// Iterate over return/throws types for async functions |
| 620 |
pub fn iter_async_result_types(&self) -> impl Iterator<Item = ResultType<'_>> { |
| 621 |
let unique_results = self |
| 622 |
.iter_callables() |
| 623 |
.map(|c| c.result_type()) |
| 624 |
.collect::<BTreeSet<_>>(); |
| 625 |
unique_results.into_iter() |
| 626 |
} |
| 627 |
|
| 628 |
/// Iterate over all Ffi definitions |
| 629 |
pub fn ffi_definitions(&self) -> impl Iterator<Item = FfiDefinition> + '_ { |
| 630 |
// Note: for languages like Python it's important to keep things in dependency order. |
| 631 |
// For example some FFI function definitions depend on FFI struct definitions, so the |
| 632 |
// function definitions come last. |
| 633 |
self.builtin_ffi_definitions() |
| 634 |
.into_iter() |
| 635 |
.chain( |
| 636 |
self.callback_interface_callback_definitions() |
| 637 |
.into_iter() |
| 638 |
.map(Into::into), |
| 639 |
) |
| 640 |
.chain( |
| 641 |
self.callback_interface_vtable_definitions() |
| 642 |
.into_iter() |
| 643 |
.map(Into::into), |
| 644 |
) |
| 645 |
.chain(self.iter_ffi_function_definitions().map(Into::into)) |
| 646 |
} |
| 647 |
|
| 648 |
fn builtin_ffi_definitions(&self) -> impl IntoIterator<Item = FfiDefinition> + '_ { |
| 649 |
[ |
| 650 |
FfiCallbackFunction { |
| 651 |
name: "RustFutureContinuationCallback".to_owned(), |
| 652 |
arguments: vec![ |
| 653 |
FfiArgument::new("data", FfiType::UInt64), |
| 654 |
FfiArgument::new("poll_result", FfiType::Int8), |
| 655 |
], |
| 656 |
return_type: None, |
| 657 |
has_rust_call_status_arg: false, |
| 658 |
} |
| 659 |
.into(), |
| 660 |
FfiCallbackFunction { |
| 661 |
name: "ForeignFutureFree".to_owned(), |
| 662 |
arguments: vec![FfiArgument::new("handle", FfiType::UInt64)], |
| 663 |
return_type: None, |
| 664 |
has_rust_call_status_arg: false, |
| 665 |
} |
| 666 |
.into(), |
| 667 |
FfiCallbackFunction { |
| 668 |
name: "CallbackInterfaceFree".to_owned(), |
| 669 |
arguments: vec![FfiArgument::new("handle", FfiType::UInt64)], |
| 670 |
return_type: None, |
| 671 |
has_rust_call_status_arg: false, |
| 672 |
} |
| 673 |
.into(), |
| 674 |
FfiStruct { |
| 675 |
name: "ForeignFuture".to_owned(), |
| 676 |
fields: vec![ |
| 677 |
FfiField::new("handle", FfiType::UInt64), |
| 678 |
FfiField::new("free", FfiType::Callback("ForeignFutureFree".to_owned())), |
| 679 |
], |
| 680 |
} |
| 681 |
.into(), |
| 682 |
] |
| 683 |
.into_iter() |
| 684 |
.chain( |
| 685 |
self.all_possible_return_ffi_types() |
| 686 |
.flat_map(|return_type| { |
| 687 |
[ |
| 688 |
callbacks::foreign_future_ffi_result_struct(return_type.clone()).into(), |
| 689 |
callbacks::ffi_foreign_future_complete(return_type).into(), |
| 690 |
] |
| 691 |
}), |
| 692 |
) |
| 693 |
} |
| 694 |
|
| 695 |
/// List the definitions of all FFI functions in the interface. |
| 696 |
/// |
| 697 |
/// The set of FFI functions is derived automatically from the set of higher-level types |
| 698 |
/// along with the builtin FFI helper functions. |
| 699 |
pub fn iter_ffi_function_definitions(&self) -> impl Iterator<Item = FfiFunction> + '_ { |
| 700 |
self.iter_ffi_function_definitions_conditionally_include_integrity_checks(true) |
| 701 |
} |
| 702 |
|
| 703 |
pub fn iter_ffi_function_definitions_excluding_integrity_checks( |
| 704 |
&self, |
| 705 |
) -> impl Iterator<Item = FfiFunction> + '_ { |
| 706 |
self.iter_ffi_function_definitions_conditionally_include_integrity_checks(false) |
| 707 |
} |
| 708 |
|
| 709 |
fn iter_ffi_function_definitions_conditionally_include_integrity_checks( |
| 710 |
&self, |
| 711 |
include_checksums: bool, |
| 712 |
) -> impl Iterator<Item = FfiFunction> + '_ { |
| 713 |
let iterator = self |
| 714 |
.iter_user_ffi_function_definitions() |
| 715 |
.cloned() |
| 716 |
.chain(self.iter_rust_buffer_ffi_function_definitions()) |
| 717 |
.chain(self.iter_futures_ffi_function_definitions()); |
| 718 |
|
| 719 |
// Conditionally determine if the checksums should be included or not. |
| 720 |
if include_checksums { |
| 721 |
Box::new(iterator.chain(self.iter_ffi_function_integrity_checks())) |
| 722 |
as Box<dyn Iterator<Item = FfiFunction> + '_> |
| 723 |
} else { |
| 724 |
Box::new(iterator) as Box<dyn Iterator<Item = FfiFunction> + '_> |
| 725 |
} |
| 726 |
} |
| 727 |
|
| 728 |
pub fn iter_ffi_function_integrity_checks(&self) -> impl Iterator<Item = FfiFunction> + '_ { |
| 729 |
iter::empty() |
| 730 |
.chain(self.iter_checksum_ffi_functions()) |
| 731 |
.chain([self.ffi_uniffi_contract_version()]) |
| 732 |
} |
| 733 |
|
| 734 |
/// Alternate version of iter_ffi_function_definitions for languages that don't support async |
| 735 |
pub fn iter_ffi_function_definitions_non_async( |
| 736 |
&self, |
| 737 |
) -> impl Iterator<Item = FfiFunction> + '_ { |
| 738 |
self.iter_user_ffi_function_definitions() |
| 739 |
.cloned() |
| 740 |
.chain(self.iter_rust_buffer_ffi_function_definitions()) |
| 741 |
.chain(self.iter_ffi_function_integrity_checks()) |
| 742 |
} |
| 743 |
|
| 744 |
/// List all FFI functions definitions for user-defined interfaces |
| 745 |
/// |
| 746 |
/// This includes FFI functions for: |
| 747 |
/// - Top-level functions |
| 748 |
/// - Object methods |
| 749 |
/// - Callback interfaces |
| 750 |
pub fn iter_user_ffi_function_definitions(&self) -> impl Iterator<Item = &FfiFunction> + '_ { |
| 751 |
iter::empty() |
| 752 |
.chain( |
| 753 |
self.objects |
| 754 |
.iter() |
| 755 |
.flat_map(|obj| obj.iter_ffi_function_definitions()), |
| 756 |
) |
| 757 |
.chain( |
| 758 |
self.callback_interfaces |
| 759 |
.iter() |
| 760 |
.map(|cb| cb.ffi_init_callback()), |
| 761 |
) |
| 762 |
.chain(self.functions.iter().map(|f| &f.ffi_func)) |
| 763 |
} |
| 764 |
|
| 765 |
/// List all FFI functions definitions for RustBuffer functionality. |
| 766 |
pub fn iter_rust_buffer_ffi_function_definitions(&self) -> impl Iterator<Item = FfiFunction> { |
| 767 |
[ |
| 768 |
self.ffi_rustbuffer_alloc(), |
| 769 |
self.ffi_rustbuffer_from_bytes(), |
| 770 |
self.ffi_rustbuffer_free(), |
| 771 |
self.ffi_rustbuffer_reserve(), |
| 772 |
] |
| 773 |
.into_iter() |
| 774 |
} |
| 775 |
|
| 776 |
fn all_possible_return_ffi_types(&self) -> impl Iterator<Item = Option<FfiType>> { |
| 777 |
[ |
| 778 |
Some(FfiType::UInt8), |
| 779 |
Some(FfiType::Int8), |
| 780 |
Some(FfiType::UInt16), |
| 781 |
Some(FfiType::Int16), |
| 782 |
Some(FfiType::UInt32), |
| 783 |
Some(FfiType::Int32), |
| 784 |
Some(FfiType::UInt64), |
| 785 |
Some(FfiType::Int64), |
| 786 |
Some(FfiType::Float32), |
| 787 |
Some(FfiType::Float64), |
| 788 |
// RustBuffer and RustArcPtr have an inner field which we have to fill in with a |
| 789 |
// placeholder value. |
| 790 |
Some(FfiType::RustArcPtr("".to_owned())), |
| 791 |
Some(FfiType::RustBuffer(None)), |
| 792 |
None, |
| 793 |
] |
| 794 |
.into_iter() |
| 795 |
} |
| 796 |
|
| 797 |
/// List all FFI functions definitions for async functionality. |
| 798 |
pub fn iter_futures_ffi_function_definitions(&self) -> impl Iterator<Item = FfiFunction> + '_ { |
| 799 |
self.all_possible_return_ffi_types() |
| 800 |
.flat_map(|return_type| { |
| 801 |
[ |
| 802 |
self.ffi_rust_future_poll(return_type.clone()), |
| 803 |
self.ffi_rust_future_cancel(return_type.clone()), |
| 804 |
self.ffi_rust_future_free(return_type.clone()), |
| 805 |
self.ffi_rust_future_complete(return_type), |
| 806 |
] |
| 807 |
}) |
| 808 |
} |
| 809 |
|
| 810 |
/// List all API checksums to check |
| 811 |
/// |
| 812 |
/// Returns a list of (export_symbol_name, checksum) items |
| 813 |
pub fn iter_checksums(&self) -> impl Iterator<Item = (String, u16)> + '_ { |
| 814 |
let func_checksums = self |
| 815 |
.functions |
| 816 |
.iter() |
| 817 |
.map(|f| (f.checksum_fn_name(), f.checksum())); |
| 818 |
let method_checksums = self.objects.iter().flat_map(|o| { |
| 819 |
o.methods() |
| 820 |
.into_iter() |
| 821 |
.map(|m| (m.checksum_fn_name(), m.checksum())) |
| 822 |
}); |
| 823 |
let constructor_checksums = self.objects.iter().flat_map(|o| { |
| 824 |
o.constructors() |
| 825 |
.into_iter() |
| 826 |
.map(|c| (c.checksum_fn_name(), c.checksum())) |
| 827 |
}); |
| 828 |
let callback_method_checksums = self.callback_interfaces.iter().flat_map(|cbi| { |
| 829 |
cbi.methods().into_iter().filter_map(|m| { |
| 830 |
if m.checksum_fn_name().is_empty() { |
| 831 |
// UDL-based callbacks don't have checksum functions, skip these |
| 832 |
None |
| 833 |
} else { |
| 834 |
Some((m.checksum_fn_name(), m.checksum())) |
| 835 |
} |
| 836 |
}) |
| 837 |
}); |
| 838 |
func_checksums |
| 839 |
.chain(method_checksums) |
| 840 |
.chain(constructor_checksums) |
| 841 |
.chain(callback_method_checksums) |
| 842 |
.map(|(fn_name, checksum)| (fn_name.to_string(), checksum)) |
| 843 |
} |
| 844 |
|
| 845 |
pub fn iter_checksum_ffi_functions(&self) -> impl Iterator<Item = FfiFunction> + '_ { |
| 846 |
self.iter_checksums().map(|(name, _)| FfiFunction { |
| 847 |
name, |
| 848 |
is_async: false, |
| 849 |
arguments: vec![], |
| 850 |
return_type: Some(FfiType::UInt16), |
| 851 |
has_rust_call_status_arg: false, |
| 852 |
is_object_free_function: false, |
| 853 |
}) |
| 854 |
} |
| 855 |
|
| 856 |
// Private methods for building a ComponentInterface. |
| 857 |
// |
| 858 |
/// Called by `APIBuilder` impls to add a newly-parsed enum definition to the `ComponentInterface`. |
| 859 |
pub(super) fn add_enum_definition(&mut self, defn: Enum) -> Result<()> { |
| 860 |
match self.enums.entry(defn.name().to_owned()) { |
| 861 |
Entry::Vacant(v) => { |
| 862 |
if matches!(defn.shape, EnumShape::Error { .. }) { |
| 863 |
self.errors.insert(defn.name.clone()); |
| 864 |
} |
| 865 |
self.types |
| 866 |
.add_known_types(defn.iter_types()) |
| 867 |
.with_context(|| format!("adding enum {defn:?}"))?; |
| 868 |
v.insert(defn); |
| 869 |
} |
| 870 |
Entry::Occupied(o) => { |
| 871 |
let existing_def = o.get(); |
| 872 |
if defn != *existing_def { |
| 873 |
bail!( |
| 874 |
"Mismatching definition for enum `{}`!\n\ |
| 875 |
existing definition: {existing_def:#?},\n\ |
| 876 |
new definition: {defn:#?}", |
| 877 |
defn.name(), |
| 878 |
); |
| 879 |
} |
| 880 |
} |
| 881 |
} |
| 882 |
|
| 883 |
Ok(()) |
| 884 |
} |
| 885 |
|
| 886 |
/// Adds a newly-parsed record definition to the `ComponentInterface`. |
| 887 |
pub(super) fn add_record_definition(&mut self, defn: Record) -> Result<()> { |
| 888 |
match self.records.entry(defn.name().to_owned()) { |
| 889 |
Entry::Vacant(v) => { |
| 890 |
self.types |
| 891 |
.add_known_types(defn.iter_types()) |
| 892 |
.with_context(|| format!("adding record {defn:?}"))?; |
| 893 |
v.insert(defn); |
| 894 |
} |
| 895 |
Entry::Occupied(o) => { |
| 896 |
let existing_def = o.get(); |
| 897 |
if defn != *existing_def { |
| 898 |
bail!( |
| 899 |
"Mismatching definition for record `{}`!\n\ |
| 900 |
existing definition: {existing_def:#?},\n\ |
| 901 |
new definition: {defn:#?}", |
| 902 |
defn.name(), |
| 903 |
); |
| 904 |
} |
| 905 |
} |
| 906 |
} |
| 907 |
|
| 908 |
Ok(()) |
| 909 |
} |
| 910 |
|
| 911 |
/// Called by `APIBuilder` impls to add a newly-parsed function definition to the `ComponentInterface`. |
| 912 |
pub(super) fn add_function_definition(&mut self, defn: Function) -> Result<()> { |
| 913 |
// Since functions are not a first-class type, we have to check for duplicates here |
| 914 |
// rather than relying on the type-finding pass to catch them. |
| 915 |
if self.functions.iter().any(|f| f.name == defn.name) { |
| 916 |
bail!("duplicate function definition: \"{}\"", defn.name); |
| 917 |
} |
| 918 |
if self.types.get_type_definition(defn.name()).is_some() { |
| 919 |
bail!("Conflicting type definition for \"{}\"", defn.name()); |
| 920 |
} |
| 921 |
self.types |
| 922 |
.add_known_types(defn.iter_types()) |
| 923 |
.with_context(|| format!("adding function {defn:?}"))?; |
| 924 |
defn.throws_name() |
| 925 |
.map(|n| self.errors.insert(n.to_string())); |
| 926 |
self.functions.push(defn); |
| 927 |
|
| 928 |
Ok(()) |
| 929 |
} |
| 930 |
|
| 931 |
pub(super) fn add_constructor_meta(&mut self, meta: ConstructorMetadata) -> Result<()> { |
| 932 |
let object = get_object(&mut self.objects, &meta.self_name) |
| 933 |
.ok_or_else(|| anyhow!("add_constructor_meta: object {} not found", &meta.self_name))?; |
| 934 |
let defn: Constructor = meta.into(); |
| 935 |
|
| 936 |
self.types |
| 937 |
.add_known_types(defn.iter_types()) |
| 938 |
.with_context(|| format!("adding constructor {defn:?}"))?; |
| 939 |
defn.throws_name() |
| 940 |
.map(|n| self.errors.insert(n.to_string())); |
| 941 |
object.constructors.push(defn); |
| 942 |
|
| 943 |
Ok(()) |
| 944 |
} |
| 945 |
|
| 946 |
pub(super) fn add_method_meta(&mut self, meta: impl Into<Method>) -> Result<()> { |
| 947 |
let mut method: Method = meta.into(); |
| 948 |
let object = get_object(&mut self.objects, &method.object_name) |
| 949 |
.ok_or_else(|| anyhow!("add_method_meta: object {} not found", &method.object_name))?; |
| 950 |
|
| 951 |
self.types |
| 952 |
.add_known_types(method.iter_types()) |
| 953 |
.with_context(|| format!("adding method {method:?}"))?; |
| 954 |
method |
| 955 |
.throws_name() |
| 956 |
.map(|n| self.errors.insert(n.to_string())); |
| 957 |
method.object_impl = object.imp; |
| 958 |
object.methods.push(method); |
| 959 |
Ok(()) |
| 960 |
} |
| 961 |
|
| 962 |
pub(super) fn add_uniffitrait_meta(&mut self, meta: UniffiTraitMetadata) -> Result<()> { |
| 963 |
let object = get_object(&mut self.objects, meta.self_name()) |
| 964 |
.ok_or_else(|| anyhow!("add_uniffitrait_meta: object not found"))?; |
| 965 |
let ut: UniffiTrait = meta.into(); |
| 966 |
self.types |
| 967 |
.add_known_types(ut.iter_types()) |
| 968 |
.with_context(|| format!("adding builtin trait {ut:?}"))?; |
| 969 |
|
| 970 |
object.uniffi_traits.push(ut); |
| 971 |
Ok(()) |
| 972 |
} |
| 973 |
|
| 974 |
pub(super) fn add_object_meta(&mut self, meta: ObjectMetadata) -> Result<()> { |
| 975 |
self.add_object_definition(meta.into()) |
| 976 |
} |
| 977 |
|
| 978 |
/// Called by `APIBuilder` impls to add a newly-parsed object definition to the `ComponentInterface`. |
| 979 |
fn add_object_definition(&mut self, defn: Object) -> Result<()> { |
| 980 |
self.types.add_known_type(&defn.as_type())?; |
| 981 |
self.types |
| 982 |
.add_known_types(defn.iter_types()) |
| 983 |
.with_context(|| format!("adding object {defn:?}'"))?; |
| 984 |
|
| 985 |
self.objects.push(defn); |
| 986 |
Ok(()) |
| 987 |
} |
| 988 |
|
| 989 |
pub fn is_name_used_as_error(&self, name: &str) -> bool { |
| 990 |
self.errors.contains(name) |
| 991 |
} |
| 992 |
|
| 993 |
/// Called by `APIBuilder` impls to add a newly-parsed callback interface definition to the `ComponentInterface`. |
| 994 |
pub(super) fn add_callback_interface_definition( |
| 995 |
&mut self, |
| 996 |
defn: CallbackInterface, |
| 997 |
) -> Result<()> { |
| 998 |
self.types.add_known_type(&defn.as_type())?; |
| 999 |
self.types |
| 1000 |
.add_known_types(defn.iter_types()) |
| 1001 |
.with_context(|| format!("adding callback {defn:?}'"))?; |
| 1002 |
|
| 1003 |
self.callback_interfaces.push(defn); |
| 1004 |
Ok(()) |
| 1005 |
} |
| 1006 |
|
| 1007 |
pub(super) fn add_trait_method_meta(&mut self, meta: TraitMethodMetadata) -> Result<()> { |
| 1008 |
if let Some(cbi) = get_callback_interface(&mut self.callback_interfaces, &meta.trait_name) { |
| 1009 |
// uniffi_meta should ensure that we process callback interface methods in order, double |
| 1010 |
// check that here |
| 1011 |
if cbi.methods.len() != meta.index as usize { |
| 1012 |
bail!( |
| 1013 |
"UniFFI internal error: callback interface method index mismatch for {}::{} (expected {}, saw {})", |
| 1014 |
meta.trait_name, |
| 1015 |
meta.name, |
| 1016 |
cbi.methods.len(), |
| 1017 |
meta.index, |
| 1018 |
); |
| 1019 |
} |
| 1020 |
let method: Method = meta.into(); |
| 1021 |
if let Some(error) = method.throws_type() { |
| 1022 |
self.callback_interface_throws_types.insert(error.clone()); |
| 1023 |
} |
| 1024 |
self.types |
| 1025 |
.add_known_types(method.iter_types()) |
| 1026 |
.with_context(|| format!("adding trait method {method:?}"))?; |
| 1027 |
method |
| 1028 |
.throws_name() |
| 1029 |
.map(|n| self.errors.insert(n.to_string())); |
| 1030 |
cbi.methods.push(method); |
| 1031 |
} else { |
| 1032 |
self.add_method_meta(meta)?; |
| 1033 |
} |
| 1034 |
Ok(()) |
| 1035 |
} |
| 1036 |
|
| 1037 |
pub(super) fn add_object_trait_impl( |
| 1038 |
&mut self, |
| 1039 |
trait_impl: ObjectTraitImplMetadata, |
| 1040 |
) -> Result<()> { |
| 1041 |
let object = trait_impl |
| 1042 |
.ty |
| 1043 |
.name() |
| 1044 |
.and_then(|n| get_object(&mut self.objects, n)) |
| 1045 |
.ok_or_else(|| { |
| 1046 |
anyhow!( |
| 1047 |
"add_object_trait_impl: object {:?} not found", |
| 1048 |
&trait_impl.ty |
| 1049 |
) |
| 1050 |
})?; |
| 1051 |
object.trait_impls.push(trait_impl); |
| 1052 |
Ok(()) |
| 1053 |
} |
| 1054 |
|
| 1055 |
/// Perform global consistency checks on the declared interface. |
| 1056 |
/// |
| 1057 |
/// This method checks for consistency problems in the declared interface |
| 1058 |
/// as a whole, and which can only be detected after we've finished defining |
| 1059 |
/// the entire interface. |
| 1060 |
pub fn check_consistency(&self) -> Result<()> { |
| 1061 |
if self.namespace().is_empty() { |
| 1062 |
bail!("missing namespace definition"); |
| 1063 |
} |
| 1064 |
|
| 1065 |
// Because functions aren't first class types, we need to check here that |
| 1066 |
// a function name hasn't already been used as a type name. |
| 1067 |
for f in self.functions.iter() { |
| 1068 |
if self.types.get_type_definition(f.name()).is_some() { |
| 1069 |
bail!("Conflicting type definition for \"{}\"", f.name()); |
| 1070 |
} |
| 1071 |
} |
| 1072 |
Ok(()) |
| 1073 |
} |
| 1074 |
|
| 1075 |
/// Automatically derive the low-level FFI functions from the high-level types in the interface. |
| 1076 |
/// |
| 1077 |
/// This should only be called after the high-level types have been completed defined, otherwise |
| 1078 |
/// the resulting set will be missing some entries. |
| 1079 |
pub fn derive_ffi_funcs(&mut self) -> Result<()> { |
| 1080 |
for func in self.functions.iter_mut() { |
| 1081 |
func.derive_ffi_func()?; |
| 1082 |
} |
| 1083 |
for obj in self.objects.iter_mut() { |
| 1084 |
obj.derive_ffi_funcs()?; |
| 1085 |
} |
| 1086 |
for callback in self.callback_interfaces.iter_mut() { |
| 1087 |
callback.derive_ffi_funcs(); |
| 1088 |
} |
| 1089 |
Ok(()) |
| 1090 |
} |
| 1091 |
} |
| 1092 |
|
| 1093 |
fn get_object<'a>(objects: &'a mut [Object], name: &str) -> Option<&'a mut Object> { |
| 1094 |
objects.iter_mut().find(|o| o.name == name) |
| 1095 |
} |
| 1096 |
|
| 1097 |
fn get_callback_interface<'a>( |
| 1098 |
callback_interfaces: &'a mut [CallbackInterface], |
| 1099 |
name: &str, |
| 1100 |
) -> Option<&'a mut CallbackInterface> { |
| 1101 |
callback_interfaces.iter_mut().find(|o| o.name == name) |
| 1102 |
} |
| 1103 |
|
| 1104 |
/// Stateful iterator for yielding all types contained in a given type. |
| 1105 |
/// |
| 1106 |
/// This struct is the implementation of [`ComponentInterface::iter_types_in_item`] and should be |
| 1107 |
/// considered an opaque implementation detail. It's a separate struct because I couldn't |
| 1108 |
/// figure out a way to implement it using iterators and closures that would make the lifetimes |
| 1109 |
/// work out correctly. |
| 1110 |
/// |
| 1111 |
/// The idea here is that we want to yield all the types from `iter_types` on a given type, and |
| 1112 |
/// additionally we want to recurse into the definition of any user-provided types like records, |
| 1113 |
/// enums, etc so we can also yield the types contained therein. |
| 1114 |
/// |
| 1115 |
/// To guard against infinite recursion, we maintain a list of previously-seen user-defined |
| 1116 |
/// types, ensuring that we recurse into the definition of those types only once. To simplify |
| 1117 |
/// the implementation, we maintain a queue of pending user-defined types that we have seen |
| 1118 |
/// but not yet recursed into. (Ironically, the use of an explicit queue means our implementation |
| 1119 |
/// is not actually recursive...) |
| 1120 |
struct RecursiveTypeIterator<'a> { |
| 1121 |
/// The [`ComponentInterface`] from which this iterator was created. |
| 1122 |
ci: &'a ComponentInterface, |
| 1123 |
/// The currently-active iterator from which we're yielding. |
| 1124 |
current: TypeIterator<'a>, |
| 1125 |
/// A set of names of user-defined types that we have already seen. |
| 1126 |
seen: HashSet<&'a str>, |
| 1127 |
/// A queue of user-defined types that we need to recurse into. |
| 1128 |
pending: Vec<&'a Type>, |
| 1129 |
} |
| 1130 |
|
| 1131 |
impl<'a> RecursiveTypeIterator<'a> { |
| 1132 |
/// Allocate a new `RecursiveTypeIterator` over the given item. |
| 1133 |
fn new(ci: &'a ComponentInterface, item: &'a Type) -> RecursiveTypeIterator<'a> { |
| 1134 |
RecursiveTypeIterator { |
| 1135 |
ci, |
| 1136 |
// We begin by iterating over the types from the item itself. |
| 1137 |
current: item.iter_types(), |
| 1138 |
seen: Default::default(), |
| 1139 |
pending: Default::default(), |
| 1140 |
} |
| 1141 |
} |
| 1142 |
|
| 1143 |
/// Add a new type to the queue of pending types, if not previously seen. |
| 1144 |
fn add_pending_type(&mut self, type_: &'a Type) { |
| 1145 |
match type_ { |
| 1146 |
Type::Record { name, .. } |
| 1147 |
| Type::Enum { name, .. } |
| 1148 |
| Type::Object { name, .. } |
| 1149 |
| Type::CallbackInterface { name, .. } => { |
| 1150 |
if !self.seen.contains(name.as_str()) { |
| 1151 |
self.pending.push(type_); |
| 1152 |
self.seen.insert(name.as_str()); |
| 1153 |
} |
| 1154 |
} |
| 1155 |
_ => (), |
| 1156 |
} |
| 1157 |
} |
| 1158 |
|
| 1159 |
/// Advance the iterator to recurse into the next pending type, if any. |
| 1160 |
/// |
| 1161 |
/// This method is called when the current iterator is empty, and it will select |
| 1162 |
/// the next pending type from the queue and start iterating over its contained types. |
| 1163 |
/// The return value will be the first item from the new iterator. |
| 1164 |
fn advance_to_next_type(&mut self) -> Option<&'a Type> { |
| 1165 |
if let Some(next_type) = self.pending.pop() { |
| 1166 |
// This is a little awkward because the various definition lookup methods return an `Option<T>`. |
| 1167 |
// In the unlikely event that one of them returns `None` then, rather than trying to advance |
| 1168 |
// to a non-existent type, we just leave the existing iterator in place and allow the recursive |
| 1169 |
// call to `next()` to try again with the next pending type. |
| 1170 |
let next_iter = match next_type { |
| 1171 |
Type::Record { name, .. } => { |
| 1172 |
self.ci.get_record_definition(name).map(Record::iter_types) |
| 1173 |
} |
| 1174 |
Type::Enum { name, .. } => self.ci.get_enum_definition(name).map(Enum::iter_types), |
| 1175 |
Type::Object { name, .. } => { |
| 1176 |
self.ci.get_object_definition(name).map(Object::iter_types) |
| 1177 |
} |
| 1178 |
Type::CallbackInterface { name, .. } => self |
| 1179 |
.ci |
| 1180 |
.get_callback_interface_definition(name) |
| 1181 |
.map(CallbackInterface::iter_types), |
| 1182 |
_ => None, |
| 1183 |
}; |
| 1184 |
if let Some(next_iter) = next_iter { |
| 1185 |
self.current = next_iter; |
| 1186 |
} |
| 1187 |
// Advance the new iterator to its first item. If the new iterator happens to be empty, |
| 1188 |
// this will recurse back in to `advance_to_next_type` until we find one that isn't. |
| 1189 |
self.next() |
| 1190 |
} else { |
| 1191 |
// We've completely finished the iteration over all pending types. |
| 1192 |
None |
| 1193 |
} |
| 1194 |
} |
| 1195 |
} |
| 1196 |
|
| 1197 |
impl<'a> Iterator for RecursiveTypeIterator<'a> { |
| 1198 |
type Item = &'a Type; |
| 1199 |
fn next(&mut self) -> Option<Self::Item> { |
| 1200 |
if let Some(type_) = self.current.next() { |
| 1201 |
self.add_pending_type(type_); |
| 1202 |
Some(type_) |
| 1203 |
} else { |
| 1204 |
self.advance_to_next_type() |
| 1205 |
} |
| 1206 |
} |
| 1207 |
} |
| 1208 |
|
| 1209 |
// Helpers for functions/methods/constructors which all have the same "throws" semantics. |
| 1210 |
fn throws_name(throws: &Option<Type>) -> Option<&str> { |
| 1211 |
// Type has no `name()` method, just `canonical_name()` which isn't what we want. |
| 1212 |
match throws { |
| 1213 |
None => None, |
| 1214 |
Some(Type::Enum { name, .. }) | Some(Type::Object { name, .. }) => Some(name), |
| 1215 |
_ => panic!("unknown throw type: {throws:?}"), |
| 1216 |
} |
| 1217 |
} |
| 1218 |
|
| 1219 |
#[cfg(test)] |
| 1220 |
mod test { |
| 1221 |
use super::*; |
| 1222 |
|
| 1223 |
// Note that much of the functionality of `ComponentInterface` is tested via its interactions |
| 1224 |
// with specific member types, in the sub-modules defining those member types. |
| 1225 |
|
| 1226 |
#[test] |
| 1227 |
fn test_duplicate_type_names_are_an_error() { |
| 1228 |
const UDL: &str = r#" |
| 1229 |
namespace test{}; |
| 1230 |
interface Testing { |
| 1231 |
constructor(); |
| 1232 |
}; |
| 1233 |
dictionary Testing { |
| 1234 |
u32 field; |
| 1235 |
}; |
| 1236 |
"#; |
| 1237 |
let err = ComponentInterface::from_webidl(UDL, "crate_name").unwrap_err(); |
| 1238 |
assert_eq!( |
| 1239 |
err.to_string(), |
| 1240 |
"Conflicting type definition for `Testing`! \ |
| 1241 |
existing definition: Object { module_path: \"crate_name\", name: \"Testing\", imp: Struct }, \ |
| 1242 |
new definition: Record { module_path: \"crate_name\", name: \"Testing\" }" |
| 1243 |
); |
| 1244 |
|
| 1245 |
const UDL2: &str = r#" |
| 1246 |
namespace test{}; |
| 1247 |
enum Testing { |
| 1248 |
"one", "two" |
| 1249 |
}; |
| 1250 |
[Error] |
| 1251 |
enum Testing { "three", "four" }; |
| 1252 |
"#; |
| 1253 |
let err = ComponentInterface::from_webidl(UDL2, "crate_name").unwrap_err(); |
| 1254 |
assert_eq!( |
| 1255 |
err.to_string(), |
| 1256 |
"Mismatching definition for enum `Testing`! |
| 1257 |
existing definition: Enum { |
| 1258 |
name: \"Testing\", |
| 1259 |
module_path: \"crate_name\", |
| 1260 |
remote: false, |
| 1261 |
discr_type: None, |
| 1262 |
variants: [ |
| 1263 |
Variant { |
| 1264 |
name: \"one\", |
| 1265 |
discr: None, |
| 1266 |
fields: [], |
| 1267 |
docstring: None, |
| 1268 |
}, |
| 1269 |
Variant { |
| 1270 |
name: \"two\", |
| 1271 |
discr: None, |
| 1272 |
fields: [], |
| 1273 |
docstring: None, |
| 1274 |
}, |
| 1275 |
], |
| 1276 |
shape: Enum, |
| 1277 |
non_exhaustive: false, |
| 1278 |
docstring: None, |
| 1279 |
}, |
| 1280 |
new definition: Enum { |
| 1281 |
name: \"Testing\", |
| 1282 |
module_path: \"crate_name\", |
| 1283 |
remote: false, |
| 1284 |
discr_type: None, |
| 1285 |
variants: [ |
| 1286 |
Variant { |
| 1287 |
name: \"three\", |
| 1288 |
discr: None, |
| 1289 |
fields: [], |
| 1290 |
docstring: None, |
| 1291 |
}, |
| 1292 |
Variant { |
| 1293 |
name: \"four\", |
| 1294 |
discr: None, |
| 1295 |
fields: [], |
| 1296 |
docstring: None, |
| 1297 |
}, |
| 1298 |
], |
| 1299 |
shape: Error { |
| 1300 |
flat: true, |
| 1301 |
}, |
| 1302 |
non_exhaustive: false, |
| 1303 |
docstring: None, |
| 1304 |
}", |
| 1305 |
); |
| 1306 |
|
| 1307 |
const UDL3: &str = r#" |
| 1308 |
namespace test{ |
| 1309 |
u32 Testing(); |
| 1310 |
}; |
| 1311 |
enum Testing { |
| 1312 |
"one", "two" |
| 1313 |
}; |
| 1314 |
"#; |
| 1315 |
let err = ComponentInterface::from_webidl(UDL3, "crate_name").unwrap_err(); |
| 1316 |
assert!(format!("{err:#}").contains("Conflicting type definition for \"Testing\"")); |
| 1317 |
} |
| 1318 |
|
| 1319 |
#[test] |
| 1320 |
fn test_contains_optional_types() { |
| 1321 |
let mut ci = ComponentInterface::default(); |
| 1322 |
|
| 1323 |
// check that `contains_optional_types` returns false when there is no Optional type in the interface |
| 1324 |
assert!(!ci.contains_optional_types()); |
| 1325 |
|
| 1326 |
// check that `contains_optional_types` returns true when there is an Optional type in the interface |
| 1327 |
assert!(ci |
| 1328 |
.types |
| 1329 |
.add_known_type(&Type::Optional { |
| 1330 |
inner_type: Box::new(Type::String) |
| 1331 |
}) |
| 1332 |
.is_ok()); |
| 1333 |
assert!(ci.contains_optional_types()); |
| 1334 |
} |
| 1335 |
|
| 1336 |
#[test] |
| 1337 |
fn test_contains_sequence_types() { |
| 1338 |
let mut ci = ComponentInterface { |
| 1339 |
..Default::default() |
| 1340 |
}; |
| 1341 |
|
| 1342 |
// check that `contains_sequence_types` returns false when there is no Sequence type in the interface |
| 1343 |
assert!(!ci.contains_sequence_types()); |
| 1344 |
|
| 1345 |
// check that `contains_sequence_types` returns true when there is a Sequence type in the interface |
| 1346 |
assert!(ci |
| 1347 |
.types |
| 1348 |
.add_known_type(&Type::Sequence { |
| 1349 |
inner_type: Box::new(Type::UInt64) |
| 1350 |
}) |
| 1351 |
.is_ok()); |
| 1352 |
assert!(ci.contains_sequence_types()); |
| 1353 |
assert!(ci.types.contains(&Type::UInt64)); |
| 1354 |
} |
| 1355 |
|
| 1356 |
#[test] |
| 1357 |
fn test_contains_map_types() { |
| 1358 |
let mut ci = ComponentInterface { |
| 1359 |
..Default::default() |
| 1360 |
}; |
| 1361 |
|
| 1362 |
// check that `contains_map_types` returns false when there is no Map type in the interface |
| 1363 |
assert!(!ci.contains_map_types()); |
| 1364 |
|
| 1365 |
// check that `contains_map_types` returns true when there is a Map type in the interface |
| 1366 |
assert!(ci |
| 1367 |
.types |
| 1368 |
.add_known_type(&Type::Map { |
| 1369 |
key_type: Box::new(Type::String), |
| 1370 |
value_type: Box::new(Type::Boolean) |
| 1371 |
}) |
| 1372 |
.is_ok()); |
| 1373 |
assert!(ci.contains_map_types()); |
| 1374 |
assert!(ci.types.contains(&Type::String)); |
| 1375 |
assert!(ci.types.contains(&Type::Boolean)); |
| 1376 |
} |
| 1377 |
|
| 1378 |
#[test] |
| 1379 |
fn test_no_infinite_recursion_when_walking_types() { |
| 1380 |
const UDL: &str = r#" |
| 1381 |
namespace test{}; |
| 1382 |
interface Testing { |
| 1383 |
void tester(Testing foo); |
| 1384 |
}; |
| 1385 |
"#; |
| 1386 |
let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap(); |
| 1387 |
assert!(!ci.item_contains_unsigned_types(&Type::Object { |
| 1388 |
name: "Testing".into(), |
| 1389 |
module_path: "".into(), |
| 1390 |
imp: ObjectImpl::Struct, |
| 1391 |
})); |
| 1392 |
} |
| 1393 |
|
| 1394 |
#[test] |
| 1395 |
fn test_correct_recursion_when_walking_types() { |
| 1396 |
const UDL: &str = r#" |
| 1397 |
namespace test{}; |
| 1398 |
interface TestObj { |
| 1399 |
void tester(TestRecord foo); |
| 1400 |
}; |
| 1401 |
dictionary TestRecord { |
| 1402 |
NestedRecord bar; |
| 1403 |
}; |
| 1404 |
dictionary NestedRecord { |
| 1405 |
u64 baz; |
| 1406 |
}; |
| 1407 |
"#; |
| 1408 |
let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap(); |
| 1409 |
assert!(ci.item_contains_unsigned_types(&Type::Object { |
| 1410 |
name: "TestObj".into(), |
| 1411 |
module_path: "".into(), |
| 1412 |
imp: ObjectImpl::Struct, |
| 1413 |
})); |
| 1414 |
} |
| 1415 |
|
| 1416 |
#[test] |
| 1417 |
fn test_docstring_namespace() { |
| 1418 |
const UDL: &str = r#" |
| 1419 |
/// informative docstring |
| 1420 |
namespace test{}; |
| 1421 |
"#; |
| 1422 |
let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap(); |
| 1423 |
assert_eq!(ci.namespace_docstring().unwrap(), "informative docstring"); |
| 1424 |
} |
| 1425 |
|
| 1426 |
#[test] |
| 1427 |
fn test_multiline_docstring() { |
| 1428 |
const UDL: &str = r#" |
| 1429 |
/// informative |
| 1430 |
/// docstring |
| 1431 |
namespace test{}; |
| 1432 |
"#; |
| 1433 |
let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap(); |
| 1434 |
assert_eq!(ci.namespace_docstring().unwrap(), "informative\ndocstring"); |
| 1435 |
} |
| 1436 |
|
| 1437 |
#[test] |
| 1438 |
fn test_names() { |
| 1439 |
let mut ci = ComponentInterface::default(); |
| 1440 |
|
| 1441 |
let ob = Object { |
| 1442 |
name: "ob".to_string(), |
| 1443 |
module_path: "mp".to_string(), |
| 1444 |
imp: ObjectImpl::Struct, |
| 1445 |
remote: false, |
| 1446 |
constructors: Default::default(), |
| 1447 |
methods: Default::default(), |
| 1448 |
uniffi_traits: Default::default(), |
| 1449 |
ffi_func_clone: Default::default(), |
| 1450 |
trait_impls: Default::default(), |
| 1451 |
ffi_func_free: Default::default(), |
| 1452 |
ffi_init_callback: Default::default(), |
| 1453 |
docstring: Default::default(), |
| 1454 |
}; |
| 1455 |
ci.add_object_definition(ob).unwrap(); |
| 1456 |
assert!(ci.get_object_definition("ob").is_some()); |
| 1457 |
assert_eq!( |
| 1458 |
ci.types.get_type_definition("ob"), |
| 1459 |
Some(Type::Object { |
| 1460 |
module_path: "mp".to_string(), |
| 1461 |
name: "ob".to_string(), |
| 1462 |
imp: ObjectImpl::Struct |
| 1463 |
}) |
| 1464 |
); |
| 1465 |
|
| 1466 |
let cb = CallbackInterface { |
| 1467 |
name: "cb".to_string(), |
| 1468 |
module_path: "mp".to_string(), |
| 1469 |
methods: vec![], |
| 1470 |
ffi_init_callback: FfiFunction::default(), |
| 1471 |
docstring: None, |
| 1472 |
}; |
| 1473 |
ci.add_callback_interface_definition(cb).unwrap(); |
| 1474 |
assert_eq!( |
| 1475 |
ci.types.get_type_definition("cb"), |
| 1476 |
Some(Type::CallbackInterface { |
| 1477 |
module_path: "mp".to_string(), |
| 1478 |
name: "cb".to_string() |
| 1479 |
}) |
| 1480 |
); |
| 1481 |
assert!(ci.get_callback_interface_definition("cb").is_some()); |
| 1482 |
} |
| 1483 |
|
| 1484 |
#[test] |
| 1485 |
fn test_namespaces() { |
| 1486 |
let mut ci = ComponentInterface::new("crate"); |
| 1487 |
ci.types.namespace.name = "ns".to_string(); |
| 1488 |
// have not called `ci.set_crate_to_namespace_map()`, should still resolve our own |
| 1489 |
assert_eq!(ci.namespace_for_module_path("crate").unwrap(), "ns"); |
| 1490 |
assert!(ci.namespace_for_module_path("oops").is_err()); |
| 1491 |
} |
| 1492 |
} |