1 | use proc_macro2::TokenStream; |
2 | use quote::ToTokens; |
3 | use syn::{DeriveInput, Field, Ident, Meta}; |
4 | |
5 | use crate::codegen::FromVariantImpl; |
6 | use crate::options::{DataShape, OuterFrom, ParseAttribute, ParseData}; |
7 | use crate::{FromMeta, Result}; |
8 | |
9 | #[derive (Debug, Clone)] |
10 | pub struct FromVariantOptions { |
11 | pub base: OuterFrom, |
12 | /// The field on the deriving struct into which the discriminant expression |
13 | /// should be placed by the derived `FromVariant` impl. |
14 | pub discriminant: Option<Ident>, |
15 | pub fields: Option<Ident>, |
16 | pub supports: Option<DataShape>, |
17 | } |
18 | |
19 | impl FromVariantOptions { |
20 | pub fn new(di: &DeriveInput) -> Result<Self> { |
21 | (FromVariantOptions { |
22 | base: OuterFrom::start(di)?, |
23 | discriminant: Default::default(), |
24 | fields: Default::default(), |
25 | supports: Default::default(), |
26 | }) |
27 | .parse_attributes(&di.attrs)? |
28 | .parse_body(&di.data) |
29 | } |
30 | } |
31 | |
32 | impl<'a> From<&'a FromVariantOptions> for FromVariantImpl<'a> { |
33 | fn from(v: &'a FromVariantOptions) -> Self { |
34 | FromVariantImpl { |
35 | base: (&v.base.container).into(), |
36 | ident: v.base.ident.as_ref(), |
37 | discriminant: v.discriminant.as_ref(), |
38 | fields: v.fields.as_ref(), |
39 | attrs: v.base.attrs.as_ref(), |
40 | attr_names: &v.base.attr_names, |
41 | forward_attrs: v.base.forward_attrs.as_ref(), |
42 | from_ident: v.base.from_ident, |
43 | supports: v.supports.as_ref(), |
44 | } |
45 | } |
46 | } |
47 | |
48 | impl ParseAttribute for FromVariantOptions { |
49 | fn parse_nested(&mut self, mi: &Meta) -> Result<()> { |
50 | if mi.path().is_ident("supports" ) { |
51 | self.supports = FromMeta::from_meta(item:mi)?; |
52 | Ok(()) |
53 | } else { |
54 | self.base.parse_nested(mi) |
55 | } |
56 | } |
57 | } |
58 | |
59 | impl ParseData for FromVariantOptions { |
60 | fn parse_field(&mut self, field: &Field) -> Result<()> { |
61 | match field.ident.as_ref().map(|v: &Ident| v.to_string()).as_deref() { |
62 | Some("discriminant" ) => { |
63 | self.discriminant = field.ident.clone(); |
64 | Ok(()) |
65 | } |
66 | Some("fields" ) => { |
67 | self.fields = field.ident.clone(); |
68 | Ok(()) |
69 | } |
70 | _ => self.base.parse_field(field), |
71 | } |
72 | } |
73 | } |
74 | |
75 | impl ToTokens for FromVariantOptions { |
76 | fn to_tokens(&self, tokens: &mut TokenStream) { |
77 | FromVariantImpl::from(self).to_tokens(tokens) |
78 | } |
79 | } |
80 | |