Skip to content

Commit

Permalink
Merge pull request #353 from dtolnay/inferbound
Browse files Browse the repository at this point in the history
Only apply inferred bounds if interpolation refers to field
  • Loading branch information
dtolnay authored Nov 4, 2024
2 parents 6683511 + 5933179 commit b81fd86
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 19 deletions.
39 changes: 20 additions & 19 deletions impl/src/fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,20 @@ impl Display<'_> {
}
_ => continue,
};
let formatvar = match &member {
MemberUnraw::Unnamed(index) => IdentUnraw::new(format_ident!("_{}", index)),
MemberUnraw::Named(ident) => ident.clone(),
};
out += &formatvar.to_string();
if !named_args.insert(formatvar.clone()) {
// Already specified in the format argument list.
continue;
}
if !has_trailing_comma {
args.extend(quote_spanned!(span=> ,));
}
let local = formatvar.to_local();
args.extend(quote_spanned!(span=> #formatvar = #local));
if let Some(&field) = member_index.get(&member) {
let end_spec = match read.find('}') {
Some(end_spec) => end_spec,
Expand All @@ -83,28 +97,15 @@ impl Display<'_> {
Some('b') => Trait::Binary,
Some('e') => Trait::LowerExp,
Some('E') => Trait::UpperExp,
Some(_) | None => Trait::Display,
Some(_) => Trait::Display,
None => {
has_bonus_display = true;
args.extend(quote_spanned!(span=> .as_display()));
Trait::Display
}
};
implied_bounds.insert((field, bound));
}
let formatvar = match &member {
MemberUnraw::Unnamed(index) => IdentUnraw::new(format_ident!("_{}", index)),
MemberUnraw::Named(ident) => ident.clone(),
};
out += &formatvar.to_string();
if !named_args.insert(formatvar.clone()) {
// Already specified in the format argument list.
continue;
}
if !has_trailing_comma {
args.extend(quote_spanned!(span=> ,));
}
let local = formatvar.to_local();
args.extend(quote_spanned!(span=> #formatvar = #local));
if read.starts_with('}') && member_index.contains_key(&member) {
has_bonus_display = true;
args.extend(quote_spanned!(span=> .as_display()));
}
has_trailing_comma = false;
}

Expand Down
13 changes: 13 additions & 0 deletions tests/test_generics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,16 @@ pub struct StructFromGeneric<E> {
#[derive(Error, Debug)]
#[error(transparent)]
pub struct StructTransparentGeneric<E>(pub E);

// Regression test for https://github.com/dtolnay/thiserror/issues/345
#[test]
fn test_no_bound_on_named_fmt() {
#[derive(Error, Debug)]
#[error("{thing}", thing = "...")]
struct Error<T> {
thing: T,
}

let error = Error { thing: DebugOnly };
assert_eq!(error.to_string(), "...");
}

0 comments on commit b81fd86

Please sign in to comment.