xsd_parser/optimizer/
empty_unions.rs1use std::collections::HashSet;
2
3use crate::types::{ReferenceInfo, TypeVariant};
4
5use super::{get_typedefs, Optimizer};
6
7impl Optimizer {
8 #[doc = include_str!("../../tests/optimizer/union_duplicate.xsd")]
18 #[doc = include_str!("../../tests/optimizer/expected0/remove_duplicate_union_variants.rs")]
23 #[doc = include_str!("../../tests/optimizer/expected1/remove_duplicate_union_variants.rs")]
28 pub fn remove_duplicate_union_variants(mut self) -> Self {
30 tracing::debug!("remove_duplicate_union_variants");
31
32 let typedefs = get_typedefs!(self);
33
34 for type_ in self.types.types.values_mut() {
35 if let TypeVariant::Union(x) = &mut type_.variant {
36 let mut i = 0;
37 let mut types_ = HashSet::new();
38
39 while i < x.types.len() {
40 let type_ = typedefs.resolve(&x.types[i].type_).clone();
41 if types_.insert(type_) {
42 i += 1;
43 } else {
44 x.types.remove(i);
45 }
46 }
47 }
48 }
49
50 self
51 }
52
53 #[doc = include_str!("../../tests/optimizer/union_empty.xsd")]
61 #[doc = include_str!("../../tests/optimizer/expected0/remove_empty_unions.rs")]
66 #[doc = include_str!("../../tests/optimizer/expected1/remove_empty_unions.rs")]
71 pub fn remove_empty_unions(mut self) -> Self {
73 tracing::debug!("remove_empty_unions");
74
75 for type_ in self.types.types.values_mut() {
76 if let TypeVariant::Union(x) = &type_.variant {
77 if x.types.len() <= 1 {
78 let base = x.types.first().map(|x| &x.type_).or(x.base.as_ident());
79 if let Some(base) = base {
80 self.typedefs = None;
81 type_.variant = TypeVariant::Reference(ReferenceInfo::new(base.clone()));
82 }
83 }
84 }
85 }
86
87 self
88 }
89}