forked from yewstack/yew
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhtml_component.rs
540 lines (468 loc) · 15.5 KB
/
html_component.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
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
use super::HtmlProp;
use super::HtmlPropSuffix;
use super::HtmlTreeNested;
use crate::PeekValue;
use boolinator::Boolinator;
use proc_macro2::Span;
use quote::{quote, quote_spanned, ToTokens};
use std::cmp::Ordering;
use std::collections::HashMap;
use syn::buffer::Cursor;
use syn::parse;
use syn::parse::{Parse, ParseStream, Result as ParseResult};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::{
AngleBracketedGenericArguments, Expr, GenericArgument, Ident, Path, PathArguments, PathSegment,
Token, Type, TypePath,
};
pub struct HtmlComponent {
ty: Type,
props: Props,
children: Vec<HtmlTreeNested>,
}
impl PeekValue<()> for HtmlComponent {
fn peek(cursor: Cursor) -> Option<()> {
HtmlComponentOpen::peek(cursor)
.or_else(|| HtmlComponentClose::peek(cursor))
.map(|_| ())
}
}
impl Parse for HtmlComponent {
fn parse(input: ParseStream) -> ParseResult<Self> {
if HtmlComponentClose::peek(input.cursor()).is_some() {
return match input.parse::<HtmlComponentClose>() {
Ok(close) => Err(syn::Error::new_spanned(
close,
"this close tag has no corresponding open tag",
)),
Err(err) => Err(err),
};
}
let open = input.parse::<HtmlComponentOpen>()?;
// Return early if it's a self-closing tag
if open.div.is_some() {
return Ok(HtmlComponent {
ty: open.ty,
props: open.props,
children: Vec::new(),
});
}
let mut children: Vec<HtmlTreeNested> = vec![];
loop {
if input.is_empty() {
return Err(syn::Error::new_spanned(
open,
"this open tag has no corresponding close tag",
));
}
if let Some(ty) = HtmlComponentClose::peek(input.cursor()) {
if open.ty == ty {
break;
}
}
children.push(input.parse()?);
}
input.parse::<HtmlComponentClose>()?;
Ok(HtmlComponent {
ty: open.ty,
props: open.props,
children,
})
}
}
impl ToTokens for HtmlComponent {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let Self {
ty,
props,
children,
} = self;
let validate_props = if let Props::List(list_props) = props {
let check_props = list_props.props.iter().map(|HtmlProp { label, .. }| {
quote! { props.#label; }
});
let check_children = if !children.is_empty() {
quote! { props.children; }
} else {
quote! {}
};
quote! {
let _ = |props: <#ty as ::yew::html::Component>::Properties| {
#check_children
#(#check_props)*
};
}
} else {
quote! {}
};
let set_children = if !children.is_empty() {
quote! {
.children(::yew::html::ChildrenRenderer::new({
let mut v = ::std::vec::Vec::new();
#(v.extend(::yew::utils::NodeSeq::from(#children));)*
v
}))
}
} else {
quote! {}
};
let init_props = match props {
Props::List(list_props) => {
let set_props = list_props.props.iter().map(|HtmlProp { label, value }| {
quote_spanned! { value.span()=> .#label(
<::yew::virtual_dom::vcomp::VComp as ::yew::virtual_dom::Transformer<_, _>>::transform(
#value
)
)}
});
quote! {
<<#ty as ::yew::html::Component>::Properties as ::yew::html::Properties>::builder()
#(#set_props)*
#set_children
.build()
}
}
Props::With(with_props) => {
let props = &with_props.props;
quote! { #props }
}
Props::None => quote! {
<<#ty as ::yew::html::Component>::Properties as ::yew::html::Properties>::builder()
#set_children
.build()
},
};
let validate_comp = quote_spanned! { ty.span()=>
trait __yew_validate_comp: ::yew::html::Component {}
impl __yew_validate_comp for #ty {}
};
let node_ref = if let Some(node_ref) = props.node_ref() {
quote_spanned! { node_ref.span()=> #node_ref }
} else {
quote! { ::yew::html::NodeRef::default() }
};
tokens.extend(quote! {{
// These validation checks show a nice error message to the user.
// They do not execute at runtime
if false {
#validate_comp
#validate_props
}
::yew::virtual_dom::VChild::<#ty>::new(#init_props, #node_ref)
}});
}
}
impl HtmlComponent {
fn double_colon(mut cursor: Cursor) -> Option<Cursor> {
for _ in 0..2 {
let (punct, c) = cursor.punct()?;
(punct.as_char() == ':').as_option()?;
cursor = c;
}
Some(cursor)
}
fn path_arguments(cursor: Cursor) -> Option<(PathArguments, Cursor)> {
let (punct, cursor) = cursor.punct()?;
(punct.as_char() == '<').as_option()?;
let (ty, cursor) = Self::peek_type(cursor)?;
let (punct, cursor) = cursor.punct()?;
(punct.as_char() == '>').as_option()?;
Some((
PathArguments::AngleBracketed(AngleBracketedGenericArguments {
colon2_token: None,
lt_token: Token),
args: vec![GenericArgument::Type(ty)].into_iter().collect(),
gt_token: Token),
}),
cursor,
))
}
fn peek_type(mut cursor: Cursor) -> Option<(Type, Cursor)> {
let mut colons_optional = true;
let mut last_ident = None;
let mut leading_colon = None;
let mut segments = Punctuated::new();
loop {
let mut post_colons_cursor = cursor;
if let Some(c) = Self::double_colon(post_colons_cursor) {
if colons_optional {
leading_colon = Some(Token));
}
post_colons_cursor = c;
} else if !colons_optional {
break;
}
if let Some((ident, c)) = post_colons_cursor.ident() {
cursor = c;
last_ident = Some(ident.clone());
let arguments = if let Some((args, c)) = Self::path_arguments(cursor) {
cursor = c;
args
} else {
PathArguments::None
};
segments.push(PathSegment { ident, arguments });
} else {
break;
}
// only first `::` is optional
colons_optional = false;
}
let type_str = last_ident?.to_string();
type_str.is_ascii().as_option()?;
type_str.bytes().next()?.is_ascii_uppercase().as_option()?;
Some((
Type::Path(TypePath {
qself: None,
path: Path {
leading_colon,
segments,
},
}),
cursor,
))
}
}
struct HtmlComponentOpen {
lt: Token![<],
ty: Type,
props: Props,
div: Option<Token![/]>,
gt: Token![>],
}
impl PeekValue<Type> for HtmlComponentOpen {
fn peek(cursor: Cursor) -> Option<Type> {
let (punct, cursor) = cursor.punct()?;
(punct.as_char() == '<').as_option()?;
let (typ, _) = HtmlComponent::peek_type(cursor)?;
Some(typ)
}
}
impl Parse for HtmlComponentOpen {
fn parse(input: ParseStream) -> ParseResult<Self> {
let lt = input.parse::<Token![<]>()?;
let ty = input.parse()?;
// backwards compat
let _ = input.parse::<Token![:]>();
let HtmlPropSuffix { stream, div, gt } = input.parse()?;
let props = parse(stream)?;
Ok(HtmlComponentOpen {
lt,
ty,
props,
div,
gt,
})
}
}
impl ToTokens for HtmlComponentOpen {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let HtmlComponentOpen { lt, gt, .. } = self;
tokens.extend(quote! {#lt#gt});
}
}
struct HtmlComponentClose {
lt: Token![<],
div: Token![/],
ty: Type,
gt: Token![>],
}
impl PeekValue<Type> for HtmlComponentClose {
fn peek(cursor: Cursor) -> Option<Type> {
let (punct, cursor) = cursor.punct()?;
(punct.as_char() == '<').as_option()?;
let (punct, cursor) = cursor.punct()?;
(punct.as_char() == '/').as_option()?;
let (typ, cursor) = HtmlComponent::peek_type(cursor)?;
let (punct, _) = cursor.punct()?;
(punct.as_char() == '>').as_option()?;
Some(typ)
}
}
impl Parse for HtmlComponentClose {
fn parse(input: ParseStream) -> ParseResult<Self> {
Ok(HtmlComponentClose {
lt: input.parse()?,
div: input.parse()?,
ty: input.parse()?,
gt: input.parse()?,
})
}
}
impl ToTokens for HtmlComponentClose {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let HtmlComponentClose { lt, div, ty, gt } = self;
tokens.extend(quote! {#lt#div#ty#gt});
}
}
enum PropType {
List,
With,
}
enum Props {
List(Box<ListProps>),
With(Box<WithProps>),
None,
}
impl Props {
fn node_ref(&self) -> Option<&Expr> {
match self {
Props::List(list_props) => list_props.node_ref.as_ref(),
Props::With(with_props) => with_props.node_ref.as_ref(),
Props::None => None,
}
}
fn collision_message() -> &'static str {
"Using special syntax `with props` along with named prop is not allowed. This rule does not apply to special `ref` prop"
}
}
impl PeekValue<PropType> for Props {
fn peek(cursor: Cursor) -> Option<PropType> {
let (ident, _) = cursor.ident()?;
let prop_type = if ident == "with" {
PropType::With
} else {
PropType::List
};
Some(prop_type)
}
}
impl Parse for Props {
fn parse(input: ParseStream) -> ParseResult<Self> {
match Props::peek(input.cursor()) {
Some(PropType::List) => input.parse().map(|l| Props::List(Box::new(l))),
Some(PropType::With) => input.parse().map(|w| Props::With(Box::new(w))),
None => Ok(Props::None),
}
}
}
struct ListProps {
props: Vec<HtmlProp>,
node_ref: Option<Expr>,
}
impl ListProps {
fn collect_props(input: ParseStream) -> ParseResult<Vec<HtmlProp>> {
let mut props: Vec<HtmlProp> = Vec::new();
while HtmlProp::peek(input.cursor()).is_some() {
props.push(input.parse::<HtmlProp>()?);
}
Ok(props)
}
fn remove_refs(mut props: Vec<HtmlProp>) -> ListProps {
let ref_position = props.iter().position(|p| p.label.to_string() == "ref");
let node_ref = ref_position.map(|i| props.remove(i).value);
ListProps { props, node_ref }
}
fn apply_edge_cases(props: &Vec<HtmlProp>, cases: &[&str]) -> Result<(), syn::Error> {
let mut map: HashMap<&str, Box<dyn Fn(&HtmlProp) -> Result<_, syn::Error>>> =
HashMap::new();
let ref_handler = |prop: &HtmlProp| -> Result<_, syn::Error> {
if prop.label.to_string() == "ref" {
Err(syn::Error::new_spanned(&prop.label, "too many refs set"))
} else {
Ok(())
}
};
let type_handler = |prop: &HtmlProp| -> Result<_, syn::Error> {
if prop.label.to_string() == "type" {
Err(syn::Error::new_spanned(&prop.label, "expected identifier"))
} else {
Ok(())
}
};
let unexpected_handler = |prop: &HtmlProp| -> Result<_, syn::Error> {
if !prop.label.extended.is_empty() {
Err(syn::Error::new_spanned(&prop.label, "expected identifier"))
} else {
Ok(())
}
};
map.insert("ref", Box::new(ref_handler));
map.insert("type", Box::new(type_handler));
map.insert("unexpected", Box::new(unexpected_handler));
let errors = props.iter().fold(vec![], |acc, prop: &HtmlProp| {
[
acc,
cases
.iter()
.map(|elem| match map.get(elem) {
Some(handler) => handler(prop),
None => Err(syn::Error::new_spanned(&prop.label, "something went wrong")),
})
.filter(Result::is_err)
.collect::<Vec<Result<_, syn::Error>>>(),
]
.concat()
});
for error in errors {
return error;
}
Ok(())
}
}
impl Parse for ListProps {
fn parse(input: ParseStream) -> ParseResult<Self> {
let props = ListProps::collect_props(input)?;
if let Some(ident) = input.cursor().ident() {
if ident.0 == "with" {
return Err(input.error(Props::collision_message()));
}
}
let ListProps {
mut props,
node_ref,
} = ListProps::remove_refs(props);
ListProps::apply_edge_cases(&props, &["ref"])?;
// alphabetize
props.sort_by(|a, b| {
if a.label == b.label {
Ordering::Equal
} else if a.label.to_string() == "children" {
Ordering::Greater
} else if b.label.to_string() == "children" {
Ordering::Less
} else {
a.label
.to_string()
.partial_cmp(&b.label.to_string())
.unwrap()
}
});
Ok(ListProps { props, node_ref })
}
}
struct WithProps {
props: Ident,
node_ref: Option<Expr>,
}
impl Parse for WithProps {
fn parse(input: ParseStream) -> ParseResult<Self> {
let with = input.parse::<Ident>()?;
if with != "with" {
return Err(input.error("expected to find `with` token"));
}
let props = input.parse::<Ident>()?;
let _ = input.parse::<Token![,]>();
// Check for the ref tag after `with`
let mut node_ref = None;
if input.cursor().ident().is_some() {
let ListProps {
props: list_props,
node_ref: reference,
} = ListProps::remove_refs(ListProps::collect_props(input)?);
node_ref = reference;
for prop in &list_props {
if prop.label.to_string() == "ref" {
return Err(syn::Error::new_spanned(&prop.label, "too many refs set"));
} else {
return Err(syn::Error::new_spanned(
&prop.label,
Props::collision_message(),
));
}
}
}
Ok(WithProps { props, node_ref })
}
}