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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
use super::*;
use proc_macro2::TokenStream as TokenStream2;
use quote::{quote, ToTokens, TokenStreamExt};
use syn::{
ext::IdentExt,
parse::{Parse, ParseBuffer, ParseStream},
spanned::Spanned,
token, AngleBracketedGenericArguments, Error, Expr, Ident, LitStr, PathArguments, Result,
Token,
};
#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub struct Component {
pub name: syn::Path,
pub prop_gen_args: Option<AngleBracketedGenericArguments>,
pub fields: Vec<ComponentField>,
pub children: Vec<BodyNode>,
pub manual_props: Option<Expr>,
}
impl Component {
pub fn validate_component_path(path: &syn::Path) -> Result<()> {
if path
.segments
.iter()
.take(path.segments.len() - 1)
.any(|seg| seg.arguments != PathArguments::None)
{
component_path_cannot_have_arguments!(path.span());
}
if !matches!(
path.segments.last().unwrap().arguments,
PathArguments::None | PathArguments::AngleBracketed(_)
) {
invalid_component_path!(path.span());
}
Ok(())
}
pub fn key(&self) -> Option<&IfmtInput> {
match self
.fields
.iter()
.find(|f| f.name == "key")
.map(|f| &f.content)
{
Some(ContentField::Formatted(fmt)) => Some(fmt),
_ => None,
}
}
}
impl Parse for Component {
fn parse(stream: ParseStream) -> Result<Self> {
let mut name = stream.parse::<syn::Path>()?;
Component::validate_component_path(&name)?;
let prop_gen_args = name.segments.last_mut().and_then(|seg| {
if let PathArguments::AngleBracketed(args) = seg.arguments.clone() {
seg.arguments = PathArguments::None;
Some(args)
} else {
None
}
});
let content: ParseBuffer;
if stream.peek(token::Brace) {
syn::braced!(content in stream);
} else {
syn::parenthesized!(content in stream);
}
let mut body = Vec::new();
let mut children = Vec::new();
let mut manual_props = None;
while !content.is_empty() {
if content.peek(Token![..]) {
content.parse::<Token![..]>()?;
manual_props = Some(content.parse::<Expr>()?);
} else if content.peek(Ident) && content.peek2(Token![:]) && !content.peek3(Token![:]) {
body.push(content.parse::<ComponentField>()?);
} else {
children.push(content.parse::<BodyNode>()?);
}
if content.peek(Token![,]) {
let _ = content.parse::<Token![,]>();
}
}
Ok(Self {
name,
prop_gen_args,
fields: body,
children,
manual_props,
})
}
}
impl ToTokens for Component {
fn to_tokens(&self, tokens: &mut TokenStream2) {
let name = &self.name;
let prop_gen_args = &self.prop_gen_args;
let builder = match &self.manual_props {
Some(manual_props) => {
let mut toks = quote! {
let mut __manual_props = #manual_props;
};
for field in &self.fields {
if field.name == "key" {
} else {
let name = &field.name;
let val = &field.content;
toks.append_all(quote! {
__manual_props.#name = #val;
});
}
}
toks.append_all(quote! {
__manual_props
});
quote! {{
#toks
}}
}
None => {
let mut toks = match prop_gen_args {
Some(gen_args) => quote! { fc_to_builder(#name #gen_args) },
None => quote! { fc_to_builder(#name) },
};
for field in &self.fields {
match field.name.to_string().as_str() {
"key" => {}
_ => toks.append_all(quote! {#field}),
}
}
if !self.children.is_empty() {
let renderer: TemplateRenderer = TemplateRenderer {
roots: &self.children,
};
toks.append_all(quote! {
.children(
Some({ #renderer })
)
});
}
toks.append_all(quote! {
.build()
});
toks
}
};
let fn_name = self.name.segments.last().unwrap().ident.to_string();
let gen_name = match &self.prop_gen_args {
Some(gen) => quote! { #name #gen },
None => quote! { #name },
};
tokens.append_all(quote! {
__cx.component(
#gen_name,
#builder,
#fn_name
)
})
}
}
#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub struct ComponentField {
pub name: Ident,
pub content: ContentField,
}
#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub enum ContentField {
ManExpr(Expr),
Formatted(IfmtInput),
OnHandlerRaw(Expr),
}
impl ToTokens for ContentField {
fn to_tokens(&self, tokens: &mut TokenStream2) {
match self {
ContentField::ManExpr(e) => e.to_tokens(tokens),
ContentField::Formatted(s) => tokens.append_all(quote! {
__cx.raw_text(#s)
}),
ContentField::OnHandlerRaw(e) => tokens.append_all(quote! {
__cx.event_handler(#e)
}),
}
}
}
impl Parse for ComponentField {
fn parse(input: ParseStream) -> Result<Self> {
let name = Ident::parse_any(input)?;
input.parse::<Token![:]>()?;
if name.to_string().starts_with("on") {
let content = ContentField::OnHandlerRaw(input.parse()?);
return Ok(Self { name, content });
}
if name == "key" {
let content = ContentField::Formatted(input.parse()?);
return Ok(Self { name, content });
}
if input.peek(LitStr) {
let forked = input.fork();
let t: LitStr = forked.parse()?;
if (forked.is_empty() || forked.peek(Token![,])) && is_literal_foramtted(&t) {
let content = ContentField::Formatted(input.parse()?);
return Ok(Self { name, content });
}
}
if input.peek(LitStr) && input.peek2(LitStr) {
missing_trailing_comma!(input.span());
}
let content = ContentField::ManExpr(input.parse()?);
Ok(Self { name, content })
}
}
impl ToTokens for ComponentField {
fn to_tokens(&self, tokens: &mut TokenStream2) {
let ComponentField { name, content, .. } = self;
tokens.append_all(quote! {
.#name(#content)
})
}
}
fn is_literal_foramtted(lit: &LitStr) -> bool {
let s = lit.value();
let mut chars = s.chars();
while let Some(next) = chars.next() {
if next == '{' {
let nen = chars.next();
if nen != Some('{') {
return true;
}
}
}
false
}