1use crate::prelude::*;
2
3#[derive(Clone, Debug, Serialize)]
8pub struct Enum {
9 def: Def,
10 name: &'static str,
11 variants: &'static [EnumVariant],
12 ty: Type,
13}
14
15impl Enum {
16 #[must_use]
17 pub const fn new(
18 def: Def,
19 name: &'static str,
20 variants: &'static [EnumVariant],
21 ty: Type,
22 ) -> Self {
23 Self {
24 def,
25 name,
26 variants,
27 ty,
28 }
29 }
30
31 #[must_use]
32 pub const fn def(&self) -> &Def {
33 &self.def
34 }
35
36 #[must_use]
38 pub const fn name(&self) -> &'static str {
39 self.name
40 }
41
42 #[must_use]
43 pub const fn variants(&self) -> &'static [EnumVariant] {
44 self.variants
45 }
46
47 #[must_use]
48 pub const fn ty(&self) -> &Type {
49 &self.ty
50 }
51}
52
53impl MacroNode for Enum {
54 fn as_any(&self) -> &dyn std::any::Any {
55 self
56 }
57}
58
59impl ValidateNode for Enum {
60 fn validate(&self) -> Result<(), ErrorTree> {
61 let mut errs = ErrorTree::new();
62 validate_source_name(
63 &mut errs,
64 "enum type",
65 self.name(),
66 icydb_schema::TypeSourceKey::try_new,
67 );
68 let mut seen = std::collections::BTreeSet::new();
69 for variant in self.variants() {
70 if !seen.insert(variant.name()) {
71 err!(errs, "duplicate enum variant name '{}'", variant.name(),);
72 }
73 }
74 errs.result()
75 }
76}
77
78impl VisitableNode for Enum {
79 fn route_key(&self) -> String {
80 self.def().path()
81 }
82
83 fn drive<V: Visitor>(&self, v: &mut V) {
84 self.def().accept(v);
85 for node in self.variants() {
86 node.accept(v);
87 }
88 self.ty().accept(v);
89 }
90}
91
92#[derive(Clone, Debug, Serialize)]
97pub struct EnumVariant {
98 name: &'static str,
99
100 #[serde(skip_serializing_if = "Option::is_none")]
101 value: Option<Value>,
102}
103
104impl EnumVariant {
105 #[must_use]
106 pub const fn new(name: &'static str, value: Option<Value>) -> Self {
107 Self { name, value }
108 }
109
110 #[must_use]
112 pub const fn name(&self) -> &'static str {
113 self.name
114 }
115
116 #[must_use]
117 pub const fn value(&self) -> Option<&Value> {
118 self.value.as_ref()
119 }
120}
121
122impl ValidateNode for EnumVariant {
123 fn validate(&self) -> Result<(), ErrorTree> {
124 let mut errs = ErrorTree::new();
125 validate_source_name(
126 &mut errs,
127 "enum variant",
128 self.name(),
129 icydb_schema::TypeSourceKey::try_new,
130 );
131 errs.result()
132 }
133}
134
135impl VisitableNode for EnumVariant {
136 fn drive<V: Visitor>(&self, v: &mut V) {
137 if let Some(node) = self.value() {
138 node.accept(v);
139 }
140 }
141}