Merge pull request #24 from dtolnay/inherit

Variants inherit fmt attr from the enum
This commit is contained in:
David Tolnay 2019-10-12 13:42:04 -07:00 committed by GitHub
commit 7c9dcaebbc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 25 additions and 6 deletions

View file

@ -63,15 +63,23 @@ impl<'a> Struct<'a> {
impl<'a> Enum<'a> {
fn from_syn(node: &'a DeriveInput, data: &'a DataEnum) -> Result<Self> {
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::<Result<_>>()?;
Ok(Enum {
attrs: attr::get(&node.attrs)?,
attrs,
ident: node.ident.clone(),
generics: &node.generics,
variants: data
.variants
.iter()
.map(Variant::from_syn)
.collect::<Result<_>>()?,
variants,
})
}
}

View file

@ -12,6 +12,7 @@ pub struct Attrs<'a> {
pub source: Option<Source<'a>>,
}
#[derive(Clone)]
pub struct Display {
pub fmt: LitStr,
pub args: TokenStream,

View file

@ -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));
}