evitable_syn_meta_ext/
from_derive_input.rs

1use super::error::{Error, Result};
2use proc_macro2::TokenStream;
3use syn::{
4  Attribute, Data, DataEnum, DataStruct, DataUnion, DeriveInput, Generics, Ident, Visibility,
5};
6
7/// Creates an instance by parsing an entire proc-macro `derive` input,
8/// including the, identity, generics, and visibility of the type.
9///
10/// This trait should either be derived or manually implemented by a type
11/// in the proc macro crate which is directly using `darling`. It is unlikely
12/// that these implementations will be reusable across crates.
13pub trait FromDeriveInput: Sized {
14  /// Create an instance from `syn::DeriveInput`, or return an error.
15  fn from_derive_input(input: &DeriveInput) -> Result<Self> {
16    match &input.data {
17      Data::Union(d) => {
18        Self::from_union(&input.attrs, &input.vis, &input.ident, &input.generics, d)
19      }
20      Data::Enum(d) => Self::from_enum(&input.attrs, &input.vis, &input.ident, &input.generics, d),
21      Data::Struct(d) => {
22        Self::from_struct(&input.attrs, &input.vis, &input.ident, &input.generics, d)
23      }
24    }
25  }
26
27  fn from_union(
28    attrs: &Vec<Attribute>,
29    vis: &Visibility,
30    ident: &Ident,
31    generics: &Generics,
32    input: &DataUnion,
33  ) -> Result<Self> {
34    Err(Error::unsupported_shape("union"))
35  }
36
37  fn from_enum(
38    attrs: &Vec<Attribute>,
39    vis: &Visibility,
40    ident: &Ident,
41    generics: &Generics,
42    input: &DataEnum,
43  ) -> Result<Self> {
44    Err(Error::unsupported_shape("enum"))
45  }
46
47  fn from_struct(
48    attrs: &Vec<Attribute>,
49    vis: &Visibility,
50    ident: &Ident,
51    generics: &Generics,
52    input: &DataStruct,
53  ) -> Result<Self> {
54    Err(Error::unsupported_shape("struct"))
55  }
56
57  fn parse(input: TokenStream) -> Result<Self> {
58    let input = syn::parse2(input)?;
59    Self::from_derive_input(&input)
60  }
61}
62
63impl FromDeriveInput for () {
64  fn from_derive_input(_: &DeriveInput) -> Result<Self> {
65    Ok(())
66  }
67}
68
69impl FromDeriveInput for DeriveInput {
70  fn from_derive_input(input: &DeriveInput) -> Result<Self> {
71    Ok(input.clone())
72  }
73}