Skip to main content

Crate cognomen

Crate cognomen 

Source
Expand description

Compile-time string labels for enum variants.

A cognomen is an extra name. This crate gives each variant a second, stable label: a &'static str whose case you pick in the derive attribute. Conversion runs in the proc-macro. Calls are a match on a literal.

Downstream crates use this as the seam between a Rust ident and the string a config file, log line, CLI flag, or wire protocol actually carries.

Labels and extras are trait items in this crate, not inherent methods on E. Import Label, Reason, Blurb, … to call them, or use UFCS (<E as Label>::as_str(&e)). A user fn reason() or a parent trait of the same name still compiles.

§Quick start

use cognomen::{Case, Cognomen, FromLabel, Label, Variants};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Cognomen)]
#[cognomen(snake_case, kebab-case)]
enum Mode {
    SingleProcess,
    MultiProcess,
}

assert_eq!(Mode::SingleProcess.label(), "single_process");
assert_eq!(Mode::MultiProcess.as_str(), "multi_process");
assert_eq!(Mode::SingleProcess.in_case(Case::Kebab), "single-process");
assert_eq!(Mode::try_from("single-process"), Ok(Mode::SingleProcess));
assert_eq!("multi_process".parse::<Mode>(), Ok(Mode::MultiProcess));
assert!(Mode::SingleProcess == "single-process");
assert_eq!(Mode::VARIANTS.len(), 2);

The first case in #[cognomen(...)] is the default (label() / as_str() / serde out). Label::in_case converts from the ident in any Case. PartialEq<str> on E compares the label, not an extra.

§Case styles

AttributeAliasesVariantName becomes
snake_casesnakevariant_name
kebab-casekebab_case, kebabvariant-name
camelCasecamel_case, camelvariantName
PascalCasepascal_case, pascalVariantName
SCREAMING_SNAKE_CASEscreaming_snake_case, screamingVARIANT_NAME
lowerlowercasevariantname
upperuppercaseVARIANTNAME
titletitle_caseVariant Name

§Attributes

Container (required): #[cognomen(<case>, ...)]

  • One or more cases, comma-separated. First is the default. Listed cases are accepted by parse / serde-in; Label::in_case can still produce any Case.
  • prefix = "cfg": accepted for compatibility; case accessors live on Label, so the prefix no longer names methods.
  • crate = ::other::cognomen: path used in generated code when this crate is re-exported under another name.

Variant (optional):

  • #[cognomen(rename = "io_error")]: sets the default label to that exact string and accepts it when parsing. Label::in_case still converts from the ident.
  • #[cognomen(alias = "main")]: extra parse-in string. Does not change label(), as_str(), serde-out, PartialEq<str>, or in_case. Repeat the key for more than one alias. Empty "" is a compile error.
  • #[cognomen(unknown)]: unmatched parse and serde-in become this unit variant. Fieldless enums only; exactly one such variant. The unmatched string is not stored. clap value_parser still rejects unmatched input: unknown is a wire fallback, not a flag fallback. Do not default a catch-all; mark it explicitly.
use cognomen::{Case, Cognomen, FromLabel, Label};

#[derive(Debug, PartialEq, Cognomen)]
#[cognomen(snake_case, kebab-case)]
enum Wire {
    #[cognomen(rename = "io_error")]
    IoFailed,
    OpenFailed,
}

assert_eq!(Wire::IoFailed.label(), "io_error");
assert_eq!(Wire::IoFailed.in_case(Case::Snake), "io_failed");
assert_eq!(Wire::from_label("io_error").unwrap(), Wire::IoFailed);
assert_eq!(Wire::try_from("io-failed"), Ok(Wire::IoFailed));

An alias is parse-only. "" is not an alias; keep that mapping local.

use cognomen::{Cognomen, FromLabel, Label};

#[derive(Debug, PartialEq, Cognomen)]
#[cognomen(snake_case)]
enum ProcessRole {
    #[cognomen(alias = "main")]
    Supervisor,
    Worker,
}

assert_eq!(ProcessRole::Supervisor.label(), "supervisor");
assert_eq!(ProcessRole::from_label("main").unwrap(), ProcessRole::Supervisor);
assert_eq!(ProcessRole::from_label("supervisor").unwrap(), ProcessRole::Supervisor);
assert!(ProcessRole::from_label("").is_err());
assert!(ProcessRole::Supervisor != "main");

An unknown variant receives unmatched wire tags. from_label is no longer a bijection.

use cognomen::{Cognomen, FromLabel, Label};

#[derive(Debug, PartialEq, Cognomen)]
#[cognomen(snake_case)]
enum ChannelKind {
    Trades,
    L2Book,
    #[cognomen(unknown)]
    Other,
}

assert_eq!(ChannelKind::from_label("trades").unwrap(), ChannelKind::Trades);
assert_eq!(ChannelKind::from_label("nope").unwrap(), ChannelKind::Other);
assert_eq!(ChannelKind::Other.label(), "other");

Any other name = "..." is an extra.

Violations (non-enum, missing case, collisions, empty alias, more than one unknown, bad prefix, bad extra, unknown {field} placeholder) are compile errors. Variants named Error or Err are fine: generated TryFrom / FromStr name FromLabelError instead of Self::Error / Self::Err.

§Extras

Any name = "..." in #[cognomen(...)] besides prefix, crate, rename, and alias is an extra. Known keys (reason, blurb, hint, help) implement a trait in this crate (Reason, Blurb, Hint, Help). Other keys implement Extra with a private key type.

On a variant, that string is the variant’s value. On the enum, that string is the default for variants that omit the key. If the enum does not set a default, omitted variants use as_str() / label() (including rename). name() on the enum is the same as name = "".

Every extra returns Formatted. Static text is a single literal; {field} on a variant extra appends that named (or tuple-index) payload. Adding a placeholder does not change the signature. Enum-level defaults cannot contain placeholders. { / } in the text are written {{ / }}.

use cognomen::{Blurb, Cognomen, Label};

#[derive(Cognomen)]
#[cognomen(lower)]
enum SourceKind {
    #[cognomen(blurb = "microphone / input device")]
    Mic,
    #[cognomen(blurb = "system-wide loopback")]
    System,
    App,
}

assert_eq!(SourceKind::Mic.as_str(), "mic");
assert_eq!(SourceKind::Mic.blurb(), "microphone / input device");
assert_eq!(SourceKind::App.blurb(), "app");

An enum-level default overrides as_str() for omitted variants:

use cognomen::{Blurb, Cognomen, Hint};

#[derive(Cognomen)]
#[cognomen(lower, blurb = "", hint = "n/a")]
enum SourceKind {
    #[cognomen(blurb = "microphone / input device", hint = "CoreAudio input")]
    Mic,
    App,
}

assert_eq!(SourceKind::Mic.blurb(), "microphone / input device");
assert_eq!(SourceKind::App.blurb(), "");
assert_eq!(SourceKind::Mic.hint(), "CoreAudio input");
assert_eq!(SourceKind::App.hint(), "n/a");

Fielded variants keep Label. Parse, Variants, and serde-in are omitted: a label is not enough to build a payload. Interpolate extras from the fields:

use cognomen::{Cognomen, Label, Reason};

#[derive(Debug, Clone, PartialEq, Eq, Cognomen)]
#[cognomen(snake_case)]
enum HostError {
    #[cognomen(reason = "host backend unsupported {capability}")]
    Unsupported { capability: &'static str },
    #[cognomen(reason = "host open failed {cause}")]
    OpenFailed { cause: &'static str },
    #[cognomen(reason = "host refused request {why}")]
    BadRequest { why: &'static str },
    #[cognomen(reason = "host io failed {status}")]
    Io { status: &'static str },
}

let e = HostError::OpenFailed { cause: "busy" };
assert_eq!(e.as_str(), "open_failed");
assert_eq!(e.reason(), "host open failed busy");
assert_eq!(format!("{}", e.reason()), "host open failed busy");

A unit extra and a fielded extra with the same key share one trait and one return type:

use cognomen::{Cognomen, Formatted, Reason};

#[derive(Cognomen)]
#[cognomen(snake_case)]
enum Kind {
    #[cognomen(reason = "not implemented")]
    Unimplemented,
}

#[derive(Cognomen)]
#[cognomen(snake_case)]
enum HostError {
    #[cognomen(reason = "host open failed {cause}")]
    OpenFailed { cause: &'static str },
}

fn sentence(e: &impl Reason) -> Formatted<'_> {
    e.reason()
}

assert!(sentence(&HostError::OpenFailed { cause: "busy" }) == "host open failed busy");
assert!(sentence(&Kind::Unimplemented) == "not implemented");

Several extras can coexist. They are not accepted by FromLabel or serde. Names that collide with generated items (label, as_str, …) are compile errors.

§Generated API

For #[cognomen(snake_case, kebab-case)] on E:

  • Label: label() / as_str() (default case, or rename) and in_case(Case)
  • Reason / Blurb / Hint / Help / Extra: each extra returns Formatted. Omitted variants use as_str() unless the enum sets a default
  • Variants (non-generic, fieldless enums): E::VARIANTS and E::LABELS after use cognomen::Variants. Trait items, so they cannot clash with another derive or a user const VARIANTS
  • No Display / Error impl on E. Print the label with e.label(), or an extra with write!(f, "{}", e.reason())
  • AsRef<str>, PartialEq<str> / PartialEq<&str> (label, not extra or alias)
  • TryFrom<&str>, FromStr, FromLabel (fieldless enums): declared cases, rename, and alias; unmatched input errors unless a variant is marked unknown
  • Serialize / Deserialize (feature serde, fieldless): out is label(), in accepts any declared case, rename, or alias, and an unknown variant if marked
  • clap::ArgType::value_parser (feature clap): clap flag parser in the binary; the enum crate can stay no_std. Accepts declared cases, rename, and alias. Does not follow unknown

Nothing is inherent on E. A follow-up in numbered should move number() onto a trait the same way.

§Features

FeatureDefaultUnlocks
stdyesalloc + std::error::Error for FromLabelError
allocvia stdFromLabelError::input stores the unmatched string
serdenoSerialize / Deserialize
clapnoclap::ArgType (T::value_parser()); implies std

§no_std

cognomen = { version = "0.5", default-features = false }

Labels, extras (Formatted), parse, AsRef, and Variants use only core. Add features = ["alloc"] to keep the unmatched string on parse errors. Add features = ["serde"] for wire formats. Add features = ["clap"] in the binary that owns the clap surface, not in a no_std kernel.

§Word splitting

Idents are split on ASCII camel-case boundaries. Acronyms stay together (HTTPResponse -> http_response). Digits stay glued (Utf8 -> utf8, IPv4 -> i_pv4). Re-Pascal of an acronym title-cases the run (HTTPResponse -> HttpResponse).

§MSRV

Rust 1.71.1 for default features, alloc, and serde. The clap feature follows clap’s rustc floor (4.6 needs 1.85).

Modules§

clapclap
Clap value parser for cognomen enums.

Structs§

Formatted
Extra text: one or more literal pieces plus borrowed field args.
FromLabelError
Error returned when a string matches no declared label.

Enums§

BlurbKey
Key type for Blurb.
Case
Case style used by Label::in_case.
HelpKey
Key type for Help.
HintKey
Key type for Hint.
ReasonKey
Key type for Reason.

Traits§

Blurb
Extra blurb. Import to call e.blurb(). A user inherent fn blurb still compiles; use UFCS.
Extra
Tag-typed extra. Known keys (ReasonKey, …) also get a named trait (Reason) with a method of the same name.
FromLabel
Parse a declared-case label, rename, or alias into Self.
Help
Extra help. Import to call e.help(). A user inherent fn help still compiles; use UFCS.
Hint
Extra hint. Import to call e.hint(). A user inherent fn hint still compiles; use UFCS.
Label
Stable string label for a cognomen enum.
Reason
Extra reason. Import to call e.reason(). A user inherent fn reason still compiles; use UFCS.
Variants
Declaration-order tables for a non-generic cognomen enum.

Derive Macros§

Cognomen
Derive stable, case-configured string labels for an enum.