cognomen 0.5.1

Derive stable, case-configured string labels for enum variants.
Documentation

cognomen

crates.io docs.rs license

Cognomen is Latin for "an extra name given to a person or thing". This crate gives every enum variant a second, stable string label.

Downstream crates use it as the seam between a Rust ident and the string a config file, log line, CLI flag, or wire protocol actually carries. Case conversion runs at compile time and is emitted as a &'static str.

Labels and extras are trait items (Label, Reason, Blurb, ...), not inherent methods on E. Import the trait to call e.reason(), or use UFCS when a user fn or parent trait owns the same name.

Full API reference: https://docs.rs/cognomen

[dependencies]
cognomen = "0.5"
use cognomen::{Case, Cognomen, Label, Variants};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Cognomen)]
#[cognomen(snake_case, kebab-case)]
enum Mode {
    SingleProcess, // "single_process" / "single-process"
    MultiProcess,  // "multi_process"  / "multi-process"
}

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!(Mode::SingleProcess == "single-process");
assert_eq!(Mode::VARIANTS.len(), 2);

The first case in #[cognomen(...)] is the default (label() / as_str() / serde out). PartialEq<str> on E compares the label, not an extra.

Case styles

#[cognomen(...)] short aliases VariantName becomes
snake_case snake variant_name
kebab-case / kebab_case kebab variant-name
camelCase / camel_case camel variantName
PascalCase / pascal_case pascal VariantName
SCREAMING_SNAKE_CASE screaming VARIANT_NAME
lower / lowercase variantname
upper / uppercase VARIANTNAME
title / title_case Variant 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.
  • crate = ::other::cognomen: generated path when you re-export this crate.

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(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);

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!(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, pinned by trybuild tests under tests/ui/.

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. Import it to call e.reason().

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. Write { / } as {{ / }}.

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. Interpolate extras from the fields:

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

#[derive(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 },
}

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

A unit extra and a fielded extra with the same key share one trait and one return type. A user inherent fn reason still compiles:

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

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

impl Kind {
    fn reason(&self) -> u8 {
        0
    }
}

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

assert!(sentence(&Kind::Unimplemented) == "not implemented");
assert_eq!(<Kind as Reason>::reason(&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. Nothing is inherent on E.

item notes
Label label() / as_str() (default or rename); in_case(Case)
Reason / Blurb / Hint / Help / Extra extras; always Formatted
Variants E::VARIANTS / E::LABELS after use cognomen::Variants (non-generic, fieldless)
AsRef<str>, PartialEq<str> compare against any declared label, not an alias
TryFrom<&str>, FromStr, FromLabel fieldless; cases, rename, alias; unknown if marked
Serialize / Deserialize feature serde, fieldless; out is label(), in accepts cases, rename, alias, and unknown
T::value_parser() feature clap; declared cases, rename, alias; does not follow unknown

numbered still has inherent number(); a follow-up should move that onto a trait the same way.

Features

feature default unlocks
std yes alloc + std::error::Error for FromLabelError
alloc via std FromLabelError.input stores the unmatched string
serde no Serialize / Deserialize
clap no T::value_parser() for clap flags; implies std

no_std, including embedded:

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. Enable clap in the binary that owns the CLI, not in a no_std kernel:

use clap::Parser;
use cognomen::clap::ArgType;

#[derive(Parser)]
struct Cli {
    #[arg(long, value_parser = Kind::value_parser())]
    kind: Kind,
}

Word splitting

Idents 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. Floor is the pinned proc-macro2 (rustc 1.71+). Cognomen itself only needs Option::is_some_and (1.70).

The clap feature is not part of that floor. It needs a rustc that can compile the resolved clap crate (clap 4.6 needs 1.85). CI checks clap on stable with --all-features.

Publishing

cognomen depends on cognomen-macros by version. The first crates.io upload must publish cognomen-macros first, then cognomen. New crate names cannot use trusted publishing; that first upload is manual. Later releases are prepared and published by release-plz on main.

License

Dual-licensed under MIT OR Apache-2.0, see LICENSE-MIT and LICENSE-APACHE. Copyright (c) 2026 Matheus Cardoso.