xsd_parser/optimizer/empty_enums.rs
1use crate::types::{Name, ReferenceInfo, TypeVariant};
2
3use super::Optimizer;
4
5impl Optimizer {
6 /// This will remove any enum variant that has an empty string as name.
7 ///
8 /// # Examples
9 ///
10 /// Consider the following XML schema:
11 /// ```xml
12 #[doc = include_str!("../../tests/optimizer/enum_empty_variant.xsd")]
13 /// ```
14 ///
15 /// Without this optimization this will result in the following code:
16 /// ```rust
17 #[doc = include_str!("../../tests/optimizer/expected0/remove_empty_enum_variants.rs")]
18 /// ```
19 ///
20 /// With this optimization the following code is generated:
21 /// ```rust
22 #[doc = include_str!("../../tests/optimizer/expected1/remove_empty_enum_variants.rs")]
23 /// ```
24 pub fn remove_empty_enum_variants(mut self) -> Self {
25 tracing::debug!("remove_empty_enum_variants");
26
27 for type_ in self.types.types.values_mut() {
28 if let TypeVariant::Enumeration(x) = &mut type_.variant {
29 x.variants
30 .retain(|x| !matches!(&x.ident.name, Name::Named(x) if x.is_empty()));
31 }
32 }
33
34 self
35 }
36
37 /// This will replace the enum with a type reference to the enums base type
38 /// if the enum does not have any variant.
39 ///
40 /// This optimization is usually used in combination with
41 /// [`remove_empty_enum_variants`](Self::remove_empty_enum_variants).
42 ///
43 /// # Examples
44 ///
45 /// Consider the following XML schema:
46 /// ```xml
47 #[doc = include_str!("../../tests/optimizer/enum_empty.xsd")]
48 /// ```
49 ///
50 /// Without this optimization this will result in the following code:
51 /// ```rust
52 #[doc = include_str!("../../tests/optimizer/expected0/remove_empty_enums.rs")]
53 /// ```
54 ///
55 /// With this optimization (and the [`remove_empty_enum_variants`](Self::remove_empty_enum_variants))
56 /// the following code is generated:
57 /// ```rust
58 #[doc = include_str!("../../tests/optimizer/expected1/remove_empty_enums.rs")]
59 /// ```
60 pub fn remove_empty_enums(mut self) -> Self {
61 tracing::debug!("remove_empty_enums");
62
63 for type_ in self.types.types.values_mut() {
64 if let TypeVariant::Enumeration(x) = &mut type_.variant {
65 if x.variants.is_empty() {
66 if let Some(base) = x.base.as_ident() {
67 self.typedefs = None;
68 type_.variant = TypeVariant::Reference(ReferenceInfo::new(base.clone()));
69 }
70 }
71 }
72 }
73
74 self
75 }
76}