Debian Codegraph @

third_party/rust/uniffi_bindgen/src/interface/enum_.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 //! # Enum definitions for a `ComponentInterface`.
6 //!
7 //! This module converts enum definition from UDL into structures that can be
8 //! added to a `ComponentInterface`. A declaration in the UDL like this:
9 //!
10 //! ```
11 //! # let ci = uniffi_bindgen::interface::ComponentInterface::from_webidl(r##"
12 //! # namespace example {};
13 //! enum Example {
14 //! "one",
15 //! "two"
16 //! };
17 //! # "##, "crate_name")?;
18 //! # Ok::<(), anyhow::Error>(())
19 //! ```
20 //!
21 //! Will result in a [`Enum`] member being added to the resulting [`crate::ComponentInterface`]:
22 //!
23 //! ```
24 //! # let ci = uniffi_bindgen::interface::ComponentInterface::from_webidl(r##"
25 //! # namespace example {};
26 //! # enum Example {
27 //! # "one",
28 //! # "two"
29 //! # };
30 //! # "##, "crate_name")?;
31 //! let e = ci.get_enum_definition("Example").unwrap();
32 //! assert_eq!(e.name(), "Example");
33 //! assert_eq!(e.variants().len(), 2);
34 //! assert_eq!(e.variants()[0].name(), "one");
35 //! assert_eq!(e.variants()[1].name(), "two");
36 //! # Ok::<(), anyhow::Error>(())
37 //! ```
38 //!
39 //! Like in Rust, UniFFI enums can contain associated data, but this needs to be
40 //! declared with a different syntax in order to work within the restrictions of
41 //! WebIDL. A declaration like this:
42 //!
43 //! ```
44 //! # let ci = uniffi_bindgen::interface::ComponentInterface::from_webidl(r##"
45 //! # namespace example {};
46 //! [Enum]
47 //! interface Example {
48 //! Zero();
49 //! One(u32 first);
50 //! Two(u32 first, string second);
51 //! };
52 //! # "##, "crate_name")?;
53 //! # Ok::<(), anyhow::Error>(())
54 //! ```
55 //!
56 //! Will result in an [`Enum`] member whose variants have associated fields:
57 //!
58 //! ```
59 //! # let ci = uniffi_bindgen::interface::ComponentInterface::from_webidl(r##"
60 //! # namespace example {};
61 //! # [Enum]
62 //! # interface ExampleWithData {
63 //! # Zero();
64 //! # One(u32 first);
65 //! # Two(u32 first, string second);
66 //! # };
67 //! # "##, "crate_name")?;
68 //! let e = ci.get_enum_definition("ExampleWithData").unwrap();
69 //! assert_eq!(e.name(), "ExampleWithData");
70 //! assert_eq!(e.variants().len(), 3);
71 //! assert_eq!(e.variants()[0].name(), "Zero");
72 //! assert_eq!(e.variants()[0].fields().len(), 0);
73 //! assert_eq!(e.variants()[1].name(), "One");
74 //! assert_eq!(e.variants()[1].fields().len(), 1);
75 //! assert_eq!(e.variants()[1].fields()[0].name(), "first");
76 //! # Ok::<(), anyhow::Error>(())
77 //! ```
78 //!
79 //! # Enums are also used to represent error definitions for a `ComponentInterface`.
80 //!
81 //! ```
82 //! # let ci = uniffi_bindgen::interface::ComponentInterface::from_webidl(r##"
83 //! # namespace example {};
84 //! [Error]
85 //! enum Example {
86 //! "one",
87 //! "two"
88 //! };
89 //! # "##, "crate_name")?;
90 //! # Ok::<(), anyhow::Error>(())
91 //! ```
92 //!
93 //! Will result in an [`Enum`] member with fieldless variants being added to the resulting [`crate::ComponentInterface`]:
94 //!
95 //! ```
96 //! # let ci = uniffi_bindgen::interface::ComponentInterface::from_webidl(r##"
97 //! # namespace example {
98 //! # [Throws=Example] void func();
99 //! # };
100 //! # [Error]
101 //! # enum Example {
102 //! # "one",
103 //! # "two"
104 //! # };
105 //! # "##, "crate_name")?;
106 //! let err = ci.get_enum_definition("Example").unwrap();
107 //! assert_eq!(err.name(), "Example");
108 //! assert_eq!(err.variants().len(), 2);
109 //! assert_eq!(err.variants()[0].name(), "one");
110 //! assert_eq!(err.variants()[1].name(), "two");
111 //! assert_eq!(err.is_flat(), true);
112 //! assert!(ci.is_name_used_as_error(&err.name()));
113 //! # Ok::<(), anyhow::Error>(())
114 //! ```
115 //!
116 //! A declaration in the UDL like this:
117 //!
118 //! ```
119 //! # let ci = uniffi_bindgen::interface::ComponentInterface::from_webidl(r##"
120 //! # namespace example {};
121 //! [Error]
122 //! interface Example {
123 //! one(i16 code);
124 //! two(string reason);
125 //! three(i32 x, i32 y);
126 //! };
127 //! # "##, "crate_name")?;
128 //! # Ok::<(), anyhow::Error>(())
129 //! ```
130 //!
131 //! Will result in an [`Enum`] member with variants that have fields being added to the resulting [`crate::ComponentInterface`]:
132 //!
133 //! ```
134 //! # let ci = uniffi_bindgen::interface::ComponentInterface::from_webidl(r##"
135 //! # namespace example {
136 //! # [Throws=Example] void func();
137 //! # };
138 //! # [Error]
139 //! # interface Example {
140 //! # one();
141 //! # two(string reason);
142 //! # three(i32 x, i32 y);
143 //! # };
144 //! # "##, "crate_name")?;
145 //! let err = ci.get_enum_definition("Example").unwrap();
146 //! assert_eq!(err.name(), "Example");
147 //! assert_eq!(err.variants().len(), 3);
148 //! assert_eq!(err.variants()[0].name(), "one");
149 //! assert_eq!(err.variants()[1].name(), "two");
150 //! assert_eq!(err.variants()[2].name(), "three");
151 //! assert_eq!(err.variants()[0].fields().len(), 0);
152 //! assert_eq!(err.variants()[1].fields().len(), 1);
153 //! assert_eq!(err.variants()[1].fields()[0].name(), "reason");
154 //! assert_eq!(err.variants()[2].fields().len(), 2);
155 //! assert_eq!(err.variants()[2].fields()[0].name(), "x");
156 //! assert_eq!(err.variants()[2].fields()[1].name(), "y");
157 //! assert_eq!(err.is_flat(), false);
158 //! assert!(ci.is_name_used_as_error(err.name()));
159 //! # Ok::<(), anyhow::Error>(())
160 //! ```
161
162 use anyhow::Result;
163 use uniffi_meta::{Checksum, EnumShape};
164
165 use super::record::Field;
166 use super::{AsType, Literal, Type, TypeIterator};
167
168 /// Represents an enum with named variants, each of which may have named
169 /// and typed fields.
170 ///
171 /// Enums are passed across the FFI by serializing to a bytebuffer, with a
172 /// i32 indicating the variant followed by the serialization of each field.
173 #[derive(Debug, Clone, PartialEq, Eq, Checksum)]
174 pub struct Enum {
175 pub(super) name: String,
176 pub(super) module_path: String,
177 pub(super) remote: bool,
178 pub(super) discr_type: Option<Type>,
179 pub(super) variants: Vec<Variant>,
180 pub(super) shape: EnumShape,
181 pub(super) non_exhaustive: bool,
182 #[checksum_ignore]
183 pub(super) docstring: Option<String>,
184 }
185
186 impl Enum {
187 pub fn name(&self) -> &str {
188 &self.name
189 }
190
191 pub fn rename(&mut self, name: String) {
192 self.name = name;
193 }
194
195 pub fn remote(&self) -> bool {
196 self.remote
197 }
198
199 pub fn variants(&self) -> &[Variant] {
200 &self.variants
201 }
202
203 // Get the literal value to use for the specified variant's discriminant.
204 // Follows Rust's rules when mixing specified and unspecified values; please
205 // file a bug if you find a case where it does not.
206 // However, it *does not* attempt to handle error cases - either cases where
207 // a discriminant is not unique, or where a discriminant would overflow the
208 // repr. The intention is that the Rust compiler itself will fail to build
209 // in those cases, so by the time this get's run we can be confident these
210 // error cases can't exist.
211 pub fn variant_discr(&self, variant_index: usize) -> Result<Literal> {
212 for (i, lit) in self.variant_discr_iter().enumerate() {
213 let lit = lit?;
214 if i == variant_index {
215 return Ok(lit);
216 }
217 }
218 anyhow::bail!("Invalid variant index {variant_index}");
219 }
220
221 // Iterate over variant discriminants
222 fn variant_discr_iter(&self) -> impl Iterator<Item = Result<Literal>> + '_ {
223 let mut next = 0;
224 self.variants().iter().map(move |v| {
225 let (this, this_lit) = match v.discr {
226 None => (
227 next,
228 if (next as i64) < 0 {
229 Literal::new_int(next as i64)
230 } else {
231 Literal::new_uint(next)
232 },
233 ),
234 Some(Literal::UInt(v, _, _)) => (v, Literal::new_uint(v)),
235 // in-practice, Literal::Int == a negative number.
236 Some(Literal::Int(v, _, _)) => (v as u64, Literal::new_int(v)),
237 _ => anyhow::bail!("Invalid literal type {v:?}"),
238 };
239 next = this.wrapping_add(1);
240 Ok(this_lit)
241 })
242 }
243
244 pub fn variant_discr_type(&self) -> &Option<Type> {
245 &self.discr_type
246 }
247
248 pub fn is_flat(&self) -> bool {
249 match self.shape {
250 EnumShape::Error { flat } => flat,
251 EnumShape::Enum => self.variants.iter().all(|v| v.fields.is_empty()),
252 }
253 }
254
255 pub fn is_non_exhaustive(&self) -> bool {
256 self.non_exhaustive
257 }
258
259 pub fn iter_types(&self) -> TypeIterator<'_> {
260 Box::new(self.variants.iter().flat_map(Variant::iter_types))
261 }
262
263 pub fn docstring(&self) -> Option<&str> {
264 self.docstring.as_deref()
265 }
266
267 pub fn contains_variant_fields(&self) -> bool {
268 self.variants().iter().any(|v| v.has_fields())
269 }
270 }
271
272 impl TryFrom<uniffi_meta::EnumMetadata> for Enum {
273 type Error = anyhow::Error;
274
275 fn try_from(meta: uniffi_meta::EnumMetadata) -> Result<Self> {
276 Ok(Self {
277 name: meta.name,
278 module_path: meta.module_path,
279 remote: meta.remote,
280 discr_type: meta.discr_type,
281 variants: meta
282 .variants
283 .into_iter()
284 .map(TryInto::try_into)
285 .collect::<Result<_>>()?,
286 shape: meta.shape,
287 non_exhaustive: meta.non_exhaustive,
288 docstring: meta.docstring.clone(),
289 })
290 }
291 }
292
293 impl AsType for Enum {
294 fn as_type(&self) -> Type {
295 Type::Enum {
296 name: self.name.clone(),
297 module_path: self.module_path.clone(),
298 }
299 }
300 }
301
302 /// Represents an individual variant in an Enum.
303 ///
304 /// Each variant has a name and zero or more fields.
305 #[derive(Debug, Clone, Default, PartialEq, Eq, Checksum)]
306 pub struct Variant {
307 pub(super) name: String,
308 pub(super) discr: Option<Literal>,
309 pub(super) fields: Vec<Field>,
310 #[checksum_ignore]
311 pub(super) docstring: Option<String>,
312 }
313
314 impl Variant {
315 pub fn name(&self) -> &str {
316 &self.name
317 }
318
319 pub fn rename(&mut self, new_name: String) {
320 self.name = new_name;
321 }
322
323 pub fn fields(&self) -> &[Field] {
324 &self.fields
325 }
326
327 pub fn has_fields(&self) -> bool {
328 !self.fields.is_empty()
329 }
330
331 pub fn has_nameless_fields(&self) -> bool {
332 self.fields.iter().any(|f| f.name.is_empty())
333 }
334
335 pub fn docstring(&self) -> Option<&str> {
336 self.docstring.as_deref()
337 }
338
339 pub fn iter_types(&self) -> TypeIterator<'_> {
340 Box::new(self.fields.iter().flat_map(Field::iter_types))
341 }
342 }
343
344 impl TryFrom<uniffi_meta::VariantMetadata> for Variant {
345 type Error = anyhow::Error;
346
347 fn try_from(meta: uniffi_meta::VariantMetadata) -> Result<Self> {
348 Ok(Self {
349 name: meta.name,
350 discr: meta.discr,
351 fields: meta
352 .fields
353 .into_iter()
354 .map(TryInto::try_into)
355 .collect::<Result<_>>()?,
356 docstring: meta.docstring.clone(),
357 })
358 }
359 }
360
361 #[cfg(test)]
362 mod test {
363 use super::super::{ComponentInterface, FfiType};
364 use super::*;
365
366 #[test]
367 fn test_duplicate_variants() {
368 const UDL: &str = r#"
369 namespace test{};
370 // Weird, but currently allowed!
371 // We should probably disallow this...
372 enum Testing { "one", "two", "one" };
373 "#;
374 let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap();
375 assert_eq!(ci.enum_definitions().count(), 1);
376 assert_eq!(
377 ci.get_enum_definition("Testing").unwrap().variants().len(),
378 3
379 );
380 }
381
382 #[test]
383 fn test_associated_data() {
384 const UDL: &str = r#"
385 namespace test {
386 void takes_an_enum(TestEnum e);
387 void takes_an_enum_with_data(TestEnumWithData ed);
388 TestEnum returns_an_enum();
389 TestEnumWithData returns_an_enum_with_data();
390 };
391
392 enum TestEnum { "one", "two" };
393
394 [Enum]
395 interface TestEnumWithData {
396 Zero();
397 One(u32 first);
398 Two(u32 first, string second);
399 };
400
401 [Enum]
402 interface TestEnumWithoutData {
403 One();
404 Two();
405 };
406 "#;
407 let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap();
408 assert_eq!(ci.enum_definitions().count(), 3);
409 assert_eq!(ci.function_definitions().len(), 4);
410
411 // The "flat" enum with no associated data.
412 let e = ci.get_enum_definition("TestEnum").unwrap();
413 assert!(e.is_flat());
414 assert_eq!(e.variants().len(), 2);
415 assert_eq!(
416 e.variants().iter().map(|v| v.name()).collect::<Vec<_>>(),
417 vec!["one", "two"]
418 );
419 assert_eq!(e.variants()[0].fields().len(), 0);
420 assert_eq!(e.variants()[1].fields().len(), 0);
421
422 // The enum with associated data.
423 let ed = ci.get_enum_definition("TestEnumWithData").unwrap();
424 assert!(!ed.is_flat());
425 assert_eq!(ed.shape, EnumShape::Enum);
426 assert_eq!(ed.variants().len(), 3);
427 assert_eq!(
428 ed.variants().iter().map(|v| v.name()).collect::<Vec<_>>(),
429 vec!["Zero", "One", "Two"]
430 );
431 assert_eq!(ed.variants()[0].fields().len(), 0);
432 assert_eq!(
433 ed.variants()[1]
434 .fields()
435 .iter()
436 .map(|f| f.name())
437 .collect::<Vec<_>>(),
438 vec!["first"]
439 );
440 assert_eq!(
441 ed.variants()[1]
442 .fields()
443 .iter()
444 .map(|f| f.as_type())
445 .collect::<Vec<_>>(),
446 vec![Type::UInt32]
447 );
448 assert_eq!(
449 ed.variants()[2]
450 .fields()
451 .iter()
452 .map(|f| f.name())
453 .collect::<Vec<_>>(),
454 vec!["first", "second"]
455 );
456 assert_eq!(
457 ed.variants()[2]
458 .fields()
459 .iter()
460 .map(|f| f.as_type())
461 .collect::<Vec<_>>(),
462 vec![Type::UInt32, Type::String]
463 );
464
465 // The enum declared via interface, but with no associated data.
466 let ewd = ci.get_enum_definition("TestEnumWithoutData").unwrap();
467 assert_eq!(ewd.variants().len(), 2);
468 assert_eq!(
469 ewd.variants().iter().map(|v| v.name()).collect::<Vec<_>>(),
470 vec!["One", "Two"]
471 );
472 assert_eq!(ewd.variants()[0].fields().len(), 0);
473 assert_eq!(ewd.variants()[1].fields().len(), 0);
474 assert!(ewd.is_flat());
475 assert_eq!(ewd.shape, EnumShape::Enum);
476
477 // Flat enums pass over the FFI as bytebuffers.
478 // (It might be nice to optimize these to pass as plain integers, but that's
479 // difficult atop the current factoring of `ComponentInterface` and friends).
480 let farg = ci.get_function_definition("takes_an_enum").unwrap();
481 assert_eq!(
482 farg.arguments()[0].as_type(),
483 Type::Enum {
484 name: "TestEnum".into(),
485 module_path: "crate_name".into()
486 }
487 );
488 assert!(matches!(
489 farg.ffi_func().arguments()[0].type_(),
490 FfiType::RustBuffer(_)
491 ));
492 let fret = ci.get_function_definition("returns_an_enum").unwrap();
493 assert!(
494 matches!(fret.return_type(), Some(Type::Enum { name, .. }) if name == "TestEnum" && !ci.is_name_used_as_error(name))
495 );
496 assert!(matches!(
497 fret.ffi_func().return_type(),
498 Some(FfiType::RustBuffer(_))
499 ));
500
501 // Enums with associated data pass over the FFI as bytebuffers.
502 let farg = ci
503 .get_function_definition("takes_an_enum_with_data")
504 .unwrap();
505 assert_eq!(
506 farg.arguments()[0].as_type(),
507 Type::Enum {
508 name: "TestEnumWithData".into(),
509 module_path: "crate_name".into()
510 }
511 );
512 assert!(matches!(
513 farg.ffi_func().arguments()[0].type_(),
514 FfiType::RustBuffer(_)
515 ));
516 let fret = ci
517 .get_function_definition("returns_an_enum_with_data")
518 .unwrap();
519 assert!(
520 matches!(fret.return_type(), Some(Type::Enum { name, .. }) if name == "TestEnumWithData" && !ci.is_name_used_as_error(name))
521 );
522 assert!(matches!(
523 fret.ffi_func().return_type(),
524 Some(FfiType::RustBuffer(_))
525 ));
526 }
527
528 // Tests for [Error], which are represented as `Enum`
529 #[test]
530 fn test_variants() {
531 const UDL: &str = r#"
532 namespace test{
533 [Throws=Testing]
534 void func();
535 };
536 [Error]
537 enum Testing { "one", "two", "three" };
538 "#;
539 let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap();
540 assert_eq!(ci.enum_definitions().count(), 1);
541 let error = ci.get_enum_definition("Testing").unwrap();
542 assert_eq!(
543 error
544 .variants()
545 .iter()
546 .map(|v| v.name())
547 .collect::<Vec<&str>>(),
548 vec!("one", "two", "three")
549 );
550 assert!(error.is_flat());
551 assert!(ci.is_name_used_as_error(&error.name));
552 }
553
554 #[test]
555 fn test_duplicate_error_variants() {
556 const UDL: &str = r#"
557 namespace test{};
558 // Weird, but currently allowed!
559 // We should probably disallow this...
560 [Error]
561 enum Testing { "one", "two", "one" };
562 "#;
563 let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap();
564 assert_eq!(ci.enum_definitions().count(), 1);
565 assert_eq!(
566 ci.get_enum_definition("Testing").unwrap().variants().len(),
567 3
568 );
569 }
570
571 #[test]
572 fn test_variant_data() {
573 const UDL: &str = r#"
574 namespace test{
575 [Throws=Testing]
576 void func();
577 };
578
579 [Error]
580 interface Testing {
581 One(string reason);
582 Two(u8 code);
583 };
584 "#;
585 let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap();
586 assert_eq!(ci.enum_definitions().count(), 1);
587 let error: &Enum = ci.get_enum_definition("Testing").unwrap();
588 assert_eq!(
589 error
590 .variants()
591 .iter()
592 .map(|v| v.name())
593 .collect::<Vec<&str>>(),
594 vec!("One", "Two")
595 );
596 assert!(!error.is_flat());
597 assert!(ci.is_name_used_as_error(&error.name));
598 }
599
600 #[test]
601 fn test_enum_variant_named_error() {
602 const UDL: &str = r#"
603 namespace test{};
604
605 [Enum]
606 interface Testing {
607 Normal(string first);
608 Error(string first);
609 };
610 "#;
611 let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap();
612 assert_eq!(ci.enum_definitions().count(), 1);
613 let testing: &Enum = ci.get_enum_definition("Testing").unwrap();
614 assert_eq!(
615 testing.variants()[0]
616 .fields()
617 .iter()
618 .map(|f| f.name())
619 .collect::<Vec<_>>(),
620 vec!["first"]
621 );
622 assert_eq!(
623 testing.variants()[0]
624 .fields()
625 .iter()
626 .map(|f| f.as_type())
627 .collect::<Vec<_>>(),
628 vec![Type::String]
629 );
630 assert_eq!(
631 testing.variants()[1]
632 .fields()
633 .iter()
634 .map(|f| f.name())
635 .collect::<Vec<_>>(),
636 vec!["first"]
637 );
638 assert_eq!(
639 testing.variants()[1]
640 .fields()
641 .iter()
642 .map(|f| f.as_type())
643 .collect::<Vec<_>>(),
644 vec![Type::String]
645 );
646 assert_eq!(
647 testing
648 .variants()
649 .iter()
650 .map(|v| v.name())
651 .collect::<Vec<_>>(),
652 vec!["Normal", "Error"]
653 );
654 }
655
656 fn variant(val: Option<u64>) -> Variant {
657 Variant {
658 name: "v".to_string(),
659 discr: val.map(Literal::new_uint),
660 fields: vec![],
661 docstring: None,
662 }
663 }
664
665 fn check_discrs(e: &mut Enum, vs: Vec<Variant>) -> Vec<u64> {
666 e.variants = vs;
667 (0..e.variants.len())
668 .map(|i| e.variant_discr(i).unwrap())
669 .map(|l| match l {
670 Literal::UInt(v, _, _) => v,
671 _ => unreachable!(),
672 })
673 .collect()
674 }
675
676 #[test]
677 fn test_variant_values() {
678 let mut e = Enum {
679 module_path: "test".to_string(),
680 name: "test".to_string(),
681 remote: false,
682 discr_type: None,
683 variants: vec![],
684 shape: EnumShape::Enum,
685 non_exhaustive: false,
686 docstring: None,
687 };
688
689 assert!(e.variant_discr(0).is_err());
690
691 // single values
692 assert_eq!(check_discrs(&mut e, vec![variant(None)]), vec![0]);
693 assert_eq!(check_discrs(&mut e, vec![variant(Some(3))]), vec![3]);
694
695 // no values
696 assert_eq!(
697 check_discrs(&mut e, vec![variant(None), variant(None)]),
698 vec![0, 1]
699 );
700
701 // values
702 assert_eq!(
703 check_discrs(&mut e, vec![variant(Some(1)), variant(Some(3))]),
704 vec![1, 3]
705 );
706
707 // mixed values
708 assert_eq!(
709 check_discrs(&mut e, vec![variant(None), variant(Some(3)), variant(None)]),
710 vec![0, 3, 4]
711 );
712
713 assert_eq!(
714 check_discrs(
715 &mut e,
716 vec![variant(Some(4)), variant(None), variant(Some(1))]
717 ),
718 vec![4, 5, 1]
719 );
720 }
721
722 #[test]
723 fn test_docstring_enum() {
724 const UDL: &str = r#"
725 namespace test{};
726 /// informative docstring
727 enum Testing { "foo" };
728 "#;
729 let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap();
730 assert_eq!(
731 ci.get_enum_definition("Testing")
732 .unwrap()
733 .docstring()
734 .unwrap(),
735 "informative docstring"
736 );
737 }
738
739 #[test]
740 fn test_docstring_enum_variant() {
741 const UDL: &str = r#"
742 namespace test{};
743 enum Testing {
744 /// informative docstring
745 "foo"
746 };
747 "#;
748 let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap();
749 assert_eq!(
750 ci.get_enum_definition("Testing").unwrap().variants()[0]
751 .docstring()
752 .unwrap(),
753 "informative docstring"
754 );
755 }
756
757 #[test]
758 fn test_docstring_associated_enum() {
759 const UDL: &str = r#"
760 namespace test{};
761 /// informative docstring
762 [Enum]
763 interface Testing { };
764 "#;
765 let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap();
766 assert_eq!(
767 ci.get_enum_definition("Testing")
768 .unwrap()
769 .docstring()
770 .unwrap(),
771 "informative docstring"
772 );
773 }
774
775 #[test]
776 fn test_docstring_associated_enum_variant() {
777 const UDL: &str = r#"
778 namespace test{};
779 [Enum]
780 interface Testing {
781 /// informative docstring
782 testing();
783 };
784 "#;
785 let ci = ComponentInterface::from_webidl(UDL, "crate_name").unwrap();
786 assert_eq!(
787 ci.get_enum_definition("Testing").unwrap().variants()[0]
788 .docstring()
789 .unwrap(),
790 "informative docstring"
791 );
792 }
793 }