xsd_parser/pipeline/optimizer/
empty_enums.rs

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