cheers-ast 0.1.0-alpha.1

Internal AST support crate for cheers.
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
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
use std::{collections::BTreeMap, iter};

use proc_macro2::{Ident, Span, TokenStream};
use quote::{ToTokens, format_ident, quote, quote_spanned};
use syn::{
    Error, LitStr, braced,
    parse::Parse,
    token::{Brace, Paren},
};

use super::{AttributeValueNode, DataModifierPart, DataModifiers, SyntaxStatic, UnquotedName};

fn escape_script_source_literal(value: &str) -> std::borrow::Cow<'_, str> {
    let bytes = value.as_bytes();
    let script_end = b"</script";
    let mut i = 0;
    let mut start = 0;
    let mut escaped = None::<String>;

    while i + script_end.len() <= bytes.len() {
        if bytes[i] == b'<'
            && bytes[i + 1] == b'/'
            && bytes[i + 2..i + script_end.len()].eq_ignore_ascii_case(b"script")
        {
            let escaped = escaped.get_or_insert_with(|| String::with_capacity(value.len() + 1));
            escaped.push_str(&value[start..i]);
            escaped.push_str("<\\/");
            escaped.push_str(&value[i + 2..i + script_end.len()]);
            i += script_end.len();
            start = i;
        } else {
            i += 1;
        }
    }

    if let Some(mut escaped) = escaped {
        escaped.push_str(&value[start..]);
        std::borrow::Cow::Owned(escaped)
    } else {
        std::borrow::Cow::Borrowed(value)
    }
}

fn pinned_stream_tokens_expr(stream: &TokenStream) -> TokenStream {
    quote! {
        ::std::boxed::Box::pin(#stream) as ::std::pin::Pin<::std::boxed::Box<dyn ::cheers::__internal::futures::stream::Stream<Item = ::cheers::Rendered<::std::string::String>> + ::std::marker::Send>>
    }
}

pub fn lazy<T: Parse + Generate + SyntaxStatic>(tokens: TokenStream) -> Result<TokenStream, Error> {
    lazy_with_flavour::<T>(tokens, NodeFlavour::Html)
}

pub fn lazy_with_flavour<T: Parse + Generate + SyntaxStatic>(
    tokens: TokenStream,
    flavour: NodeFlavour,
) -> Result<TokenStream, Error> {
    let mut borrow_state = BorrowState::new();
    let mut g = Generator::new_closure(T::CONTEXT, flavour, &mut borrow_state);

    let mut input = syn::parse2::<T>(tokens)?;
    let syntax_static = input.is_static();
    g.push(&mut input);

    let block = g.finish();
    let borrow_captures = borrow_state.captures;

    let buffer_ident = Generator::buffer_ident();

    let marker_ident = T::CONTEXT.marker_type();
    let lazy = if !syntax_static {
        // Dynamic render bodies can contain arbitrary Rust expressions. Keep them as normal
        // closures instead of guessing whether their paths capture caller locals.
        quote! {
            ::cheers::prelude::Lazy::<_, #marker_ident>::dangerously_create(
                move |#buffer_ident: &mut ::cheers::prelude::Buffer<#marker_ident>| {
                    ::cheers::__internal::subsecond::call(|| {
                        #block
                    })
                }
            )
        }
    } else {
        // Syntactically static render bodies cannot reference caller locals. Coerce the generated
        // closure into a real function pointer so Subsecond has a precise hot boundary.
        quote! {
            {
                let __cheers_subsecond_hot_render: fn(&mut ::cheers::prelude::Buffer<#marker_ident>) = |#buffer_ident| {
                    #block
                };

                ::cheers::prelude::Lazy::<_, #marker_ident>::dangerously_create(
                    move |#buffer_ident: &mut ::cheers::prelude::Buffer<#marker_ident>| {
                        ::cheers::__internal::subsecond::hot_call(
                            __cheers_subsecond_hot_render,
                            (#buffer_ident,),
                        );
                    }
                )
            }
        }
    };

    let rendered = if block.async_stmts.is_empty() {
        quote! {
            {
                use ::cheers::validation::attributes::*;
                #(#borrow_captures)*

                #lazy
            }
        }
    } else {
        let streams = &block.async_stmts;
        let streams = streams.iter().map(pinned_stream_tokens_expr);

        quote! {
            {
                use ::cheers::validation::attributes::*;
                #(#borrow_captures)*

                let lazy = #lazy;
                let stream = ::cheers::__internal::futures::stream::select_all([
                    #(#streams),*
                ]);
                ::cheers::prelude::AsyncLazy::__select_all(lazy, stream)
            }
        }
    };

    Ok(rendered)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NodeFlavour {
    Html,
    Xml(XmlFlavour),
}

impl NodeFlavour {
    pub const fn void_close(self) -> &'static str {
        match self {
            Self::Html => ">",
            Self::Xml(_) => "/>",
        }
    }

    pub const fn elements_module(self) -> ValidationModule {
        match self {
            Self::Html => ValidationModule::Html,
            Self::Xml(XmlFlavour::Svg) => ValidationModule::Svg,
            Self::Xml(XmlFlavour::MathMl) => ValidationModule::MathMl,
        }
    }

    pub const fn element_kind(self, is_void: bool) -> ElementKind {
        match self {
            Self::Html => {
                if is_void {
                    ElementKind::Void
                } else {
                    ElementKind::Normal
                }
            }
            Self::Xml(_) => ElementKind::Xml,
        }
    }

    pub fn child_flavour(self, element_name: &UnquotedName) -> Self {
        match self {
            Self::Html => match element_name {
                name if name == &"svg" => Self::Xml(XmlFlavour::Svg),
                name if name == &"math" => Self::Xml(XmlFlavour::MathMl),
                _ => self,
            },
            Self::Xml(XmlFlavour::Svg) => match element_name {
                name if name == &"foreignObject" => Self::Html,
                _ => self,
            },
            Self::Xml(XmlFlavour::MathMl) => self,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum XmlFlavour {
    Svg,
    MathMl,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ValidationModule {
    Html,
    Svg,
    MathMl,
}

impl ToTokens for ValidationModule {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        match self {
            Self::Html => quote!(::cheers::validation::elements),
            Self::Svg => quote!(::cheers::validation::svg::elements),
            Self::MathMl => quote!(::cheers::validation::mathml::elements),
        }
        .to_tokens(tokens);
    }
}

struct BorrowState {
    captures: Vec<TokenStream>,
    counter: usize,
}

impl BorrowState {
    fn new() -> Self {
        Self {
            captures: Vec::new(),
            counter: 0,
        }
    }

    fn hoist_ref_expr(&mut self, paren_token: Paren, expr: impl ToTokens) -> Ident {
        let ref_idx = self.counter;
        self.counter += 1;

        let ref_ident = format_ident!("__cheers_ref_{ref_idx}", span = Span::mixed_site());

        let mut ref_expr = TokenStream::new();
        paren_token.surround(&mut ref_expr, |tokens| expr.to_tokens(tokens));

        let reference = quote_spanned!(paren_token.span=> &);
        self.captures.push(quote! {
            let #ref_ident = #reference #ref_expr;
        });

        ref_ident
    }
}

pub struct Generator<'a> {
    context: Context,
    flavour: NodeFlavour,
    brace_token: Brace,
    parts: Vec<Part>,
    checks: Checks,
    async_stmts: Vec<TokenStream>,
    collect_async_stmts_into_buffer: bool,
    context_override: Option<Context>,
    borrow_state: &'a mut BorrowState,
}

impl<'a> Generator<'a> {
    pub fn buffer_ident() -> Ident {
        Ident::new("__hypertext_buffer", Span::mixed_site())
    }

    fn new_closure(
        context: Context,
        flavour: NodeFlavour,
        borrow_state: &'a mut BorrowState,
    ) -> Self {
        Self::new_root_with_brace(context, Brace::default(), flavour, borrow_state)
    }

    fn new_root_with_brace(
        context: Context,
        brace_token: Brace,
        flavour: NodeFlavour,
        borrow_state: &'a mut BorrowState,
    ) -> Self {
        Self {
            context,
            flavour,
            brace_token,
            parts: Vec::new(),
            checks: Checks::new(),
            async_stmts: Vec::new(),
            collect_async_stmts_into_buffer: false,
            context_override: None,
            borrow_state,
        }
    }

    fn new_child_with_brace<'b>(
        &'b mut self,
        brace_token: Brace,
        flavour: NodeFlavour,
    ) -> Generator<'b> {
        Generator {
            context: self.context,
            flavour,
            brace_token,
            parts: Vec::new(),
            checks: Checks::new(),
            async_stmts: Vec::new(),
            collect_async_stmts_into_buffer: self.collect_async_stmts_into_buffer,
            context_override: self.context_override,
            borrow_state: &mut *self.borrow_state,
        }
    }

    fn finish(self) -> AnyBlock {
        let buffer_ident = Self::buffer_ident();
        let mut stmts = TokenStream::new();
        let mut parts = self.parts.into_iter();
        let mut size_estimate = 0;

        while let Some(part) = parts.next() {
            match part {
                Part::Static(lit) => {
                    let mut dynamic_stmt = None;
                    let static_parts = iter::once(lit)
                        .chain(parts.by_ref().map_while(|part| match part {
                            Part::Static(lit) => Some(lit),
                            Part::Dynamic(stmt) => {
                                dynamic_stmt = Some(stmt);
                                None
                            }
                        }))
                        .inspect(|static_part| {
                            size_estimate += static_part.value().len();
                        });

                    // XSS SAFETY: static parts are literal strings pushed by us
                    stmts.extend(quote! {
                        #buffer_ident.dangerously_get_string().push_str(::core::concat!(#(#static_parts),*));
                    });
                    stmts.extend(dynamic_stmt);
                }
                Part::Dynamic(stmt) => {
                    stmts.extend(stmt);
                }
            }
        }

        // XSS SAFETY: prealoc does not add any content
        let render = quote! {
            #buffer_ident.dangerously_get_string().reserve(#size_estimate);
            #stmts
        };

        let checks = self.checks;

        AnyBlock {
            brace_token: self.brace_token,
            stmts: quote! {
                #checks
                #render
            },
            async_stmts: self.async_stmts,
        }
    }

    pub fn block_with(
        &mut self,
        brace_token: Brace,
        f: impl for<'b> FnOnce(&mut Generator<'b>),
        append_async: bool,
    ) -> AnyBlock {
        self.block_with_flavour(brace_token, self.flavour, f, append_async)
    }

    pub fn block_with_flavour(
        &mut self,
        brace_token: Brace,
        flavour: NodeFlavour,
        f: impl for<'b> FnOnce(&mut Generator<'b>),
        append_async: bool,
    ) -> AnyBlock {
        let (mut child_checks, mut block) = {
            let mut g = self.new_child_with_brace(brace_token, flavour);

            f(&mut g);

            let child_checks = std::mem::replace(&mut g.checks, Checks::new());
            let block = g.finish();

            (child_checks, block)
        };

        self.checks.append(&mut child_checks);
        if append_async {
            self.async_stmts.append(&mut block.async_stmts);
        }

        block
    }

    pub fn push_with_flavour(
        &mut self,
        flavour: NodeFlavour,
        f: impl for<'b> FnOnce(&mut Generator<'b>),
    ) {
        let block = self.block_with_flavour(Brace::default(), flavour, f, true);
        self.push_stmt(block);
    }

    pub fn push_in_block(
        &mut self,
        brace_token: Brace,
        f: impl for<'b> FnOnce(&mut Generator<'b>),
    ) {
        let block = self.block_with(brace_token, f, true);
        self.push_stmt(block);
    }

    pub fn push_str(&mut self, s: &'static str) {
        self.push_spanned_str(s, Span::mixed_site());
    }

    pub fn push_spanned_str(&mut self, s: &'static str, span: Span) {
        self.parts.push(Part::Static(LitStr::new(s, span)));
    }

    pub fn push_escaped_literal(&mut self, context: Context, lit: &LitStr) {
        let value = lit.value();
        let effective_context = self.context_override.unwrap_or(context);
        let escaped_value = match effective_context {
            Context::Element => html_escape::encode_text(&value),
            Context::AttributeValue | Context::DatastarSource => {
                html_escape::encode_double_quoted_attribute(&value)
            }
            Context::ScriptSource => escape_script_source_literal(&value),
        };

        self.parts
            .push(Part::Static(LitStr::new(&escaped_value, lit.span())));
    }

    pub fn push_literals(&mut self, literals: Vec<LitStr>) {
        for lit in literals {
            self.parts.push(Part::Static(lit));
        }
    }

    pub fn push_literal(&mut self, lit: LitStr) {
        self.parts.push(Part::Static(lit));
    }

    #[cfg(feature = "pi-extension")]
    pub fn push_element_source_hint(&mut self, source: LitStr) {
        let buffer_ident = Self::buffer_ident();
        self.push_stmt(quote! {
            #[cfg(debug_assertions)]
            {
                ::cheers::__internal::pi_extension::__push_element_source_hint(
                    #buffer_ident,
                    #source,
                );
            }
        });
    }

    pub fn with_context_override<R>(
        &mut self,
        context: Context,
        f: impl FnOnce(&mut Self) -> R,
    ) -> R {
        let prev = self.context_override.replace(context);
        let result = f(self);
        self.context_override = prev;
        result
    }

    pub fn push_expr(&mut self, paren_token: Paren, context: Context, expr: impl ToTokens) {
        let effective_context = self.context_override.unwrap_or(context);
        let buffer_ident = Self::buffer_ident();
        let buffer_expr = match (self.context, effective_context) {
            (Context::Element, Context::Element)
            | (Context::AttributeValue, Context::AttributeValue)
            | (Context::DatastarSource, Context::DatastarSource)
            | (Context::ScriptSource, Context::ScriptSource) => {
                quote!(#buffer_ident)
            }
            (Context::Element, Context::AttributeValue) => {
                quote!(#buffer_ident.as_attribute_buffer())
            }
            (Context::Element, Context::DatastarSource) => {
                quote!(#buffer_ident.as_datastar_buffer())
            }
            (Context::Element, Context::ScriptSource) => {
                quote!(#buffer_ident.as_script_buffer())
            }
            (Context::AttributeValue, Context::DatastarSource) => {
                quote!(#buffer_ident.as_datastar_buffer())
            }
            (Context::AttributeValue, Context::ScriptSource) => unreachable!(),
            (Context::DatastarSource, Context::Element) => unreachable!(),
            (Context::DatastarSource, Context::AttributeValue) => {
                quote!(#buffer_ident.as_attribute_buffer())
            }
            (Context::DatastarSource, Context::ScriptSource) => unreachable!(),
            (Context::AttributeValue, Context::Element) => unreachable!(),
            (Context::ScriptSource, Context::Element)
            | (Context::ScriptSource, Context::AttributeValue)
            | (Context::ScriptSource, Context::DatastarSource) => unreachable!(),
        };

        let mut paren_expr = TokenStream::new();
        paren_token.surround(&mut paren_expr, |tokens| expr.to_tokens(tokens));
        let reference = quote_spanned!(paren_token.span=> &);
        self.push_stmt(quote! {
            ::cheers::prelude::Render::render_to(
                #reference #paren_expr,
                #buffer_expr
            );
        });
    }

    pub fn push_js_value_node(&mut self, node: &mut AttributeValueNode) {
        self.with_context_override(Context::DatastarSource, |g| g.push(node));
    }

    pub fn hoist_ref_expr(&mut self, paren_token: Paren, expr: impl ToTokens) -> Ident {
        self.borrow_state.hoist_ref_expr(paren_token, expr)
    }

    pub fn push_ref_expr(&mut self, paren_token: Paren, context: Context, expr: impl ToTokens) {
        let ref_ident = self.hoist_ref_expr(paren_token, expr);
        self.push_expr(Paren::default(), context, ref_ident);
    }

    pub fn push_async_stmt(&mut self, async_stmt: impl ToTokens) {
        let async_stmt = async_stmt.to_token_stream();
        if self.collect_async_stmts_into_buffer {
            let buffer_ident = Self::buffer_ident();
            let async_stmt = pinned_stream_tokens_expr(&async_stmt);
            self.push_stmt(quote! {
                ::cheers::__internal::async_streams::push(&mut *#buffer_ident, #async_stmt);
            });
        } else {
            self.async_stmts.push(async_stmt);
        }
    }

    pub fn with_async_stream_collection<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
        let prev = self.collect_async_stmts_into_buffer;
        self.collect_async_stmts_into_buffer = true;
        let result = f(self);
        self.collect_async_stmts_into_buffer = prev;
        result
    }

    pub fn push_stmt(&mut self, stmt: impl ToTokens) {
        self.parts.push(Part::Dynamic(stmt.to_token_stream()));
    }

    pub fn push_conditional(
        &mut self,
        cond: impl ToTokens,
        f: impl for<'b> FnOnce(&mut Generator<'b>),
    ) {
        let then_block = self.block_with(Brace::default(), f, true);
        self.push_stmt(quote! {
            if #cond #then_block
        });
    }

    pub fn push(&mut self, mut value: impl Generate) {
        value.generate(self);
    }

    pub fn record_element(&mut self, el_checks: ElementCheck) {
        self.checks.push_element(el_checks);
    }

    pub fn push_diagnostic(&mut self, diagnostic: impl ToTokens) {
        self.checks.push_diagnostic(diagnostic.to_token_stream());
    }

    pub const fn node_flavour(&self) -> NodeFlavour {
        self.flavour
    }

    pub fn push_all(&mut self, values: impl IntoIterator<Item = impl Generate>) {
        for value in values {
            self.push(value);
        }
    }
}

enum Part {
    Static(LitStr),
    Dynamic(TokenStream),
}

#[derive(Debug, Clone, Copy)]
pub enum Context {
    Element,
    AttributeValue,
    DatastarSource,
    ScriptSource,
}

impl Context {
    pub fn marker_type(self) -> TokenStream {
        let ident = match self {
            Self::Element => Ident::new("Element", Span::mixed_site()),
            Self::AttributeValue => Ident::new("AttributeValue", Span::mixed_site()),
            Self::DatastarSource => Ident::new("DatastarSource", Span::mixed_site()),
            Self::ScriptSource => Ident::new("ScriptSource", Span::mixed_site()),
        };

        quote!(::cheers::prelude::#ident)
    }
}

pub trait Generate {
    const CONTEXT: Context;
    fn generate(&mut self, g: &mut Generator<'_>);
}

impl<T: Generate> Generate for &mut T {
    const CONTEXT: Context = T::CONTEXT;

    fn generate(&mut self, g: &mut Generator<'_>) {
        (*self).generate(g);
    }
}

struct Checks {
    elements: Vec<ElementCheck>,
    recovered_errors: Vec<TokenStream>,
}

impl Checks {
    const fn new() -> Self {
        Self {
            elements: Vec::new(),
            recovered_errors: Vec::new(),
        }
    }

    fn append(&mut self, other: &mut Self) {
        self.elements.append(&mut other.elements);
        self.recovered_errors.append(&mut other.recovered_errors);
    }

    fn is_empty(&self) -> bool {
        self.elements.is_empty() && self.recovered_errors.is_empty()
    }

    fn push_element(&mut self, element: ElementCheck) {
        self.elements.push(element);
    }

    fn push_diagnostic(&mut self, diagnostic: TokenStream) {
        self.recovered_errors.push(diagnostic);
    }
}

impl ToTokens for Checks {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        if self.is_empty() {
            return;
        }

        for diagnostic in &self.recovered_errors {
            diagnostic.to_tokens(tokens);
        }

        let mut by_module: BTreeMap<ValidationModule, Vec<&ElementCheck>> = BTreeMap::new();
        for check in &self.elements {
            by_module.entry(check.module).or_default().push(check);
        }

        for (module, checks) in by_module {
            quote! {
                const _: fn() = || {
                    #[allow(unused_imports)]
                    use #module::*;

                    #[doc(hidden)]
                    /// Used by the `html!`, `svg!`, and `attribute!` macros to
                    /// trigger compile-time element
                    /// validation.
                    fn check_element<
                        K: ::cheers::validation::ElementKind
                    >(_: impl ::cheers::validation::Element<Kind = K>) {}

                    #(#checks)*
                };
            }
            .to_tokens(tokens);
        }
    }
}

pub struct ElementCheck {
    module: ValidationModule,
    ident: UnquotedName,
    kind: ElementKind,
    attributes: Vec<AttributeNameCheck>,
}

impl ElementCheck {
    pub fn new(
        el_name: &UnquotedName,
        element_kind: ElementKind,
        module: ValidationModule,
    ) -> Self {
        Self {
            module,
            ident: el_name.clone(),
            kind: element_kind,
            attributes: Vec::new(),
        }
    }

    pub fn push_attribute(&mut self, attr: AttributeNameCheck) {
        self.attributes.push(attr);
    }
}

impl ToTokens for ElementCheck {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let el = &self.ident;
        let kind = self.kind;

        let el_check = {
            quote! {
                check_element::<#kind>(#el);
            }
        };

        let attr_checks = self
            .attributes
            .iter()
            .map(|attr| attr.to_token_stream_with_el(el));

        quote! {
            #el_check
            #(#attr_checks)*
        }
        .to_tokens(tokens);
    }
}

#[derive(Debug, Clone, Copy)]
pub enum ElementKind {
    Normal,
    Void,
    Xml,
}

impl ToTokens for ElementKind {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        match self {
            Self::Normal => quote!(::cheers::validation::Normal),
            Self::Void => quote!(::cheers::validation::Void),
            Self::Xml => quote!(::cheers::validation::Xml),
        }
        .to_tokens(tokens);
    }
}

pub struct AttributeNameCheck {
    kind: AttributeNameCheckKind,
    ident: UnquotedName,
    data: bool,
    data_modifiers: Vec<UnquotedName>,
}

struct DataModifierNameCheck<'a>(&'a UnquotedName);

impl ToTokens for DataModifierNameCheck<'_> {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        if self.0 == &"self" {
            // `self` cannot be used as an item name, so the validation table stores it as
            // `self_` while rendering still emits the Datastar modifier name `self`.
            format_ident!("self_", span = self.0.span()).to_tokens(tokens);
        } else {
            self.0.to_tokens(tokens);
        }
    }
}

impl AttributeNameCheck {
    pub fn new(kind: AttributeNameCheckKind, ident: UnquotedName, data: bool) -> Self {
        Self {
            kind,
            ident,
            data,
            data_modifiers: Vec::new(),
        }
    }

    pub fn push_data_modifiers(&mut self, modifiers: Option<&DataModifiers>) {
        if let Some(modifiers) = modifiers {
            self.data_modifiers
                .extend(
                    modifiers
                        .modifiers
                        .iter()
                        .filter_map(|modifier| match &modifier.name {
                            DataModifierPart::Ident(ident) => Some(ident.clone()),
                            DataModifierPart::Literal(_) => None,
                        }),
                );
        }
    }

    fn data_modifier_checks(&self) -> TokenStream {
        if !self.data || self.data_modifiers.is_empty() {
            return TokenStream::new();
        }

        let plugin = match &self.kind {
            AttributeNameCheckKind::Normal => &self.ident,
            AttributeNameCheckKind::Namespace(namespace) => namespace,
        };
        let modifiers = self.data_modifiers.iter().map(DataModifierNameCheck);

        quote! {
            #(
                let _: ::cheers::validation::data::Modifier = ::cheers::validation::data::modifiers::#plugin::#modifiers;
            )*
        }
    }

    fn to_token_stream_with_el(&self, el: &UnquotedName) -> TokenStream {
        let data_modifier_checks = self.data_modifier_checks();

        match &self.kind {
            AttributeNameCheckKind::Namespace(namespace) => {
                let ident = &self.ident;

                if self.data {
                    quote! {
                        {
                            let _: ::cheers::validation::data::#namespace::Namespace = ::cheers::validation::data::#namespace::Namespace;
                            #[allow(unused_imports)]
                            use ::cheers::validation::data::#namespace::*;
                            let _: ::cheers::validation::Attribute = #ident;
                            #data_modifier_checks
                        }
                    }
                } else {
                    quote! {
                        let _: ::cheers::validation::#namespace::Namespace = <#el>::#namespace;
                        let _: ::cheers::validation::Attribute = ::cheers::validation::#namespace::#ident;
                    }
                }
            }
            AttributeNameCheckKind::Normal => {
                let ident = &self.ident;
                if self.data {
                    quote! {
                        let _: ::cheers::validation::Attribute = ::cheers::validation::data::#ident;
                        #data_modifier_checks
                    }
                } else {
                    quote! {
                        let _: ::cheers::validation::Attribute = <#el>::#ident;
                    }
                }
            }
        }
    }
}

pub enum AttributeNameCheckKind {
    Normal,
    Namespace(UnquotedName),
}

pub struct AnyBlock {
    pub brace_token: Brace,
    pub stmts: TokenStream,
    pub async_stmts: Vec<TokenStream>,
}

impl Parse for AnyBlock {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let content;

        Ok(Self {
            brace_token: braced!(content in input),
            stmts: content.parse()?,
            async_stmts: Vec::new(),
        })
    }
}

impl ToTokens for AnyBlock {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        self.brace_token.surround(tokens, |tokens| {
            self.stmts.to_tokens(tokens);
        });
    }
}