Skip to content

Commit

Permalink
fix(derive): Don't generate dead code
Browse files Browse the repository at this point in the history
When debugging clap-rs#2586, I noticed we were developing match cases for
variant names that were flattened.  At minimum, this is dead code and at
worst this could cause the wrong behavior if a user does an update with
one of those names.

Depends on clap-rs#2587

Fixes clap-rs#2588
  • Loading branch information
epage committed Jul 14, 2021
1 parent 61f34a1 commit fd033d7
Showing 1 changed file with 6 additions and 33 deletions.
39 changes: 6 additions & 33 deletions clap_derive/src/derives/subcommand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ fn gen_update_from_args(
) -> TokenStream {
use syn::Fields::*;

let (flatten_variants, variants): (Vec<_>, Vec<_>) = variants
let variants: Vec<_> = variants
.iter()
.filter_map(|variant| {
let attrs = Attrs::from_variant(
Expand All @@ -370,16 +370,13 @@ fn gen_update_from_args(
parent_attribute.env_casing(),
);

if let Kind::ExternalSubcommand = &*attrs.kind() {
None
} else {
Some((variant, attrs))
match &*attrs.kind() {
// Fallback to `from_arg_matches`
Kind::ExternalSubcommand | Kind::Flatten => None,
_ => Some((variant, attrs)),
}
})
.partition(|(_, attrs)| {
let kind = attrs.kind();
matches!(&*kind, Kind::Flatten)
});
.collect();

let subcommands = variants.iter().map(|(variant, attrs)| {
let sub_name = attrs.cased_name();
Expand Down Expand Up @@ -428,29 +425,6 @@ fn gen_update_from_args(
}
});

let child_subcommands = flatten_variants.iter().map(|(variant, attrs)| {
let sub_name = attrs.cased_name();
let variant_name = &variant.ident;
let (pattern, updater) = match variant.fields {
Unnamed(ref fields) if fields.unnamed.len() == 1 => {
let ty = &fields.unnamed[0];
(
quote!((ref mut arg)),
quote! {
<#ty as clap::FromArgMatches>::update_from_arg_matches(arg, sub_arg_matches);
},
)
}
_ => abort!(
variant,
"`flatten` is usable only with single-typed tuple variants"
),
};
quote! {
(#sub_name, #name :: #variant_name #pattern) => { #updater }
}
});

quote! {
fn update_from_arg_matches<'b>(
&mut self,
Expand All @@ -459,7 +433,6 @@ fn gen_update_from_args(
if let Some((name, sub_arg_matches)) = arg_matches.subcommand() {
match (name, self) {
#( #subcommands ),*
#( #child_subcommands ),*
(other_name, s) => {
if let Some(sub) = <Self as clap::FromArgMatches>::from_arg_matches(arg_matches) {
*s = sub;
Expand Down

0 comments on commit fd033d7

Please sign in to comment.