Implement derive for unit struct errors

This commit is contained in:
David Tolnay 2019-10-09 06:41:42 -07:00
parent c30d847847
commit 1f02d8d9fd
No known key found for this signature in database
GPG key ID: F9BA143B95FF6D82
2 changed files with 43 additions and 3 deletions

View file

@ -1,7 +1,47 @@
use proc_macro2::TokenStream;
use syn::{DeriveInput, Result};
use quote::quote;
use syn::{Data, DataEnum, DataStruct, DeriveInput, Error, Result, FieldsNamed, FieldsUnnamed, Fields};
pub fn derive(input: DeriveInput) -> Result<TokenStream> {
pub fn derive(input: &DeriveInput) -> Result<TokenStream> {
match &input.data {
Data::Struct(data) => struct_error(input, data),
Data::Enum(data) => enum_error(input, data),
Data::Union(_) => Err(Error::new_spanned(
input,
"union as errors are not supported",
)),
}
}
fn struct_error(input: &DeriveInput, data: &DataStruct) -> Result<TokenStream> {
match &data.fields {
Fields::Named(fields) => braced_struct_error(input, fields),
Fields::Unnamed(fields) => tuple_struct_error(input, fields),
Fields::Unit => unit_struct_error(input),
}
}
fn braced_struct_error(input: &DeriveInput, fields: &FieldsNamed) -> Result<TokenStream> {
let _ = input;
let _ = fields;
unimplemented!()
}
fn tuple_struct_error(input: &DeriveInput, fields: &FieldsUnnamed) -> Result<TokenStream> {
let _ = input;
let _ = fields;
unimplemented!()
}
fn unit_struct_error(input: &DeriveInput) -> Result<TokenStream> {
let ident = &input.ident;
Ok(quote! {
impl std::error::Error for #ident {}
})
}
fn enum_error(input: &DeriveInput, data: &DataEnum) -> Result<TokenStream> {
let _ = input;
let _ = data;
unimplemented!()
}

View file

@ -8,7 +8,7 @@ use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(Error)]
pub fn derive_error(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
expand::derive(input)
expand::derive(&input)
.unwrap_or_else(|err| err.to_compile_error())
.into()
}