forked from yewstack/yew
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.rs
90 lines (79 loc) · 3.12 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
mod builder;
mod field;
mod generics;
mod wrapper;
use builder::PropsBuilder;
use field::PropField;
use proc_macro2::{Ident, Span};
use quote::{format_ident, quote, ToTokens};
use std::convert::TryInto;
use syn::parse::{Parse, ParseStream, Result};
use syn::{DeriveInput, Generics, Visibility};
use wrapper::PropsWrapper;
pub struct DerivePropsInput {
vis: Visibility,
generics: Generics,
props_name: Ident,
prop_fields: Vec<PropField>,
}
impl Parse for DerivePropsInput {
fn parse(input: ParseStream) -> Result<Self> {
let input: DeriveInput = input.parse()?;
let prop_fields = match input.data {
syn::Data::Struct(data) => match data.fields {
syn::Fields::Named(fields) => {
let mut prop_fields: Vec<PropField> = fields
.named
.into_iter()
.map(|f| f.try_into())
.collect::<Result<Vec<PropField>>>()?;
// Alphabetize
prop_fields.sort();
prop_fields
}
syn::Fields::Unit => Vec::new(),
_ => unimplemented!("only structs are supported"),
},
_ => unimplemented!("only structs are supported"),
};
Ok(Self {
vis: input.vis,
props_name: input.ident,
generics: input.generics,
prop_fields,
})
}
}
impl ToTokens for DerivePropsInput {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let Self {
generics,
props_name,
..
} = self;
// The wrapper is a new struct which wraps required props in `Option`
let wrapper_name = format_ident!("{}Wrapper", props_name, span = Span::call_site());
let wrapper = PropsWrapper::new(&wrapper_name, generics, &self.prop_fields);
tokens.extend(wrapper.into_token_stream());
// The builder will only build if all required props have been set
let builder_name = format_ident!("{}Builder", props_name, span = Span::call_site());
let builder_step = format_ident!("{}BuilderStep", props_name, span = Span::call_site());
let builder = PropsBuilder::new(&builder_name, &builder_step, self, &wrapper_name);
let builder_generic_args = builder.first_step_generic_args();
tokens.extend(builder.into_token_stream());
// The properties trait has a `builder` method which creates the props builder
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let properties = quote! {
impl#impl_generics ::yew::html::Properties for #props_name#ty_generics #where_clause {
type Builder = #builder_name<#builder_generic_args>;
fn builder() -> Self::Builder {
#builder_name {
wrapped: ::std::boxed::Box::new(::std::default::Default::default()),
_marker: ::std::marker::PhantomData,
}
}
}
};
tokens.extend(properties);
}
}