Skip to main content

ef_vocabulary

Macro ef_vocabulary 

Source
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 V with 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_code returns None for an unassigned code rather than guessing at the nearest variant. code being const lets a consumer that cannot call it directly (a #[pyclass] discriminant, which PyO3 requires to be a literal) instead pin its own literal to it with const _: () = assert!(...).
  • V::as_str(self) -> &'static str / V::from_str_code(&str) -> Option<V>, the wire string form (not Debug, 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 = ...; }, one const per variant, for const-only consumers (cbindgen headers, match-free FFI code). This is the shape protocol::dtype / protocol::format / protocol::kind already use by hand. The mod clause accepts its own $(#[meta])* prefix (e.g. #[doc(hidden)]), the same as the enum clause does – m has to be pub for a different module (typically protocol) to pub use it 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.