euv-macros 0.18.26

Procedural macros for the euv UI framework, providing the macro and attribute for declarative UI composition.
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
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
use super::*;

/// Parses a Rust expression from the parse stream, stopping before a top-level brace.
///
/// This is used for inline `if` conditions, `match` scrutinees, and `for` iterables
/// where a plain identifier followed by `{` would otherwise be misinterpreted as a
/// struct literal expression (e.g., `if has_subtitle { ... }` would try to parse
/// `has_subtitle { ... }` as `ExprStruct`).
///
/// Tokens are collected until a top-level `Brace` delimiter is encountered, then
/// parsed as an `Expr`. Nested groups (parens, brackets) are consumed as single
/// `TokenTree` units, so braces inside them do not terminate the collection.
///
/// # Arguments
///
/// - `ParseStream` - The parse stream positioned at the start of the expression.
///
/// # Returns
///
/// - `syn::Result<Expr>` - The parsed expression, or a syntax error.
pub(crate) fn parse_expr_until_brace(input: ParseStream) -> syn::Result<Expr> {
    let mut tokens: proc_macro2::TokenStream = proc_macro2::TokenStream::new();
    while !input.peek(Brace) {
        let token_tree: proc_macro2::TokenTree = input.parse()?;
        tokens.extend([token_tree]);
    }
    syn::parse2(tokens)
}

/// Determines whether the macro should automatically append `.get()` to an expression
/// inside a reactive `{}` position (e.g. `if { signal }`, `match { signal }`,
/// `for x in { signal }`, `{ signal }` DOM child).
///
/// Returns `true` only for plain single-segment identifier paths such as `signal`
/// or `value`. Chained expressions like `state.field`, `signal.iter()`, or
/// `signal == X` are NOT auto-unwrapped — the user must call `.get()` explicitly
/// in those cases (e.g., `state.field.get()`, `signal.get().iter()`,
/// `signal.get() == X`).
///
/// This is a conservative heuristic: the macro only adds `.get()` where the
/// expression is unambiguously a single identifier, which is the most common
/// case for signal references. Other expression kinds pass through unchanged
/// so that non-signal expressions (literals, function calls, etc.) keep working.
///
/// # Arguments
///
/// - `&Expr` - The expression to inspect.
///
/// # Returns
///
/// - `bool` - `true` if the expression is a single-segment path suitable for
///   automatic `.get()` unwrapping.
pub(crate) fn should_auto_get(expr: &Expr) -> bool {
    matches!(
        expr,
        Expr::Path(expr_path)
            if expr_path.qself.is_none()
                && expr_path.path.leading_colon.is_none()
                && expr_path.path.segments.len() == 1
                && matches!(
                    expr_path.path.segments[0].arguments,
                    syn::PathArguments::None
                )
    )
}

/// Wraps an expression with `.get()` when it is a single-segment identifier path,
/// otherwise returns the expression unchanged.
///
/// When `enabled` is `false`, the expression is returned as-is (used for inline
/// `if`/`match`/`for` whose conditions were NOT written inside `{}`).
///
/// # Arguments
///
/// - `&Expr` - The expression to optionally unwrap.
/// - `bool` - Whether the wrapping should be applied.
///
/// # Returns
///
/// - `proc_macro2::TokenStream` - The wrapped or unchanged expression tokens.
pub(crate) fn auto_get_expr_tokens(expr: &Expr, enabled: bool) -> proc_macro2::TokenStream {
    if enabled && should_auto_get(expr) {
        quote! { #expr.get() }
    } else {
        quote! { #expr }
    }
}

/// Checks whether the next tokens after the current position form a `::` path separator.
///
/// This is used to distinguish between a single `:` (attribute key-value separator)
/// and `::` (Rust path separator like `Enum::Variant`). When an `Ident` is followed
/// by `::`, it should be treated as the start of a path expression rather than an
/// attribute key.
///
/// # Arguments
///
/// - `&ParseStream` - The parse stream to check.
///
/// # Returns
///
/// - `bool` - `true` if the next two tokens after the current position are `::`.
pub(crate) fn is_double_colon(content: ParseStream) -> bool {
    let forked: ParseBuffer<'_> = content.fork();
    let _: Ident = match forked.parse() {
        Ok(ident) => ident,
        Err(_) => return false,
    };
    forked.peek(Token![::])
}

/// Sets the user-defined component registry for the current thread.
///
/// # Arguments
///
/// - `HashMap<String, ComponentInfo>` - The map of function names to component metadata.
pub(crate) fn set_user_fn_names(names: HashMap<String, ComponentInfo>) {
    unsafe {
        let pointer: *mut MaybeUninit<HashMap<String, ComponentInfo>> = &raw mut USER_FN_NAMES;
        (*pointer).write(names);
    }
}

/// Invokes `f` with a borrow of the loaded component registry, returning `f`'s
/// result without cloning the registry.
///
/// This is the preferred accessor for render-time callers such as
/// `HtmlDynamicTag::to_tokens`.
///
/// The registry lives in `static` storage for the duration of the
/// `html!` expansion, so the returned reference is valid for as long as
/// the borrow on `with_loaded_component_registry` lasts. The closure
/// must not outlive its own call frame.
///
/// # Arguments
///
/// - `F` - The closure to invoke with the borrowed registry. Any return
///   value is forwarded back to the caller.
///
/// # Returns
///
/// - `R` - Whatever `f` returns.
pub(crate) fn with_loaded_component_registry<F, R>(f: F) -> R
where
    F: FnOnce(&HashMap<String, ComponentInfo>) -> R,
{
    unsafe {
        let pointer: *const MaybeUninit<HashMap<String, ComponentInfo>> = &raw const USER_FN_NAMES;
        f((*pointer).assume_init_ref())
    }
}

/// Checks whether a given name corresponds to a user-defined component function.
///
/// # Arguments
///
/// - `&str` - The name to check against the stored component registry.
///
/// # Returns
///
/// - `bool` - `true` if the name exists in the component registry, `false` otherwise.
pub(crate) fn is_user_fn(name: &str) -> bool {
    unsafe {
        let pointer: *const MaybeUninit<HashMap<String, ComponentInfo>> = &raw const USER_FN_NAMES;
        (*pointer).assume_init_ref().contains_key(name)
    }
}

/// Returns the Props type name for a given component function name.
///
/// # Arguments
///
/// - `&str` - The component function name.
///
/// # Returns
///
/// - `Option<&'static str>` - The Props type name if found.
pub(crate) fn get_user_fn_props_type(name: &str) -> Option<&'static str> {
    unsafe {
        let pointer: *const MaybeUninit<HashMap<String, ComponentInfo>> = &raw const USER_FN_NAMES;
        (*pointer)
            .assume_init_ref()
            .get(name)
            .map(|info: &ComponentInfo| info.get_props_type().as_str())
    }
}

/// Returns the props field names for a given component function name.
///
/// Used to determine whether a standalone identifier inside a component body
/// should be treated as an attribute shorthand (e.g., `panel_open` → `panel_open: panel_open`).
///
/// # Arguments
///
/// - `&str` - The component function name.
///
/// # Returns
///
/// - `Option<&'static Vec<String>>` - The list of props field names if the component is found.
pub(crate) fn get_user_fn_props_fields(name: &str) -> Option<&'static Vec<String>> {
    unsafe {
        let pointer: *const MaybeUninit<HashMap<String, ComponentInfo>> = &raw const USER_FN_NAMES;
        (*pointer)
            .assume_init_ref()
            .get(name)
            .map(|info: &ComponentInfo| info.get_props_fields())
    }
}

/// Returns the props field type map for a given component function name.
///
/// Maps field name → type string (e.g., `"children"` → `"VirtualNode"`).
///
/// # Arguments
///
/// - `&str` - The component function name.
///
/// # Returns
///
/// - `Option<&'static HashMap<String, String>>` - The field type map if the component is found.
pub(crate) fn get_user_fn_props_field_types(
    name: &str,
) -> Option<&'static HashMap<String, String>> {
    unsafe {
        let pointer: *const MaybeUninit<HashMap<String, ComponentInfo>> = &raw const USER_FN_NAMES;
        (*pointer)
            .assume_init_ref()
            .get(name)
            .map(|info: &ComponentInfo| info.get_props_field_types())
    }
}

/// Parses the input tokens into a euv VNode expression.
///
/// Supports zero, one, or multiple root-level HTML nodes:
/// - `html! {}` → `VirtualNode::Empty`
/// - `html! { div { ... } }` → single `VirtualNode`
/// - `html! { div { ... } span { ... } }` → `VirtualNode::Fragment(vec![...])`
///
/// Before parsing, reads the component registry file to discover which
/// function names are marked as components via `#[component]`. This allows
/// the `html!` macro to distinguish between component function calls and
/// native HTML element tags.
///
/// # Arguments
///
/// - `TokenStream` - The raw token stream representing HTML markup.
///
/// # Returns
///
/// - `TokenStream` - The generated token stream constructing the corresponding virtual node.
pub(crate) fn parse_html(input: TokenStream) -> TokenStream {
    let fn_names: HashMap<String, ComponentInfo> = load_component_registry();
    set_user_fn_names(fn_names);
    let tokens: proc_macro2::TokenStream = match parse::<HtmlRoot>(input) {
        Ok(nodes) => nodes.into_token_stream(),
        Err(error) => return error.to_compile_error().into(),
    };
    TokenStream::from(tokens)
}

/// Loads the component registry by scanning the project source for `#[component]` annotations.
///
/// Uses a file-based cache in the `OUT_DIR` directory to avoid re-scanning and
/// re-parsing all source files on every `html!` macro invocation. The cache is
/// invalidated when the set of source files or their modification times change.
///
/// Recursively scans `.rs` files under `CARGO_MANIFEST_DIR/src/` and extracts
/// function names and their Props type names from annotated functions.
///
/// # Returns
///
/// - `HashMap<String, ComponentInfo>` - Map of component function names to component metadata.
pub(crate) fn load_component_registry() -> HashMap<String, ComponentInfo> {
    let Ok(manifest_dir) = env::var(CARGO_MANIFEST_DIR) else {
        return HashMap::new();
    };
    let mut rust_source_files: Vec<PathBuf> = Vec::new();
    let src_dir: PathBuf = PathBuf::from(&manifest_dir).join(SRC_DIR);
    collect_rs_files(&src_dir, &mut rust_source_files);
    let dep_src_dirs: Vec<PathBuf> = collect_local_dep_src_dirs(&manifest_dir);
    for dep_src_dir in dep_src_dirs {
        collect_rs_files(&dep_src_dir, &mut rust_source_files);
    }
    let fingerprint: String = compute_fingerprint(&rust_source_files);
    // `OUT_DIR` only exists for crates with a build script; without a cache
    // every `html!` invocation would rescan and reparse all sources. Fall back
    // to a per-manifest directory under the system temp dir so crates without
    // a build script are cached too.
    let cache_dir: PathBuf =
        env::var(ENV_OUT_DIR)
            .map(PathBuf::from)
            .unwrap_or_else(|_: VarError| {
                let mut hasher: DefaultHasher = DefaultHasher::new();
                Hash::hash(&manifest_dir, &mut hasher);
                let hash: u64 = Hasher::finish(&hasher);
                env::temp_dir().join(format!("euv_registry_{hash:x}"))
            });
    let _: io::Result<()> = create_dir_all(&cache_dir);
    let cache_path: PathBuf = cache_dir.join(REGISTRY_CACHE_FILE_NAME);
    if let Some(cached) = try_load_cache(&cache_path, &fingerprint) {
        return cached;
    }
    let registry: HashMap<String, ComponentInfo> = build_registry_from_files(&rust_source_files);
    try_save_cache(&cache_path, &fingerprint, &registry);
    registry
}

/// Computes a fingerprint string from the sorted list of source file paths
/// and their modification timestamps. Used to determine whether the cache
/// is still valid or needs to be rebuilt.
///
/// # Arguments
///
/// - `&[PathBuf]` - The sorted list of source file paths.
///
/// # Returns
///
/// - `String` - The computed fingerprint string.
fn compute_fingerprint(files: &[PathBuf]) -> String {
    // Each file contributes roughly `path.len() + 24` bytes to the
    // fingerprint (the path's `to_string_lossy()` plus a `;` delimiter
    // and the millisecond timestamp plus its own `;`). Pre-sizing the
    // buffer avoids the ~O(N) reallocations that the default-growth
    // path incurs while scanning a workspace's full `src/` tree.
    const APPROX_BYTES_PER_FILE: usize = 96;
    let mut sorted_files: Vec<&PathBuf> = files.iter().collect();
    sorted_files.sort();
    let mut fingerprint: String = String::with_capacity(sorted_files.len() * APPROX_BYTES_PER_FILE);
    for path in sorted_files {
        fingerprint.push_str(&path.to_string_lossy());
        fingerprint.push(CHAR_SEMICOLON);
        if let Ok(metadata) = metadata(path)
            && let Ok(modified) = metadata.modified()
            && let Ok(duration) = modified.duration_since(UNIX_EPOCH)
        {
            // `u128::from(duration.as_millis())` is at most 13 decimal
            // digits; writing into the String directly via `write!`
            // avoids the intermediate `String` allocation that
            // `as_millis().to_string()` performs before pushing onto
            // the parent String.
            let _: fmt::Result = write!(&mut fingerprint, "{};", duration.as_millis());
        } else {
            fingerprint.push(CHAR_SEMICOLON);
        }
    }
    fingerprint
}

/// Attempts to load a cached component registry from the given cache path.
///
/// Returns `Some(registry)` if the cache exists and the stored fingerprint
/// matches the current fingerprint, indicating the cache is still valid.
/// Returns `None` if the cache does not exist, cannot be read, or is stale.
///
/// # Arguments
///
/// - `&PathBuf` - The path to the cache file.
/// - `&str` - The current fingerprint to validate against.
///
/// # Returns
///
/// - `Option<HashMap<String, ComponentInfo>>` - The cached registry if valid, or `None`.
fn try_load_cache(
    cache_path: &PathBuf,
    current_fingerprint: &str,
) -> Option<HashMap<String, ComponentInfo>> {
    let content: String = read_to_string(cache_path).ok()?;
    let (stored_fingerprint, data) = content.split_once(CHAR_NEWLINE)?;
    if stored_fingerprint != current_fingerprint {
        return None;
    }
    serde_json::from_str(data).ok()
}

/// Attempts to save the component registry to the given cache path,
/// along with the current fingerprint for future validation.
///
/// Silently ignores errors since caching is optional.
///
/// # Arguments
///
/// - `&PathBuf` - The path to the cache file.
/// - `&str` - The current fingerprint string.
/// - `&HashMap<String, ComponentInfo>` - The registry to cache.
fn try_save_cache(
    cache_path: &PathBuf,
    fingerprint: &str,
    registry: &HashMap<String, ComponentInfo>,
) {
    if let Ok(data) = serde_json::to_string(registry) {
        let content: String = format!("{fingerprint}{CHAR_NEWLINE}{data}");
        let _: io::Result<()> = write(cache_path, content);
    }
}

/// Collects the `src/` directories of local path dependencies from `Cargo.toml`.
///
/// Parses the `Cargo.toml` at the given manifest directory and extracts
/// all dependency entries that specify a `path` field pointing to a local
/// directory, or reference a workspace dependency. Returns the `src/` subdirectory
/// of each such dependency so that the component registry scanner can also
/// discover `#[component]` functions defined in local dependency crates.
///
/// # Arguments
///
/// - `&str` - The `CARGO_MANIFEST_DIR` path containing the `Cargo.toml`.
///
/// # Returns
///
/// - `Vec<PathBuf>` - A list of `src/` directory paths for local path dependencies.
fn collect_local_dep_src_dirs(manifest_dir: &str) -> Vec<PathBuf> {
    let cargo_toml_path: PathBuf = PathBuf::from(manifest_dir).join(CARGO_TOML);
    let Ok(content) = read_to_string(&cargo_toml_path) else {
        return Vec::new();
    };
    let Ok(manifest) = toml::from_str::<toml::Value>(&content) else {
        return Vec::new();
    };
    let mut dep_dirs: Vec<PathBuf> = Vec::new();
    let mut registry_dep_names: Vec<String> = Vec::new();
    let manifest_dir_path: PathBuf = PathBuf::from(manifest_dir);
    let workspace_root: PathBuf = find_workspace_root(manifest_dir);
    let workspace_toml: Option<toml::Value> = if workspace_root != manifest_dir_path {
        read_to_string(workspace_root.join(CARGO_TOML))
            .ok()
            .and_then(|toml_content: String| toml::from_str::<toml::Value>(&toml_content).ok())
    } else {
        None
    };
    for section_key in [DEPENDENCIES, WORKSPACE_DEPENDENCIES] {
        let Some(deps) = manifest
            .get(section_key)
            .and_then(|table_value: &toml::Value| table_value.as_table())
        else {
            continue;
        };
        for (name, value) in deps {
            let path_str: Option<&str> = if let Some(table) = value.as_table() {
                if table
                    .get(WORKSPACE_KEY)
                    .and_then(|workspace_flag: &toml::Value| workspace_flag.as_bool())
                    == Some(true)
                {
                    workspace_toml
                        .as_ref()
                        .and_then(|workspace_manifest: &toml::Value| {
                            workspace_manifest.get(WORKSPACE_KEY)
                        })
                        .and_then(|workspace_table: &toml::Value| workspace_table.get(DEPENDENCIES))
                        .and_then(|deps_table: &toml::Value| deps_table.get(name))
                        .and_then(|dep_entry: &toml::Value| dep_entry.as_table())
                        .and_then(|dep_table: &toml::Table| dep_table.get(PATH_KEY))
                        .and_then(|path_value: &toml::Value| path_value.as_str())
                } else {
                    table
                        .get(PATH_KEY)
                        .and_then(|path_value: &toml::Value| path_value.as_str())
                }
            } else {
                None
            };
            if let Some(path_str) = path_str {
                let path: PathBuf = PathBuf::from(path_str);
                let dep_dir: PathBuf = if path.is_absolute() {
                    path.join(SRC_DIR)
                } else if workspace_root != manifest_dir_path {
                    workspace_root.join(path_str).join(SRC_DIR)
                } else {
                    manifest_dir_path.join(path_str).join(SRC_DIR)
                };
                if dep_dir.is_dir() {
                    dep_dirs.push(dep_dir);
                }
            } else {
                // Registry (`crates.io`) dependencies are resolved into
                // `$CARGO_HOME/registry/src/<registry-hash>/<name>-<version>/`;
                // remember the name so their sources can be located below.
                registry_dep_names.push(name.clone());
            }
        }
    }
    dep_dirs.extend(collect_registry_dep_src_dirs(&registry_dep_names));
    dep_dirs
}

/// Locates the `src/` directories of registry (crates.io) dependencies.
///
/// Proc macros cannot query cargo metadata, so this walks
/// `$CARGO_HOME/registry/src/<registry-hash>/` and matches extracted sources
/// by `<name>-<version>` directory prefix. Multiple versions of the same
/// crate are all included; the registry deduplicates component names.
///
/// # Arguments
///
/// - `&[String]` - The dependency names without a `path` source.
///
/// # Returns
///
/// - `Vec<PathBuf>` - The located dependency `src/` directories.
fn collect_registry_dep_src_dirs(dep_names: &[String]) -> Vec<PathBuf> {
    let mut dep_dirs: Vec<PathBuf> = Vec::new();
    if dep_names.is_empty() {
        return dep_dirs;
    }
    let cargo_home: PathBuf =
        env::var(CARGO_HOME_ENV)
            .map(PathBuf::from)
            .unwrap_or_else(|_: VarError| {
                env::var(HOME_ENV)
                    .map(|home: String| PathBuf::from(home).join(CARGO_DIR))
                    .unwrap_or_default()
            });
    let registry_src: PathBuf = cargo_home.join(REGISTRY_DIR).join(REGISTRY_SRC_DIR);
    let Ok(registry_entries) = read_dir(&registry_src) else {
        return dep_dirs;
    };
    for registry_entry in registry_entries.flatten() {
        let Ok(package_entries) = read_dir(registry_entry.path()) else {
            continue;
        };
        for package_entry in package_entries.flatten() {
            let package_dir_name: String = package_entry.file_name().to_string_lossy().to_string();
            let matched: bool = dep_names.iter().any(|name: &String| {
                package_dir_name.starts_with(&format!("{name}-"))
                    && package_dir_name[name.len() + 1..]
                        .chars()
                        .next()
                        .map(|c: char| c.is_ascii_digit())
                        .unwrap_or(false)
            });
            if matched {
                let dep_dir: PathBuf = package_entry.path().join(SRC_DIR);
                if dep_dir.is_dir() {
                    dep_dirs.push(dep_dir);
                }
            }
        }
    }
    dep_dirs
}

/// Finds the workspace root directory by traversing up from the manifest directory.
///
/// Searches for a `Cargo.toml` containing `[workspace]` section by walking up
/// the directory tree until the root is reached.
///
/// # Arguments
///
/// - `&str` - The starting manifest directory path.
///
/// # Returns
///
/// - `PathBuf` - The workspace root directory, or the starting directory if no workspace found.
fn find_workspace_root(manifest_dir: &str) -> PathBuf {
    let mut current: PathBuf = PathBuf::from(manifest_dir);
    loop {
        let cargo_toml: PathBuf = current.join(CARGO_TOML);
        if let Ok(content) = read_to_string(&cargo_toml)
            && content.contains(WORKSPACE_SECTION)
        {
            return current;
        }
        if !current.pop() {
            break;
        }
    }
    PathBuf::from(manifest_dir)
}

/// Builds the component registry by parsing all source files in a single pass.
///
/// Each file is read and parsed exactly once, extracting both struct definitions
/// (for Props field information) and component function annotations simultaneously.
///
/// # Arguments
///
/// - `&[PathBuf]` - The list of source file paths to parse.
///
/// # Returns
///
/// - `HashMap<String, ComponentInfo>` - Map of component function names to component metadata.
fn build_registry_from_files(files: &[PathBuf]) -> HashMap<String, ComponentInfo> {
    let mut global_props_fields_map: HashMap<String, Vec<String>> = HashMap::new();
    let mut global_props_field_types_map: HashMap<String, HashMap<String, String>> = HashMap::new();
    let mut component_entries: Vec<(String, String)> = Vec::new();
    for path in files {
        let Ok(content) = read_to_string(path) else {
            continue;
        };
        let Ok(file) = parse_file(&content) else {
            continue;
        };
        global_props_fields_map.extend(extract_props_structs(&file));
        global_props_field_types_map.extend(extract_props_struct_types(&file));
        extract_component_entries(&file, &mut component_entries);
    }
    component_entries
        .into_iter()
        .map(|(fn_name, props_type): (String, String)| {
            let props_fields: Vec<String> = global_props_fields_map
                .get(&props_type)
                .cloned()
                .unwrap_or_default();
            let props_field_types: HashMap<String, String> = global_props_field_types_map
                .get(&props_type)
                .cloned()
                .unwrap_or_default();
            (
                fn_name,
                ComponentInfo {
                    props_type,
                    props_fields,
                    props_field_types,
                },
            )
        })
        .collect()
}

/// Extracts component function entries from a parsed file.
///
/// Collects (function_name, props_type) pairs for functions annotated with `#[component]`.
///
/// # Arguments
///
/// - `&File` - The parsed Rust source file.
/// - `&mut Vec<(String, String)>` - The vector to populate with (fn_name, props_type) pairs.
fn extract_component_entries(file: &File, entries: &mut Vec<(String, String)>) {
    file.items
        .iter()
        .filter_map(|item: &Item| {
            let Item::Fn(item_fn) = item else {
                return None;
            };
            item_fn
                .attrs
                .iter()
                .any(|attr: &Attribute| attr.path().is_ident(COMPONENT_ATTR))
                .then(|| {
                    let fn_name: String = item_fn.sig.ident.to_string();
                    let props_type: String = extract_props_type_from_fn(item_fn);
                    (fn_name, props_type)
                })
        })
        .for_each(|entry: (String, String)| {
            entries.push(entry);
        });
}

/// Recursively scans a directory for `.rs` files and collects their paths.
///
/// # Arguments
///
/// - `&PathBuf` - The directory to scan.
/// - `&mut Vec<PathBuf>` - The vector to populate with discovered file paths.
fn collect_rs_files(dir: &PathBuf, files: &mut Vec<PathBuf>) {
    let Ok(entries) = read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let path: PathBuf = entry.path();
        if path.is_dir() {
            collect_rs_files(&path, files);
        } else if path
            .extension()
            .is_some_and(|ext: &OsStr| ext == OsStr::new(RUST_FILE_EXTENSION))
        {
            files.push(path);
        }
    }
}

/// Extracts all struct definitions from a file and maps their names to field name lists.
///
/// # Arguments
///
/// - `&File` - The parsed Rust source file.
///
/// # Returns
///
/// - `HashMap<String, Vec<String>>` - Map of struct name → list of field names.
fn extract_props_structs(file: &File) -> HashMap<String, Vec<String>> {
    file.items
        .iter()
        .filter_map(|item: &Item| {
            let Item::Struct(item_struct) = item else {
                return None;
            };
            Some((
                item_struct.ident.to_string(),
                item_struct
                    .fields
                    .iter()
                    .filter_map(|field: &Field| {
                        field.ident.as_ref().map(|ident: &Ident| ident.to_string())
                    })
                    .collect(),
            ))
        })
        .collect()
}

/// Extracts all struct definitions from a file and maps their names to field-type maps.
///
/// Each field's type is resolved to its last path segment (e.g., `VirtualNode`, `String`).
///
/// # Arguments
///
/// - `&File` - The parsed Rust source file.
///
/// # Returns
///
/// - `HashMap<String, HashMap<String, String>>` - Map of struct name → (field name → type string).
fn extract_props_struct_types(file: &File) -> HashMap<String, HashMap<String, String>> {
    file.items
        .iter()
        .filter_map(|item: &Item| {
            let Item::Struct(item_struct) = item else {
                return None;
            };
            Some((
                item_struct.ident.to_string(),
                item_struct
                    .fields
                    .iter()
                    .filter_map(|field: &Field| {
                        field.ident.as_ref().map(|ident: &Ident| {
                            (ident.to_string(), extract_type_last_segment(&field.ty))
                        })
                    })
                    .collect(),
            ))
        })
        .collect()
}

/// Extracts the last segment identifier from a type path.
///
/// For example, `::euv::VirtualNode` → `"VirtualNode"`, `String` → `"String"`.
/// Falls back to the full type string representation if the type is not a path.
///
/// # Arguments
///
/// - `&Type` - The syn type to extract from.
///
/// # Returns
///
/// - `String` - The last segment of the type path.
fn extract_type_last_segment(param_type: &Type) -> String {
    if let Type::Path(type_path) = param_type
        && let Some(segment) = type_path.path.segments.last()
    {
        return segment.ident.to_string();
    }
    param_type
        .to_token_stream()
        .to_string()
        .replace(CHAR_SPACE, STR_EMPTY)
}

/// Extracts the Props type name from the first parameter of a component function.
///
/// Looks for the first parameter's type. If the type is `VirtualNode<T>`,
/// extracts the generic argument `T` as the Props type name. Falls back to
/// checking for a simple path type (e.g., `PrimaryButtonProps`) for backward
/// compatibility. Returns an empty string if neither pattern matches.
///
/// # Arguments
///
/// - `&syn::ItemFn` - The function item to extract from.
///
/// # Returns
///
/// - `String` - The Props type name, or empty string if not extractable.
fn extract_props_type_from_fn(item_fn: &syn::ItemFn) -> String {
    let inputs: &syn::punctuated::Punctuated<syn::FnArg, Token![,]> = &item_fn.sig.inputs;
    for input in inputs {
        if let syn::FnArg::Typed(pat_type) = input {
            let param_type: &Type = &pat_type.ty;
            if let Type::Path(type_path) = param_type
                && let Some(segment) = type_path.path.segments.last()
                && segment.ident == VIRTUAL_NODE_TYPE
            {
                if let syn::PathArguments::AngleBracketed(args) = &segment.arguments
                    && let Some(syn::GenericArgument::Type(inner_param_type)) = args.args.first()
                    && let Type::Path(inner_path) = inner_param_type
                    && let Some(inner_segment) = inner_path.path.segments.last()
                {
                    return inner_segment.ident.to_string();
                }
            } else if let Type::Path(type_path) = param_type
                && let Some(segment) = type_path.path.segments.last()
            {
                return segment.ident.to_string();
            }
        }
    }
    String::new()
}

/// Checks whether a double-brace pattern `{{ ... }}` represents a dynamic tag
/// rather than a simple braced expression.
///
/// A dynamic tag is detected when the second brace group contains:
/// - Empty content, or
/// - An identifier followed by `:` or `-` (attribute pattern), or
/// - Keywords `if`, `match`, `for`, or
/// - A string literal, or
/// - A braced expression followed by `:` (dynamic key), or
/// - Another double brace (nested dynamic tag).
///
/// # Arguments
///
/// - `&ParseBuffer` - The parse buffer of the second brace group.
/// - `&ParseStream` - The outer parse stream (for `peek2` checks).
///
/// # Returns
///
/// - `bool` - `true` if the pattern is a dynamic tag.
pub(crate) fn is_dynamic_tag_pattern(second_brace: ParseStream, outer: ParseStream) -> bool {
    second_brace.is_empty()
        || is_attr_key_pattern(second_brace)
        || second_brace.peek(Token![if])
        || second_brace.peek(Token![match])
        || second_brace.peek(Token![for])
        || second_brace.peek(LitStr)
        || (second_brace.peek(Brace) && outer.peek2(Colon))
        || (second_brace.peek(Brace) && second_brace.peek2(Brace))
}

/// Parses a stream of tokens into a list of HTML child nodes.
///
/// # Arguments
///
/// - `ParseStream` - The parse stream containing HTML child content.
///
/// # Returns
///
/// - `syn::Result<Vec<HtmlNode>>` - The parsed list of HTML child nodes, or a syntax error.
pub(crate) fn parse_html_children(content: ParseStream) -> syn::Result<Vec<HtmlNode>> {
    let mut children: Vec<HtmlNode> = Vec::new();
    while !content.is_empty() {
        if content.peek(Brace) && content.peek2(Brace) {
            let forked: ParseBuffer<'_> = content.fork();
            let _first_brace: ParseBuffer<'_>;
            braced!(_first_brace in forked);
            let second_brace: ParseBuffer<'_>;
            braced!(second_brace in forked);
            if is_dynamic_tag_pattern(&second_brace, content) {
                let tag_content: ParseBuffer<'_>;
                braced!(tag_content in content);
                let tag_expr: Expr = tag_content.parse()?;
                let body_content: ParseBuffer<'_>;
                braced!(body_content in content);
                let (dynamic_attrs, dynamic_children): (HtmlAttrs, Vec<HtmlNode>) =
                    parse_dynamic_component_children(&body_content)?;
                children.push(HtmlNode::DynamicTag(HtmlDynamicTag::new(
                    tag_expr,
                    dynamic_attrs,
                    dynamic_children,
                )));
            } else {
                let child_content: ParseBuffer<'_>;
                braced!(child_content in content);
                let expr: Expr = child_content.parse()?;
                children.push(HtmlNode::Dynamic(expr));
            }
        } else if content.peek(LitStr) && content.peek2(Brace) {
            let element: HtmlElement = content.parse()?;
            children.push(HtmlNode::Element(element));
        } else if content.peek(LitStr) {
            let literal_string: LitStr = content.parse()?;
            children.push(HtmlNode::Text(literal_string.value()));
        } else if (is_attr_key_pattern(content) || content.peek(LitStr) && content.peek2(Colon))
            && !is_double_colon(content)
        {
            break;
        } else if content.peek(Token![if]) {
            let html_if: HtmlIf = content.parse()?;
            children.push(HtmlNode::If(html_if));
        } else if content.peek(Token![match]) {
            let html_match: HtmlMatch = content.parse()?;
            children.push(HtmlNode::Match(html_match));
        } else if content.peek(Token![for]) {
            let html_for: HtmlFor = content.parse()?;
            children.push(HtmlNode::For(html_for));
        } else if content.peek(Brace) {
            let child_content: ParseBuffer<'_>;
            braced!(child_content in content);
            let expr: Expr = child_content.parse()?;
            children.push(HtmlNode::Dynamic(expr));
        } else if content.peek(Ident) {
            if content.peek2(Brace) {
                let element: HtmlElement = content.parse()?;
                children.push(HtmlNode::Element(element));
            } else {
                let expr: Expr = content.parse()?;
                children.push(HtmlNode::Expr(expr));
            }
        } else {
            return Err(content.error(ERR_UNEXPECTED_TOKEN_IN_HTML));
        }
    }
    Ok(children)
}

/// Parses the body of a match arm after the `=>` token.
///
/// Unlike `parse_html_children` which operates on a braced scope, this function
/// reads directly from the arms content stream and stops when it encounters a
/// top-level comma (indicating the next arm) or the end of the stream.
/// Supports all HTML node types: elements, text, expressions, if, match, for,
/// and braced dynamic expressions.
///
/// # Arguments
///
/// - `ParseStream` - The parse stream positioned after `=>` in a match arm.
///
/// # Returns
///
/// - `syn::Result<Vec<HtmlNode>>` - The parsed list of HTML nodes for the arm body.
pub(crate) fn parse_match_arm_body(content: ParseStream) -> syn::Result<Vec<HtmlNode>> {
    if content.peek(Brace) {
        let child_content: ParseBuffer<'_>;
        braced!(child_content in content);
        parse_html_children(&child_content)
    } else {
        let node: HtmlNode = content.parse()?;
        Ok(vec![node])
    }
}

/// Parses the body of a dynamic component `@ {expr} { ... }`.
///
/// The body contains attributes (key: value) and children (HTML nodes),
/// similar to an `HtmlElement` body but without a tag name.
/// Attributes are recognized by the pattern `ident:` or `ident-...:`.
/// Everything else is treated as child content.
///
/// # Arguments
///
/// - `ParseStream` - The parse stream containing the dynamic component body.
///
/// # Returns
///
/// - `syn::Result<(HtmlAttrs, Vec<HtmlNode>)>` - The parsed attributes and children.
pub(crate) fn parse_dynamic_component_children(
    content: ParseStream,
) -> syn::Result<(HtmlAttrs, Vec<HtmlNode>)> {
    let mut attributes: HtmlAttrs = Vec::new();
    let mut children: Vec<HtmlNode> = Vec::new();
    while !content.is_empty() {
        if content.peek(Brace) && content.peek2(Brace) {
            let forked: ParseBuffer<'_> = content.fork();
            let _first_brace: ParseBuffer<'_>;
            braced!(_first_brace in forked);
            let second_brace: ParseBuffer<'_>;
            braced!(second_brace in forked);
            if is_dynamic_tag_pattern(&second_brace, content) {
                let tag_content: ParseBuffer<'_>;
                braced!(tag_content in content);
                let tag_expr: Expr = tag_content.parse()?;
                let body_content: ParseBuffer<'_>;
                braced!(body_content in content);
                let (dynamic_attrs, dynamic_children): (HtmlAttrs, Vec<HtmlNode>) =
                    parse_dynamic_component_children(&body_content)?;
                children.push(HtmlNode::DynamicTag(HtmlDynamicTag::new(
                    tag_expr,
                    dynamic_attrs,
                    dynamic_children,
                )));
            } else {
                let child_content: ParseBuffer<'_>;
                braced!(child_content in content);
                let expr: Expr = child_content.parse()?;
                children.push(HtmlNode::Dynamic(expr));
            }
        } else if is_attr_key_pattern(content) && !is_double_colon(content) {
            let key_string: String = parse_ident_name(content)?;
            let key_literal: LitStr = LitStr::new(&key_string, content.span());
            content.parse::<Colon>()?;
            let key_str: String = key_string
                .strip_prefix(RAW_IDENT_PREFIX)
                .unwrap_or(&key_string)
                .to_string();
            let value: HtmlAttrValue = parse_attr_value(content, &key_str)?;
            attributes.push((key_literal.to_token_stream(), value));
        } else if content.peek(Token![if]) {
            let html_if: HtmlIf = content.parse()?;
            children.push(HtmlNode::If(html_if));
        } else if content.peek(Token![match]) {
            let html_match: HtmlMatch = content.parse()?;
            children.push(HtmlNode::Match(html_match));
        } else if content.peek(Token![for]) {
            let html_for: HtmlFor = content.parse()?;
            children.push(HtmlNode::For(html_for));
        } else if content.peek(Brace) && content.peek2(Colon) {
            let key_content: ParseBuffer<'_>;
            braced!(key_content in content);
            let key_expr: Expr = key_content.parse()?;
            content.parse::<Colon>()?;
            let value: HtmlAttrValue = parse_attr_value(content, STR_EMPTY)?;
            attributes.push((key_expr.to_token_stream(), value));
        } else if content.peek(Brace) {
            let child_content: ParseBuffer<'_>;
            braced!(child_content in content);
            let expr: Expr = child_content.parse()?;
            children.push(HtmlNode::Dynamic(expr));
        } else if content.peek(LitStr) && content.peek2(Brace) {
            let element: HtmlElement = content.parse()?;
            children.push(HtmlNode::Element(element));
        } else if content.peek(LitStr) && content.peek2(Colon) {
            let key_literal: LitStr = content.parse()?;
            let key_str: String = key_literal.value();
            content.parse::<Colon>()?;
            let value: HtmlAttrValue = parse_attr_value(content, &key_str)?;
            attributes.push((key_literal.to_token_stream(), value));
        } else if content.peek(LitStr) {
            let literal_string: LitStr = content.parse()?;
            children.push(HtmlNode::Text(literal_string.value()));
        } else if content.peek(Ident) {
            if content.peek2(Brace) {
                let element: HtmlElement = content.parse()?;
                children.push(HtmlNode::Element(element));
            } else {
                let expr: Expr = content.parse()?;
                children.push(HtmlNode::Expr(expr));
            }
        } else {
            return Err(content.error(ERR_UNEXPECTED_TOKEN_IN_DYNAMIC_COMPONENT));
        }
    }
    let merged_attributes: HtmlAttrs = merge_same_key_attributes(attributes);
    Ok((merged_attributes, children))
}

/// Converts a slice of `HtmlNode` children into a `Vec<proc_macro2::TokenStream>`.
///
/// Shared helper used by both `children_to_node_tokens` and `children_to_tokens`.
///
/// # Arguments
///
/// - `&[HtmlNode]` - The slice of HTML child nodes to convert.
///
/// # Returns
///
/// - `Vec<proc_macro2::TokenStream>` - The generated token stream representing a single `VirtualNode`.
pub(crate) fn nodes_to_token_vec(children: &[HtmlNode]) -> Vec<proc_macro2::TokenStream> {
    children
        .iter()
        .map(|child: &HtmlNode| {
            let mut token_stream: proc_macro2::TokenStream = proc_macro2::TokenStream::new();
            child.to_tokens(&mut token_stream);
            token_stream
        })
        .collect()
}

/// Builds a Rust `if/else if/else` chain token stream from `HtmlIf` branches,
/// where each branch body produces a single `VirtualNode`.
///
/// Used for inline (non-reactive) conditionals at the top level or inside
/// other conditionals/match arms where a single `VirtualNode` is expected.
///
/// # Arguments
///
/// - `&[(Option<Expr>, Vec<HtmlNode>)]` - The branches from an `HtmlIf`.
///
/// # Returns
///
/// - `proc_macro2::TokenStream` - The generated if-chain token stream producing a `VirtualNode`.
pub(crate) fn build_html_if_chain(
    branches: &[(Option<Expr>, Vec<HtmlNode>, bool)],
) -> proc_macro2::TokenStream {
    let mut if_chain: proc_macro2::TokenStream = proc_macro2::TokenStream::new();
    let has_else: bool = branches
        .last()
        .is_some_and(|(condition, _, _): &(Option<Expr>, Vec<HtmlNode>, bool)| condition.is_none());
    for (branch_index, (condition, body, is_reactive)) in branches.iter().enumerate() {
        let body_expr: proc_macro2::TokenStream = children_to_node_tokens(body);
        match (branch_index, condition) {
            (0, Some(cond)) => {
                let cond_tokens: proc_macro2::TokenStream =
                    auto_get_expr_tokens(cond, *is_reactive);
                if_chain.extend(quote! { if #cond_tokens { #body_expr } });
            }
            (_, Some(cond)) => {
                let cond_tokens: proc_macro2::TokenStream =
                    auto_get_expr_tokens(cond, *is_reactive);
                if_chain.extend(quote! { else if #cond_tokens { #body_expr } });
            }
            (_, None) => {
                if_chain.extend(quote! { else { #body_expr } });
            }
        }
    }
    if !has_else {
        if_chain.extend(quote! { else { ::euv::VirtualNode::Empty } });
    }
    if_chain
}

/// Converts a list of `HtmlNode` children into a single `VirtualNode` token stream.
///
/// - 0 children → `VirtualNode::Empty`
/// - 1 child → the child's token stream directly (no Fragment wrapper)
/// - N children → `VirtualNode::Fragment(vec![...])`
///
/// Inline (non-reactive) `if` conditionals are expanded as Rust `if` expressions
/// that produce a `VirtualNode`.
///
/// # Arguments
///
/// - `&[HtmlNode]` - The slice of HTML child nodes to convert.
///
/// # Returns
///
/// - `proc_macro2::TokenStream` - The generated token stream representing a single `VirtualNode`.
pub(crate) fn children_to_node_tokens(children: &[HtmlNode]) -> proc_macro2::TokenStream {
    let has_inline_if: bool = children.iter().any(
        |child: &HtmlNode| matches!(child, HtmlNode::If(html_if) if !html_if.get_is_reactive()),
    );
    if has_inline_if {
        let vec_tokens: proc_macro2::TokenStream = children_to_tokens(children);
        return quote! { ::euv::VirtualNode::Fragment(#vec_tokens) };
    }
    match children.len() {
        0 => quote! { ::euv::VirtualNode::Empty },
        1 => {
            let mut token_stream: proc_macro2::TokenStream = proc_macro2::TokenStream::new();
            children[0].to_tokens(&mut token_stream);
            token_stream
        }
        _ => {
            let child_tokens: Vec<proc_macro2::TokenStream> = nodes_to_token_vec(children);
            quote! { ::euv::VirtualNode::Fragment(vec![#(#child_tokens), *]) }
        }
    }
}

/// Builds a Rust `if/else if/else` chain token stream from `HtmlIf` branches,
/// where each branch body produces a `Vec<VirtualNode>`.
///
/// Used for inline (non-reactive) conditionals inside `for` loops and flattened
/// element children, where each branch result is collected via `.extend()`.
///
/// # Arguments
///
/// - `&[(Option<Expr>, Vec<HtmlNode>)]` - The branches from an `HtmlIf`.
///
/// # Returns
///
/// - `proc_macro2::TokenStream` - The generated if-chain token stream producing `Vec<VirtualNode>`.
pub(crate) fn build_html_if_chain_to_vec(
    branches: &[(Option<Expr>, Vec<HtmlNode>, bool)],
) -> proc_macro2::TokenStream {
    let mut if_chain: proc_macro2::TokenStream = proc_macro2::TokenStream::new();
    let has_else: bool = branches
        .last()
        .is_some_and(|(condition, _, _): &(Option<Expr>, Vec<HtmlNode>, bool)| condition.is_none());
    for (branch_index, (condition, body, is_reactive)) in branches.iter().enumerate() {
        let body_expr: proc_macro2::TokenStream = children_to_tokens(body);
        match (branch_index, condition) {
            (0, Some(cond)) => {
                let cond_tokens: proc_macro2::TokenStream =
                    auto_get_expr_tokens(cond, *is_reactive);
                if_chain.extend(quote! { if #cond_tokens { #body_expr } });
            }
            (_, Some(cond)) => {
                let cond_tokens: proc_macro2::TokenStream =
                    auto_get_expr_tokens(cond, *is_reactive);
                if_chain.extend(quote! { else if #cond_tokens { #body_expr } });
            }
            (_, None) => {
                if_chain.extend(quote! { else { #body_expr } });
            }
        }
    }
    if !has_else {
        if_chain.extend(quote! { else { Vec::new() } });
    }
    if_chain
}

/// Converts a list of `HtmlNode` children into a `Vec<VirtualNode>` token stream.
///
/// Always produces `vec![...]` format when no inline conditionals are present.
/// When inline (non-reactive) `if` conditionals exist, generates a block that
/// builds the `Vec<VirtualNode>` incrementally using `.push()` and `.extend()`.
///
/// # Arguments
///
/// - `&[HtmlNode]` - The slice of HTML child nodes to convert.
///
/// # Returns
///
/// - `proc_macro2::TokenStream` - The generated token stream representing a `Vec<VirtualNode>`.
pub(crate) fn children_to_tokens(children: &[HtmlNode]) -> proc_macro2::TokenStream {
    let has_inline_if: bool = children.iter().any(
        |child: &HtmlNode| matches!(child, HtmlNode::If(html_if) if !html_if.get_is_reactive()),
    );
    if !has_inline_if {
        let child_tokens: Vec<proc_macro2::TokenStream> = nodes_to_token_vec(children);
        return quote! { vec![#(#child_tokens), *] };
    }
    let mut parts: Vec<proc_macro2::TokenStream> = Vec::new();
    for child in children {
        match child {
            HtmlNode::If(html_if) if !html_if.get_is_reactive() => {
                let if_chain: proc_macro2::TokenStream =
                    build_html_if_chain_to_vec(html_if.get_branches());
                parts.push(quote! {
                    __euv_nodes.extend(#if_chain);
                });
            }
            _ => {
                let mut token_stream: proc_macro2::TokenStream = proc_macro2::TokenStream::new();
                child.to_tokens(&mut token_stream);
                parts.push(quote! {
                    __euv_nodes.push(#token_stream);
                });
            }
        }
    }
    quote! {
        {
            let mut __euv_nodes: Vec<::euv::VirtualNode> = Vec::new();
            #(#parts)*
            __euv_nodes
        }
    }
}

/// Generates a token stream that builds a `Vec<VirtualNode>` with `For` loops
/// and inline `if` conditionals expanded inline via `.extend()` instead of being
/// wrapped in `VirtualNode::Fragment`.
///
/// This is critical for elements like `<select>` where intermediate wrapper elements
/// (such as `<slot>` used by `VirtualNode::Fragment`) are invalid HTML and cause
/// browser rendering issues. By flattening `For` loop outputs directly into the
/// parent's children list, option elements appear as direct children of `<select>`.
///
/// # Arguments
///
/// - `&[HtmlNode]` - The slice of HTML child nodes to convert.
///
/// # Returns
///
/// - `proc_macro2::TokenStream` - The generated token stream representing a `Vec<VirtualNode>`.
pub(crate) fn children_to_flattened_tokens(children: &[HtmlNode]) -> proc_macro2::TokenStream {
    let needs_flatten: bool = children.iter().any(|child: &HtmlNode| {
        matches!(child, HtmlNode::For(_))
            || matches!(child, HtmlNode::If(html_if) if !html_if.get_is_reactive())
    });
    if !needs_flatten {
        let child_tokens: Vec<proc_macro2::TokenStream> = nodes_to_token_vec(children);
        return quote! { vec![#(#child_tokens), *] };
    }
    let mut parts: Vec<proc_macro2::TokenStream> = Vec::new();
    for child in children {
        match child {
            HtmlNode::For(html_for) => {
                let pattern: &proc_macro2::TokenStream = html_for.get_pattern();
                let iterable: &Expr = html_for.get_iterable();
                let iterable_tokens: proc_macro2::TokenStream =
                    auto_get_expr_tokens(iterable, html_for.get_is_reactive());
                let body_tokens: proc_macro2::TokenStream = children_to_tokens(html_for.get_body());
                if html_for.get_is_reactive() {
                    // A braced reactive iterable (`for x in { signal }`) must
                    // re-run whenever the signal changes. The inline snapshot
                    // loop below would run exactly once at mount outside any
                    // tracking scope, registering no dependent, so the list
                    // would never update. Wrap the loop in a dynamic node
                    // instead: its render closure runs with an active tracking
                    // id, so `Signal::get` subscribes this node, and `Signal::set`
                    // later marks it dirty and re-renders the `Fragment`.
                    parts.push(quote! {
                        __euv_nodes.push(::euv::VirtualNode::create_dynamic(
                            move |_: &mut ::euv::HookContext| {
                                let mut __euv_inner: Vec<::euv::VirtualNode> = Vec::new();
                                for #pattern in #iterable_tokens {
                                    __euv_inner.extend(#body_tokens);
                                }
                                ::euv::VirtualNode::Fragment(__euv_inner)
                            }
                        ));
                    });
                } else {
                    parts.push(quote! {
                        for #pattern in #iterable_tokens {
                            __euv_nodes.extend(#body_tokens);
                        }
                    });
                }
            }
            HtmlNode::If(html_if) if !html_if.get_is_reactive() => {
                let if_chain: proc_macro2::TokenStream =
                    build_html_if_chain_to_vec(html_if.get_branches());
                parts.push(quote! {
                    __euv_nodes.extend(#if_chain);
                });
            }
            _ => {
                let mut token_stream: proc_macro2::TokenStream = proc_macro2::TokenStream::new();
                child.to_tokens(&mut token_stream);
                parts.push(quote! {
                    __euv_nodes.push(#token_stream);
                });
            }
        }
    }
    quote! {
        {
            let mut __euv_nodes: Vec<::euv::VirtualNode> = Vec::new();
            #(#parts)*
            __euv_nodes
        }
    }
}

/// Parses a reactive or inline `if` conditional in attribute value position.
///
/// Each branch condition is independently parsed as either reactive (braced)
/// or inline (plain expression). The overall `is_inline` flag is set to
/// `false` if any branch has a braced condition, causing the entire if-chain
/// to be wrapped in a reactive `AttributeValue`.
///
/// Supported syntaxes per branch:
/// - Reactive: `{expr}` — the braced expression is treated as a signal.
/// - Inline: `condition` — a plain Rust boolean expression.
///
/// Any combination is valid, e.g.:
/// - `if {a} { v } else if {b} { v }` — all reactive
/// - `if a { v } else if b { v }` — all inline
/// - `if {a} { v } else if b { v }` — mixed (first reactive, second inline)
/// - `if a { v } else if {b} { v }` — mixed (first inline, second reactive)
///
/// When no explicit `else` branch is provided, an empty string is used as the default.
///
/// # Arguments
///
/// - `ParseStream` - The parse stream positioned at the `if` keyword.
///
/// # Returns
///
/// - `syn::Result<HtmlAttrIf>` - The parsed attribute-level reactive or inline conditional.
pub(crate) fn parse_attr_if(content: ParseStream) -> syn::Result<HtmlAttrIf> {
    let mut branches: Vec<(Option<Expr>, Expr, bool)> = Vec::new();
    let mut is_inline: bool = true;
    content.parse::<Token![if]>()?;
    let branch_reactive: bool = content.peek(Brace);
    is_inline = is_inline && !branch_reactive;
    let condition: Expr = if branch_reactive {
        let cond_content: ParseBuffer<'_>;
        braced!(cond_content in content);
        cond_content.parse()?
    } else {
        parse_expr_until_brace(content)?
    };
    let body_content: ParseBuffer<'_>;
    braced!(body_content in content);
    let body: Expr = body_content.parse()?;
    branches.push((Some(condition), body, branch_reactive));
    while content.peek(Token![else]) {
        content.parse::<Token![else]>()?;
        if content.peek(Token![if]) {
            content.parse::<Token![if]>()?;
            let branch_reactive: bool = content.peek(Brace);
            is_inline = is_inline && !branch_reactive;
            let condition: Expr = if branch_reactive {
                let cond_content: ParseBuffer<'_>;
                braced!(cond_content in content);
                cond_content.parse()?
            } else {
                parse_expr_until_brace(content)?
            };
            let body_content: ParseBuffer<'_>;
            braced!(body_content in content);
            let body: Expr = body_content.parse()?;
            branches.push((Some(condition), body, branch_reactive));
        } else {
            let body_content: ParseBuffer<'_>;
            braced!(body_content in content);
            let body: Expr = body_content.parse()?;
            branches.push((None, body, false));
            break;
        }
    }
    let else_default: proc_macro2::TokenStream = quote! { #STR_EMPTY };
    Ok(HtmlAttrIf {
        is_inline,
        branches,
        else_default,
    })
}

/// Parses a reactive or inline `match` expression in attribute value position.
///
/// Supports two syntaxes:
/// - Reactive: `match {expr} { pattern => value, ... }`
///   Detected when `match` is immediately followed by `{`.
/// - Inline: `match expr { pattern => value, ... }`
///   Detected when `match` is followed by a non-`{` token.
///
/// # Arguments
///
/// - `ParseStream` - The parse stream positioned at the `match` keyword.
///
/// # Returns
///
/// - `syn::Result<HtmlAttrMatch>` - The parsed attribute-level reactive or inline match expression.
pub(crate) fn parse_attr_match(content: ParseStream) -> syn::Result<HtmlAttrMatch> {
    let is_inline: bool = !content.peek2(Brace);
    content.parse::<Token![match]>()?;
    let scrutinee: Expr = if is_inline {
        parse_expr_until_brace(content)?
    } else {
        let scrutinee_content: ParseBuffer<'_>;
        braced!(scrutinee_content in content);
        scrutinee_content.parse()?
    };
    let arms_content: ParseBuffer<'_>;
    braced!(arms_content in content);
    let mut arms: Vec<(proc_macro2::TokenStream, Expr)> = Vec::new();
    while !arms_content.is_empty() {
        let mut pattern_tokens: proc_macro2::TokenStream = proc_macro2::TokenStream::new();
        while !arms_content.peek(Token![=>]) {
            let token_tree: proc_macro2::TokenTree = arms_content.parse()?;
            pattern_tokens.extend([token_tree]);
        }
        arms_content.parse::<Token![=>]>()?;
        let body: Expr = if arms_content.peek(Brace) {
            let body_content: ParseBuffer<'_>;
            braced!(body_content in arms_content);
            body_content.parse()?
        } else {
            arms_content.parse()?
        };
        arms.push((pattern_tokens, body));
        if arms_content.peek(Token![,]) {
            arms_content.parse::<Token![,]>()?;
        }
    }
    Ok(HtmlAttrMatch {
        is_inline,
        scrutinee,
        arms,
    })
}

/// Strips outer braces from an `Expr` if it is an `Expr::Block` with a single expression,
/// avoiding Rust `unused_braces` warnings in generated `if` conditions.
///
/// # Arguments
///
/// - `&Expr` - The expression to potentially strip.
///
/// # Returns
///
/// - `&Expr` - The inner expression if the input was a braced single-expression block, otherwise the original.
pub(crate) fn strip_braces_from_expr(expr: &Expr) -> &Expr {
    if let Expr::Block(expr_block) = expr {
        let stmts: &Vec<Stmt> = &expr_block.block.stmts;
        if stmts.len() == 1
            && let Stmt::Expr(inner, None) = &stmts[0]
        {
            return inner;
        }
    }
    expr
}

/// Generates a token stream for an `HtmlAttrIf` as a Rust `if` expression.
///
/// The generated code is used inside a reactive closure so that when signals
/// change, the conditional is re-evaluated.
///
/// The `mode` parameter controls how branch bodies are emitted:
/// - `AttrIfMode::Reactive` - Each branch body is wrapped in
///   `::euv::IntoReactiveString::into_reactive_string(...)` so that all branches
///   produce a `String` regardless of their original type (e.g., `Css`, `&str`, `String`).
///   This ensures type compatibility when the `if` and implicit `else` branches
///   return different types.
/// - `AttrIfMode::Raw` - Branch bodies are emitted as-is without wrapping.
///   Used for component props where branch types are already consistent.
///
/// # Arguments
///
/// - `&HtmlAttrIf` - The parsed attribute-level reactive conditional.
/// - `proc_macro2::TokenStream` - The default else branch token stream, used when no explicit else branch exists.
/// - `AttrIfMode` - The code generation mode for branch body wrapping.
///
/// # Returns
///
/// - `proc_macro2::TokenStream` - The generated `if ... { ... } else if ... { ... } else { ... }` token stream.
pub(crate) fn attr_if_to_tokens(ctx: &AttrIfContext<'_>) -> proc_macro2::TokenStream {
    let html_attr_if: &HtmlAttrIf = ctx.get_html_attr_if();
    let else_default: &proc_macro2::TokenStream = ctx.get_else_default();
    let mode: AttrIfMode = ctx.get_mode();
    let mut if_chain: proc_macro2::TokenStream = proc_macro2::TokenStream::new();
    let has_else: bool = html_attr_if
        .branches
        .last()
        .is_some_and(|(condition, _, _): &(Option<Expr>, Expr, bool)| condition.is_none());
    for (branch_index, (condition, body, is_reactive)) in html_attr_if.branches.iter().enumerate() {
        let body_tokens: proc_macro2::TokenStream = match mode {
            AttrIfMode::Reactive => {
                quote! { (#body).to_string() }
            }
            AttrIfMode::Raw => quote! { #body },
        };
        match (branch_index, condition) {
            (0, Some(cond)) => {
                let cond_tokens: proc_macro2::TokenStream =
                    auto_get_expr_tokens(cond, *is_reactive);
                if_chain.extend(quote! { if #cond_tokens { #body_tokens } });
            }
            (_, Some(cond)) => {
                let cond_tokens: proc_macro2::TokenStream =
                    auto_get_expr_tokens(cond, *is_reactive);
                if_chain.extend(quote! { else if #cond_tokens { #body_tokens } });
            }
            (_, None) => {
                if_chain.extend(quote! { else { #body_tokens } });
            }
        }
    }
    if !has_else {
        let else_tokens: proc_macro2::TokenStream = match mode {
            AttrIfMode::Reactive => {
                quote! { (#else_default).to_string() }
            }
            AttrIfMode::Raw => quote! { #else_default },
        };
        if_chain.extend(quote! { else { #else_tokens } });
    }
    if_chain
}

/// Generates a token stream for an `HtmlAttrMatch` as a Rust `match` expression.
///
/// The `mode` parameter controls how arm bodies are emitted:
/// - `AttrIfMode::Reactive` - Each arm body is wrapped with `.to_string()`.
/// - `AttrIfMode::Raw` - Arm bodies are emitted as-is without wrapping.
///
/// # Arguments
///
/// - `&HtmlAttrMatch` - The parsed attribute-level match expression.
/// - `AttrIfMode` - The code generation mode for arm body wrapping.
///
/// # Returns
///
/// - `proc_macro2::TokenStream` - The generated `match ... { ... }` token stream.
pub(crate) fn attr_match_to_tokens(
    html_attr_match: &HtmlAttrMatch,
    mode: AttrIfMode,
) -> proc_macro2::TokenStream {
    let scrutinee: &Expr = html_attr_match.get_scrutinee();
    let scrutinee_tokens: proc_macro2::TokenStream =
        auto_get_expr_tokens(scrutinee, !html_attr_match.get_is_inline());
    let arm_tokens: Vec<proc_macro2::TokenStream> = html_attr_match
        .get_arms()
        .iter()
        .map(|(pattern, body): &(proc_macro2::TokenStream, Expr)| {
            let body_tokens: proc_macro2::TokenStream = match mode {
                AttrIfMode::Reactive => {
                    quote! { (#body).to_string() }
                }
                AttrIfMode::Raw => quote! { #body },
            };
            quote! { #pattern => #body_tokens, }
        })
        .collect();
    quote! { match #scrutinee_tokens { #(#arm_tokens)* } }
}

/// Checks whether an `HtmlAttrValue` contains any inline (non-reactive) conditional logic.
///
/// Returns `true` if the value is an inline `If` or inline `Match`, or if it contains
/// inline conditionals in `Style` properties.
///
/// # Arguments
///
/// - `&HtmlAttrValue` - The attribute value to check.
///
/// # Returns
///
/// - `bool` - `true` if the value contains inline conditional logic.
pub(crate) fn is_attr_value_inline(value: &HtmlAttrValue) -> bool {
    match value {
        HtmlAttrValue::If(html_attr_if) => html_attr_if.get_is_inline(),
        HtmlAttrValue::Match(html_attr_match) => html_attr_match.get_is_inline(),
        HtmlAttrValue::Style(props) => props.iter().any(
            |(_, style_value): &(String, HtmlStylePropValue)| {
                matches!(style_value, HtmlStylePropValue::If(html_attr_if) if html_attr_if.get_is_inline())
                    || matches!(style_value, HtmlStylePropValue::Match(html_attr_match) if html_attr_match.get_is_inline())
            },
        ),
        _ => false,
    }
}

/// Checks whether style properties contain any conditional logic.
///
/// # Arguments
///
/// - `&[(String, HtmlStylePropValue)]` - The style properties to check.
///
/// # Returns
///
/// - `bool` - `true` if any style property contains a conditional.
pub(crate) fn is_style_props_conditional(props: &[(String, HtmlStylePropValue)]) -> bool {
    props
        .iter()
        .any(|(_, value): &(String, HtmlStylePropValue)| {
            matches!(
                value,
                HtmlStylePropValue::If(_) | HtmlStylePropValue::Match(_)
            )
        })
}

/// Parses the value side of an attribute, handling the special `style:` attribute.
///
/// If the key is `"style"` and the value is a braced expression that looks like
/// a style object (key-value pairs separated by `;`), it is parsed as
/// `HtmlAttrValue::Style`. Otherwise, the value is parsed as a normal expression
/// or a reactive `if` conditional.
///
/// # Arguments
///
/// - `ParseStream` - The parse stream positioned after the ` -` token.
/// - `&str` - The attribute key string (e.g., `"style"`, `"class"`).
///
/// # Returns
///
/// - `syn::Result<HtmlAttrValue>` - The parsed attribute value.
pub(crate) fn parse_attr_value(content: ParseStream, key_str: &str) -> syn::Result<HtmlAttrValue> {
    if content.peek(Token![if]) {
        return Ok(HtmlAttrValue::If(parse_attr_if(content)?));
    }
    if content.peek(Token![match]) {
        return Ok(HtmlAttrValue::Match(parse_attr_match(content)?));
    }
    if key_str == ATTR_KEY_STYLE && content.peek(Brace) {
        let style_content: ParseBuffer<'_>;
        braced!(style_content in content);
        let is_style_object: bool = style_content.peek(LitStr) || style_content.peek(Ident);
        if is_style_object {
            let mut style_props: Vec<(String, HtmlStylePropValue)> = Vec::new();
            while !style_content.is_empty() {
                let css_key: String = parse_ident_name(&style_content)?;
                style_content.parse::<Colon>()?;
                let prop_value: HtmlStylePropValue = if style_content.peek(Token![if]) {
                    let html_attr_if: HtmlAttrIf = parse_attr_if(&style_content)?;
                    HtmlStylePropValue::If(html_attr_if)
                } else if style_content.peek(Token![match]) {
                    let html_attr_match: HtmlAttrMatch = parse_attr_match(&style_content)?;
                    HtmlStylePropValue::Match(html_attr_match)
                } else if style_content.peek(LitStr) {
                    let literal_string: LitStr = style_content.parse()?;
                    HtmlStylePropValue::Literal(literal_string.value())
                } else if style_content.peek(Brace) {
                    let expr_content: ParseBuffer<'_>;
                    braced!(expr_content in style_content);
                    if expr_content.peek(Token![if]) {
                        let html_attr_if: HtmlAttrIf = parse_attr_if(&expr_content)?;
                        HtmlStylePropValue::If(html_attr_if)
                    } else if expr_content.peek(Token![match]) {
                        let html_attr_match: HtmlAttrMatch = parse_attr_match(&expr_content)?;
                        HtmlStylePropValue::Match(html_attr_match)
                    } else {
                        let expr: Expr = expr_content.parse()?;
                        HtmlStylePropValue::Expr(expr)
                    }
                } else {
                    let expr: Expr = style_content.parse()?;
                    HtmlStylePropValue::Expr(expr)
                };
                style_props.push((css_key, prop_value));
                if style_content.peek(Semi) {
                    style_content.parse::<Semi>()?;
                }
            }
            Ok(HtmlAttrValue::Style(style_props))
        } else {
            Ok(HtmlAttrValue::Expr(style_content.parse()?))
        }
    } else {
        Ok(HtmlAttrValue::Expr(content.parse()?))
    }
}

/// Merges attributes with the same key name for `class` and `style`.
///
/// When multiple `class:` or `style:` attributes are declared on the same
/// element, they are combined into a single `HtmlAttrValue::Classes` or
/// `HtmlAttrValue::Styles` entry so that the renderer can merge their
/// values at runtime rather than overwriting.
///
/// Non-mergeable attribute keys keep only the last occurrence.
///
/// # Arguments
///
/// - `Vec<(Ident, HtmlAttrValue)>` - The raw parsed attributes (may contain duplicate keys).
///
/// # Returns
///
/// - `Vec<(Ident, HtmlAttrValue)>` - The merged attributes with at most one `class` and one `style` entry.
pub(crate) fn merge_same_key_attributes(attributes: HtmlAttrs) -> HtmlAttrs {
    let mut class_values: Vec<HtmlAttrValue> = Vec::new();
    let mut style_values: Vec<HtmlAttrValue> = Vec::new();
    let mut result: HtmlAttrs = Vec::new();
    for (key, value) in attributes {
        let key_string: String = extract_attr_key_string(&key);
        if key_string == ATTR_KEY_CLASS {
            class_values.push(value);
        } else if key_string == ATTR_KEY_STYLE {
            style_values.push(value);
        } else {
            result.push((key, value));
        }
    }
    let push_merged = |result: &mut HtmlAttrs,
                       key_str: &str,
                       mut values: Vec<HtmlAttrValue>,
                       wrap: fn(Vec<HtmlAttrValue>) -> HtmlAttrValue|
     -> () {
        match values.len() {
            0 => {}
            1 => result.push((
                LitStr::new(key_str, proc_macro2::Span::call_site()).to_token_stream(),
                values.remove(0),
            )),
            _ => result.push((
                LitStr::new(key_str, proc_macro2::Span::call_site()).to_token_stream(),
                wrap(values),
            )),
        }
    };
    push_merged(
        &mut result,
        ATTR_KEY_CLASS,
        class_values,
        HtmlAttrValue::Classes,
    );
    push_merged(
        &mut result,
        ATTR_KEY_STYLE,
        style_values,
        HtmlAttrValue::Styles,
    );
    result
}

/// Converts an `HtmlAttrValue` into a token stream that produces an `AttributeValue`.
///
/// This function mirrors the logic in `HtmlElement::ToTokens` for converting
/// attribute values, but always wraps the result as an `AttributeValue` variant
/// suitable for passing to `AttributeValue::merge_class`.
///
/// # Arguments
///
/// - `&HtmlAttrValue` - The attribute value to convert.
/// - `&str` - The attribute key name (used for event detection).
/// - `bool` - Whether this is a component attribute.
///
/// # Returns
///
/// - `proc_macro2::TokenStream` - Token stream that evaluates to an `AttributeValue`.
pub(crate) fn attr_value_to_attribute_value_tokens(
    ctx: &AttrValueContext<'_>,
) -> proc_macro2::TokenStream {
    let value: &HtmlAttrValue = ctx.get_value();
    let key_str: &str = ctx.get_key_str();
    let is_component: bool = ctx.get_is_component();
    match value {
        HtmlAttrValue::Expr(expr) => {
            if let Some(event_name_str) = key_str.strip_prefix(EVENT_ATTR_PREFIX) {
                if is_component {
                    quote! {
                        ::euv::CallbackNamedAdapter::new(#expr, #key_str).into()
                    }
                } else {
                    quote! {
                        ::euv::EventNamedAdapter::new(#expr, #event_name_str).into()
                    }
                }
            } else if key_str == ATTR_KEY_CHILDREN {
                quote! { ::euv::AttributeValue::Dynamic(Box::new(#expr)) }
            } else if key_str == ATTR_KEY_INNER_HTML {
                // `inner_html:` accepts either a `String` / `&str` for a
                // static payload or a `Signal<String>` for a reactive
                // one. The adapter's `From` impls disambiguate at compile
                // time. We pass the raw expression through so the user
                // gets the same Rust type inference they'd see from
                // `let _: AttributeValue = my_html.into()`.
                quote! { ::euv::InnerHtmlAdapter::new(#expr).into() }
            } else {
                quote! {
                    ::euv::AttrValueAdapter::new(#expr).into()
                }
            }
        }
        HtmlAttrValue::If(_) | HtmlAttrValue::Match(_) => {
            quote! { #value }
        }
        HtmlAttrValue::Style(props) => {
            let has_conditional: bool =
                props
                    .iter()
                    .any(|(_, style_value): &(String, HtmlStylePropValue)| {
                        matches!(
                            style_value,
                            HtmlStylePropValue::If(_) | HtmlStylePropValue::Match(_)
                        )
                    });
            if has_conditional {
                quote! { #value }
            } else {
                quote! { ::euv::AttributeValue::Text(#value) }
            }
        }
        HtmlAttrValue::Classes(_) | HtmlAttrValue::Styles(_) => {
            quote! { #value }
        }
    }
}

/// Converts a style-related `HtmlAttrValue` into a token stream that produces
/// an `AttributeValue`.
///
/// Style values are wrapped in `AttributeValue::Text(...)` for static strings,
/// or kept as `AttributeValue::Signal(...)` for reactive style attributes.
///
/// # Arguments
///
/// - `&HtmlAttrValue` - The style attribute value to convert.
///
/// # Returns
///
/// - `proc_macro2::TokenStream` - Token stream that evaluates to an `AttributeValue`.
pub(crate) fn style_value_to_attribute_value_tokens(
    value: &HtmlAttrValue,
) -> proc_macro2::TokenStream {
    match value {
        HtmlAttrValue::Style(props) => {
            let has_conditional: bool =
                props
                    .iter()
                    .any(|(_, style_value): &(String, HtmlStylePropValue)| {
                        matches!(
                            style_value,
                            HtmlStylePropValue::If(_) | HtmlStylePropValue::Match(_)
                        )
                    });
            if has_conditional {
                quote! { #value }
            } else {
                quote! { ::euv::AttributeValue::Text(#value) }
            }
        }
        HtmlAttrValue::If(_) | HtmlAttrValue::Match(_) => {
            quote! { #value }
        }
        HtmlAttrValue::Expr(expr) => {
            quote! { ::euv::AttributeValue::Text(#expr.to_string()) }
        }
        HtmlAttrValue::Classes(_) | HtmlAttrValue::Styles(_) => {
            quote! { #value }
        }
    }
}

/// Extracts the clean attribute key string from a token stream.
///
/// For a static literal/ident key (e.g. `"data-foo"` or `class`) the result is
/// the literal text. For a dynamic braced key (e.g. `{expr}`) the result is
/// the empty string — the runtime attribute name is computed from `expr` and
/// is therefore unknowable at macro-expansion time.
///
/// # Arguments
///
/// - `&proc_macro2::TokenStream` - The token stream representing an attribute key.
///
/// # Returns
///
/// - `String` - The clean attribute key string.
pub(crate) fn extract_attr_key_string(key: &proc_macro2::TokenStream) -> String {
    // A dynamic braced key keeps no brace group in its token stream (the
    // parser strips the surrounding `{ }` before storing the inner `Expr`),
    // so we cannot distinguish it from a bare ident here on shape alone.
    // Distinguish by checking whether the very first token is a string
    // literal (only the literal/ident parser branches produce quoted keys);
    // anything else falls through to the raw token text, which the caller
    // matches against known special key names (`class`, `style`, `on*`,
    // `target`, ...). A braced dynamic key such as `{dynamic_key.get()}`
    // therefore yields the empty string, signalling "no compile-time name".
    let raw: String = key.to_string().replace(CHAR_SPACE, STR_EMPTY);
    if raw.starts_with(CHAR_DOUBLE_QUOTE) && raw.ends_with(CHAR_DOUBLE_QUOTE) {
        raw[1..raw.len() - 1].to_string()
    } else if raw.starts_with(CHAR_DOUBLE_QUOTE) {
        raw[1..].to_string()
    } else if raw.is_empty() {
        raw
    } else {
        raw.strip_prefix(RAW_IDENT_PREFIX)
            .unwrap_or(&raw)
            .to_string()
    }
}

/// Builds a token stream that evaluates to the runtime attribute name as a
/// `String`.
///
/// - Static literal/ident keys produce `#name.to_string()`.
/// - Dynamic braced keys produce `Into::<String>::into(#inner_expr)`, which
///   is evaluated at runtime so the attribute name tracks the current signal
///   value. `Into` is used instead of `ToString` on purpose: the dominant
///   expression shape is `some_signal.get()` on a `Signal<String>`, which
///   already yields an owned `String`. `Into::<String>::into` on a `String`
///   is the identity conversion (a move, zero allocation), whereas
///   `.to_string()` would route through `Display` and allocate a second,
///   redundant copy. `&str` and `&String` expressions still allocate exactly
///   once, same as before.
///
/// The result is intended to be wrapped in `Cow::Owned` at the call site so
/// every key path produces an owned name; for the static case this is
/// equivalent to `Cow::Borrowed` after one `String::from`.
pub(crate) fn extract_attr_key_tokens(key: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
    let raw: String = key.to_string().replace(CHAR_SPACE, STR_EMPTY);
    if raw.starts_with(CHAR_DOUBLE_QUOTE) && raw.ends_with(CHAR_DOUBLE_QUOTE) {
        let inner: String = raw[1..raw.len() - 1].to_string();
        quote! { #inner.to_string() }
    } else if raw.is_empty() {
        quote! { String::new() }
    } else {
        // Either a bare ident key (`class`, `style`, `onclick`, ...) or a
        // dynamic braced key whose surrounding braces were stripped by the
        // parser. Both are valid Rust expressions convertible into a `String`
        // at runtime. `Into::<String>::into` avoids the redundant `Display`
        // round-trip (and its extra allocation) when the expression already
        // produces an owned `String`, which is the common case for
        // `signal.get()` on `Signal<String>`.
        quote! { ::std::convert::Into::<String>::into(#key) }
    }
}

/// Returns `true` when the attribute key token stream is a static literal or
/// identifier (e.g. `"data-foo"`, `class`, `onclick`, `r#type`) that can be
/// embedded as a `Cow::Borrowed(&'static str)` to avoid the per-render
/// `String` allocation that `extract_attr_key_tokens` would otherwise incur.
///
/// Returns `false` for any token stream that contains a punctuation, group,
/// or non-literal/ident token — in particular a dynamic braced key such as
/// `{dynamic_key.get()}` collapses to a bare expression token stream after
/// parsing, which only this predicate can distinguish from a plain ident key
/// like `class`. Static keys keep their zero-allocation fast path; dynamic
/// keys take the `Cow::Owned` runtime-evaluate path.
///
/// # Arguments
///
/// - `&proc_macro2::TokenStream` - The token stream representing the
///   attribute key, exactly as the parser stored it.
///
/// # Returns
///
/// - `bool` - `true` if every token is either a literal (string, char,
///   numeric) or a plain identifier (including raw idents like `r#type`),
///   `false` otherwise.
pub(crate) fn is_static_attr_key_token(key: &proc_macro2::TokenStream) -> bool {
    use proc_macro2::TokenTree;
    let mut has_token: bool = false;
    // `proc_macro2::TokenStream` only implements `IntoIterator` by value
    // (not by reference), so iterating without `clone()` is impossible at
    // the API level. On the proc-macro host (wasm32 or compile-time
    // evaluation under rustc) the inner `proc_macro::TokenStream` is an
    // `Arc`-backed structure, so `clone()` is cheap. The clone below is
    // therefore equivalent in cost to a shallow Arc bump.
    for token in key.clone() {
        has_token = true;
        match token {
            TokenTree::Ident(_) | TokenTree::Literal(_) => continue,
            _ => return false,
        }
    }
    has_token
}

/// Constructs a `Cow::Borrowed(&'static str)` token stream for a static
/// attribute key whose compile-time value is `key_str`.
///
/// The caller must guarantee `is_static_attr_key_token(key)` is `true` and
/// that `extract_attr_key_string(key)` equals `key_str`. Together those
/// preconditions let the macro emit a shared `&'static str` for the
/// attribute name across the whole rendered DOM, instead of allocating a
/// fresh `String` per element on every render.
///
/// # Arguments
///
/// - `&str` - The compile-time attribute key, e.g. `"class"`, `"data-foo"`,
///   `"onclick"`.
///
/// # Returns
///
/// - `proc_macro2::TokenStream` - A token stream that evaluates to
///   `Cow::Borrowed(key_str)` at runtime.
pub(crate) fn borrowed_attr_name_token(key_str: &str) -> proc_macro2::TokenStream {
    quote! { ::std::borrow::Cow::Borrowed(#key_str) }
}

/// Constructs a `Cow::Owned(String)` token stream for a dynamic attribute
/// key that must be evaluated at runtime, given the inner expression
/// tokens.
///
/// The inner expression is converted via `Into::<String>::into(...)`, which
/// is a zero-allocation move when the expression already yields an owned
/// `String` (the common `signal.get()` case) and a single allocation for
/// `&str` / `&String` / `Cow<str>`. The caller must guarantee
/// `!is_static_attr_key_token(key)` so this path is only used for keys
/// that genuinely depend on runtime state.
///
/// # Arguments
///
/// - `&proc_macro2::TokenStream` - The original attribute key token stream,
///   exactly as the parser stored it.
///
/// # Returns
///
/// - `proc_macro2::TokenStream` - A token stream that evaluates to
///   `Cow::Owned(Into::<String>::into(#key))` at runtime.
pub(crate) fn owned_attr_name_token(key: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
    let key_name_token: proc_macro2::TokenStream = extract_attr_key_tokens(key);
    quote! { ::std::borrow::Cow::Owned(#key_name_token) }
}

/// Converts an `HtmlAttrValue` into a token stream that produces an `AttributeValue`
/// for use inside an `AttributeEntry::new()` call.
///
/// This is the shared conversion logic used by both `HtmlElement::to_tokens` and
/// `HtmlDynamicTag::to_tokens` to avoid duplicating the attribute value dispatch.
///
/// # Arguments
///
/// - `&HtmlAttrValue` - The attribute value to convert.
/// - `&str` - The attribute key name (used for event and special key detection).
///
/// # Returns
///
/// - `proc_macro2::TokenStream` - Token stream that evaluates to an `AttributeValue`.
pub(crate) fn attr_value_to_entry_value_tokens(
    ctx: &AttrEntryContext<'_>,
) -> proc_macro2::TokenStream {
    let value: &HtmlAttrValue = ctx.get_value();
    let key_str: &str = ctx.get_key_str();
    match value {
        HtmlAttrValue::Style(props) => {
            let has_conditional: bool = is_style_props_conditional(props);
            if has_conditional {
                quote! { #value }
            } else {
                quote! { ::euv::AttributeValue::Text(#value) }
            }
        }
        HtmlAttrValue::If(_) | HtmlAttrValue::Match(_) => {
            quote! { #value }
        }
        HtmlAttrValue::Classes(_) | HtmlAttrValue::Styles(_) => {
            quote! { #value }
        }
        HtmlAttrValue::Expr(expr) => {
            if let Some(event_name_str) = key_str.strip_prefix(EVENT_ATTR_PREFIX) {
                quote! {
                    ::euv::EventNamedAdapter::new(#expr, #event_name_str).into()
                }
            } else if key_str == ATTR_KEY_CHILDREN {
                quote! { ::euv::AttributeValue::Dynamic(Box::new(#expr)) }
            } else if key_str == ATTR_KEY_INNER_HTML {
                // `inner_html:` accepts either a `String` / `&str` for a
                // static payload or a `Signal<String>` for a reactive
                // one. The adapter's `From` impls disambiguate at compile
                // time. We pass the raw expression through so the user
                // gets the same Rust type inference they'd see from
                // `let _: AttributeValue = my_html.into()`.
                quote! { ::euv::InnerHtmlAdapter::new(#expr).into() }
            } else {
                quote! {
                    ::euv::AttrValueAdapter::new(#expr).into()
                }
            }
        }
    }
}

/// Builds a single `field: expr` token used inside a component's Props
/// struct literal, converting the attribute value to the right Rust
/// expression for the component's Props struct field. Used by both
/// `HtmlElement::to_tokens` (for direct component tags) and
/// `HtmlDynamicTag::to_tokens` (for dynamic tags dispatched to a component).
///
/// # Arguments
///
/// - `&Ident` - Shared reference to a `Ident`.
/// - `&str` - Shared reference to a `str`.
/// - `&HtmlAttrValue` - Shared reference to a `HtmlAttrValue`.
/// - `Option<&HashMap<String, String>>` - Optional borrowed view of the
///   field-type map; `None` means the caller has no component-registry
///   context available (dynamic-tag path).
///
/// # Returns
///
/// - `proc_macro2::TokenStream` - A `proc_macro2::TokenStream` value.
pub(crate) fn prop_field_token(
    field_ident: &Ident,
    key_string: &str,
    value: &HtmlAttrValue,
    props_field_types: Option<&HashMap<String, String>>,
) -> proc_macro2::TokenStream {
    match value {
        HtmlAttrValue::Expr(expr) => {
            quote! { #field_ident: #expr }
        }
        HtmlAttrValue::If(html_attr_if) => {
            let else_default: proc_macro2::TokenStream = match props_field_types
                .and_then(|m: &HashMap<_, _>| m.get(key_string))
                .map(|field_type: &String| field_type.as_str())
            {
                Some(TYPE_VIRTUAL_NODE) => quote! { ::euv::VirtualNode::Empty },
                _ => quote! { #STR_EMPTY },
            };
            let ctx: AttrIfContext<'_> =
                AttrIfContext::new(html_attr_if, &else_default, AttrIfMode::Raw);
            let if_chain: proc_macro2::TokenStream = attr_if_to_tokens(&ctx);
            quote! { #field_ident: #if_chain }
        }
        HtmlAttrValue::Match(html_attr_match) => {
            let match_expr: proc_macro2::TokenStream =
                attr_match_to_tokens(html_attr_match, AttrIfMode::Raw);
            quote! { #field_ident: #match_expr }
        }
        HtmlAttrValue::Style(props) => {
            let has_conditional: bool = is_style_props_conditional(props);
            if has_conditional {
                quote! { #field_ident: #value }
            } else {
                quote! { #field_ident: (#value).to_string() }
            }
        }
        _ => {
            quote! { #field_ident: #value }
        }
    }
}