diff --git a/clap_derive/src/attrs.rs b/clap_derive/src/attrs.rs index 85b86154..61fd4ad6 100644 --- a/clap_derive/src/attrs.rs +++ b/clap_derive/src/attrs.rs @@ -340,27 +340,28 @@ impl Attrs { VerbatimDocComment(ident) => self.verbatim_doc_comment = Some(ident), DefaultValueT(ident, expr) => { + let ty = if let Some(ty) = self.ty.as_ref() { + ty + } else { + abort!( + ident, + "#[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") + }; + 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_t)] (without an argument) can be used \ - only on field level"; - - note = "see \ - https://docs.rs/structopt/0.3.5/structopt/#magical-methods") - }; quote!(<#ty as ::std::default::Default>::default()) }; let val = quote_spanned!(ident.span()=> { clap::lazy_static::lazy_static! { static ref DEFAULT_VALUE: &'static str = { - let val = #val; + let val: #ty = #val; let s = ::std::string::ToString::to_string(&val); ::std::boxed::Box::leak(s.into_boxed_str()) }; diff --git a/clap_derive/tests/ui/default_value_t_invalid.rs b/clap_derive/tests/ui/default_value_t_invalid.rs new file mode 100644 index 00000000..5f68be63 --- /dev/null +++ b/clap_derive/tests/ui/default_value_t_invalid.rs @@ -0,0 +1,21 @@ +// Copyright 2018 Guillaume Pinot (@TeXitoi) +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use clap::Clap; + +#[derive(Clap, Debug)] +#[clap(name = "basic")] +struct Opt { + #[clap(default_value_t = -10)] + value: u32, +} + +fn main() { + let opt = Opt::parse(); + println!("{:?}", opt); +} diff --git a/clap_derive/tests/ui/default_value_t_invalid.stderr b/clap_derive/tests/ui/default_value_t_invalid.stderr new file mode 100644 index 00000000..db54dc82 --- /dev/null +++ b/clap_derive/tests/ui/default_value_t_invalid.stderr @@ -0,0 +1,7 @@ +error[E0600]: cannot apply unary operator `-` to type `u32` + --> $DIR/default_value_t_invalid.rs:14:30 + | +14 | #[clap(default_value_t = -10)] + | ^^^ cannot apply unary operator `-` + | + = note: unsigned values cannot be negated