Support Display impl for void enums

This commit is contained in:
David Tolnay 2019-10-12 13:50:46 -07:00
parent acaa504718
commit 5ea03dd7da
No known key found for this signature in database
GPG Key ID: F9BA143B95FF6D82
3 changed files with 15 additions and 4 deletions

View File

@ -110,6 +110,11 @@ fn impl_enum(input: Enum) -> TokenStream {
}; };
let display_impl = if input.has_display() { let display_impl = if input.has_display() {
let void_deref = if input.variants.is_empty() {
Some(quote!(*))
} else {
None
};
let arms = input.variants.iter().map(|variant| { let arms = input.variants.iter().map(|variant| {
let display = variant.attrs.display.as_ref().expect(valid::CHECKED); let display = variant.attrs.display.as_ref().expect(valid::CHECKED);
let ident = &variant.ident; let ident = &variant.ident;
@ -122,7 +127,7 @@ fn impl_enum(input: Enum) -> TokenStream {
impl #impl_generics std::fmt::Display for #ty #ty_generics #where_clause { impl #impl_generics std::fmt::Display for #ty #ty_generics #where_clause {
fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
#[allow(unused_variables)] #[allow(unused_variables)]
match self { match #void_deref self {
#(#arms,)* #(#arms,)*
} }
} }

View File

@ -25,9 +25,11 @@ impl Enum<'_> {
} }
pub(crate) fn has_display(&self) -> bool { pub(crate) fn has_display(&self) -> bool {
self.variants self.attrs.display.is_some()
.iter() || self
.any(|variant| variant.attrs.display.is_some()) .variants
.iter()
.any(|variant| variant.attrs.display.is_some())
} }
} }

View File

@ -47,6 +47,10 @@ struct Arithmetic;
#[error("!bool = {}", not(.0))] #[error("!bool = {}", not(.0))]
struct NestedShorthand(bool); struct NestedShorthand(bool);
#[derive(Error, Debug)]
#[error("...")]
enum Void {}
fn not(bool: &bool) -> bool { fn not(bool: &bool) -> bool {
!*bool !*bool
} }