Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bound generic for Error and Display impls #107

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 16 additions & 1 deletion impl/src/expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,9 +296,16 @@ fn impl_enum(input: Enum) -> TokenStream {
#ty::#ident #pat => #display
}
});
let display_impl_generics = {
let type_params = input.generics.type_params();

quote! {
<#(#type_params: std::fmt::Display),*>
}
};
Some(quote! {
#[allow(unused_qualifications)]
impl #impl_generics std::fmt::Display for #ty #ty_generics #where_clause {
impl #display_impl_generics std::fmt::Display for #ty #ty_generics #where_clause {
fn fmt(&self, __formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
#use_as_display
#[allow(unused_variables, deprecated, clippy::used_underscore_binding)]
Expand Down Expand Up @@ -331,6 +338,14 @@ fn impl_enum(input: Enum) -> TokenStream {

let error_trait = spanned_error_trait(input.original);

let impl_generics = {
let type_params = input.generics.type_params();

quote! {
<#(#type_params: std::fmt::Debug + std::fmt::Display),*>
}
};

quote! {
#[allow(unused_qualifications)]
impl #impl_generics #error_trait for #ty #ty_generics #where_clause {
Expand Down
14 changes: 14 additions & 0 deletions tests/test_display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,20 @@ fn test_field() {
assert("0", Error(Inner { data: 0 }));
}

#[test]
fn test_generic() {
#[derive(Error, Debug)]
enum Error<T> {
#[error("variant")]
Variant,
#[error("{0}")]
Generic(T),
}

assert("variant", Error::<&str>::Variant);
assert("err", Error::Generic("err"));
}

#[test]
fn test_macro_rules() {
// Regression test for https://github.com/dtolnay/thiserror/issues/86
Expand Down
12 changes: 12 additions & 0 deletions tests/test_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,18 @@ enum EnumError {
Unit,
}

#[derive(Error, Debug)]
enum WithGeneric<T> {
Variant,
Generic(T),
}

impl<T: Display> Display for WithGeneric<T> {
fn fmt(&self, _formatter: &mut fmt::Formatter) -> fmt::Result {
unimplemented!()
}
}

unimplemented_display!(BracedError);
unimplemented_display!(TupleError);
unimplemented_display!(UnitError);
Expand Down