-
Notifications
You must be signed in to change notification settings - Fork 145
/
component.rs
80 lines (73 loc) · 2.79 KB
/
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
use std::mem;
use proc_macro2::TokenStream;
use quote::{quote, quote_spanned, ToTokens};
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::token::{Comma, Paren};
use syn::{parenthesized, parse_quote, Expr, GenericArgument, Path, Result};
/// Components are identical to function calls.
pub struct Component {
pub path: Path,
pub paren: Paren,
pub args: Punctuated<Expr, Comma>,
}
impl Parse for Component {
fn parse(input: ParseStream) -> Result<Self> {
let content;
Ok(Self {
path: input.parse()?,
paren: parenthesized!(content in input),
args: content.parse_terminated(Expr::parse)?,
})
}
}
impl ToTokens for Component {
fn to_tokens(&self, tokens: &mut TokenStream) {
let Component { path, paren, args } = self;
let mut path = path.clone();
let generic_arg: GenericArgument = parse_quote! { _ };
let generics = mem::take(&mut path.segments.last_mut().unwrap().arguments);
let generics = match generics {
syn::PathArguments::None => quote! {},
syn::PathArguments::AngleBracketed(mut generics) => {
if !generics.args.is_empty() {
// Add the GenericNode type param to generics.
let first_generic_param_index = generics
.args
.iter()
.enumerate()
.find(|(_, arg)| {
matches!(arg, GenericArgument::Type(_) | GenericArgument::Const(_))
})
.map(|(i, _)| i);
if let Some(first_generic_param_index) = first_generic_param_index {
generics.args.insert(first_generic_param_index, generic_arg);
} else {
generics.args.push(generic_arg);
}
}
generics.into_token_stream()
}
syn::PathArguments::Parenthesized(_) => unreachable!(),
};
let quoted = if args.empty_or_trailing() {
quote_spanned! { paren.span=>
::sycamore::reactive::untrack(|| {
#[allow(unused_imports)]
use ::sycamore::component::Component as __Component;
#path#generics::__create_component(())
})
}
} else {
quote_spanned! { path.span()=>
::sycamore::reactive::untrack(|| {
#[allow(unused_imports)]
use ::sycamore::component::Component as __Component;
#path#generics::__create_component(#args)
})
}
};
tokens.extend(quoted);
}
}