Debian Codegraph @

third_party/rust/uniffi_bindgen/src/interface/object.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 //! # Object definitions for a `ComponentInterface`.
6 //!
7 //! This module converts "interface" definitions from UDL into [`Object`] structures
8 //! that can be added to a `ComponentInterface`, which are the main way we define stateful
9 //! objects with behaviour for a UniFFI Rust Component. An [`Object`] is an opaque handle
10 //! to some state on which methods can be invoked.
11 //!
12 //! (The terminology mismatch between "interface" and "object" is a historical artifact of
13 //! this tool prior to committing to WebIDL syntax).
14 //!
15 //! A declaration in the UDL like this:
16 //!
17 //! ```
18 //! # let ci = uniffi_bindgen::interface::ComponentInterface::from_webidl(r##"
19 //! # namespace example {};
20 //! interface Example {
21 //! constructor(string? name);
22 //! string my_name();
23 //! };
24 //! # "##, "crate_name")?;
25 //! # Ok::<(), anyhow::Error>(())
26 //! ```
27 //!
28 //! Will result in an [`Object`] member with one [`Constructor`] and one [`Method`] being added
29 //! to the resulting [`crate::ComponentInterface`]:
30 //!
31 //! ```
32 //! # let ci = uniffi_bindgen::interface::ComponentInterface::from_webidl(r##"
33 //! # namespace example {};
34 //! # interface Example {
35 //! # constructor(string? name);
36 //! # string my_name();
37 //! # };
38 //! # "##, "crate_name")?;
39 //! let obj = ci.get_object_definition("Example").unwrap();
40 //! assert_eq!(obj.name(), "Example");
41 //! assert_eq!(obj.constructors().len(), 1);
42 //! assert_eq!(obj.constructors()[0].arguments()[0].name(), "name");
43 //! assert_eq!(obj.methods().len(),1 );
44 //! assert_eq!(obj.methods()[0].name(), "my_name");
45 //! # Ok::<(), anyhow::Error>(())
46 //! ```
47 //!
48 //! It's not necessary for all interfaces to have constructors.
49 //! ```
50 //! # let ci = uniffi_bindgen::interface::ComponentInterface::from_webidl(r##"
51 //! # namespace example {};
52 //! # interface Example {};
53 //! # "##, "crate_name")?;
54 //! let obj = ci.get_object_definition("Example").unwrap();
55 //! assert_eq!(obj.name(), "Example");
56 //! assert_eq!(obj.constructors().len(), 0);
57 //! # Ok::<(), anyhow::Error>(())
58 //! ```
59
60 use anyhow::Result;
61 use uniffi_meta::{Checksum, ObjectTraitImplMetadata};
62
63 use super::callbacks;
64 use super::ffi::{FfiArgument, FfiCallbackFunction, FfiFunction, FfiStruct, FfiType};
65 use super::function::{Argument, Callable};
66 use super::{AsType, ObjectImpl, Type, TypeIterator};
67
68 /// An "object" is an opaque type that is passed around by reference, can
69 /// have methods called on it, and so on - basically your classic Object Oriented Programming
70 /// type of deal, except without elaborate inheritance hierarchies. Some can be instantiated.
71 ///
72 /// In UDL these correspond to the `interface` keyword.
73 ///
74 /// At the FFI layer, objects are represented by an opaque integer handle and a set of functions
75 /// a common prefix. The object's constructors are functions that return new objects by handle,
76 /// and its methods are functions that take a handle as first argument. The foreign language
77 /// binding code is expected to stitch these functions back together into an appropriate class
78 /// definition (or that language's equivalent thereof).
79 ///
80 /// TODO:
81 /// - maybe "Class" would be a better name than "Object" here?
82 #[derive(Debug, Clone, Checksum)]
83 pub struct Object {
84 pub(super) name: String,
85 /// How this object is implemented in Rust
86 pub(super) imp: ObjectImpl,
87 pub(super) module_path: String,
88 pub(super) remote: bool,
89 pub(super) constructors: Vec<Constructor>,
90 pub(super) methods: Vec<Method>,
91 // The "trait" methods - they have a (presumably "well known") name, and
92 // a regular method (albeit with a generated name)
93 // XXX - this should really be a HashSet, but not enough transient types support hash to make it worthwhile now.
94 pub(super) uniffi_traits: Vec<UniffiTrait>,
95 // These are traits described in our CI which this object has declared it implements.
96 // This allows foreign bindings to implement things like inheritance or whatever makes sense for them.
97 pub(super) trait_impls: Vec<ObjectTraitImplMetadata>,
98 // We don't include the FfiFuncs in the hash calculation, because:
99 // - it is entirely determined by the other fields,
100 // so excluding it is safe.
101 // - its `name` property includes a checksum derived from the very
102 // hash value we're trying to calculate here, so excluding it
103 // avoids a weird circular dependency in the calculation.
104
105 // FFI function to clone a pointer for this object
106 #[checksum_ignore]
107 pub(super) ffi_func_clone: FfiFunction,
108 // FFI function to free a pointer for this object
109 #[checksum_ignore]
110 pub(super) ffi_func_free: FfiFunction,
111 // Ffi function to initialize the foreign callback for trait interfaces
112 #[checksum_ignore]
113 pub(super) ffi_init_callback: Option<FfiFunction>,
114 #[checksum_ignore]
115 pub(super) docstring: Option<String>,
116 }
117
118 impl Object {
119 pub fn name(&self) -> &str {
120 &self.name
121 }
122
123 pub fn rename(&mut self, new_name: String) {
124 self.name = new_name;
125 }
126
127 /// Returns the fully qualified name that should be used by Rust code for this object.
128 /// Includes `r#`, traits get a leading `dyn`. If we ever supported associated types, then
129 /// this would also include them.
130 pub fn rust_name(&self) -> String {
131 self.imp.rust_name_for(&self.name)
132 }
133
134 pub fn imp(&self) -> &ObjectImpl {
135 &self.imp
136 }
137
138 pub fn remote(&self) -> bool {
139 self.remote
140 }
141
142 pub fn is_trait_interface(&self) -> bool {
143 self.imp.is_trait_interface()
144 }
145
146 pub fn has_callback_interface(&self) -> bool {
147 self.imp.has_callback_interface()
148 }
149
150 pub fn has_async_method(&self) -> bool {
151 self.methods.iter().any(Method::is_async)
152 }
153
154 pub fn constructors(&self) -> Vec<&Constructor> {
155 self.constructors.iter().collect()
156 }
157
158 pub fn primary_constructor(&self) -> Option<&Constructor> {
159 self.constructors
160 .iter()
161 .find(|cons| cons.is_primary_constructor())
162 }
163
164 pub fn alternate_constructors(&self) -> Vec<&Constructor> {
165 self.constructors
166 .iter()
167 .filter(|cons| !cons.is_primary_constructor())
168 .collect()
169 }
170
171 pub fn methods(&self) -> Vec<&Method> {
172 self.methods.iter().collect()
173 }
174
175 pub fn get_method(&self, name: &str) -> Method {
176 let matches: Vec<_> = self.methods.iter().filter(|m| m.name() == name).collect();
177 match matches.len() {
178 1 => matches[0].clone(),
179 n => panic!("{n} methods named {name}"),
180 }
181 }
182
183 pub fn uniffi_traits(&self) -> Vec<&UniffiTrait> {
184 self.uniffi_traits.iter().collect()
185 }
186
187 pub fn trait_impls(&self) -> Vec<&ObjectTraitImplMetadata> {
188 self.trait_impls.iter().collect()
189 }
190
191 // used by bindings for renaming.
192 pub fn trait_impls_mut(&mut self) -> &mut Vec<ObjectTraitImplMetadata> {
193 &mut self.trait_impls
194 }
195
196 pub fn ffi_object_clone(&self) -> &FfiFunction {
197 &self.ffi_func_clone
198 }
199
200 pub fn ffi_object_free(&self) -> &FfiFunction {
201 &self.ffi_func_free
202 }
203
204 pub fn ffi_init_callback(&self) -> &FfiFunction {
205 self.ffi_init_callback
206 .as_ref()
207 .unwrap_or_else(|| panic!("No ffi_init_callback set for {}", &self.name))
208 }
209
210 pub fn docstring(&self) -> Option<&str> {
211 self.docstring.as_deref()
212 }
213
214 pub fn iter_ffi_function_definitions(&self) -> impl Iterator<Item = &FfiFunction> {
215 [&self.ffi_func_clone, &self.ffi_func_free]
216 .into_iter()
217 .chain(&self.ffi_init_callback)
218 .chain(self.constructors.iter().map(|f| &f.ffi_func))
219 .chain(self.methods.iter().map(|f| &f.ffi_func))
220 .chain(
221 self.uniffi_traits
222 .iter()
223 .flat_map(|ut| match ut {
224 UniffiTrait::Display { fmt: m }
225 | UniffiTrait::Debug { fmt: m }
226 | UniffiTrait::Hash { hash: m } => vec![m],
227 UniffiTrait::Eq { eq, ne } => vec![eq, ne],
228 })
229 .map(|m| &m.ffi_func),
230 )
231 }
232
233 pub fn derive_ffi_funcs(&mut self) -> Result<()> {
234 assert!(!self.ffi_func_clone.name().is_empty());
235 assert!(!self.ffi_func_free.name().is_empty());
236 self.ffi_func_clone.arguments = vec![FfiArgument {
237 name: "ptr".to_string(),
238 type_: FfiType::RustArcPtr(self.name.to_string()),
239 }];
240 self.ffi_func_clone.return_type = Some(FfiType::RustArcPtr(self.name.to_string()));
241 self.ffi_func_free.arguments = vec![FfiArgument {
242 name: "ptr".to_string(),
243 type_: FfiType::RustArcPtr(self.name.to_string()),
244 }];
245 self.ffi_func_free.return_type = None;
246 self.ffi_func_free.is_object_free_function = true;
247 if self.has_callback_interface() {
248 self.ffi_init_callback = Some(FfiFunction::callback_init(
249 &self.module_path,
250 &self.name,
251 callbacks::vtable_name(&self.name),
252 ));
253 }
254
255 for cons in self.constructors.iter_mut() {
256 cons.derive_ffi_func();
257 }
258 for meth in self.methods.iter_mut() {
259 meth.derive_ffi_func()?;
260 }
261 for ut in self.uniffi_traits.iter_mut() {
262 ut.derive_ffi_func()?;
263 }
264
265 Ok(())
266 }
267
268 /// For trait interfaces, FfiCallbacks to define for our methods, otherwise an empty vec.
269 pub fn ffi_callbacks(&self) -> Vec<FfiCallbackFunction> {
270 if self.is_trait_interface() {
271 callbacks::ffi_callbacks(&self.name, &self.methods)
272 } else {
273 vec![]
274 }
275 }
276
277 /// For trait interfaces, the VTable FFI type
278 pub fn vtable(&self) -> Option<FfiType> {
279 self.is_trait_interface()
280 .then(|| FfiType::Struct(callbacks::vtable_name(&self.name)))
281 }
282
283 /// For trait interfaces, the VTable struct to define. Otherwise None.
284 pub fn vtable_definition(&self) -> Option<FfiStruct> {
285 self.is_trait_interface()
286 .then(|| callbacks::vtable_struct(&self.name, &self.methods))
287 }
288
289 /// Vec of (ffi_callback_name, method) pairs
290 pub fn vtable_methods(&self) -> Vec<(FfiCallbackFunction, Method)> {
291 self.methods
292 .iter()
293 .enumerate()
294 .map(|(i, method)| {
295 (
296 callbacks::method_ffi_callback(&self.name, method, i),
297 method.clone(),
298 )
299 })
300 .collect()
301 }
302
303 pub fn iter_types(&self) -> TypeIterator<'_> {
304 Box::new(
305 self.methods
306 .iter()
307 .map(Method::iter_types)
308 .chain(self.uniffi_traits.iter().map(UniffiTrait::iter_types))
309 .chain(self.constructors.iter().map(Constructor::iter_types))
310 .flatten(),
311 )
312 }
313 }
314
315 impl AsType for Object {
316 fn as_type(&self) -> Type {
317 Type::Object {
318 name: self.name.clone(),
319 module_path: self.module_path.clone(),
320 imp: self.imp,
321 }
322 }
323 }
324
325 impl From<uniffi_meta::ObjectMetadata> for Object {
326 fn from(meta: uniffi_meta::ObjectMetadata) -> Self {
327 let ffi_clone_name = meta.clone_ffi_symbol_name();
328 let ffi_free_name = meta.free_ffi_symbol_name();
329 Object {
330 module_path: meta.module_path,
331 name: meta.name,
332 imp: meta.imp,
333 remote: meta.remote,
334 constructors: Default::default(),
335 methods: Default::default(),
336 uniffi_traits: Default::default(),
337 trait_impls: Default::default(),
338 ffi_func_clone: FfiFunction {
339 name: ffi_clone_name,
340 ..Default::default()
341 },
342 ffi_func_free: FfiFunction {
343 name: ffi_free_name,
344 ..Default::default()
345 },
346 ffi_init_callback: None,
347 docstring: meta.docstring.clone(),
348 }
349 }
350 }
351
352 impl From<uniffi_meta::UniffiTraitMetadata> for UniffiTrait {
353 fn from(meta: uniffi_meta::UniffiTraitMetadata) -> Self {
354 match meta {
355 uniffi_meta::UniffiTraitMetadata::Debug { fmt } => {
356 UniffiTrait::Debug { fmt: fmt.into() }
357 }
358 uniffi_meta::UniffiTraitMetadata::Display { fmt } => {
359 UniffiTrait::Display { fmt: fmt.into() }
360 }
361 uniffi_meta::UniffiTraitMetadata::Eq { eq, ne } => UniffiTrait::Eq {
362 eq: eq.into(),
363 ne: ne.into(),
364 },
365 uniffi_meta::UniffiTraitMetadata::Hash { hash } => {
366 UniffiTrait::Hash { hash: hash.into() }
367 }
368 }
369 }
370 }
371
372 // Represents a constructor for an object type.
373 //
374 // In the FFI, this will be a function that returns a pointer to an instance
375 // of the corresponding object type.
376 #[derive(Debug, Clone, Checksum)]
377 pub struct Constructor {
378 pub(super) name: String,
379 pub(super) object_name: String,
380 pub(super) object_module_path: String,
381 pub(super) is_async: bool,
382 pub(super) arguments: Vec<Argument>,
383 // We don't include the FFIFunc in the hash calculation, because:
384 // - it is entirely determined by the other fields,
385 // so excluding it is safe.
386 // - its `name` property includes a checksum derived from the very
387 // hash value we're trying to calculate here, so excluding it
388 // avoids a weird circular dependency in the calculation.
389 #[checksum_ignore]
390 pub(super) ffi_func: FfiFunction,
391 #[checksum_ignore]
392 pub(super) docstring: Option<String>,
393 pub(super) throws: Option<Type>,
394 pub(super) checksum_fn_name: String,
395 // Force a checksum value, or we'll fallback to the trait.
396 #[checksum_ignore]
397 pub(super) checksum: Option<u16>,
398 // to help with lifetimes elsewhere...
399 pub(super) self_type: Type,
400 }
401
402 impl Constructor {
403 pub fn name(&self) -> &str {
404 &self.name
405 }
406
407 pub fn rename(&mut self, new_name: String) {
408 self.name = new_name;
409 }
410
411 pub fn is_async(&self) -> bool {
412 self.is_async
413 }
414
415 pub fn object_name(&self) -> &str {
416 &self.object_name
417 }
418
419 pub fn arguments(&self) -> Vec<&Argument> {
420 self.arguments.iter().collect()
421 }
422
423 pub fn full_arguments(&self) -> Vec<Argument> {
424 self.arguments.to_vec()
425 }
426
427 pub fn ffi_func(&self) -> &FfiFunction {
428 &self.ffi_func
429 }
430
431 pub fn checksum_fn_name(&self) -> &str {
432 &self.checksum_fn_name
433 }
434
435 pub fn checksum(&self) -> u16 {
436 self.checksum.unwrap_or_else(|| uniffi_meta::checksum(self))
437 }
438
439 pub fn throws(&self) -> bool {
440 self.throws.is_some()
441 }
442
443 pub fn throws_name(&self) -> Option<&str> {
444 super::throws_name(&self.throws)
445 }
446
447 pub fn throws_type(&self) -> Option<&Type> {
448 self.throws.as_ref()
449 }
450
451 pub fn docstring(&self) -> Option<&str> {
452 self.docstring.as_deref()
453 }
454
455 pub fn is_primary_constructor(&self) -> bool {
456 self.name == "new"
457 }
458
459 fn derive_ffi_func(&mut self) {
460 assert!(!self.ffi_func.name().is_empty());
461 self.ffi_func.init(
462 Some(FfiType::RustArcPtr(self.object_name.clone())),
463 self.arguments.iter().map(Into::into),
464 );
465 }
466 }
467
468 impl From<uniffi_meta::ConstructorMetadata> for Constructor {
469 fn from(meta: uniffi_meta::ConstructorMetadata) -> Self {
470 let ffi_name = meta.ffi_symbol_name();
471 let checksum_fn_name = meta.checksum_symbol_name();
472 let arguments = meta.inputs.into_iter().map(Into::into).collect();
473
474 let ffi_func = FfiFunction {
475 name: ffi_name,
476 is_async: meta.is_async,
477 ..FfiFunction::default()
478 };
479 let self_type = Type::Object {
480 module_path: meta.module_path.clone(),
481 name: meta.self_name.clone(),
482 imp: ObjectImpl::Struct,
483 };
484 Self {
485 name: meta.name,
486 object_name: meta.self_name,
487 is_async: meta.is_async,
488 object_module_path: meta.module_path,
489 arguments,
490 ffi_func,
491 docstring: meta.docstring.clone(),
492 throws: meta.throws,
493 checksum_fn_name,
494 checksum: meta.checksum,
495 self_type,
496 }
497 }
498 }
499
500 // Represents an instance method for an object type.
501 //
502 // The FFI will represent this as a function whose first/self argument is a
503 // `FfiType::RustArcPtr` to the instance.
504 #[derive(Debug, Clone, Checksum)]
505 pub struct Method {
506 pub(super) name: String,
507 pub(super) object_name: String,
508 pub(super) object_module_path: String,
509 pub(super) is_async: bool,
510 pub(super) object_impl: ObjectImpl,
511 pub(super) arguments: Vec<Argument>,
512 pub(super) return_type: Option<Type>,
513 // We don't include the FFIFunc in the hash calculation, because:
514 // - it is entirely determined by the other fields,
515 // so excluding it is safe.
516 // - its `name` property includes a checksum derived from the very
517 // hash value we're trying to calculate here, so excluding it
518 // avoids a weird circular dependency in the calculation.
519 #[checksum_ignore]
520 pub(super) ffi_func: FfiFunction,
521 #[checksum_ignore]
522 pub(super) docstring: Option<String>,
523 pub(super) throws: Option<Type>,
524 pub(super) takes_self_by_arc: bool,
525 pub(super) checksum_fn_name: String,
526 // Force a checksum value, or we'll fallback to the trait.
527 #[checksum_ignore]
528 pub(super) checksum: Option<u16>,
529 }
530
531 impl Method {
532 pub fn name(&self) -> &str {
533 &self.name
534 }
535
536 pub fn rename(&mut self, new_name: String) {
537 self.name = new_name;
538 }
539
540 pub fn is_async(&self) -> bool {
541 self.is_async
542 }
543
544 pub fn object_name(&self) -> &str {
545 &self.object_name
546 }
547
548 pub fn arguments(&self) -> Vec<&Argument> {
549 self.arguments.iter().collect()
550 }
551
552 // Methods have a special implicit first argument for the object instance,
553 // hence `arguments` and `full_arguments` are different.
554 pub fn full_arguments(&self) -> Vec<Argument> {
555 vec![Argument {
556 name: "ptr".to_string(),
557 // TODO: ideally we'd get this via `ci.resolve_type_expression` so that it
558 // is contained in the proper `TypeUniverse`, but this works for now.
559 type_: Type::Object {
560 name: self.object_name.clone(),
561 module_path: self.object_module_path.clone(),
562 imp: self.object_impl,
563 },
564 by_ref: !self.takes_self_by_arc,
565 optional: false,
566 default: None,
567 }]
568 .into_iter()
569 .chain(self.arguments.iter().cloned())
570 .collect()
571 }
572
573 pub fn return_type(&self) -> Option<&Type> {
574 self.return_type.as_ref()
575 }
576
577 pub fn ffi_func(&self) -> &FfiFunction {
578 &self.ffi_func
579 }
580
581 pub fn checksum_fn_name(&self) -> &str {
582 &self.checksum_fn_name
583 }
584
585 pub fn checksum(&self) -> u16 {
586 self.checksum.unwrap_or_else(|| uniffi_meta::checksum(self))
587 }
588
589 pub fn throws(&self) -> bool {
590 self.throws.is_some()
591 }
592
593 pub fn throws_name(&self) -> Option<&str> {
594 super::throws_name(&self.throws)
595 }
596
597 pub fn throws_type(&self) -> Option<&Type> {
598 self.throws.as_ref()
599 }
600
601 pub fn docstring(&self) -> Option<&str> {
602 self.docstring.as_deref()
603 }
604
605 pub fn takes_self_by_arc(&self) -> bool {
606 self.takes_self_by_arc
607 }
608
609 pub fn derive_ffi_func(&mut self) -> Result<()> {
610 assert!(!self.ffi_func.name().is_empty());
611 self.ffi_func.init(
612 self.return_type.as_ref().map(Into::into),
613 self.full_arguments().iter().map(Into::into),
614 );
615 Ok(())
616 }
617
618 /// For async callback interface methods, the FFI struct to pass to the completion function.
619 pub fn foreign_future_ffi_result_struct(&self) -> FfiStruct {
620 callbacks::foreign_future_ffi_result_struct(self.return_type.as_ref().map(FfiType::from))
621 }
622 }
623
624 impl From<uniffi_meta::MethodMetadata> for Method {
625 fn from(meta: uniffi_meta::MethodMetadata) -> Self {
626 let ffi_name = meta.ffi_symbol_name();
627 let checksum_fn_name = meta.checksum_symbol_name();
628 let is_async = meta.is_async;
629 let return_type = meta.return_type;
630 let arguments = meta.inputs.into_iter().map(Into::into).collect();
631
632 let ffi_func = FfiFunction {
633 name: ffi_name,
634 is_async,
635 ..FfiFunction::default()
636 };
637
638 Self {
639 name: meta.name,
640 object_name: meta.self_name,
641 object_module_path: meta.module_path,
642 is_async,
643 object_impl: ObjectImpl::Struct, // will be filled in later
644 arguments,
645 return_type,
646 ffi_func,
647 docstring: meta.docstring.clone(),
648 throws: meta.throws,
649 takes_self_by_arc: meta.takes_self_by_arc,
650 checksum_fn_name,
651 checksum: meta.checksum,
652 }
653 }
654 }
655
656 impl From<uniffi_meta::TraitMethodMetadata> for Method {
657 fn from(meta: uniffi_meta::TraitMethodMetadata) -> Self {
658 let ffi_name = meta.ffi_symbol_name();
659 let checksum_fn_name = meta.checksum_symbol_name();
660 let is_async = meta.is_async;
661 let return_type = meta.return_type;
662 let arguments = meta.inputs.into_iter().map(Into::into).collect();
663 let ffi_func = FfiFunction {
664 name: ffi_name,
665 is_async,
666 ..FfiFunction::default()
667 };
668 Self {
669 name: meta.name,
670 object_name: meta.trait_name,
671 object_module_path: meta.module_path,
672 is_async,
673 arguments,
674 return_type,
675 docstring: meta.docstring.clone(),
676 throws: meta.throws,
677 takes_self_by_arc: meta.takes_self_by_arc,
678 checksum_fn_name,
679 checksum: meta.checksum,
680 ffi_func,
681 object_impl: ObjectImpl::Struct,
682 }
683 }
684 }
685
686 /// The list of traits we support generating helper methods for.
687 #[derive(Clone, Debug, Checksum)]
688 pub enum UniffiTrait {
689 Debug { fmt: Method },
690 Display { fmt: Method },
691 Eq { eq: Method, ne: Method },
692 Hash { hash: Method },
693 }
694
695 impl UniffiTrait {
696 pub fn iter_types(&self) -> TypeIterator<'_> {
697 Box::new(
698 match self {
699 UniffiTrait::Display { fmt: m }
700 | UniffiTrait::Debug { fmt: m }
701 | UniffiTrait::Hash { hash: m } => vec![m.iter_types()],
702 UniffiTrait::Eq { eq, ne } => vec![eq.iter_types(), ne.iter_types()],
703 }
704 .into_iter()
705 .flatten(),
706 )
707 }
708
709 pub fn derive_ffi_func(&mut self) -> Result<()> {
710 match self {
711 UniffiTrait::Display { fmt: m }
712 | UniffiTrait::Debug { fmt: m }
713 | UniffiTrait::Hash { hash: m } => {
714 m.derive_ffi_func()?;
715 }
716 UniffiTrait::Eq { eq, ne } => {
717 eq.derive_ffi_func()?;
718 ne.derive_ffi_func()?;
719 }
720 }
721 Ok(())
722 }
723 }
724
725 impl Callable for Constructor {
726 fn arguments(&self) -> Vec<&Argument> {
727 self.arguments()
728 }
729
730 fn return_type(&self) -> Option<&Type> {
731 Some(&self.self_type)
732 }
733
734 fn throws_type(&self) -> Option<&Type> {
735 self.throws_type()
736 }
737
738 fn docstring(&self) -> Option<&str> {
739 self.docstring()
740 }
741
742 fn is_async(&self) -> bool {
743 self.is_async
744 }
745
746 fn ffi_func(&self) -> &FfiFunction {
747 &self.ffi_func
748 }
749 }
750
751 impl Callable for Method {
752 fn arguments(&self) -> Vec<&Argument> {
753 self.arguments()
754 }
755
756 fn return_type(&self) -> Option<&Type> {
757 self.return_type()
758 }
759
760 fn throws_type(&self) -> Option<&Type> {
761 self.throws_type()
762 }
763
764 fn docstring(&self) -> Option<&str> {
765 self.docstring()
766 }
767
768 fn is_async(&self) -> bool {
769 self.is_async
770 }
771
772 fn takes_self(&self) -> bool {
773 true
774 }
775
776 fn ffi_func(&self) -> &FfiFunction {
777 &self.ffi_func
778 }
779 }
780
781 #[cfg(test)]
782 mod test {
783 use super::super::ComponentInterface;
784 use super::*;
785
786 #[test]
787 fn test_that_all_argument_and_return_types_become_known() {
788 const UDL: &str = r#"
789 namespace test{};
790 interface Testing {
791 constructor(string? name, u16 age);
792 sequence<u32> code_points_of_name();
793 };
794 "#;
795 let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap();
796 assert_eq!(ci.object_definitions().len(), 1);
797 ci.get_object_definition("Testing").unwrap();
798
799 assert_eq!(ci.iter_local_types().count(), 6);
800 assert!(ci.iter_local_types().any(|t| t == &Type::UInt16));
801 assert!(ci.iter_local_types().any(|t| t == &Type::UInt32));
802 assert!(ci.iter_local_types().any(|t| t
803 == &Type::Sequence {
804 inner_type: Box::new(Type::UInt32)
805 }));
806 assert!(ci.iter_local_types().any(|t| t == &Type::String));
807 assert!(ci.iter_local_types().any(|t| t
808 == &Type::Optional {
809 inner_type: Box::new(Type::String)
810 }));
811 assert!(ci
812 .iter_local_types()
813 .any(|t| matches!(t, Type::Object { name, ..} if name == "Testing")));
814 }
815
816 #[test]
817 fn test_alternate_constructors() {
818 const UDL: &str = r#"
819 namespace test{};
820 interface Testing {
821 constructor();
822 [Name=new_with_u32]
823 constructor(u32 v);
824 };
825 "#;
826 let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap();
827 assert_eq!(ci.object_definitions().len(), 1);
828
829 let obj = ci.get_object_definition("Testing").unwrap();
830 assert!(obj.primary_constructor().is_some());
831 assert_eq!(obj.alternate_constructors().len(), 1);
832 assert_eq!(obj.methods().len(), 0);
833
834 let cons = obj.primary_constructor().unwrap();
835 assert_eq!(cons.name(), "new");
836 assert_eq!(cons.arguments.len(), 0);
837 assert_eq!(cons.ffi_func.arguments.len(), 0);
838
839 let cons = obj.alternate_constructors()[0];
840 assert_eq!(cons.name(), "new_with_u32");
841 assert_eq!(cons.arguments.len(), 1);
842 assert_eq!(cons.ffi_func.arguments.len(), 1);
843 }
844
845 #[test]
846 fn test_the_name_new_identifies_the_primary_constructor() {
847 const UDL: &str = r#"
848 namespace test{};
849 interface Testing {
850 [Name=newish]
851 constructor();
852 [Name=new]
853 constructor(u32 v);
854 };
855 "#;
856 let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap();
857 assert_eq!(ci.object_definitions().len(), 1);
858
859 let obj = ci.get_object_definition("Testing").unwrap();
860 assert!(obj.primary_constructor().is_some());
861 assert_eq!(obj.alternate_constructors().len(), 1);
862 assert_eq!(obj.methods().len(), 0);
863
864 let cons = obj.primary_constructor().unwrap();
865 assert_eq!(cons.name(), "new");
866 assert_eq!(cons.arguments.len(), 1);
867
868 let cons = obj.alternate_constructors()[0];
869 assert_eq!(cons.name(), "newish");
870 assert_eq!(cons.arguments.len(), 0);
871 assert_eq!(cons.ffi_func.arguments.len(), 0);
872 }
873
874 #[test]
875 fn test_the_name_new_is_reserved_for_constructors() {
876 const UDL: &str = r#"
877 namespace test{};
878 interface Testing {
879 constructor();
880 void new(u32 v);
881 };
882 "#;
883 let err = ComponentInterface::from_webidl(UDL, "crate_name").unwrap_err();
884 assert_eq!(
885 err.to_string(),
886 "the method name \"new\" is reserved for the default constructor"
887 );
888 }
889
890 #[test]
891 fn test_duplicate_primary_constructors_not_allowed() {
892 const UDL: &str = r#"
893 namespace test{};
894 interface Testing {
895 constructor();
896 constructor(u32 v);
897 };
898 "#;
899 let err = ComponentInterface::from_webidl(UDL, "crate_name").unwrap_err();
900 assert_eq!(err.to_string(), "Duplicate interface member name: \"new\"");
901
902 const UDL2: &str = r#"
903 namespace test{};
904 interface Testing {
905 constructor();
906 [Name=new]
907 constructor(u32 v);
908 };
909 "#;
910 let err = ComponentInterface::from_webidl(UDL2, "crate_name").unwrap_err();
911 assert_eq!(err.to_string(), "Duplicate interface member name: \"new\"");
912 }
913
914 #[test]
915 fn test_trait_attribute() {
916 const UDL: &str = r#"
917 namespace test{};
918 interface NotATrait {
919 };
920 [Trait]
921 interface ATrait {
922 };
923 "#;
924 let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap();
925 let obj = ci.get_object_definition("NotATrait").unwrap();
926 assert_eq!(obj.imp.rust_name_for(&obj.name), "r#NotATrait");
927 let obj = ci.get_object_definition("ATrait").unwrap();
928 assert_eq!(obj.imp.rust_name_for(&obj.name), "dyn r#ATrait");
929 }
930
931 #[test]
932 fn test_trait_constructors_not_allowed() {
933 const UDL: &str = r#"
934 namespace test{};
935 [Trait]
936 interface Testing {
937 constructor();
938 };
939 "#;
940 let err = ComponentInterface::from_webidl(UDL, "crate_name").unwrap_err();
941 assert_eq!(
942 err.to_string(),
943 "Trait interfaces can not have constructors: \"new\""
944 );
945 }
946
947 #[test]
948 fn test_docstring_object() {
949 const UDL: &str = r#"
950 namespace test{};
951 /// informative docstring
952 interface Testing { };
953 "#;
954 let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap();
955 assert_eq!(
956 ci.get_object_definition("Testing")
957 .unwrap()
958 .docstring()
959 .unwrap(),
960 "informative docstring"
961 );
962 }
963
964 #[test]
965 fn test_docstring_constructor() {
966 const UDL: &str = r#"
967 namespace test{};
968 interface Testing {
969 /// informative docstring
970 constructor();
971 };
972 "#;
973 let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap();
974 assert_eq!(
975 ci.get_object_definition("Testing")
976 .unwrap()
977 .primary_constructor()
978 .unwrap()
979 .docstring()
980 .unwrap(),
981 "informative docstring"
982 );
983 }
984
985 #[test]
986 fn test_docstring_method() {
987 const UDL: &str = r#"
988 namespace test{};
989 interface Testing {
990 /// informative docstring
991 void testing();
992 };
993 "#;
994 let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap();
995 assert_eq!(
996 ci.get_object_definition("Testing")
997 .unwrap()
998 .get_method("testing")
999 .docstring()
1000 .unwrap(),
1001 "informative docstring"
1002 );
1003 }
1004 }