GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(derive): bind value enums directly · jdx/usage@f236c01

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • PLAN.md
  • argv/src
    • spec.rs
  • derive/src
    • codegen.rs
    • lib.rs
  • docs/rust
    • clap-compatibility.md
    • subcommands.md
  • usage-rs/tests
    • facade.rs
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎PLAN.md‎

Copy file name to clipboardExpand all lines: PLAN.md
+3Lines changed: 3 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -518,6 +518,9 @@ Groups are the opposite case: `Command::get_groups`, `ArgGroup::get_args` and
518518
a bare flag, and an explicit value. The derive infers zero-or-one value arity,
519519
usage-argv binds all three states, and emitted KDL/help use an optional
520520
placeholder without requiring a synthetic `default_missing`.
521+
- [x] **Direct `ValueEnum` binding.** The derive converts canonical words and
522+
aliases directly to variants, including case-insensitive declarations, so a
523+
clap migration does not need to add a redundant `FromStr` implementation.
521524

522525
**Help output**
523526

Collapse file

‎argv/src/spec.rs‎

Copy file name to clipboardExpand all lines: argv/src/spec.rs
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2383,6 +2383,8 @@ pub trait ValueEnum: Sized {
23832383
/// Presentation metadata for canonical values and aliases.
23842384
const DETAILS: &'static [ChoiceMeta<'static>] = &[];
23852385
const IGNORE_CASE: bool = false;
2386+
/// Convert one canonical word or alias into its enum variant.
2387+
fn from_choice(value: &str) -> Option<Self>;
23862388
}
23872389

23882390
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
Collapse file

‎derive/src/codegen.rs‎

Copy file name to clipboardExpand all lines: derive/src/codegen.rs
+42-3Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2987,6 +2987,27 @@ fn field_final(field: &Field) -> TokenStream {
29872987
}
29882988
}
29892989
};
2990+
if field.value_enum {
2991+
return quote! {{
2992+
let __usage_text = #text;
2993+
match <#ty as usage_argv::spec::ValueEnum>::from_choice(&__usage_text) {
2994+
::std::option::Option::Some(parsed) => parsed,
2995+
::std::option::Option::None => {
2996+
return ::std::result::Result::Err(
2997+
usage_argv::Error::InvalidValue(::std::boxed::Box::new(
2998+
usage_argv::InvalidValue {
2999+
name: #name,
3000+
value: __usage_text,
3001+
reason: ::std::string::String::from(
3002+
"not one of the declared values",
3003+
),
3004+
},
3005+
)),
3006+
);
3007+
}
3008+
}
3009+
}};
3010+
}
29903011
if is_std_string {
29913012
return text;
29923013
}
@@ -5632,9 +5653,9 @@ fn post_binding(cli: &Cli) -> TokenStream {
56325653

56335654
/// The word list for a value enum.
56345655
///
5635-
/// Conversion remains the type's own `FromStr` implementation, like every other typed
5636-
/// field. This derive owns only CLI metadata, so it can coexist with a domain parser whose
5637-
/// accepted syntax or error type is broader than the choices presented in help.
5656+
/// Conversion is generated from the same canonical words and aliases as the metadata, so
5657+
/// parsing, help, and completion cannot drift. A separate domain `FromStr` implementation
5658+
/// may still coexist; value-enum fields do not call it.
56385659
pub fn emit_value_enum(value_enum: &ValueEnum) -> TokenStream {
56395660
let ident = &value_enum.ident;
56405661
let runtime = runtime_path();
@@ -5684,6 +5705,19 @@ pub fn emit_value_enum(value_enum: &ValueEnum) -> TokenStream {
56845705
)
56855706
});
56865707
let ignore_case = value_enum.ignore_case;
5708+
let parse_arms = value_enum.variants.iter().map(|value| {
5709+
let ident = &value.ident;
5710+
let cfg = &value.cfg_attrs;
5711+
let names = ::std::iter::once(&value.name).chain(value.aliases.iter().map(|a| &a.name));
5712+
quote! {
5713+
#(#cfg)*
5714+
if [#(#names),*].iter().any(|candidate| {
5715+
*candidate == value || #ignore_case && candidate.eq_ignore_ascii_case(value)
5716+
}) {
5717+
return ::std::option::Option::Some(Self::#ident);
5718+
}
5719+
}
5720+
});
56875721

56885722
quote! {
56895723
#[doc(hidden)]
@@ -5696,6 +5730,11 @@ pub fn emit_value_enum(value_enum: &ValueEnum) -> TokenStream {
56965730
const ALIASES: &'static [(&'static str, &'static str)] = &[#(#aliases),*];
56975731
const DETAILS: &'static [usage_argv::spec::ChoiceMeta<'static>] = &[#(#details),*];
56985732
const IGNORE_CASE: bool = #ignore_case;
5733+
5734+
fn from_choice(value: &str) -> ::std::option::Option<Self> {
5735+
#(#parse_arms)*
5736+
::std::option::Option::None
5737+
}
56995738
}
57005739
};
57015740
}
Collapse file

‎derive/src/lib.rs‎

Copy file name to clipboardExpand all lines: derive/src/lib.rs
+3-3Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -416,9 +416,9 @@ pub fn derive_subcommands(input: TokenStream) -> TokenStream {
416416
/// it, `hide` keeps the value accepted while omitting it from help and completion,
417417
/// `alias` is hidden, and `visible_alias` is advertised alongside the canonical word.
418418
///
419-
/// The enum must implement [`FromStr`](std::str::FromStr); this derive owns only its CLI
420-
/// word metadata and does not replace domain parsing. Variant `cfg` and `cfg_attr`
421-
/// attributes are copied to their entries in the static word tables.
419+
/// The derive binds canonical words and aliases directly to their variants; a separate
420+
/// [`FromStr`](std::str::FromStr) implementation is not required. Variant `cfg` and
421+
/// `cfg_attr` attributes are copied to their entries in the static word tables.
422422
///
423423
/// A field holding one says `value_enum`, which is what puts the words in the spec — so
424424
/// help, completions and the check that rejects a wrong word all read the same list, and
Collapse file

‎docs/rust/clap-compatibility.md‎

Copy file name to clipboardExpand all lines: docs/rust/clap-compatibility.md
+1Lines changed: 1 addition & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ the Rust declaration, not only from generated KDL, wherever the bridge column sa
5858
| explicit `id` | yes | yes | yes | yes | yes | yes | `#[arg(id = "…")]` supplies the stable field identity used by relationships and generated specs. |
5959
| positional arguments | yes | yes | yes | yes | yes | yes | Required, optional, and variadic positionals are supported. |
6060
| `Option<T>`, `Vec<T>`, `Option<Vec<T>>`, `Option<Option<T>>` | yes | yes | yes | yes | yes | n/a | Nested `Option` preserves absent, bare, and explicitly valued flags; values use `FromStr`. |
61+
| derived `ValueEnum` | yes | yes | yes | yes | yes | n/a | Canonical values, aliases, case policy, help, and direct enum binding come from one derive; no separate `FromStr` is required. |
6162
| `ArgAction::Set`, `SetTrue`, `SetFalse`, `Append`, `Count` | yes | yes | yes | yes | yes | lossy | Common typed shapes are covered; arbitrary action/type combinations are not. |
6263
| `default_value` | yes | yes | yes | yes | yes | yes | Defaults apply after argv and environment values and clear token-required metadata. |
6364
| `default_missing_value` | yes | yes | yes | yes | yes | usage-only | `#[usage(default_missing = "…")]`; clap has no getter. |
Collapse file

‎docs/rust/subcommands.md‎

Copy file name to clipboardExpand all lines: docs/rust/subcommands.md
+3-2Lines changed: 3 additions & 2 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -175,8 +175,9 @@ hidden spelling, and `visible_alias` advertises the alternate spelling. Plural a
175175
accept lists. `#[usage(ignore_case)]` applies to the whole enum, and `cfg`-gated variants remain
176176
gated in every generated metadata table.
177177

178-
The type still implements its own `FromStr`: `ValueEnum` owns the portable CLI metadata and
179-
does not replace domain parsing.
178+
`ValueEnum` also binds those words directly to their variants, so the type needs no separate
179+
`FromStr`. An existing domain `FromStr` implementation may still coexist; value-enum fields
180+
use the derive's canonical values and aliases.
180181

181182
## Mounts and restart tokens
182183

Collapse file

‎usage-rs/tests/facade.rs‎

Copy file name to clipboardExpand all lines: usage-rs/tests/facade.rs
+3-18Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -317,24 +317,6 @@ enum Shell {
317317
PowerShell,
318318
}
319319

320-
impl std::str::FromStr for Shell {
321-
type Err = String;
322-
323-
fn from_str(value: &str) -> Result<Self, Self::Err> {
324-
#[cfg(windows)]
325-
if value.eq_ignore_ascii_case("power-shell") {
326-
return Ok(Self::PowerShell);
327-
}
328-
if value.eq_ignore_ascii_case("bash") {
329-
Ok(Self::Bash)
330-
} else if value.eq_ignore_ascii_case("zsh") || value.eq_ignore_ascii_case("shell-z") {
331-
Ok(Self::Zsh)
332-
} else {
333-
Err(format!("unsupported shell: {value}"))
334-
}
335-
}
336-
}
337-
338320
#[derive(Cli)]
339321
#[usage(bin = "choice-ex")]
340322
struct ChoiceEx {
@@ -696,6 +678,9 @@ fn emitted_specs_preserve_value_enum_aliases_and_case_policy() {
696678
let cli = ChoiceEx::parse_from(&[OsStr::new("--shell"), OsStr::new("SHELL-Z")])
697679
.expect("aliases and ASCII case folding should parse");
698680
assert!(matches!(cli.shell, Shell::Zsh));
681+
let cli = ChoiceEx::parse_from(&[OsStr::new("--shell"), OsStr::new("Z-SHELL")])
682+
.expect("every declared alias should bind without a separate FromStr");
683+
assert!(matches!(cli.shell, Shell::Zsh));
699684

700685
let kdl = ChoiceEx::to_kdl();
701686
assert!(kdl.contains("choices ignore_case=#true"), "{kdl}");

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.