mirror of
https://github.com/dtolnay/thiserror.git
synced 2025-04-06 22:37:38 +03:00
Merge pull request #24 from dtolnay/inherit
Variants inherit fmt attr from the enum
This commit is contained in:
commit
7c9dcaebbc
3 changed files with 25 additions and 6 deletions
|
@ -63,15 +63,23 @@ impl<'a> Struct<'a> {
|
||||||
|
|
||||||
impl<'a> Enum<'a> {
|
impl<'a> Enum<'a> {
|
||||||
fn from_syn(node: &'a DeriveInput, data: &'a DataEnum) -> Result<Self> {
|
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 {
|
Ok(Enum {
|
||||||
attrs: attr::get(&node.attrs)?,
|
attrs,
|
||||||
ident: node.ident.clone(),
|
ident: node.ident.clone(),
|
||||||
generics: &node.generics,
|
generics: &node.generics,
|
||||||
variants: data
|
variants,
|
||||||
.variants
|
|
||||||
.iter()
|
|
||||||
.map(Variant::from_syn)
|
|
||||||
.collect::<Result<_>>()?,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -12,6 +12,7 @@ pub struct Attrs<'a> {
|
||||||
pub source: Option<Source<'a>>,
|
pub source: Option<Source<'a>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
pub struct Display {
|
pub struct Display {
|
||||||
pub fmt: LitStr,
|
pub fmt: LitStr,
|
||||||
pub args: TokenStream,
|
pub args: TokenStream,
|
||||||
|
|
|
@ -31,6 +31,14 @@ enum EnumError {
|
||||||
Unit,
|
Unit,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Error, Debug)]
|
||||||
|
#[error("{0}")]
|
||||||
|
enum Inherit {
|
||||||
|
Unit(UnitError),
|
||||||
|
#[error("other error")]
|
||||||
|
Other(UnitError),
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Error, Debug)]
|
#[derive(Error, Debug)]
|
||||||
#[error("1 + 1 = {}", 1 + 1)]
|
#[error("1 + 1 = {}", 1 + 1)]
|
||||||
struct Arithmetic;
|
struct Arithmetic;
|
||||||
|
@ -57,6 +65,8 @@ fn test_display() {
|
||||||
assert("braced error: 0", EnumError::Braced { id: 0 });
|
assert("braced error: 0", EnumError::Braced { id: 0 });
|
||||||
assert("tuple error: 0", EnumError::Tuple(0));
|
assert("tuple error: 0", EnumError::Tuple(0));
|
||||||
assert("unit error", EnumError::Unit);
|
assert("unit error", EnumError::Unit);
|
||||||
|
assert("unit error", Inherit::Unit(UnitError));
|
||||||
|
assert("other error", Inherit::Other(UnitError));
|
||||||
assert("1 + 1 = 2", Arithmetic);
|
assert("1 + 1 = 2", Arithmetic);
|
||||||
assert("!bool = false", NestedShorthand(true));
|
assert("!bool = false", NestedShorthand(true));
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue