workers-rsx-impl 0.1.0

Proc macros for workers-rsx
Documentation
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
use crate::children::Children;
use crate::element::Element;
use quote::{quote, ToTokens};
use syn::parse::{Parse, ParseStream, Result};

pub enum Child {
    /// `<div>...</div>` or `<br />`
    Element(Element),
    /// `{expr}` — generic expression container
    RawBlock(syn::Block),
    /// `Hello world!` — unquoted text child (collected at compile time, HTML-escaped at render)
    UnquotedText(String, proc_macro2::Span),
    /// `{text expr}` — forced escaped text
    TextDirective(syn::Block),
    /// `{html expr}` — raw HTML insertion (trusted content only)
    HtmlDirective(syn::Block),
    /// `if cond { ... } else if cond { ... } else { ... }`
    IfBlock(IfBlock),
    /// `for pat in expr { ... }`
    ForBlock(ForBlock),
    /// `match expr { pat => { ... }, ... }`
    MatchBlock(MatchBlock),
    /// `let` or `const` statement inside template body — scoped local
    LetStatement(syn::Stmt),
    /// Injected at compile time — generates a `<style>` tag with Tailwind CSS
    TailwindStyle(Vec<String>),
}

pub struct IfBlock {
    pub condition: proc_macro2::TokenStream,
    pub children: Children,
    pub else_branch: Option<ElseBranch>,
}

pub enum ElseBranch {
    ElseIf(Box<IfBlock>),
    Else(Children),
}

pub struct ForBlock {
    pub pattern: proc_macro2::TokenStream,
    pub iter_expr: proc_macro2::TokenStream,
    pub children: Children,
}

pub struct MatchBlock {
    pub expr: proc_macro2::TokenStream,
    pub arms: Vec<MatchArm>,
}

pub struct MatchArm {
    pub pattern: proc_macro2::TokenStream,
    pub guard: Option<proc_macro2::TokenStream>,
    pub children: Children,
}

impl Child {
    /// Recursively collect static class names from this child and its descendants.
    pub fn collect_class_names_from(child: &Child, classes: &mut Vec<String>) {
        match child {
            Child::Element(element) => {
                classes.extend(element.collect_class_names());
            }
            Child::IfBlock(if_block) => {
                Self::collect_from_if_block(if_block, classes);
            }
            Child::ForBlock(for_block) => {
                for c in &for_block.children.nodes {
                    Self::collect_class_names_from(c, classes);
                }
            }
            Child::MatchBlock(match_block) => {
                for arm in &match_block.arms {
                    for c in &arm.children.nodes {
                        Self::collect_class_names_from(c, classes);
                    }
                }
            }
            _ => {}
        }
    }

    fn collect_from_if_block(if_block: &IfBlock, classes: &mut Vec<String>) {
        for c in &if_block.children.nodes {
            Self::collect_class_names_from(c, classes);
        }
        if let Some(else_branch) = &if_block.else_branch {
            match else_branch {
                ElseBranch::ElseIf(nested) => Self::collect_from_if_block(nested, classes),
                ElseBranch::Else(children) => {
                    for c in &children.nodes {
                        Self::collect_class_names_from(c, classes);
                    }
                }
            }
        }
    }
}

fn parse_tokens_until_brace(input: ParseStream) -> Result<proc_macro2::TokenStream> {
    let mut tokens = proc_macro2::TokenStream::new();
    while !input.peek(syn::token::Brace) {
        let token: proc_macro2::TokenTree = input.parse()?;
        tokens.extend(std::iter::once(token));
    }
    Ok(tokens)
}

impl Parse for IfBlock {
    fn parse(input: ParseStream) -> Result<Self> {
        input.parse::<syn::Token![if]>()?;
        let condition = parse_tokens_until_brace(input)?;

        let content;
        syn::braced!(content in input);
        let children = Children::parse_until_empty(&content)?;

        let else_branch = if input.peek(syn::Token![else]) {
            input.parse::<syn::Token![else]>()?;
            if input.peek(syn::Token![if]) {
                Some(ElseBranch::ElseIf(Box::new(input.parse::<IfBlock>()?)))
            } else {
                let content;
                syn::braced!(content in input);
                let else_children = Children::parse_until_empty(&content)?;
                Some(ElseBranch::Else(else_children))
            }
        } else {
            None
        };

        Ok(IfBlock {
            condition,
            children,
            else_branch,
        })
    }
}

impl Parse for ForBlock {
    fn parse(input: ParseStream) -> Result<Self> {
        input.parse::<syn::Token![for]>()?;

        let mut pattern = proc_macro2::TokenStream::new();
        while !input.peek(syn::Token![in]) {
            let token: proc_macro2::TokenTree = input.parse()?;
            pattern.extend(std::iter::once(token));
        }
        input.parse::<syn::Token![in]>()?;

        let iter_expr = parse_tokens_until_brace(input)?;

        let content;
        syn::braced!(content in input);
        let children = Children::parse_until_empty(&content)?;

        Ok(ForBlock {
            pattern,
            iter_expr,
            children,
        })
    }
}

impl Parse for MatchBlock {
    fn parse(input: ParseStream) -> Result<Self> {
        input.parse::<syn::Token![match]>()?;
        let expr = parse_tokens_until_brace(input)?;

        let match_content;
        syn::braced!(match_content in input);

        let mut arms = Vec::new();
        while !match_content.is_empty() {
            let mut arm_pattern = proc_macro2::TokenStream::new();
            // Parse pattern tokens until `=>` or `if` (guard)
            while !match_content.peek(syn::Token![=>])
                && !(match_content.peek(syn::Token![if])
                    && !match_content.peek2(syn::Token![let]))
            {
                let token: proc_macro2::TokenTree = match_content.parse()?;
                arm_pattern.extend(std::iter::once(token));
            }

            // Parse optional guard: `if condition`
            let guard = if match_content.peek(syn::Token![if]) {
                match_content.parse::<syn::Token![if]>()?;
                let mut guard_tokens = proc_macro2::TokenStream::new();
                while !match_content.peek(syn::Token![=>]) {
                    let token: proc_macro2::TokenTree = match_content.parse()?;
                    guard_tokens.extend(std::iter::once(token));
                }
                Some(guard_tokens)
            } else {
                None
            };

            match_content.parse::<syn::Token![=>]>()?;

            let arm_content;
            syn::braced!(arm_content in match_content);
            let arm_children = Children::parse_until_empty(&arm_content)?;

            // Optional trailing comma
            let _ = match_content.parse::<syn::Token![,]>();

            arms.push(MatchArm {
                pattern: arm_pattern,
                guard,
                children: arm_children,
            });
        }

        Ok(MatchBlock { expr, arms })
    }
}

impl IfBlock {
    fn render_tokens(&self, buf_ident: &syn::Ident) -> proc_macro2::TokenStream {
        let condition = &self.condition;
        let children_tuple = self.children.as_tuples_tokens();

        match &self.else_branch {
            None => {
                quote! {
                    if #condition {
                        workers_rsx::Render::render_into(#children_tuple, &mut #buf_ident).unwrap();
                    }
                }
            }
            Some(ElseBranch::Else(else_children)) => {
                let else_tuple = else_children.as_tuples_tokens();
                quote! {
                    if #condition {
                        workers_rsx::Render::render_into(#children_tuple, &mut #buf_ident).unwrap();
                    } else {
                        workers_rsx::Render::render_into(#else_tuple, &mut #buf_ident).unwrap();
                    }
                }
            }
            Some(ElseBranch::ElseIf(else_if_block)) => {
                let else_if_render = else_if_block.render_tokens(buf_ident);
                quote! {
                    if #condition {
                        workers_rsx::Render::render_into(#children_tuple, &mut #buf_ident).unwrap();
                    } else {
                        #else_if_render
                    }
                }
            }
        }
    }
}

impl ToTokens for Child {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        match self {
            Self::Element(element) => element.to_tokens(tokens),
            Self::RawBlock(block) => {
                let ts = if block.stmts.len() == 1 {
                    let first = &block.stmts[0];
                    quote!(#first)
                } else {
                    quote!(#block)
                };
                ts.to_tokens(tokens);
            }
            Self::UnquotedText(text, _span) => {
                // Unquoted text is collected at compile time, emitted as a string literal
                let lit = syn::LitStr::new(text, proc_macro2::Span::call_site());
                lit.to_tokens(tokens);
            }
            Self::TextDirective(block) => {
                // {text expr} — force to string and escape
                let ts = if block.stmts.len() == 1 {
                    let first = &block.stmts[0];
                    quote!(#first)
                } else {
                    quote!(#block)
                };
                // Convert to String to ensure HTML escaping via the String Render impl
                let result = quote! {{
                    let __text_val = #ts;
                    format!("{}", __text_val)
                }};
                result.to_tokens(tokens);
            }
            Self::HtmlDirective(block) => {
                // {html expr} — raw HTML, no escaping (trusted content only)
                let ts = if block.stmts.len() == 1 {
                    let first = &block.stmts[0];
                    quote!(#first)
                } else {
                    quote!(#block)
                };
                let result = quote! {
                    workers_rsx::RawOwned(format!("{}", #ts))
                };
                result.to_tokens(tokens);
            }
            Self::IfBlock(if_block) => {
                let buf_ident =
                    syn::Ident::new("__rsx_buf", proc_macro2::Span::call_site());
                let render_code = if_block.render_tokens(&buf_ident);
                let result = quote! {{
                    let mut #buf_ident = String::new();
                    #render_code
                    workers_rsx::RawOwned(#buf_ident)
                }};
                result.to_tokens(tokens);
            }
            Self::ForBlock(for_block) => {
                let buf_ident =
                    syn::Ident::new("__rsx_buf", proc_macro2::Span::call_site());
                let pattern = &for_block.pattern;
                let iter_expr = &for_block.iter_expr;
                let children_tuple = for_block.children.as_tuples_tokens();
                let result = quote! {{
                    let mut #buf_ident = String::new();
                    for #pattern in #iter_expr {
                        workers_rsx::Render::render_into(#children_tuple, &mut #buf_ident).unwrap();
                    }
                    workers_rsx::RawOwned(#buf_ident)
                }};
                result.to_tokens(tokens);
            }
            Self::MatchBlock(match_block) => {
                let buf_ident =
                    syn::Ident::new("__rsx_buf", proc_macro2::Span::call_site());
                let expr = &match_block.expr;
                let arms: Vec<_> = match_block
                    .arms
                    .iter()
                    .map(|arm| {
                        let pattern = &arm.pattern;
                        let guard = &arm.guard;
                        let children_tuple = arm.children.as_tuples_tokens();
                        match guard {
                            Some(guard_expr) => quote! {
                                #pattern if #guard_expr => {
                                    workers_rsx::Render::render_into(#children_tuple, &mut #buf_ident).unwrap();
                                }
                            },
                            None => quote! {
                                #pattern => {
                                    workers_rsx::Render::render_into(#children_tuple, &mut #buf_ident).unwrap();
                                }
                            },
                        }
                    })
                    .collect();
                let result = quote! {{
                    let mut #buf_ident = String::new();
                    match #expr {
                        #(#arms)*
                    }
                    workers_rsx::RawOwned(#buf_ident)
                }};
                result.to_tokens(tokens);
            }
            Self::LetStatement(stmt) => {
                // Scoped local: rendered as a block that evaluates to ()
                // The let statement is emitted inline, and the next sibling will use it
                let result = quote! {{
                    #stmt
                    ()
                }};
                result.to_tokens(tokens);
            }
            Self::TailwindStyle(class_names) => {
                // Generate a <style> tag with Tailwind CSS at runtime
                let class_lits: Vec<_> = class_names
                    .iter()
                    .map(|s| syn::LitStr::new(s, proc_macro2::Span::call_site()))
                    .collect();
                let result = quote! {{
                    let __css = ::workers_rsx::generate_tailwind_css(&[#(#class_lits),*]);
                    if __css.is_empty() {
                        workers_rsx::RawOwned(String::new())
                    } else {
                        workers_rsx::RawOwned(format!("<style>{}</style>", __css))
                    }
                }};
                result.to_tokens(tokens);
            }
        }
    }
}

impl Parse for Child {
    fn parse(input: ParseStream) -> Result<Self> {
        if input.peek(syn::Token![if]) {
            Ok(Self::IfBlock(input.parse()?))
        } else if input.peek(syn::Token![for]) {
            Ok(Self::ForBlock(input.parse()?))
        } else if input.peek(syn::Token![match]) {
            Ok(Self::MatchBlock(input.parse()?))
        } else if input.peek(syn::Token![let]) || input.peek(syn::Token![const]) {
            // let/const statement — scoped local in template body
            let stmt: syn::Stmt = input.parse()?;
            Ok(Self::LetStatement(stmt))
        } else if input.peek(syn::token::Brace) {
            // Could be {text expr}, {html expr}, or {expr}
            let fork = input.fork();
            let content;
            syn::braced!(content in fork);

            // Check for `text` keyword directive
            if content.peek(syn::Ident) {
                let ident: syn::Ident = content.fork().parse()?;
                if ident == "text" {
                    // Consume from real input
                    let content;
                    syn::braced!(content in input);
                    content.parse::<syn::Ident>()?; // consume "text"
                    let inner_block = syn::Block {
                        brace_token: syn::token::Brace::default(),
                        stmts: vec![syn::Stmt::Expr(content.parse()?)],
                    };
                    return Ok(Self::TextDirective(inner_block));
                } else if ident == "html" {
                    // Consume from real input
                    let content;
                    syn::braced!(content in input);
                    content.parse::<syn::Ident>()?; // consume "html"
                    let inner_block = syn::Block {
                        brace_token: syn::token::Brace::default(),
                        stmts: vec![syn::Stmt::Expr(content.parse()?)],
                    };
                    return Ok(Self::HtmlDirective(inner_block));
                }
            }

            // Regular {expr} block
            let block = input.parse::<syn::Block>()?;
            Ok(Self::RawBlock(block))
        } else if input.peek(syn::Token![<]) {
            match input.parse::<Element>() {
                Ok(element) => Ok(Self::Element(element)),
                Err(_) => {
                    let block = input.parse::<syn::Block>()?;
                    Ok(Self::RawBlock(block))
                }
            }
        } else {
            // Unquoted text: collect tokens until we hit `<`, `{`, or end of stream.
            // String literals are also collected (their content is extracted without quotes).
            // e.g. `Hello world!` or `"Hello, world!"` becomes a compile-time string literal.
            let mut text = String::new();
            let span = input.span();
            while !input.is_empty()
                && !input.peek(syn::Token![<])
                && !input.peek(syn::token::Brace)
            {
                if input.peek(syn::LitStr) {
                    // String literal: extract the value without quotes
                    let lit = input.parse::<syn::LitStr>()?;
                    text.push_str(&lit.value());
                } else {
                    let tt: proc_macro2::TokenTree = input.parse()?;
                    let s = tt.to_string();
                    if !text.is_empty() {
                        // Don't add a space before trailing punctuation
                        let no_space_before = matches!(
                            s.as_str(),
                            "!" | "," | "." | "?" | ";" | ":" | "'" | ")" | "]"
                        );
                        if !no_space_before {
                            text.push(' ');
                        }
                    }
                    text.push_str(&s);
                }
            }
            if text.is_empty() {
                return Err(input.error("expected a child element, text, or expression"));
            }
            Ok(Self::UnquotedText(text, span))
        }
    }
}