Skip to content

Commit

Permalink
feat(derive): Specify defaults by native expressions
Browse files Browse the repository at this point in the history
Right now
- `default_value="something"` is a raw method
- `default_value` uses native types

This commit splits the meanings
- `default_value="something"` is a raw method
- `default_value_t` uses `T::default()`
- `default_value_t=expr` uses an expression that evaluates to `T`

This is meant to mirror the `value_of` / `value_of_t` API.

At the moment, this is limited to `T: Display` to work with clap's
default system.  Something we can look at in the future is a way to
loosen that restriction.  One quick win is to specialize when `arg_enum`
is set.  The main downside is complicating the processing of attributes
because it then means we need some processed before others.

Since this builds on `clap`s existing default system, this also means
users do not get any performance gains out of using `default_value_t`,
since we still need to parse it but we also need to convert it to a
string.

Fixes clap-rs#1694
  • Loading branch information
epage committed Jul 28, 2021
1 parent 35db529 commit 7dda564
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 27 deletions.
37 changes: 22 additions & 15 deletions clap_derive/src/attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -340,34 +340,41 @@ impl Attrs {
VerbatimDocComment(ident) => self.verbatim_doc_comment = Some(ident),

DefaultValue(ident, lit) => {
let val = if let Some(lit) = lit {
quote!(#lit)
let val = quote!(#lit);
self.methods.push(Method::new(ident, val));
}

DefaultValueT(ident, expr) => {
let val = if let Some(expr) = expr {
quote!(#expr)
} else {
let ty = if let Some(ty) = self.ty.as_ref() {
ty
} else {
abort!(
ident,
"#[clap(default_value)] (without an argument) can be used \
"#[clap(default_value_t)] (without an argument) can be used \
only on field level";

note = "see \
https://docs.rs/structopt/0.3.5/structopt/#magical-methods")
};

quote_spanned!(ident.span()=> {
clap::lazy_static::lazy_static! {
static ref DEFAULT_VALUE: &'static str = {
let val = <#ty as ::std::default::Default>::default();
let s = ::std::string::ToString::to_string(&val);
::std::boxed::Box::leak(s.into_boxed_str())
};
}
*DEFAULT_VALUE
})
quote!(<#ty as ::std::default::Default>::default())
};

self.methods.push(Method::new(ident, val));
let val = quote_spanned!(ident.span()=> {
clap::lazy_static::lazy_static! {
static ref DEFAULT_VALUE: &'static str = {
let val = #val;
let s = ::std::string::ToString::to_string(&val);
::std::boxed::Box::leak(s.into_boxed_str())
};
}
*DEFAULT_VALUE
});

let raw_ident = Ident::new("default_value", ident.span());
self.methods.push(Method::new(raw_ident, val));
}

About(ident, about) => {
Expand Down
19 changes: 9 additions & 10 deletions clap_derive/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub enum ClapAttr {
About(Ident, Option<LitStr>),
Author(Ident, Option<LitStr>),
Version(Ident, Option<LitStr>),
DefaultValue(Ident, Option<LitStr>),
DefaultValue(Ident, LitStr),

// ident = "string literal"
RenameAllEnv(Ident, LitStr),
Expand All @@ -41,6 +41,7 @@ pub enum ClapAttr {

// ident = arbitrary_expr
NameExpr(Ident, Expr),
DefaultValueT(Ident, Option<Expr>),

// ident(arbitrary_expr,*)
MethodCall(Ident, Vec<Expr>),
Expand Down Expand Up @@ -75,7 +76,7 @@ impl Parse for ClapAttr {
match &*name_str {
"rename_all" => Ok(RenameAll(name, lit)),
"rename_all_env" => Ok(RenameAllEnv(name, lit)),
"default_value" => Ok(DefaultValue(name, Some(lit))),
"default_value" => Ok(DefaultValue(name, lit)),

"version" => {
check_empty_lit("version");
Expand Down Expand Up @@ -105,13 +106,11 @@ impl Parse for ClapAttr {
}
} else {
match input.parse::<Expr>() {
Ok(expr) => {
if name_str == "skip" {
Ok(Skip(name, Some(expr)))
} else {
Ok(NameExpr(name, expr))
}
}
Ok(expr) => match &*name_str {
"skip" => Ok(Skip(name, Some(expr))),
"default_value_t" => Ok(DefaultValueT(name, Some(expr))),
_ => Ok(NameExpr(name, expr)),
},

Err(_) => abort! {
assign_token,
Expand Down Expand Up @@ -176,7 +175,7 @@ impl Parse for ClapAttr {
"external_subcommand" => Ok(ExternalSubcommand(name)),
"verbatim_doc_comment" => Ok(VerbatimDocComment(name)),

"default_value" => Ok(DefaultValue(name, None)),
"default_value_t" => Ok(DefaultValueT(name, None)),
"about" => (Ok(About(name, None))),
"author" => (Ok(Author(name, None))),
"version" => Ok(Version(name, None)),
Expand Down
32 changes: 30 additions & 2 deletions clap_derive/tests/default_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ mod utils;
use utils::*;

#[test]
fn auto_default_value() {
fn default_value() {
#[derive(Clap, PartialEq, Debug)]
struct Opt {
#[clap(default_value)]
#[clap(default_value = "0")]
arg: i32,
}
assert_eq!(Opt { arg: 0 }, Opt::parse_from(&["test"]));
Expand All @@ -17,3 +17,31 @@ fn auto_default_value() {
let help = get_long_help::<Opt>();
assert!(help.contains("[default: 0]"));
}

#[test]
fn auto_default_value_t() {
#[derive(Clap, PartialEq, Debug)]
struct Opt {
#[clap(default_value_t)]
arg: i32,
}
assert_eq!(Opt { arg: 0 }, Opt::parse_from(&["test"]));
assert_eq!(Opt { arg: 1 }, Opt::parse_from(&["test", "1"]));

let help = get_long_help::<Opt>();
assert!(help.contains("[default: 0]"));
}

#[test]
fn simple_default_value_t() {
#[derive(Clap, PartialEq, Debug)]
struct Opt {
#[clap(default_value_t = 3)]
arg: i32,
}
assert_eq!(Opt { arg: 3 }, Opt::parse_from(&["test"]));
assert_eq!(Opt { arg: 1 }, Opt::parse_from(&["test", "1"]));

let help = get_long_help::<Opt>();
assert!(help.contains("[default: 3]"));
}

0 comments on commit 7dda564

Please sign in to comment.