Remove incorrect detection of simple fmt cases

This was intended to detect the simple cases "{var}" and "{var:?}" and emit them
as straightforward Display::fmt and Debug::fmt method calls rather than a write
macro, but this was only to keep the generated code simple and is not important.
It was broken by the changes to how we parse the fmt attr in 1.0.7.

Fixes #53.
This commit is contained in:
David Tolnay 2019-12-03 19:29:56 -08:00
parent d53be52a3b
commit 20202db299
3 changed files with 17 additions and 18 deletions

View File

@ -20,7 +20,6 @@ pub struct Display<'a> {
pub original: &'a Attribute, pub original: &'a Attribute,
pub fmt: LitStr, pub fmt: LitStr,
pub args: TokenStream, pub args: TokenStream,
pub was_shorthand: bool,
pub has_bonus_display: bool, pub has_bonus_display: bool,
} }
@ -82,7 +81,6 @@ fn parse_error_attribute<'a>(attrs: &mut Attrs<'a>, attr: &'a Attribute) -> Resu
original: attr, original: attr,
fmt: input.parse()?, fmt: input.parse()?,
args: parse_token_expr(input, false)?, args: parse_token_expr(input, false)?,
was_shorthand: false,
has_bonus_display: false, has_bonus_display: false,
}; };
if attrs.display.is_some() { if attrs.display.is_some() {
@ -153,20 +151,8 @@ impl ToTokens for Display<'_> {
fn to_tokens(&self, tokens: &mut TokenStream) { fn to_tokens(&self, tokens: &mut TokenStream) {
let fmt = &self.fmt; let fmt = &self.fmt;
let args = &self.args; let args = &self.args;
if self.was_shorthand && fmt.value() == "{}" { tokens.extend(quote! {
let arg = args.clone().into_iter().nth(1).unwrap(); write!(__formatter, #fmt #args)
tokens.extend(quote! { });
std::fmt::Display::fmt(#arg, __formatter)
});
} else if self.was_shorthand && fmt.value() == "{:?}" {
let arg = args.clone().into_iter().nth(1).unwrap();
tokens.extend(quote! {
std::fmt::Debug::fmt(#arg, __formatter)
});
} else {
tokens.extend(quote! {
write!(__formatter, #fmt #args)
});
}
} }
} }

View File

@ -88,7 +88,6 @@ impl Display<'_> {
out += read; out += read;
self.fmt = LitStr::new(&out, self.fmt.span()); self.fmt = LitStr::new(&out, self.fmt.span());
self.args = args; self.args = args;
self.was_shorthand = true;
self.has_bonus_display = has_bonus_display; self.has_bonus_display = has_bonus_display;
} }
} }

View File

@ -165,3 +165,17 @@ fn test_trailing_comma() {
assert("error ?", Error('?')); assert("error ?", Error('?'));
} }
#[test]
fn test_field() {
#[derive(Debug)]
struct Inner {
data: usize,
}
#[derive(Error, Debug)]
#[error("{}", .0.data)]
struct Error(Inner);
assert("0", Error(Inner { data: 0 }));
}