summary refs log tree commit diff
path: root/modules/morgana_proc/src/lib.rs
blob: 7730f6ba44c02d3b4dd76b994f6a105ab447a4a4 (plain)
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
extern crate proc_macro;

use unsynn::*;
use quote::quote;

unsynn! {
    keyword MorxDocKey = "doctype";
    struct MorxBlock(Vec<Either<MorxDoctype, MorxNode, MorxChild, Literal>>);
    struct MorxDoctype(Cons<PunctAny<'!'>, MorxDocKey, Vec<Either<Ident, LiteralString>>, NodeSeparator>);
    struct MorxNode(Cons<Ident, Either<
        NodeSeparator,
        MorxChildren,
        MorxChild,
        Cons<MorxAttrs, Either<MorxChildren, NodeSeparator>>,
    >>);
    struct NodeSeparator(Either<EndOfStream, Semicolon>);
    struct MorxAttrs(Vec<MorxAttr>);
    struct MorxAttr(Cons<Ident, Optional<Cons<PunctAny<'='>, MorxAttrValue>>>);
    struct MorxAttrValue(Either<Literal, Ident, BraceGroup>);
    struct MorxChildren(Cons<BraceGroupContaining<MorxBlock>, Optional<NodeSeparator>>);
    struct MorxChild(Cons<PunctAny<'='>, Either<Literal, BraceGroup, EndOfStream>, Optional<NodeSeparator>>);
}

#[proc_macro]
pub fn morx(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let tokens = unsynn::TokenStream::from(input);

    let ast = tokens.to_token_iter().parse_all::<MorxBlock>().expect("syntax error");

    let child_vec_expr = generate_block(&ast);
    quote! {
        ::morgana::RenderNode::Fragment {
            children: #child_vec_expr
        }
    }.into()
}

fn generate_block(ast: &MorxBlock) -> unsynn::TokenStream {
    let children: Vec<unsynn::TokenStream> = ast.0.iter().map(|child| {
        match child {
            Either::First(doctype) => generate_doctype(doctype),
            Either::Second(node) => generate_node(node),
            Either::Third(child_expression) => generate_expr_node(&child_expression.0.second),
            Either::Fourth(literal) => generate_literal(literal),
        }
    }).collect();

    quote! {
        vec! [
            #(#children),*
        ]
    }.into()
}

fn generate_doctype(ast: &MorxDoctype) -> unsynn::TokenStream {
    let elem_expressions: Vec<unsynn::TokenStream> = ast.0.third.iter().map(|elem| {
        match elem {
            Either::First(ident) => {
                let ident_string = Literal::string(&ident.to_string()).into_token_stream();
                quote! {::morgana::DoctypeElem::Word( #ident_string )}
            },
            Either::Second(literal) => {
                let literal = literal.clone().into_token_stream();
                quote! {::morgana::DoctypeElem::String( #literal )}
            },
            _ => unreachable!("Invalid doctype AST"),
        }
    }).collect();
    
    quote! {
        ::morgana::RenderNode::Doctype(vec![
            #(#elem_expressions),*
        ])
    }
}

fn generate_node(ast: &MorxNode) -> unsynn::TokenStream {
    let elem_name = &ast.0.first;
    let attrs_or_props = match &ast.0.second {
        Either::Fourth(cons) => {
            let attrs = &cons.first;
            attrs.0.iter().map(|attr| {
                let attr_name = attr.0.first.clone();
                let attr_value = attr.0.second.0.iter().next().map(|val_expr| {
                    val_expr.value.second.0.clone()
                });
                (attr_name, attr_value)
            }).collect()
        },
        _ => Vec::new(),
    };

    let elem_attrs = attrs_or_props.iter().map(|attr| {
        let name = Literal::string(&attr.0.to_string()).into_token_stream();

        let value = match &attr.1 {
            Some(Either::First(literal)) => quote!{ format!("{}", #literal) },
            Some(Either::Second(ident)) => quote!{ format!("{}", #ident) },
            Some(Either::Third(bracegroup)) => {
                let inner = bracegroup.0.stream();
                quote!{ {#inner}.into() }
            },
            Some(Either::Fourth(_invalid)) => unreachable!("Invalid element attribute type"),
            None => quote!{ String::new() },
        };

        quote! { (#name.to_string(), #value) }
    });

    let elem_props = attrs_or_props.iter().map(|attr| {
        let name = &attr.0;
        let value = match &attr.1 {
            Some(Either::First(literal)) => quote!{ {String::from(#literal).into()} },
            Some(Either::Second(ident)) => quote!{ {String::from(#ident).into()} },
            Some(Either::Third(bracegroup)) => {
                let inner = bracegroup.0.stream();
                quote!{ {#inner}.into() }
            },
            Some(Either::Fourth(_invalid)) => unreachable!("Invalid element attribute type"),
            None => quote!{ true },
        };

        quote! { #name: #value }
    });

    let children = match &ast.0.second {
        Either::Second(children) => generate_block(&children.0.first.content),
        Either::Third(single_child) => {
            let node = generate_expr_node(&single_child.0.second);
            quote!{ vec![ #node ] }
        },
        Either::Fourth(Cons {first: _, second: Either::First(children), third: _, fourth: _}) => generate_block(&children.0.first.content),
        _ => quote!{ vec![] }
    };

    let is_component_node = elem_name.to_string().chars().next().map_or(false, |char| char.is_uppercase());

    if is_component_node {
        quote! {
            ::morgana::RenderNode::Component(
                Box::new({ #elem_name {
                    children: #children,
                    #(#elem_props),*
                } })
            )
        }.into()
    } else {
        let elem_name = Literal::string(&elem_name.to_string()).into_token_stream();
        quote! {
            ::morgana::RenderNode::Element {
                name: #elem_name.to_string(),
                children: #children,
                attributes: std::collections::HashMap::from([#(#elem_attrs),*])
            }
        }.into()
    }
}

// This is the ={something} expression as a child of a node
fn generate_expr_node(ast: &Either<Literal, BraceGroup, EndOfStream>) -> unsynn::TokenStream {
    match ast {
        Either::First(literal) => generate_literal(&literal),
        Either::Second(brace_expr) => {
            let children = brace_expr.0.stream();
            quote! {
                ::morgana::RenderNode::Fragment {
                    children: ::morgana::IntoRender::into_render(#children)
                }
            }
        },
        _ => unreachable!("Invalid expr node"),
    }
}

fn generate_literal(ast: &Literal) -> unsynn::TokenStream {
    quote! {
        ::morgana::RenderNode::TextNode { content: format!("{}", #ast) }
    }
}