engenho_substrate_core/closed_enum.rs
1//! `closed_enum!` — a fieldless enum, the list of its variants, and
2//! optionally their names, all written once.
3//!
4//! A catalog enum is only useful if something can walk every variant: the
5//! runtime spawns each child in its catalog, the scheduler runs each filter
6//! plugin in its list, a test ticks each one, a decoder maps each stored code
7//! back. A hand-written `ALL` array next to the enum is a second list, and the
8//! second list is where a new variant goes missing — the enum compiles, every
9//! exhaustive `match` gets its arm, and the variant is simply never walked.
10//!
11//! This macro generates the enum and `ALL` from the SAME token list, so `ALL`
12//! cannot miss a variant or hold one twice. Every per-variant fact stays an
13//! exhaustive `match` on the enum, which is a compile error (E0004) when a
14//! variant is added without its row.
15//!
16//! `ALL` is in declaration order, and a fieldless enum's discriminants are
17//! `0..N` in declaration order, so `ALL[v as usize] == v` for every variant.
18//! A decoder that maps a stored code back to a variant relies on that.
19//!
20//! ## Why it lives here
21//!
22//! This shape was derived three separate times — `engenho-controllers`, the
23//! scheduler's `filter_plugins!` (which added `name()`), and a test-local copy
24//! in `engenho-apiserver` — and `engenho-config` could reach none of them, so
25//! `KubeletBackendKind` has a hand-written list. Three independent arrivals at
26//! one shape is the signal to extract, and the extraction belongs in the crate
27//! every other crate may depend on: this one is tokio-free and has no engenho
28//! edges, so no crate is barred from the macro by its dependency set.
29
30/// Declare a fieldless enum together with `pub const ALL: &[Self]`, every
31/// variant in declaration order, generated from the enum's own variant list.
32///
33/// ```
34/// engenho_substrate_core::closed_enum! {
35/// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
36/// pub enum Colour { Red, Green }
37/// }
38/// assert_eq!(Colour::ALL, &[Colour::Red, Colour::Green]);
39/// ```
40///
41/// Lead the invocation with `#[named]` to also generate
42/// `pub const fn name(self) -> &'static str`, each variant's name taken from
43/// its own spelling, so the enum, its list and its identifiers are one list:
44///
45/// ```
46/// engenho_substrate_core::closed_enum! {
47/// #[named]
48/// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
49/// pub enum Plugin { NodeReady, TaintToleration }
50/// }
51/// assert_eq!(Plugin::NodeReady.name(), "NodeReady");
52/// ```
53///
54/// `#[named]` must come first. Written after a `derive`, it is consumed as an
55/// ordinary attribute and rustc rejects it (`cannot find attribute 'named'`),
56/// so a misplaced marker is a compile error rather than an enum that silently
57/// has no `name`.
58#[macro_export]
59macro_rules! closed_enum {
60 // Named: `ALL` and `name()`, both from the one variant list.
61 (
62 #[named]
63 $(#[$meta:meta])*
64 $vis:vis enum $name:ident {
65 $( $(#[$vmeta:meta])* $variant:ident ),+ $(,)?
66 }
67 ) => {
68 $crate::closed_enum! {
69 $(#[$meta])*
70 $vis enum $name {
71 $( $(#[$vmeta])* $variant ),+
72 }
73 }
74
75 impl $name {
76 /// This variant's stable identifier: its own spelling, for logs,
77 /// metric dimensions and census rows.
78 #[must_use]
79 pub const fn name(self) -> &'static str {
80 match self {
81 $( Self::$variant => stringify!($variant), )+
82 }
83 }
84 }
85 };
86
87 // Plain: `ALL` only.
88 (
89 $(#[$meta:meta])*
90 $vis:vis enum $name:ident {
91 $( $(#[$vmeta:meta])* $variant:ident ),+ $(,)?
92 }
93 ) => {
94 $(#[$meta])*
95 $vis enum $name {
96 $( $(#[$vmeta])* $variant ),+
97 }
98
99 impl $name {
100 /// Every variant, in declaration order. Generated from the enum's
101 /// own variant list, so it is complete by construction.
102 pub const ALL: &'static [Self] = &[ $( Self::$variant ),+ ];
103 }
104 };
105}
106
107#[cfg(test)]
108mod tests {
109 crate::closed_enum! {
110 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
111 enum Probe { A, B, C }
112 }
113
114 crate::closed_enum! {
115 #[named]
116 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
117 enum Plugin {
118 /// A per-variant doc comment rides through the named arm too.
119 NodeReady,
120 TaintToleration,
121 Resources,
122 }
123 }
124
125 #[test]
126 fn all_is_every_variant_in_declaration_order() {
127 assert_eq!(Probe::ALL, &[Probe::A, Probe::B, Probe::C]);
128 for (i, v) in Probe::ALL.iter().enumerate() {
129 assert_eq!(
130 *v as usize, i,
131 "ALL[{i}] is not the variant with discriminant {i}"
132 );
133 }
134 }
135
136 #[test]
137 fn the_named_arm_still_generates_all_in_declaration_order() {
138 assert_eq!(
139 Plugin::ALL,
140 &[
141 Plugin::NodeReady,
142 Plugin::TaintToleration,
143 Plugin::Resources
144 ]
145 );
146 for (i, v) in Plugin::ALL.iter().enumerate() {
147 assert_eq!(
148 *v as usize, i,
149 "ALL[{i}] is not the variant with discriminant {i}"
150 );
151 }
152 }
153
154 #[test]
155 fn name_is_the_variants_own_spelling() {
156 assert_eq!(Plugin::NodeReady.name(), "NodeReady");
157 assert_eq!(Plugin::TaintToleration.name(), "TaintToleration");
158 assert_eq!(Plugin::Resources.name(), "Resources");
159 }
160
161 /// The names come from the same list as the variants, so every variant
162 /// has one and no two share one. A hand-written `match` could return the
163 /// neighbour's string for a new variant and still compile; this asserts
164 /// the property, not the arm.
165 #[test]
166 fn every_variant_has_a_distinct_name() {
167 let mut names: Vec<&'static str> = Plugin::ALL.iter().map(|p| p.name()).collect();
168 assert_eq!(names.len(), Plugin::ALL.len());
169 names.sort_unstable();
170 let before = names.len();
171 names.dedup();
172 assert_eq!(names.len(), before, "two variants report the same name");
173 }
174}