From 41068e543530a23bf329ed905c821387a185a462 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Sat, 12 Oct 2019 13:28:04 -0700 Subject: [PATCH] Variants inherit fmt attr from the enum --- impl/src/ast.rs | 20 ++++++++++++++------ impl/src/attr.rs | 1 + tests/test_display.rs | 10 ++++++++++ 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/impl/src/ast.rs b/impl/src/ast.rs index f68820e..bc4e90a 100644 --- a/impl/src/ast.rs +++ b/impl/src/ast.rs @@ -63,15 +63,23 @@ impl<'a> Struct<'a> { impl<'a> Enum<'a> { fn from_syn(node: &'a DeriveInput, data: &'a DataEnum) -> Result { + let attrs = attr::get(&node.attrs)?; + let variants = data + .variants + .iter() + .map(|node| { + let mut variant = Variant::from_syn(node)?; + if let display @ None = &mut variant.attrs.display { + *display = attrs.display.clone(); + } + Ok(variant) + }) + .collect::>()?; Ok(Enum { - attrs: attr::get(&node.attrs)?, + attrs, ident: node.ident.clone(), generics: &node.generics, - variants: data - .variants - .iter() - .map(Variant::from_syn) - .collect::>()?, + variants, }) } } diff --git a/impl/src/attr.rs b/impl/src/attr.rs index e741c64..93e95dd 100644 --- a/impl/src/attr.rs +++ b/impl/src/attr.rs @@ -12,6 +12,7 @@ pub struct Attrs<'a> { pub source: Option>, } +#[derive(Clone)] pub struct Display { pub fmt: LitStr, pub args: TokenStream, diff --git a/tests/test_display.rs b/tests/test_display.rs index c7bb857..50a59e2 100644 --- a/tests/test_display.rs +++ b/tests/test_display.rs @@ -31,6 +31,14 @@ enum EnumError { Unit, } +#[derive(Error, Debug)] +#[error("{0}")] +enum Inherit { + Unit(UnitError), + #[error("other error")] + Other(UnitError), +} + #[derive(Error, Debug)] #[error("1 + 1 = {}", 1 + 1)] struct Arithmetic; @@ -57,6 +65,8 @@ fn test_display() { assert("braced error: 0", EnumError::Braced { id: 0 }); assert("tuple error: 0", EnumError::Tuple(0)); assert("unit error", EnumError::Unit); + assert("unit error", Inherit::Unit(UnitError)); + assert("other error", Inherit::Other(UnitError)); assert("1 + 1 = 2", Arithmetic); assert("!bool = false", NestedShorthand(true)); }