Debian Codegraph @

third_party/rust/uniffi_bindgen/src/interface/ffi.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 //! # Low-level typesystem for the FFI layer of a component interface.
6 //!
7 //! This module provides the "FFI-level" typesystem of a UniFFI Rust Component, that is,
8 //! the C-style functions and structs and primitive datatypes that are used to interface
9 //! between the Rust component code and the foreign-language bindings.
10 //!
11 //! These types are purely an implementation detail of UniFFI, so consumers shouldn't
12 //! need to know about them. But as a developer working on UniFFI itself, you're likely
13 //! to spend a lot of time thinking about how these low-level types are used to represent
14 //! the higher-level "interface types" from the [`Type`] enum.
15 /// Represents the restricted set of low-level types that can be used to construct
16 /// the C-style FFI layer between a rust component and its foreign language bindings.
17 ///
18 /// For the types that involve memory allocation, we make a distinction between
19 /// "owned" types (the recipient must free it, or pass it to someone else) and
20 /// "borrowed" types (the sender must keep it alive for the duration of the call).
21 use uniffi_meta::Type;
22
23 #[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
24 pub enum FfiType {
25 // N.B. there are no booleans at this layer, since they cause problems for JNA.
26 UInt8,
27 Int8,
28 UInt16,
29 Int16,
30 UInt32,
31 Int32,
32 UInt64,
33 Int64,
34 Float32,
35 Float64,
36 /// A `*const c_void` pointer to a rust-owned `Arc<T>`.
37 /// If you've got one of these, you must call the appropriate rust function to free it.
38 /// The templates will generate a unique `free` function for each T.
39 /// The inner string references the name of the `T` type.
40 RustArcPtr(String),
41 /// A byte buffer allocated by rust, and owned by whoever currently holds it.
42 /// If you've got one of these, you must either call the appropriate rust function to free it
43 /// or pass it to someone that will.
44 /// If the inner option is Some, it is the name of the external type. The bindings may need
45 /// to use this name to import the correct RustBuffer for that type.
46 RustBuffer(Option<ExternalFfiMetadata>),
47 /// A borrowed reference to some raw bytes owned by foreign language code.
48 /// The provider of this reference must keep it alive for the duration of the receiving call.
49 ForeignBytes,
50 /// Pointer to a callback function. The inner value which matches one of the callback
51 /// definitions in [crate::ComponentInterface::ffi_definitions].
52 Callback(String),
53 /// Pointer to a FFI struct (e.g. a VTable). The inner value matches one of the struct
54 /// definitions in [crate::ComponentInterface::ffi_definitions].
55 Struct(String),
56 /// Opaque 64-bit handle
57 ///
58 /// These are used to pass objects across the FFI.
59 Handle,
60 RustCallStatus,
61 /// Const pointer to an FfiType.
62 Reference(Box<FfiType>),
63 /// Mutable pointer to an FfiType.
64 MutReference(Box<FfiType>),
65 /// Opaque pointer
66 VoidPointer,
67 }
68
69 impl FfiType {
70 pub fn reference(self) -> FfiType {
71 FfiType::Reference(Box::new(self))
72 }
73
74 pub fn mut_reference(self) -> FfiType {
75 FfiType::MutReference(Box::new(self))
76 }
77
78 /// Unique name for an FFI return type
79 pub fn return_type_name(return_type: Option<&FfiType>) -> String {
80 match return_type {
81 Some(t) => match t {
82 FfiType::UInt8 => "u8".to_owned(),
83 FfiType::Int8 => "i8".to_owned(),
84 FfiType::UInt16 => "u16".to_owned(),
85 FfiType::Int16 => "i16".to_owned(),
86 FfiType::UInt32 => "u32".to_owned(),
87 FfiType::Int32 => "i32".to_owned(),
88 FfiType::UInt64 => "u64".to_owned(),
89 FfiType::Int64 => "i64".to_owned(),
90 FfiType::Float32 => "f32".to_owned(),
91 FfiType::Float64 => "f64".to_owned(),
92 FfiType::RustArcPtr(_) => "pointer".to_owned(),
93 FfiType::RustBuffer(_) => "rust_buffer".to_owned(),
94 _ => unimplemented!("FFI return type: {t:?}"),
95 },
96 None => "void".to_owned(),
97 }
98 }
99 }
100
101 /// When passing data across the FFI, each `Type` value will be lowered into a corresponding
102 /// `FfiType` value. This conversion tells you which one.
103 ///
104 /// Note that the conversion is one-way - given an FfiType, it is not in general possible to
105 /// tell what the corresponding Type is that it's being used to represent.
106 impl From<&Type> for FfiType {
107 fn from(t: &Type) -> FfiType {
108 match t {
109 // Types that are the same map to themselves, naturally.
110 Type::UInt8 => FfiType::UInt8,
111 Type::Int8 => FfiType::Int8,
112 Type::UInt16 => FfiType::UInt16,
113 Type::Int16 => FfiType::Int16,
114 Type::UInt32 => FfiType::UInt32,
115 Type::Int32 => FfiType::Int32,
116 Type::UInt64 => FfiType::UInt64,
117 Type::Int64 => FfiType::Int64,
118 Type::Float32 => FfiType::Float32,
119 Type::Float64 => FfiType::Float64,
120 // Booleans lower into an Int8, to work around a bug in JNA.
121 Type::Boolean => FfiType::Int8,
122 // Strings are always owned rust values.
123 // We might add a separate type for borrowed strings in future.
124 Type::String => FfiType::RustBuffer(None),
125 // Byte strings are also always owned rust values.
126 // We might add a separate type for borrowed byte strings in future as well.
127 Type::Bytes => FfiType::RustBuffer(None),
128 // Objects are pointers to an Arc<>
129 Type::Object { name, .. } => FfiType::RustArcPtr(name.to_owned()),
130 // Callback interfaces are passed as opaque integer handles.
131 Type::CallbackInterface { .. } => FfiType::UInt64,
132 // Other types are serialized into a bytebuffer and deserialized on the other side.
133 Type::Enum { name, module_path } | Type::Record { name, module_path } => {
134 FfiType::RustBuffer(Some(ExternalFfiMetadata {
135 name: name.clone(),
136 module_path: module_path.clone(),
137 }))
138 }
139 Type::Optional { .. }
140 | Type::Sequence { .. }
141 | Type::Map { .. }
142 | Type::Timestamp
143 | Type::Duration => FfiType::RustBuffer(None),
144 Type::Custom {
145 builtin,
146 name,
147 module_path,
148 ..
149 } => {
150 // We need ffitype of the builtin.
151 match FfiType::from(builtin.as_ref()) {
152 // and if that builtin was a "local" RustBuffer, we need to
153 // let emit enough metadata so the bindings can call the rustbuffer impl
154 // if necessary.
155 FfiType::RustBuffer(None) => FfiType::RustBuffer(Some(ExternalFfiMetadata {
156 name: name.clone(),
157 module_path: module_path.clone(),
158 })),
159 t => t,
160 }
161 }
162 }
163 }
164 }
165
166 #[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
167 pub struct ExternalFfiMetadata {
168 pub name: String,
169 pub module_path: String,
170 }
171
172 // Needed for rust scaffolding askama template
173 impl From<Type> for FfiType {
174 fn from(ty: Type) -> Self {
175 (&ty).into()
176 }
177 }
178
179 impl From<&&Type> for FfiType {
180 fn from(ty: &&Type) -> Self {
181 (*ty).into()
182 }
183 }
184
185 /// An Ffi definition
186 #[derive(Debug, Clone)]
187 pub enum FfiDefinition {
188 Function(FfiFunction),
189 CallbackFunction(FfiCallbackFunction),
190 Struct(FfiStruct),
191 }
192
193 impl FfiDefinition {
194 pub fn name(&self) -> &str {
195 match self {
196 Self::Function(f) => f.name(),
197 Self::CallbackFunction(f) => f.name(),
198 Self::Struct(s) => s.name(),
199 }
200 }
201 }
202
203 /// Represents an "extern C"-style function that will be part of the FFI.
204 ///
205 /// These can't be declared explicitly in the UDL, but rather, are derived automatically
206 /// from the high-level interface. Each callable thing in the component API will have a
207 /// corresponding `FfiFunction` through which it can be invoked, and UniFFI also provides
208 /// some built-in `FfiFunction` helpers for use in the foreign language bindings.
209 #[derive(Debug, Clone)]
210 pub struct FfiFunction {
211 pub(super) name: String,
212 pub(super) is_async: bool,
213 pub(super) arguments: Vec<FfiArgument>,
214 pub(super) return_type: Option<FfiType>,
215 pub(super) has_rust_call_status_arg: bool,
216 /// Used by C# generator to differentiate the free function and call it with void*
217 /// instead of C# `SafeHandle` type. See <https://github.com/mozilla/uniffi-rs/pull/1488>.
218 pub(super) is_object_free_function: bool,
219 }
220
221 impl FfiFunction {
222 pub fn callback_init(module_path: &str, trait_name: &str, vtable_name: String) -> Self {
223 Self {
224 name: uniffi_meta::init_callback_vtable_fn_symbol_name(module_path, trait_name),
225 arguments: vec![FfiArgument {
226 name: "vtable".to_string(),
227 type_: FfiType::Struct(vtable_name).reference(),
228 }],
229 return_type: None,
230 has_rust_call_status_arg: false,
231 ..Self::default()
232 }
233 }
234
235 pub fn name(&self) -> &str {
236 &self.name
237 }
238
239 pub fn rename(&mut self, new_name: String) {
240 self.name = new_name;
241 }
242
243 /// Name of the FFI buffer version of this function that's generated when the
244 /// `scaffolding-ffi-buffer-fns` feature is enabled.
245 pub fn ffi_buffer_fn_name(&self) -> String {
246 uniffi_meta::ffi_buffer_symbol_name(&self.name)
247 }
248
249 pub fn is_async(&self) -> bool {
250 self.is_async
251 }
252
253 pub fn arguments(&self) -> Vec<&FfiArgument> {
254 self.arguments.iter().collect()
255 }
256
257 pub fn return_type(&self) -> Option<&FfiType> {
258 self.return_type.as_ref()
259 }
260
261 pub fn has_rust_call_status_arg(&self) -> bool {
262 self.has_rust_call_status_arg
263 }
264
265 pub fn is_object_free_function(&self) -> bool {
266 self.is_object_free_function
267 }
268
269 pub fn init(
270 &mut self,
271 return_type: Option<FfiType>,
272 args: impl IntoIterator<Item = FfiArgument>,
273 ) {
274 self.arguments = args.into_iter().collect();
275 if self.is_async() {
276 self.return_type = Some(FfiType::Handle);
277 self.has_rust_call_status_arg = false;
278 } else {
279 self.return_type = return_type;
280 }
281 }
282 }
283
284 impl Default for FfiFunction {
285 fn default() -> Self {
286 Self {
287 name: "".into(),
288 is_async: false,
289 arguments: Vec::new(),
290 return_type: None,
291 has_rust_call_status_arg: true,
292 is_object_free_function: false,
293 }
294 }
295 }
296
297 /// Represents an argument to an FFI function.
298 ///
299 /// Each argument has a name and a type.
300 #[derive(Debug, Clone)]
301 pub struct FfiArgument {
302 pub(super) name: String,
303 pub(super) type_: FfiType,
304 }
305
306 impl FfiArgument {
307 pub fn new(name: impl Into<String>, type_: FfiType) -> Self {
308 Self {
309 name: name.into(),
310 type_,
311 }
312 }
313
314 pub fn name(&self) -> &str {
315 &self.name
316 }
317
318 pub fn rename(&mut self, new_name: String) {
319 self.name = new_name;
320 }
321
322 pub fn type_(&self) -> FfiType {
323 self.type_.clone()
324 }
325 }
326
327 /// Represents an "extern C"-style callback function
328 ///
329 /// These are defined in the foreign code and passed to Rust as a function pointer.
330 #[derive(Debug, Default, Clone)]
331 pub struct FfiCallbackFunction {
332 // Name for this function type. This matches the value inside `FfiType::Callback`
333 pub(super) name: String,
334 pub(super) arguments: Vec<FfiArgument>,
335 pub(super) return_type: Option<FfiType>,
336 pub(super) has_rust_call_status_arg: bool,
337 }
338
339 impl FfiCallbackFunction {
340 pub fn name(&self) -> &str {
341 &self.name
342 }
343
344 pub fn rename(&mut self, new_name: String) {
345 self.name = new_name;
346 }
347
348 pub fn arguments(&self) -> Vec<&FfiArgument> {
349 self.arguments.iter().collect()
350 }
351
352 pub fn return_type(&self) -> Option<&FfiType> {
353 self.return_type.as_ref()
354 }
355
356 pub fn has_rust_call_status_arg(&self) -> bool {
357 self.has_rust_call_status_arg
358 }
359 }
360
361 /// Represents a repr(C) struct used in the FFI
362 #[derive(Debug, Default, Clone)]
363 pub struct FfiStruct {
364 pub(super) name: String,
365 pub(super) fields: Vec<FfiField>,
366 }
367
368 impl FfiStruct {
369 /// Get the name of this struct
370 pub fn name(&self) -> &str {
371 &self.name
372 }
373
374 pub fn rename(&mut self, new_name: String) {
375 self.name = new_name;
376 }
377
378 /// Get the fields for this struct
379 pub fn fields(&self) -> &[FfiField] {
380 &self.fields
381 }
382 }
383
384 /// Represents a field of an [FfiStruct]
385 #[derive(Debug, Clone)]
386 pub struct FfiField {
387 pub(super) name: String,
388 pub(super) type_: FfiType,
389 }
390
391 impl FfiField {
392 pub fn new(name: impl Into<String>, type_: FfiType) -> Self {
393 Self {
394 name: name.into(),
395 type_,
396 }
397 }
398
399 pub fn name(&self) -> &str {
400 &self.name
401 }
402
403 pub fn type_(&self) -> FfiType {
404 self.type_.clone()
405 }
406
407 pub fn rename(&mut self, name: String) {
408 self.name = name;
409 }
410 }
411
412 impl From<FfiFunction> for FfiDefinition {
413 fn from(value: FfiFunction) -> FfiDefinition {
414 FfiDefinition::Function(value)
415 }
416 }
417
418 impl From<FfiStruct> for FfiDefinition {
419 fn from(value: FfiStruct) -> FfiDefinition {
420 FfiDefinition::Struct(value)
421 }
422 }
423
424 impl From<FfiCallbackFunction> for FfiDefinition {
425 fn from(value: FfiCallbackFunction) -> FfiDefinition {
426 FfiDefinition::CallbackFunction(value)
427 }
428 }
429
430 #[cfg(test)]
431 mod test {
432 // There's not really much to test here to be honest,
433 // it's mostly type declarations.
434 }