whisker-macros 0.2.2

Procedural macros for Whisker: #[whisker::main], 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
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
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
//! `render!` macro — compose-style, kwarg-only DSL.
//!
//! ```text
//! root      := node
//! node      := IDENT ( '(' kwargs ')' )? ( '{' children '}' )?
//! kwargs    := IDENT ':' expr ( ',' IDENT ':' expr )* ','?
//!            | IDENT                           # partial (mid-typing)
//! children  := node*
//! ```
//!
//! Each `node` is classified by its leading ident:
//!
//! - Built-in tag (`view`, `page`, `text`, `raw_text`,
//!   `scroll_view`) → lowered to a builder chain
//!   `::whisker::__tags::__<tag>_ctor().style(…).…__h()`.
//! - `Show` / `For` → lowered to the matching `whisker::show` /
//!   `whisker::for_each` helper.
//! - `children()` (lowercase ident + empty parens, no block) → lowered
//!   to `view::mount_children(&children)`. Mounts the surrounding
//!   `#[component]`'s `children: Children` prop at this position.
//!   Anywhere a regular node would go; can appear multiple times for
//!   multi-projection. See `mount_children` in `whisker-runtime`.
//! - Anything else → user `#[component]` invocation; lowered to
//!   `name(<Name>Props::builder().k(v)…build())`.
//!
//! ## Children-block restriction
//!
//! Every item in a `{ … }` children block MUST be node-shaped
//! (`IDENT(kwargs?) { … }?`). Bare string literals and bare
//! `{expr}` blocks are rejected with a hard parser error.
//!
//! Why: RA experiments (kept as integration tests in
//! `tests/ra_completion.rs`) showed that
//! rust-analyzer's input fixup gives up on children blocks that
//! contain anything other than `IDENT(name: value, …)` shapes at
//! their top level. With a bare `"hi"` or `{count}` present, the
//! sibling element's kwarg-position completion stops working — no
//! emission-side workaround helped. The fix is to forbid those
//! shapes at the DSL level so the block stays on RA's happy path.
//!
//! For text content, use a kwarg-styled element:
//!
//! ```ignore
//! render! {
//!     view(style: "...") {
//!         text(value: "Hello")
//!         text(value: format!("count: {}", c.get()))
//!     }
//! }
//! ```

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote, quote_spanned};
use syn::{
    braced,
    ext::IdentExt,
    parenthesized,
    parse::{Parse, ParseStream, Result},
    token, Expr, Ident, LitStr, Token,
};

pub fn expand(input: TokenStream) -> TokenStream {
    let tokens: TokenStream2 = input.into();
    match syn::parse2::<Root>(tokens) {
        Ok(root) => root.to_tokens().into(),
        Err(err) => {
            // Pair the compile_error with a same-typed placeholder
            // so the surrounding code (`let h: Element = render!
            // { … };`) keeps type-checking and diagnostics stay
            // confined to the actual syntax error. Same approach
            // leptos uses for its `view!` macro.
            let err_tokens = err.to_compile_error();
            quote! {
                {
                    #err_tokens
                    ::whisker::runtime::view::create_element(
                        ::whisker::ElementTag::View,
                    )
                }
            }
            .into()
        }
    }
}

/// Test-only hook for the unit tests at the bottom of this file.
#[cfg(test)]
fn expand_test(input: TokenStream2) -> TokenStream2 {
    let root: Root = syn::parse2(input).expect("test input must parse");
    root.to_tokens()
}

// ---- AST ----------------------------------------------------------------

struct Root {
    node: Node,
}

impl Parse for Root {
    fn parse(input: ParseStream) -> Result<Self> {
        Ok(Self {
            node: input.parse()?,
        })
    }
}

enum Node {
    Element(ElementNode),
    UserComponent(UserComponentNode),
    /// `children()` — the lone special-cased ident in the children
    /// grammar. Lowers to
    /// `::whisker::runtime::view::mount_children(&children)` so the
    /// surrounding `#[component]`'s `children: Children` prop gets
    /// realised at this position. See `mount_children` in
    /// `crates/whisker-runtime/src/view/into_view.rs` for the
    /// phantom-mount mechanics.
    ChildrenSlot {
        span: proc_macro2::Span,
    },
}

struct ElementNode {
    tag: Ident,
    kwargs: Vec<Kwarg>,
    children: Vec<Node>,
}

struct UserComponentNode {
    /// PascalCase ident the call site resolves to. `#[component]`
    /// emits a `pub use __<name>_inner::<fn> as <PascalCase>;`
    /// alias under this name; the snake_case fn itself lives
    /// inside the inner module and isn't reachable from outer
    /// scope, so the emission MUST go through this alias.
    alias_ident: Ident,
    kwargs: Vec<Kwarg>,
    children: Vec<Node>,
}

struct Kwarg {
    name: Ident,
    value: Expr,
    /// `true` when the user hasn't typed `:` + an expression yet
    /// (cursor sits at the end of the kwarg name). The builder-
    /// chain emitter routes these through `.#name(())` so RA's
    /// method completion can fire on the partial prefix.
    partial: bool,
}

impl Parse for Node {
    fn parse(input: ParseStream) -> Result<Self> {
        // Every node starts with an ident. Reject anything else at
        // this position with a targeted error message — that's the
        // only way to give a useful hint when the user writes bare
        // `"hi"` or `{ count }` as a child.
        if input.peek(LitStr) {
            let lit: LitStr = input.parse()?;
            return Err(syn::Error::new(
                lit.span(),
                "bare string literals are not allowed in render!; \
                 use `text(value: \"\")` to render text content",
            ));
        }
        if input.peek(token::Brace) {
            // Take the span from the brace itself for a clean
            // arrow in the diagnostic.
            let body;
            let _ = braced!(body in input);
            let _ = body; // discard contents — we're erroring out
            return Err(input.error(
                "bare `{expr}` blocks are not allowed in render!; \
                 use `text(value: <expr>)` to render dynamic text",
            ));
        }

        let tag: Ident = input.parse()?;

        // Special-case the `children()` slot before the regular
        // kwarg path runs. Shape requirements:
        //   - ident `children`
        //   - immediately followed by an EMPTY paren group `()`
        //   - no `{ … }` block after it
        // Anything else (`children(arg)`, `children { … }`, bare
        // `children`) falls through to the standard tag path, so a
        // user `#[component] fn children(…)` would still resolve
        // correctly via the snake_case → PascalCase route. The
        // empty-paren requirement keeps RA's "you typed `children` —
        // suggest completions" behaviour usable; the `()` is the
        // explicit signal "this is the slot, not an arbitrary ident".
        if tag == "children" && input.peek(token::Paren) {
            // Speculative parse of the paren body — we only commit
            // to the slot interpretation if the body is empty AND
            // no `{}` block follows.
            let fork = input.fork();
            let body;
            parenthesized!(body in fork);
            if body.is_empty() && !fork.peek(token::Brace) {
                // Consume the same tokens off the real input cursor
                // now that we've decided.
                let consume;
                parenthesized!(consume in input);
                debug_assert!(consume.is_empty());
                return Ok(Node::ChildrenSlot { span: tag.span() });
            }
            // Not a slot — fall through to the regular tag path.
            // The paren tokens are still on `input` for the
            // `parenthesized!` call below to consume.
        }

        let mut kwargs = Vec::new();
        if input.peek(token::Paren) {
            let body;
            parenthesized!(body in input);
            while !body.is_empty() {
                // `Ident::peek_any` / `Ident::parse_any` admits
                // raw-style identifiers AND Rust keywords. Required
                // for the `ref:` kwarg (the most natural call-site
                // name; `ref` itself is a Rust keyword). Plain
                // `body.peek(Ident)` would reject `ref` outright;
                // `peek_any` lets it through as an `Ident` whose text
                // is `"ref"`, and the `name_str == "ref"` branch below
                // routes it to the `.with_ref(...)` setter.
                if !body.peek(syn::Ident::peek_any) {
                    return Err(body.error(
                        "kwargs must be `name: expr` — positional arguments \
                         not allowed",
                    ));
                }
                let name: Ident = body.call(syn::Ident::parse_any)?;
                let (value, partial) = if body.peek(Token![:]) {
                    body.parse::<Token![:]>()?;
                    (body.parse::<Expr>()?, false)
                } else {
                    // Partial — synthesize `()` as a placeholder so
                    // the emitter can still place the method-name
                    // token at the user's source span.
                    let placeholder: Expr = syn::parse_quote_spanned!(name.span()=> ());
                    (placeholder, true)
                };
                kwargs.push(Kwarg {
                    name,
                    value,
                    partial,
                });
                if body.peek(Token![,]) {
                    body.parse::<Token![,]>()?;
                }
            }
        }

        let mut children = Vec::new();
        if input.peek(token::Brace) {
            let body;
            braced!(body in input);
            while !body.is_empty() {
                children.push(body.parse::<Node>()?);
            }
        }

        let name = tag.to_string();
        // Classification by casing + whitelist:
        //
        //   snake_case + in built-in whitelist  → Element (Lynx tag)
        //   PascalCase (anything)                → UserComponent
        //                                          (preferred: PascalCase
        //                                          alias from #[component])
        //   snake_case + not in whitelist        → UserComponent
        //                                          (back-compat path:
        //                                          fn name as-is, Props
        //                                          derived from snake_case)
        //
        // The PascalCase form is the canonical convention now (matches
        // React / Leptos / Solid). Snake_case stays parseable so:
        //   (1) mid-typing partials (`vie|`) don't blow up the macro
        //       — RA needs the expansion to succeed for completion,
        //   (2) older code calling snake_case names keeps compiling.
        //
        // Built-in control flow (`ForEach` / `Show`) is no longer
        // special-cased: those are `#[component]` functions in the
        // `whisker` crate (see `crates/whisker/src/control_flow.rs`)
        // and resolve through the UserComponent path just like a
        // user-implemented control flow.
        if is_builtin_tag(&name) {
            Ok(Node::Element(ElementNode {
                tag,
                kwargs,
                children,
            }))
        } else {
            // User component. Derive `alias_ident` (PascalCase —
            // the public re-exported name) and `props_ident`
            // (PascalCase + "Props") from whichever form the user
            // wrote. The snake_case fn itself stays inside the
            // inner module and we never reference it directly
            // from the lowering.
            let span = tag.span();
            let alias_str = if is_pascal_case(&name) {
                name.clone()
            } else {
                snake_to_pascal(&name)
            };
            let alias_ident = Ident::new(&alias_str, span);
            Ok(Node::UserComponent(UserComponentNode {
                alias_ident,
                kwargs,
                children,
            }))
        }
    }
}

/// `my_card` → `MyCard`. Snake-to-PascalCase for the back-compat
/// snake_case path of user components in `render!`.
fn snake_to_pascal(name: &str) -> String {
    let mut out = String::with_capacity(name.len());
    let mut upper_next = true;
    for c in name.chars() {
        if c == '_' {
            upper_next = true;
            continue;
        }
        if upper_next {
            for u in c.to_uppercase() {
                out.push(u);
            }
            upper_next = false;
        } else {
            out.push(c);
        }
    }
    out
}

/// Lowercase identifiers that lower to `view::create_element` calls
/// rather than user component invocations. Matches the `ElementTag`
/// enum + the C bridge's `whisker_bridge_create_element` switch.
fn is_builtin_tag(name: &str) -> bool {
    matches!(
        name,
        "page" | "view" | "text" | "raw_text" | "scroll_view" | "list" | "fragment"
    )
    // `list_item` is intentionally NOT exposed as a user-writable
    // tag. The `list` render-props builder auto-wraps every
    // `children(item)` result in a `<list-item>` for the Lynx
    // platform UI layer's UIComponent contract — there's no path
    // for user code to reach a list-item, so surfacing it would
    // only invite confusion. The `__list_item_ctor` builder is
    // kept in `__tags` as a `pub(crate)` runtime helper the list
    // builder calls directly.
}

/// `true` if `name`'s first character is ASCII uppercase. Used to
/// route PascalCase idents (user components / control flow) away
/// from the snake_case-only Element path.
fn is_pascal_case(name: &str) -> bool {
    name.chars().next().is_some_and(|c| c.is_ascii_uppercase())
}

// ---- Codegen ------------------------------------------------------------

impl Root {
    fn to_tokens(&self) -> TokenStream2 {
        self.node.to_tokens_returning_handle()
    }
}

impl Node {
    fn to_tokens_returning_handle(&self) -> TokenStream2 {
        match self {
            Node::Element(el) => el.to_tokens(),
            Node::UserComponent(u) => u.to_tokens(),
            // `children()` resolves the surrounding `#[component]`'s
            // `children: Children` prop by name. The body of a
            // `#[component]` fn always destructures `children` into
            // scope when the prop is declared, so this is a plain
            // local-ident reference — no closure capture, no `move`,
            // and (crucially) no `Rc::clone` either: `mount_children`
            // takes `&Children` so the outer `FnMut` body can re-run
            // (e.g. hot-reload remount) without `cannot move out`.
            Node::ChildrenSlot { span } => quote_spanned! {*span=>
                ::whisker::runtime::view::mount_children(&children)
            },
        }
    }

    /// Emit a `View`-shaped expression. Used by `Show` and
    /// `For`'s children-callback case; each child needs to be
    /// wrapped via `IntoView::into_view(…)` for the helper's
    /// signature.
    fn to_tokens_as_view(&self) -> TokenStream2 {
        let h = self.to_tokens_returning_handle();
        quote! {
            ::whisker::runtime::view::IntoView::into_view(#h)
        }
    }
}

impl ElementNode {
    /// Lower a built-in element to a builder chain on
    /// `::whisker::__tags::<tag>`. The inline-chain form
    /// (`__tags::__view_ctor().style(…).…__h()` with no intermediate
    /// `let __h = …; __h` binding) is load-bearing: a let-binding
    /// breaks RA's receiver-type threading and kills kwarg
    /// completion. See `tests/ra_completion.rs`.
    fn to_tokens(&self) -> TokenStream2 {
        let tag_ident = &self.tag;
        let tag_name = tag_ident.to_string();
        let tag_span = tag_ident.span();
        let ctor_ident = format_ident!("__{}_ctor", tag_ident, span = tag_span);
        // Inline the full `::whisker::__tags::__<tag>_ctor()` path
        // into the outer `quote!`s below. Storing it into an
        // intermediate TokenStream and interpolating captures span /
        // grouping info differently and breaks RA's kwarg completion.

        // One `.kwarg(value)` token group per attr, span-anchored
        // at the user's kwarg-name source position so RA's
        // method-name completion lands on the right token.
        let setter_calls: Vec<TokenStream2> = self
            .kwargs
            .iter()
            .filter_map(|kw| self.kwarg_to_setter(kw))
            .collect();

        // Every partial kwarg routes through the setter chain as a
        // method call — see the long comment in `kwarg_to_setter`.
        let ident_refs: Vec<TokenStream2> = Vec::new();
        let _ = tag_name;

        // Children: each child becomes a `.child({ inner_chain })`
        // method call on the builder.
        let child_calls: Vec<TokenStream2> = self
            .children
            .iter()
            .map(|c| {
                let inner = c.to_tokens_returning_handle();
                quote! { .child(#inner) }
            })
            .collect();

        // No children AND no ident-refs → bare expression form.
        // Keeps the chain on RA's happy path for partial-kwarg
        // completion.
        if child_calls.is_empty() && ident_refs.is_empty() {
            return quote! {
                {
                    use ::whisker::__tags::ElementBuilder as _;
                    ::whisker::__tags::#ctor_ident() #(#setter_calls)* .__h()
                }
            };
        }

        // Has children or ident-refs → still keep chain inline (no
        // `let __h = … ; __h` binding around it), but add the
        // ident-refs in a side block. The chain itself stays
        // a single expression so RA can thread its receiver type.
        let ident_refs_block = if ident_refs.is_empty() {
            quote! {}
        } else {
            quote! {
                #[allow(dead_code, unused_variables, path_statements)]
                {
                    #(#ident_refs)*
                }
            }
        };

        if ident_refs.is_empty() {
            quote! {
                {
                    use ::whisker::__tags::ElementBuilder as _;
                    ::whisker::__tags::#ctor_ident() #(#setter_calls)* #(#child_calls)* .__h()
                }
            }
        } else {
            quote! {
                {
                    use ::whisker::__tags::ElementBuilder as _;
                    #ident_refs_block
                    ::whisker::__tags::#ctor_ident() #(#setter_calls)* #(#child_calls)* .__h()
                }
            }
        }
    }

    /// Lower one kwarg to a `.method(value)` token group, or
    /// `None` if this kwarg is partial-with-no-method-match (the
    /// emitter handles those via ident-refs instead).
    fn kwarg_to_setter(&self, kw: &Kwarg) -> Option<TokenStream2> {
        let name = &kw.name;
        let value = &kw.value;
        let name_str = name.to_string();
        let span = name.span();
        let tag_name = self.tag.to_string();

        if name_str == "key" && tag_name != "list" {
            // `key:` on a direct element is a no-op (reconciliation
            // hint with no semantic effect outside keyed lists). The
            // `list` builder has its own typed `key` setter for the
            // keyed-list key extractor closure, so let it through.
            return None;
        }

        if kw.partial {
            // ALWAYS emit a method call for partial kwargs. RA
            // injects a sentinel suffix at the cursor during its
            // expansion-for-completion pass, so any prefix-match
            // heuristic (e.g. "only emit `.sty(())` if some builder
            // method starts with `sty`") sees the suffixed name and
            // returns false, breaking method-name completion.
            return Some(quote_spanned! {span=> .#name(()) });
        }

        let call = if is_known_attr_method(&tag_name, &name_str) {
            // Named builder attribute method (`style`, `class`, the
            // universal trait attrs, and per-tag ones like
            // `scroll_view::bounces`, `text::text_maxline`). The method
            // takes `impl Into<Signal<T>>` for its semantic `T` and
            // handles Static / Dynamic dispatch internally; the value
            // flows as-is and type inference picks the right `From`
            // (`From<T>` static / `From<ReadSignal<T>>` reactive) — so
            // `bounces: true` / `text_maxline: 3` /
            // `mode: ImageMode::AspectFit` all just work.
            quote_spanned! {span=> .#name(#value) }
        } else if name_str == "ref" {
            // `ref: <ElementRef>` on a built-in element → bind the ref
            // to this element so its UI methods are invokable after
            // mount. (`ref` is a keyword, so the builder method is
            // `bind_ref`.)
            quote_spanned! {span=> .bind_ref(#value) }
        } else if is_known_event_method(&name_str) {
            // Typed event helper on `ElementBuilder` — `.on_tap(f)`,
            // `.on_longpress(f)`, … — where `f` receives a typed
            // `TouchEvent` / `CustomEvent` / `AnimationEvent`. The
            // closure flows through unchanged; the builder method
            // fixes the event type.
            quote_spanned! {span=> .#name(#value) }
        } else if let Some(event) = strip_on_prefix(&name_str) {
            // Unknown event name → raw `WhiskerValue` escape hatch
            // (`.on("name", |e: WhiskerValue| …)`).
            let event_lit = LitStr::new(&event, span);
            quote_spanned! {span=> .on(#event_lit, #value) }
        } else {
            // Catch-all → `.attr("kebab-name", value)`. The builder's
            // `.attr` accepts `impl Into<Signal<T>>` like the named
            // attr methods; no closure wrapping here either.
            let kebab = name_str.replace('_', "-");
            let kebab_lit = LitStr::new(&kebab, span);
            quote_spanned! {span=>
                .attr(#kebab_lit, #value)
            }
        };
        Some(call)
    }
}

/// Kwargs that map to a **named** builder attribute method
/// (`.#name(value)`) rather than the catch-all `.attr("kebab", value)`.
/// Each method takes `impl Into<Signal<T>>` for its semantic `T`
/// (bool / number / String), so the value flows through unchanged and
/// type inference picks the right `From` — crucial for bool/number
/// attrs, which `.attr` (String-only) couldn't accept. Mirrors the
/// methods on `ElementBuilder` + the per-tag inherent impls in
/// `whisker::__tags`; tag-specific names only match their tag, so using
/// one on the wrong element is a clear "no method" error.
fn is_known_attr_method(tag: &str, attr: &str) -> bool {
    // Universal attributes (the `ElementBuilder` trait — any tag).
    let common = matches!(
        attr,
        "style"
            | "class"
            | "id"
            | "name"
            | "event_through"
            | "exposure_id"
            | "exposure_scene"
            | "exposure_area"
            | "accessibility_label"
            | "accessibility_trait"
            | "accessibility_element"
            | "accessibility_elements"
            | "accessibility_elements_hidden"
            | "accessibility_exclusive_focus"
            | "a11y_id"
            | "user_interaction_enabled"
            | "native_interaction_enabled"
            | "block_native_event"
            | "consume_slide_event"
            | "pan_intercept_direction"
            | "pan_intercept_scope"
            | "hit_slop"
            | "flatten"
    );
    if common {
        return true;
    }
    // Tag-specific inherent attributes.
    matches!(
        (tag, attr),
        ("raw_text", "text")
            | ("text", "value")
            | ("text", "text_maxline")
            | ("text", "text_selection")
            | ("text", "include_font_padding")
            | ("text", "tail_color_convert")
            | ("text", "text_single_line_vertical_align")
            | ("text", "custom_context_menu")
            | ("text", "custom_text_selection")
            | ("scroll_view", "scroll_orientation")
            | ("scroll_view", "bounces")
            | ("scroll_view", "enable_scroll")
            | ("scroll_view", "scroll_bar_enable")
            | ("scroll_view", "initial_scroll_offset")
            | ("scroll_view", "initial_scroll_to_index")
            | ("scroll_view", "upper_threshold")
            | ("scroll_view", "lower_threshold")
            | ("list", "list_type")
            | ("list", "column_count")
            | ("list", "span_count")
            | ("list", "vertical_orientation")
            // Render-props setters on `list` — type-stated, take
            // closure literals via `Into<EachFn<T>>` etc. The
            // typed-setter route is what makes the closure flow
            // through the right `Into` impl (the generic `attr`
            // fallback would try `Into<Signal<String>>`).
            | ("list", "each")
            | ("list", "key")
            | ("list", "children") // (`list_item` is no longer a user-writable tag; the
                                   // list builder owns the wrap. `item_key` is set by the
                                   // list's effect, not by author code.)
    )
}

/// Event kwargs that map to a **typed** `ElementBuilder::on_<event>`
/// method (the closure receives a typed `TouchEvent` /
/// `CustomEvent` / `AnimationEvent`). Any other `on_*` kwarg falls
/// through to the raw `.on("name", |e: WhiskerValue| …)` escape
/// hatch. Mirrors the `on_*` methods on the trait in
/// `whisker::__tags`.
fn is_known_event_method(name: &str) -> bool {
    // Bubble-phase bind variant for every typed event …
    let bind_variant = matches!(
        name,
        "on_tap"
            | "on_longpress"
            | "on_click"
            | "on_touchstart"
            | "on_touchmove"
            | "on_touchend"
            | "on_touchcancel"
            | "on_layoutchange"
            | "on_uiappear"
            | "on_uidisappear"
            | "on_animationstart"
            | "on_animationend"
            | "on_animationcancel"
            | "on_animationiteration"
            | "on_transitionstart"
            | "on_transitionend"
            | "on_transitioncancel"
            // Component-specific events (CustomEvent → bind only). These
            // are inherent methods on a single tag's builder (scroll_view
            // / text), so the macro emits `.on_scroll(f)` etc.;
            // using one on the wrong tag is a clear "no method" error.
            | "on_scroll"
            | "on_scrolltoupper"
            | "on_scrolltolower"
            | "on_scrollend"
            | "on_contentsizechanged"
            | "on_layout"
            | "on_selectionchange"
    );
    // … plus the catch / capture propagation variants for the touch
    // family (`on_tap_catch`, `on_capture_tap`, `on_capture_tap_catch`,
    // …). These map 1:1 to Lynx's `catchtap` / `capture-bindtap` /
    // `capture-catchtap` handler kinds. Mirrors the `on_*` methods on
    // `ElementBuilder` in `whisker::__tags`.
    let propagation_variant = matches!(
        name,
        "on_tap_catch"
            | "on_capture_tap"
            | "on_capture_tap_catch"
            | "on_longpress_catch"
            | "on_capture_longpress"
            | "on_capture_longpress_catch"
            | "on_click_catch"
            | "on_capture_click"
            | "on_capture_click_catch"
            | "on_touchstart_catch"
            | "on_capture_touchstart"
            | "on_capture_touchstart_catch"
            | "on_touchmove_catch"
            | "on_capture_touchmove"
            | "on_capture_touchmove_catch"
            | "on_touchend_catch"
            | "on_capture_touchend"
            | "on_capture_touchend_catch"
            | "on_touchcancel_catch"
            | "on_capture_touchcancel"
            | "on_capture_touchcancel_catch"
    );
    bind_variant || propagation_variant
}

// ---- User-component codegen ---------------------------------------------

impl UserComponentNode {
    fn to_tokens(&self) -> TokenStream2 {
        let fn_ident = &self.alias_ident;

        let setter_calls: Vec<TokenStream2> = self
            .kwargs
            .iter()
            .map(|kw| {
                let name = &kw.name;
                let name_str = name.to_string();
                let span = name.span();
                if kw.partial {
                    // Partial kwarg on a user component → emit
                    // `.name(())` so typed-builder's per-field
                    // setter shows up under RA's method completion.
                    quote_spanned! {span=> .#name(()) }
                } else if name_str == "ref" {
                    // `ref:` is the canonical call-site name for the
                    // implicit ElementRef prop. `ref` is a Rust
                    // keyword so the setter is exposed as
                    // `.with_ref(...)`; re-route here.
                    let value = &kw.value;
                    quote_spanned! {span=> .with_ref(#value) }
                } else {
                    let value = &kw.value;
                    quote_spanned! {span=> .#name(#value) }
                }
            })
            .collect();

        // `key` flows as a regular Props field — control-flow
        // components like `ForEach` are themselves `#[component]`s
        // and read it directly off `XxxProps`.

        let children_call = if self.children.is_empty() {
            quote! {}
        } else {
            let child_views: Vec<TokenStream2> = self
                .children
                .iter()
                .map(|c| c.to_tokens_as_view())
                .collect();
            let body = if child_views.len() == 1 {
                let only = &child_views[0];
                quote! { #only }
            } else {
                quote! {
                    ::whisker::runtime::view::View::Fragment(
                        ::std::vec![#(#child_views),*]
                    )
                }
            };
            quote! {
                .children(::std::rc::Rc::new(move || { #body }))
            }
        };

        // `#fn_ident::builder()` (not `#props_ident::builder()`): the
        // component name doubles as a TYPE alias to its Props struct (see
        // `#[component]`), so a single `use crate::Icon` is enough — no
        // separate `IconProps` import. The outer `#fn_ident(…)` resolves
        // to the callable (value namespace), the inner `#fn_ident::` to
        // the Props type (type namespace).
        quote! {
            #fn_ident(
                #fn_ident::builder()
                    #(#setter_calls)*
                    #children_call
                    .build()
            )
        }
    }
}

fn strip_on_prefix(name: &str) -> Option<String> {
    if let Some(rest) = name.strip_prefix("on_") {
        Some(rest.to_string())
    } else if let Some(rest) = name.strip_prefix("on") {
        if let Some(first) = rest.chars().next() {
            if first.is_uppercase() {
                let mut owned = first.to_lowercase().to_string();
                owned.push_str(&rest[first.len_utf8()..]);
                return Some(owned);
            }
        }
        None
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::{is_builtin_tag, snake_to_pascal, strip_on_prefix};
    use proc_macro2::TokenStream as TokenStream2;

    #[test]
    fn strips_snake_case() {
        assert_eq!(strip_on_prefix("on_tap"), Some("tap".into()));
    }

    #[test]
    fn strips_camel_case() {
        assert_eq!(strip_on_prefix("onTap"), Some("tap".into()));
    }

    #[test]
    fn rejects_non_event_prefixes() {
        assert_eq!(strip_on_prefix("tap"), None);
        assert_eq!(strip_on_prefix("ontap"), None);
    }

    #[test]
    fn builtin_tags_recognised() {
        for t in ["page", "view", "text", "raw_text", "scroll_view"] {
            assert!(is_builtin_tag(t));
        }
    }

    #[test]
    fn non_builtin_lowercase_is_not_builtin() {
        for t in ["card", "my_component", "tab_item", "header"] {
            assert!(!is_builtin_tag(t));
        }
    }

    #[test]
    fn snake_to_pascal_basic() {
        assert_eq!(snake_to_pascal("my_card"), "MyCard");
        assert_eq!(snake_to_pascal("card"), "Card");
        assert_eq!(snake_to_pascal("tab_item"), "TabItem");
    }

    // ---- Compose-syntax parser & emission --------------------------------

    #[test]
    fn view_emission_uses_builder_chain() {
        let input: TokenStream2 = quote::quote! { view(style: "x") };
        let output = super::expand_test(input).to_string();
        assert!(
            output.contains("__view_ctor"),
            "view emission must call `__view_ctor()`; output was: {output}"
        );
        assert!(
            output.contains(". style"),
            "view emission must call `.style(value)`; output was: {output}"
        );
        assert!(
            output.contains(". __h ()"),
            "builder chain must finalise with `.__h()`; output was: {output}"
        );
    }

    #[test]
    fn ref_kwarg_on_builtin_routes_to_bind_ref() {
        // `ref:` on a built-in element binds an ElementRef to the
        // element (vs the catch-all `.attr("ref", …)`), so its UI
        // methods (bounding_client_rect, …) are invokable after mount.
        let input: TokenStream2 = quote::quote! { view(ref: my_ref) };
        let output = super::expand_test(input).to_string();
        assert!(
            output.contains(". bind_ref"),
            "ref: on a built-in must emit `.bind_ref(value)`; output was: {output}"
        );
        assert!(
            !output.contains("\"ref\""),
            "ref: must NOT fall through to `.attr(\"ref\", …)`; output was: {output}"
        );
    }

    #[test]
    fn no_children_emits_bare_chain_expression() {
        // No-children case must stay a bare chain expression — a
        // `let __h = …; __h` wrapper breaks RA's kwarg completion.
        let input: TokenStream2 = quote::quote! { view(style: "x") };
        let output = super::expand_test(input).to_string();
        assert!(
            !output.contains("let __h"),
            "no-children emission must NOT use `let __h = …; __h` binding; \
             output was: {output}"
        );
    }

    #[test]
    fn partial_kwarg_emits_method_call_for_method_prefix() {
        let input: TokenStream2 = quote::quote! { view(sty) };
        let output = super::expand_test(input).to_string();
        eprintln!("EMISSION: {output}");
        assert!(
            output.contains(". sty"),
            "partial kwarg matching method prefix must emit `.sty(())`; \
             output was: {output}"
        );
    }

    #[test]
    fn every_partial_kwarg_emits_method_call() {
        // All partial kwargs route through `.name(())` — even
        // prefixes that don't match any builder method. RA's
        // sentinel-suffix injection during completion makes any
        // "does this prefix match a method" heuristic unreliable.
        let input: TokenStream2 = quote::quote! { view(v) };
        let output = super::expand_test(input).to_string();
        assert!(
            output.contains(". v ("),
            "non-method-matching partial should still emit `.v(())`; \
             output was: {output}"
        );
        assert!(
            !output.contains("let _ = v"),
            "ident-ref side block was dropped — no `let _ = v;` expected; \
             output was: {output}"
        );
    }

    #[test]
    fn bare_string_literal_child_is_rejected() {
        let input: TokenStream2 = quote::quote! { view { "hi" } };
        let result = syn::parse2::<super::Root>(input);
        match result {
            Err(e) => assert!(
                e.to_string().contains("string literals are not allowed"),
                "expected hint about `text(value: \"\")`; got: {e}"
            ),
            Ok(_) => panic!("bare LitStr child should be a parse error"),
        }
    }

    #[test]
    fn bare_brace_expr_child_is_rejected() {
        let input: TokenStream2 = quote::quote! { view { { count } } };
        let result = syn::parse2::<super::Root>(input);
        match result {
            Err(e) => assert!(
                e.to_string().contains("`{expr}` blocks are not allowed")
                    || e.to_string().contains("text(value:"),
                "expected hint about `text(value: <expr>)`; got: {e}"
            ),
            Ok(_) => panic!("bare `{{expr}}` child should be a parse error"),
        }
    }

    #[test]
    fn positional_arg_is_rejected() {
        let input: TokenStream2 = quote::quote! { text("hi") };
        let result = syn::parse2::<super::Root>(input);
        assert!(result.is_err(), "positional arg should be a parse error");
    }

    #[test]
    fn text_value_kwarg_lowers_to_value_method() {
        let input: TokenStream2 = quote::quote! { text(value: "Hello") };
        let output = super::expand_test(input).to_string();
        assert!(
            output.contains("__text_ctor"),
            "text must use the text builder; output was: {output}"
        );
        assert!(
            output.contains(". value"),
            "text(value: …) must lower to `.value(…)`; output was: {output}"
        );
    }

    #[test]
    fn user_component_does_not_use_builtin_tags_module() {
        let input: TokenStream2 = quote::quote! { MyCard(title: "x") };
        let output = super::expand_test(input).to_string();
        assert!(
            !output.contains("__tags"),
            "user components must not touch the built-in tags module; \
             output was: {output}"
        );
        // Emission goes through the PascalCase alias the `#[component]`
        // macro emits — both the value-namespace fn AND the
        // type-namespace `type MyCard = MyCardProps` alias share that
        // name, so `MyCard::builder()` resolves without a separate
        // `MyCardProps` import (issue #1). The `…Props` name must NOT
        // appear in the emission.
        assert!(
            output.contains("MyCard (MyCard :: builder ()") && !output.contains("MyCardProps"),
            "user component must lower to `MyCard(MyCard::builder()…)` \
             — the PascalCase alias is the public call surface and the \
             `…Props` name should not leak into the call site; \
             output was: {output}",
        );
    }

    #[test]
    fn snake_case_non_builtin_is_back_compat_user_component() {
        // Snake-case still parses (so mid-typing partials like `my_c|`
        // don't blow up the macro), but the emission still goes
        // through the PascalCase alias derived from the input.
        let input: TokenStream2 = quote::quote! { my_card(title: "x") };
        let output = super::expand_test(input).to_string();
        assert!(
            output.contains("MyCard (MyCard :: builder ()") && !output.contains("MyCardProps"),
            "snake_case input should lower to the PascalCase alias call site; \
             output was: {output}",
        );
    }

    #[test]
    fn children_block_emits_child_method() {
        let input: TokenStream2 = quote::quote! {
            view(style: "x") {
                view(class: "y")
            }
        };
        let output = super::expand_test(input).to_string();
        assert!(
            output.contains(". child"),
            "children must lower to `.child({{…}})`; output was: {output}"
        );
    }

    #[test]
    fn nested_children_use_inline_chain() {
        // Verify the chain stays a single expression even with
        // children — no `let __h = …; __h` wrapper.
        let input: TokenStream2 = quote::quote! {
            view(style: "outer") {
                view(class: "inner")
            }
        };
        let output = super::expand_test(input).to_string();
        assert!(
            !output.contains("let __h"),
            "children-bearing emission should stay inline-chain; \
             output was: {output}"
        );
    }

    // ---- `children()` slot ---------------------------------------------

    #[test]
    fn children_slot_lowers_to_mount_children() {
        // `children()` inside a `render!` body should resolve to
        // `view::mount_children(&children)`, where `children` is the
        // surrounding `#[component]`'s `children: Children` prop in
        // local scope.
        let input: TokenStream2 = quote::quote! {
            view(style: "x") {
                children()
            }
        };
        let output = super::expand_test(input).to_string();
        assert!(
            output.contains("mount_children"),
            "children() must lower to mount_children(&children); \
             output was: {output}"
        );
        assert!(
            output.contains("& children"),
            "children() must borrow (not move) the `children` ident; \
             output was: {output}"
        );
    }

    #[test]
    fn children_slot_can_appear_multiple_times() {
        // Multi-projection: `children()` appearing N times produces
        // N independent `mount_children(&children)` calls. The Rc
        // is borrowed, never moved, so all N calls succeed.
        let input: TokenStream2 = quote::quote! {
            view(style: "x") {
                children()
                view(class: "sep")
                children()
            }
        };
        let output = super::expand_test(input).to_string();
        let mounts = output.matches("mount_children").count();
        assert_eq!(
            mounts, 2,
            "expected 2 mount_children calls, got {mounts}; \
             output was: {output}"
        );
    }

    #[test]
    fn children_slot_sits_inside_child_method_call() {
        // The slot lowers to a `.child(mount_children(&children))`
        // call on the parent builder — i.e. it goes through the
        // exact same shape as any other child node, so the parent's
        // builder chain stays a single expression.
        let input: TokenStream2 = quote::quote! {
            view(style: "x") {
                children()
            }
        };
        let output = super::expand_test(input).to_string();
        assert!(
            output.contains(". child") && output.contains("mount_children"),
            "children() must be wrapped in `.child(mount_children(&children))`; \
             output was: {output}"
        );
        assert!(
            !output.contains("let __h"),
            "children-slot-bearing emission should stay inline-chain; \
             output was: {output}"
        );
    }

    #[test]
    fn children_with_args_is_not_a_slot() {
        // `children(arg: x)` is NOT the slot — falls through to the
        // regular user-component path so a user fn named `children`
        // with props still resolves correctly. (Esoteric, but the
        // grammar must not steal the identifier.)
        let input: TokenStream2 = quote::quote! {
            children(title: "x")
        };
        let output = super::expand_test(input).to_string();
        assert!(
            output.contains("Children (Children :: builder ()"),
            "children(arg: x) should route through the user-component \
             path → Children::builder(); output was: {output}"
        );
        assert!(
            !output.contains("mount_children"),
            "children(arg: …) must NOT lower to mount_children; \
             output was: {output}"
        );
    }

    #[test]
    fn children_with_block_is_not_a_slot() {
        // `children() { … }` is also NOT the slot — that's a tag
        // invocation with empty kwargs and a children block. The
        // user is using a component literally named `children`; let
        // the regular path handle it.
        let input: TokenStream2 = quote::quote! {
            children() {
                text(value: "y")
            }
        };
        let output = super::expand_test(input).to_string();
        assert!(
            !output.contains("mount_children"),
            "children() with a `{{ … }}` block must not be a slot; \
             output was: {output}"
        );
    }
}