Debian Codegraph @

third_party/rust/uniffi_bindgen/src/pipeline/general/nodes.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 use indexmap::IndexMap;
6 use uniffi_pipeline::Node;
7
8 /// Initial IR, this stores the metadata and other data
9 #[derive(Debug, Clone, Node)]
10 pub struct Root {
11 /// In library mode, the library path the user passed to us
12 pub cdylib: Option<String>,
13 pub modules: IndexMap<String, Module>,
14 }
15
16 #[derive(Debug, Clone, Node)]
17 pub struct Module {
18 pub name: String,
19 pub crate_name: String,
20 /// contents of the `uniffi.toml` file for this module, if present
21 pub config_toml: Option<String>,
22 pub docstring: Option<String>,
23 pub functions: Vec<Function>,
24 pub type_definitions: Vec<TypeDefinition>,
25 pub ffi_definitions: Vec<FfiDefinition>,
26 /// Checksum functions
27 pub checksums: Vec<Checksum>,
28 // FFI functions names for this module
29 pub ffi_rustbuffer_alloc: RustFfiFunctionName,
30 pub ffi_rustbuffer_from_bytes: RustFfiFunctionName,
31 pub ffi_rustbuffer_free: RustFfiFunctionName,
32 pub ffi_rustbuffer_reserve: RustFfiFunctionName,
33 pub ffi_uniffi_contract_version: RustFfiFunctionName,
34 // Correct contract version value
35 pub correct_contract_version: String,
36 // TypeNode for String. Strings are used in error handling, this ensures that the FFI
37 // converters for them are always defined and easy to lookup.
38 pub string_type_node: TypeNode,
39 }
40
41 #[derive(Debug, Clone, Node)]
42 pub struct Function {
43 pub name: String,
44 pub callable: Callable,
45 pub is_async: bool,
46 pub inputs: Vec<Argument>,
47 pub return_type: Option<Type>,
48 pub throws: Option<Type>,
49 pub checksum: Option<u16>,
50 pub docstring: Option<String>,
51 }
52
53 #[derive(Debug, Clone, Node)]
54 pub enum TypeDefinition {
55 Interface(Interface),
56 CallbackInterface(CallbackInterface),
57 Record(Record),
58 Enum(Enum),
59 Custom(CustomType),
60 /// Type that doesn't contain any other type
61 Simple(TypeNode),
62 /// Compound types
63 Optional(OptionalType),
64 Sequence(SequenceType),
65 Map(MapType),
66 /// User types that are defined in another crate
67 External(ExternalType),
68 }
69
70 #[derive(Debug, Clone, Node)]
71 pub struct Constructor {
72 pub name: String,
73 pub callable: Callable,
74 pub is_async: bool,
75 pub inputs: Vec<Argument>,
76 pub throws: Option<Type>,
77 pub checksum: Option<u16>,
78 pub docstring: Option<String>,
79 }
80
81 #[derive(Debug, Clone, Node)]
82 pub struct Method {
83 pub name: String,
84 pub callable: Callable,
85 pub is_async: bool,
86 pub inputs: Vec<Argument>,
87 pub return_type: Option<Type>,
88 pub throws: Option<Type>,
89 pub checksum: Option<u16>,
90 pub docstring: Option<String>,
91 }
92
93 /// Common data from Function/Method/Constructor
94 #[derive(Debug, Clone, Node)]
95 pub struct Callable {
96 pub name: String,
97 pub is_async: bool,
98 pub async_data: Option<AsyncData>,
99 pub kind: CallableKind,
100 pub arguments: Vec<Argument>,
101 pub return_type: ReturnType,
102 pub throws_type: ThrowsType,
103 pub checksum: Option<u16>,
104 pub ffi_func: RustFfiFunctionName,
105 }
106
107 #[derive(Debug, Clone, Node)]
108 pub enum CallableKind {
109 /// Toplevel function
110 Function,
111 /// Interface/Trait interface method
112 Method { interface_name: String },
113 /// Interface constructor
114 Constructor {
115 interface_name: String,
116 primary: bool,
117 },
118 /// Method inside a VTable or a CallbackInterface
119 ///
120 /// For trait interfaces this only applies to the Callables inside the `vtable.methods` field.
121 /// Callables inside `Interface::methods` will still be `Callable::Method`.
122 VTableMethod { trait_name: String },
123 }
124
125 #[derive(Debug, Clone, Node)]
126 pub struct ReturnType {
127 pub ty: Option<TypeNode>,
128 }
129
130 #[derive(Debug, Clone, Node)]
131 pub struct ThrowsType {
132 pub ty: Option<TypeNode>,
133 }
134
135 #[derive(Debug, Clone, Node)]
136 pub struct AsyncData {
137 // FFI types for async Rust functions
138 pub ffi_rust_future_poll: RustFfiFunctionName,
139 pub ffi_rust_future_cancel: RustFfiFunctionName,
140 pub ffi_rust_future_free: RustFfiFunctionName,
141 pub ffi_rust_future_complete: RustFfiFunctionName,
142 // FFI types for async foreign functions
143 pub ffi_foreign_future_complete: FfiFunctionTypeName,
144 pub ffi_foreign_future_result: FfiStructName,
145 }
146
147 #[derive(Debug, Clone, Node)]
148 pub struct Argument {
149 pub name: String,
150 pub ty: TypeNode,
151 pub optional: bool,
152 pub default: Option<LiteralNode>,
153 }
154
155 #[derive(Debug, Clone, Node)]
156 pub struct LiteralNode {
157 #[node(wraps)]
158 pub lit: Literal,
159 }
160
161 #[derive(Debug, Clone, Node)]
162 pub enum Literal {
163 Boolean(bool),
164 String(String),
165 // Integers are represented as the widest representation we can.
166 // Number formatting vary with language and radix, so we avoid a lot of parsing and
167 // formatting duplication by using only signed and unsigned variants.
168 UInt(u64, Radix, TypeNode),
169 Int(i64, Radix, TypeNode),
170 // Pass the string representation through as typed in the UDL.
171 // This avoids a lot of uncertainty around precision and accuracy,
172 // though bindings for languages less sophisticated number parsing than WebIDL
173 // will have to do extra work.
174 Float(String, TypeNode),
175 Enum(String, TypeNode),
176 EmptySequence,
177 EmptyMap,
178 None,
179 Some { inner: Box<Literal> },
180 }
181
182 // Represent the radix of integer literal values.
183 // We preserve the radix into the generated bindings for readability reasons.
184 #[derive(Debug, Clone, Node)]
185 pub enum Radix {
186 Decimal = 10,
187 Octal = 8,
188 Hexadecimal = 16,
189 }
190
191 #[derive(Debug, Clone, Node)]
192 pub struct Record {
193 pub name: String,
194 pub fields: Vec<Field>,
195 pub docstring: Option<String>,
196 pub self_type: TypeNode,
197 }
198
199 #[derive(Debug, Clone, Node)]
200 pub struct Field {
201 pub name: String,
202 pub ty: TypeNode,
203 pub default: Option<LiteralNode>,
204 pub docstring: Option<String>,
205 }
206
207 #[derive(Debug, Clone, Node)]
208 pub enum EnumShape {
209 Enum,
210 Error { flat: bool },
211 }
212
213 #[derive(Debug, Clone, Node)]
214 pub struct Enum {
215 pub name: String,
216 /// Is this a "flat" enum -- one with no associated data
217 pub is_flat: bool,
218 pub shape: EnumShape,
219 pub variants: Vec<Variant>,
220 pub discr_type: Option<TypeNode>,
221 pub docstring: Option<String>,
222 pub self_type: TypeNode,
223 }
224
225 #[derive(Debug, Clone, Node)]
226 pub struct Variant {
227 pub name: String,
228 pub discr: Option<LiteralNode>,
229 pub fields: Vec<Field>,
230 pub docstring: Option<String>,
231 }
232
233 #[derive(Debug, Clone, Node)]
234 pub struct Interface {
235 pub name: String,
236 pub docstring: Option<String>,
237 pub constructors: Vec<Constructor>,
238 pub methods: Vec<Method>,
239 pub uniffi_traits: Vec<UniffiTrait>,
240 pub trait_impls: Vec<ObjectTraitImpl>,
241 pub imp: ObjectImpl,
242 pub self_type: TypeNode,
243 pub vtable: Option<VTable>,
244 pub ffi_func_clone: RustFfiFunctionName,
245 pub ffi_func_free: RustFfiFunctionName,
246 }
247
248 #[derive(Debug, Clone, Node)]
249 pub struct CallbackInterface {
250 pub name: String,
251 pub docstring: Option<String>,
252 pub vtable: VTable,
253 pub methods: Vec<Method>,
254 pub self_type: TypeNode,
255 }
256
257 #[derive(Debug, Clone, Node)]
258 pub struct VTable {
259 /// Vtable struct. This has field for each callback interface method that stores a function
260 /// pointer for that method.
261 pub struct_type: FfiType,
262 /// Name of the interface/callback interface that this vtable is for
263 pub interface_name: String,
264 /// Rust FFI function to initialize the vtable.
265 ///
266 /// Foreign code should call this function, passing it a pointer to the VTable struct.
267 pub init_fn: RustFfiFunctionName,
268 pub methods: Vec<VTableMethod>,
269 }
270
271 /// Single method in a vtable
272 #[derive(Debug, Clone, Node)]
273 pub struct VTableMethod {
274 pub callable: Callable,
275 /// FfiType::Function type that corresponds to the method
276 pub ffi_type: FfiType,
277 }
278
279 #[derive(Debug, Clone, Node)]
280 pub enum UniffiTrait {
281 Debug { fmt: Method },
282 Display { fmt: Method },
283 Eq { eq: Method, ne: Method },
284 Hash { hash: Method },
285 }
286
287 #[derive(Debug, Clone, Node)]
288 pub struct ObjectTraitImpl {
289 pub ty: TypeNode,
290 pub trait_name: String,
291 pub tr_module_name: Option<String>,
292 }
293
294 #[derive(Debug, Clone, Node)]
295 pub struct CustomType {
296 pub name: String,
297 pub builtin: TypeNode,
298 pub docstring: Option<String>,
299 pub self_type: TypeNode,
300 }
301
302 #[derive(Debug, Clone, Node)]
303 pub struct OptionalType {
304 pub inner: TypeNode,
305 pub self_type: TypeNode,
306 }
307
308 #[derive(Debug, Clone, Node)]
309 pub struct SequenceType {
310 pub inner: TypeNode,
311 pub self_type: TypeNode,
312 }
313
314 #[derive(Debug, Clone, Node)]
315 pub struct MapType {
316 pub key: TypeNode,
317 pub value: TypeNode,
318 pub self_type: TypeNode,
319 }
320
321 #[derive(Debug, Clone, Node)]
322 pub struct ExternalType {
323 pub module_name: String,
324 pub name: String,
325 pub self_type: TypeNode,
326 }
327
328 #[derive(Debug, Clone, Node)]
329 pub struct TypeNode {
330 #[node(wraps)]
331 pub ty: Type,
332 /// Unique UpperCamelCase name for the type
333 ///
334 /// This is used for a couple reasons:
335 /// - Defining classes to handle things related to the type.
336 /// Many bindings will create a `UniffiConverter[canonical_name]` class.
337 /// - Creating a unique key for a type
338 pub canonical_name: String,
339 pub is_used_as_error: bool,
340 pub ffi_type: FfiType,
341 }
342
343 #[derive(Debug, Clone, PartialEq, Eq, Hash, Node)]
344 pub enum Type {
345 // Primitive types.
346 UInt8,
347 Int8,
348 UInt16,
349 Int16,
350 UInt32,
351 Int32,
352 UInt64,
353 Int64,
354 Float32,
355 Float64,
356 Boolean,
357 String,
358 Bytes,
359 Timestamp,
360 Duration,
361 // Structurally recursive types.
362 Optional {
363 inner_type: Box<Type>,
364 },
365 Sequence {
366 inner_type: Box<Type>,
367 },
368 Map {
369 key_type: Box<Type>,
370 value_type: Box<Type>,
371 },
372 // User defined types in the API
373 Interface {
374 module_name: String,
375 name: String,
376 imp: ObjectImpl,
377 },
378 Record {
379 module_name: String,
380 name: String,
381 },
382 Enum {
383 module_name: String,
384 name: String,
385 },
386 CallbackInterface {
387 module_name: String,
388 name: String,
389 },
390 Custom {
391 module_name: String,
392 name: String,
393 builtin: Box<Type>,
394 },
395 }
396
397 #[derive(Debug, Clone, Node, PartialEq, Eq, Hash)]
398 pub enum ObjectImpl {
399 // A single Rust type
400 Struct,
401 // A trait that's can be implemented by Rust types
402 Trait,
403 // A trait + a callback interface -- can be implemented by both Rust and foreign types.
404 CallbackTrait,
405 }
406
407 #[derive(Debug, Clone, Node)]
408 pub enum FfiDefinition {
409 /// FFI Function exported in the Rust library
410 RustFunction(FfiFunction),
411 /// FFI Function definition used in the interface, language, for example a callback interface method.
412 FunctionType(FfiFunctionType),
413 /// Struct definition used in the interface, for example a callback interface Vtable.
414 Struct(FfiStruct),
415 }
416
417 /// Name of a FFI function from the Rust library
418 #[derive(Debug, Clone, Node, PartialEq, Eq, Hash)]
419 pub struct RustFfiFunctionName(pub String);
420
421 /// Name of an FfiStruct
422 #[derive(Debug, Clone, Node, PartialEq, Eq, Hash)]
423 pub struct FfiStructName(pub String);
424
425 /// Name of an FfiFunctionType (i.e. a function pointer type)
426 #[derive(Debug, Clone, Node, PartialEq, Eq, Hash)]
427 pub struct FfiFunctionTypeName(pub String);
428
429 #[derive(Debug, Clone, Node)]
430 pub struct FfiFunction {
431 pub name: RustFfiFunctionName,
432 pub is_async: bool,
433 pub async_data: Option<AsyncData>,
434 pub arguments: Vec<FfiArgument>,
435 pub return_type: FfiReturnType,
436 pub has_rust_call_status_arg: bool,
437 pub kind: FfiFunctionKind,
438 }
439
440 #[derive(Debug, Clone, Node)]
441 pub enum FfiFunctionKind {
442 Scaffolding,
443 ObjectClone,
444 ObjectFree,
445 RustFuturePoll,
446 RustFutureComplete,
447 RustFutureCancel,
448 RustFutureFree,
449 RustBufferFromBytes,
450 RustBufferFree,
451 RustBufferAlloc,
452 RustBufferReserve,
453 RustVtableInit,
454 UniffiContractVersion,
455 Checksum,
456 }
457
458 #[derive(Debug, Clone, Node)]
459 pub struct FfiFunctionType {
460 pub name: FfiFunctionTypeName,
461 pub arguments: Vec<FfiArgument>,
462 pub return_type: FfiReturnType,
463 pub has_rust_call_status_arg: bool,
464 }
465
466 #[derive(Debug, Clone, Node)]
467 pub struct FfiReturnType {
468 pub ty: Option<FfiType>,
469 }
470
471 #[derive(Debug, Clone, Node)]
472 pub struct FfiStruct {
473 pub name: FfiStructName,
474 pub fields: Vec<FfiField>,
475 }
476
477 #[derive(Debug, Clone, Node)]
478 pub struct FfiField {
479 pub name: String,
480 pub ty: FfiType,
481 }
482
483 #[derive(Debug, Clone, Node)]
484 pub struct FfiArgument {
485 pub name: String,
486 pub ty: FfiType,
487 }
488
489 #[derive(Debug, Clone, Node, PartialEq, Eq, Hash)]
490 pub enum FfiType {
491 // N.B. there are no booleans at this layer, since they cause problems for JNA.
492 UInt8,
493 Int8,
494 UInt16,
495 Int16,
496 UInt32,
497 Int32,
498 UInt64,
499 Int64,
500 Float32,
501 Float64,
502 /// A `*const c_void` pointer to a rust-owned `Arc<T>`.
503 /// If you've got one of these, you must call the appropriate rust function to free it.
504 /// The templates will generate a unique `free` function for each T.
505 /// The inner string references the name of the `T` type.
506 RustArcPtr {
507 module_name: String,
508 object_name: String,
509 },
510 /// A byte buffer allocated by rust, and owned by whoever currently holds it.
511 /// If you've got one of these, you must either call the appropriate rust function to free it
512 /// or pass it to someone that will.
513 ///
514 /// For user-defined types like Record, Enum, CustomType, etc., the inner value will be the
515 /// module name for that type. This is needed for some languages, because each module
516 /// defines a different RustBuffer type and using the wrong one will result in a type
517 /// error.
518 ///
519 /// For builtin types like String, this is always None. It's safe to assume that the
520 /// RustBuffer is for the local module -- at least this has been true for all our languages
521 /// so far, maybe we should revisit this.
522 RustBuffer(Option<String>),
523 /// A borrowed reference to some raw bytes owned by foreign language code.
524 /// The provider of this reference must keep it alive for the duration of the receiving call.
525 ForeignBytes,
526 /// Value for a FfiDefinition::FunctionType.
527 Function(FfiFunctionTypeName),
528 /// Pointer to a FFI struct (e.g. a VTable). The inner value matches one of the struct
529 /// definitions in [crate::ComponentInterface::ffi_definitions].
530 Struct(FfiStructName),
531 /// Opaque 64-bit handle
532 ///
533 /// These are used to pass objects across the FFI.
534 Handle(HandleKind),
535 RustCallStatus,
536 /// Const pointer to an FfiType.
537 Reference(Box<FfiType>),
538 /// Mutable pointer to an FfiType.
539 MutReference(Box<FfiType>),
540 /// Opaque pointer
541 VoidPointer,
542 }
543
544 #[derive(Debug, Clone, Node, PartialEq, Eq, Hash)]
545 pub enum HandleKind {
546 RustFuture,
547 ForeignFuture,
548 ForeignFutureCallbackData,
549 CallbackInterface {
550 module_name: String,
551 interface_name: String,
552 },
553 // TODO: dust off https://github.com/mozilla/uniffi-rs/pull/1823 and also use handles for
554 // interfaces and trait interfaces
555 }
556
557 #[derive(Debug, Clone, Node)]
558 pub struct Checksum {
559 pub fn_name: RustFfiFunctionName,
560 pub checksum: u16,
561 }
562
563 impl FfiDefinition {
564 pub fn name(&self) -> &str {
565 match self {
566 Self::RustFunction(func) => &func.name.0,
567 Self::FunctionType(func_type) => &func_type.name.0,
568 Self::Struct(st) => &st.name.0,
569 }
570 }
571 }
572
573 impl From<FfiFunction> for FfiDefinition {
574 fn from(func: FfiFunction) -> Self {
575 Self::RustFunction(func)
576 }
577 }
578
579 impl From<FfiFunctionType> for FfiDefinition {
580 fn from(func_type: FfiFunctionType) -> Self {
581 Self::FunctionType(func_type)
582 }
583 }
584
585 impl From<FfiStruct> for FfiDefinition {
586 fn from(st: FfiStruct) -> Self {
587 Self::Struct(st)
588 }
589 }
590
591 impl FfiArgument {
592 pub fn new(name: impl Into<String>, ty: FfiType) -> Self {
593 Self {
594 name: name.into(),
595 ty,
596 }
597 }
598 }
599
600 impl FfiField {
601 pub fn new(name: impl Into<String>, ty: FfiType) -> Self {
602 Self {
603 name: name.into(),
604 ty,
605 }
606 }
607 }
608
609 impl Callable {
610 pub fn is_async(&self) -> bool {
611 self.async_data.is_some()
612 }
613
614 pub fn ffi_return_type(&self) -> Option<&FfiType> {
615 self.return_type.ty.as_ref().map(|ty| &ty.ffi_type)
616 }
617 }
618
619 impl Type {
620 pub fn name(&self) -> Option<&str> {
621 match &self {
622 Type::Record { name, .. }
623 | Type::Enum { name, .. }
624 | Type::Interface { name, .. }
625 | Type::CallbackInterface { name, .. }
626 | Type::Custom { name, .. } => Some(name.as_str()),
627 _ => None,
628 }
629 }
630 }
631
632 impl ObjectImpl {
633 pub fn has_callback_interface(&self) -> bool {
634 matches!(self, Self::CallbackTrait)
635 }
636 }