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
| Attribute | 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_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_casecan still produce anyCase. prefix = "cfg": accepted for compatibility; case accessors live onLabel, 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_casestill converts from the ident.#[cognomen(alias = "main")]: extra parse-in string. Does not changelabel(),as_str(), serde-out,PartialEq<str>, orin_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. clapvalue_parserstill 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, orrename) andin_case(Case)Reason/Blurb/Hint/Help/Extra: each extra returnsFormatted. Omitted variants useas_str()unless the enum sets a defaultVariants(non-generic, fieldless enums):E::VARIANTSandE::LABELSafteruse cognomen::Variants. Trait items, so they cannot clash with another derive or a userconst VARIANTS- No
Display/Errorimpl onE. Print the label withe.label(), or an extra withwrite!(f, "{}", e.reason()) AsRef<str>,PartialEq<str>/PartialEq<&str>(label, not extra or alias)TryFrom<&str>,FromStr,FromLabel(fieldless enums): declared cases,rename, andalias; unmatched input errors unless a variant is markedunknownSerialize/Deserialize(featureserde, fieldless): out islabel(), in accepts any declared case,rename, oralias, and anunknownvariant if markedclap::ArgType::value_parser(featureclap): clap flag parser in the binary; the enum crate can stayno_std. Accepts declared cases,rename, andalias. Does not followunknown
Nothing is inherent on E. A follow-up in numbered should move
number() 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 | clap::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§
- clap
clap - Clap value parser for cognomen enums.
Structs§
- Formatted
- Extra text: one or more literal pieces plus borrowed field args.
- From
Label Error - Error returned when a string matches no declared label.
Enums§
- Blurb
Key - Key type for
Blurb. - Case
- Case style used by
Label::in_case. - HelpKey
- Key type for
Help. - HintKey
- Key type for
Hint. - Reason
Key - Key type for
Reason.
Traits§
- Blurb
- Extra
blurb. Import to calle.blurb(). A user inherentfn blurbstill compiles; use UFCS. - Extra
- Tag-typed extra. Known keys (
ReasonKey, …) also get a named trait (Reason) with a method of the same name. - From
Label - Parse a declared-case label,
rename, oraliasintoSelf. - Help
- Extra
help. Import to calle.help(). A user inherentfn helpstill compiles; use UFCS. - Hint
- Extra
hint. Import to calle.hint(). A user inherentfn hintstill compiles; use UFCS. - Label
- Stable string label for a cognomen enum.
- Reason
- Extra
reason. Import to calle.reason(). A user inherentfn reasonstill 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.