macro_rules! ef_vocabulary {
(
$(#[$meta:meta])*
$vis:vis enum $name:ident {
$( $(#[$vmeta:meta])* $variant:ident = $code:expr, $text:literal, $const:ident ),+ $(,)?
}
$(#[$mmeta:meta])*
$modvis:vis mod $modname:ident;
) => { ... };
}Expand description
Declare a vocabulary once, emit every surface from it.
Discriminants are MANDATORY and explicit. A cfg-gated variant therefore
keeps its number reserved when absent, instead of shifting every variant
after it – which is how PyTensorMemory ended up platform-dependent.
Emits, for a vocabulary V with wire module m:
pub enum Vwith explicit#[repr(u32)]discriminants taken verbatim from the declaration.V::code(self) -> u32(const fn) /V::from_code(u32) -> Option<V>, the wire numbering.from_codereturnsNonefor an unassigned code rather than guessing at the nearest variant.codebeingconstlets a consumer that cannot call it directly (a#[pyclass]discriminant, which PyO3 requires to be a literal) instead pin its own literal to it withconst _: () = assert!(...).V::as_str(self) -> &'static str/V::from_str_code(&str) -> Option<V>, the wire string form (notDebug, which is free to change).V::all() -> &'static [V], every variant in declaration order, so cross-surface consistency tests can be exhaustive instead of a sample.pub mod m { pub const CONST_NAME: u32 = ...; }, oneconstper variant, forconst-only consumers (cbindgen headers, match-free FFI code). This is the shapeprotocol::dtype/protocol::format/protocol::kindalready use by hand. Themodclause accepts its own$(#[meta])*prefix (e.g.#[doc(hidden)]), the same as theenumclause does –mhas to bepubfor a different module (typicallyprotocol) topub useit back out under its real, documented name, so#[doc(hidden)]is how a caller marks it as emission plumbing rather than a second, undocumented public API surface for the same vocabulary.
The wire const’s identifier is a separate, explicit field per variant
rather than derived from the enum variant name. DType’s variants (U8,
I8, …) happen to already be valid SCREAMING_SNAKE_CASE, but
PixelFormat’s do not – PlanarRgb is the enum variant,
protocol::format::PLANAR_RGB is the existing wire constant, and no
mechanical transform of one produces the other without either an extra
dependency for identifier-pasting-with-case-conversion or a hidden
word-boundary guessing rule. Spelling both out keeps the same “explicit,
not inferred” rule this macro already applies to discriminants.