svelte-syntax 0.1.5

Lightweight syntax-layer crate for the Rust Svelte toolchain
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
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::Arc;

use self_cell::self_cell;
use tree_sitter::{InputEdit, Node, Parser, Point, Tree, TreeCursor};

use crate::ast::modern::Expression;
use crate::error::CompileError;
use crate::parse::is_component_name;
use crate::primitives::{BytePos, Span};
use crate::source::SourceText;

/// Languages supported by the CST parser.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Language {
    /// The Svelte component language.
    Svelte,
}

// ---------------------------------------------------------------------------
// ExpressionCache — pre-parsed OXC expressions indexed by byte offset
// ---------------------------------------------------------------------------

/// Cache of pre-parsed OXC expressions, keyed by node start byte offset.
#[derive(Debug, Default)]
pub struct ExpressionCache {
    expressions: HashMap<usize, Expression>,
}

impl ExpressionCache {
    /// Build the cache by walking the tree and parsing all expression nodes.
    pub fn from_tree(source: &str, tree: &Tree) -> Self {
        let mut cache = Self::default();
        cache.walk_and_parse(source, tree.root_node());
        cache
    }

    /// Look up a pre-parsed expression by its node's start byte offset.
    pub fn get(&self, start_byte: usize) -> Option<&Expression> {
        self.expressions.get(&start_byte)
    }

    /// Number of cached expressions.
    pub fn len(&self) -> usize {
        self.expressions.len()
    }

    /// Whether the cache is empty.
    pub fn is_empty(&self) -> bool {
        self.expressions.is_empty()
    }

    fn walk_and_parse(&mut self, source: &str, node: Node<'_>) {
        match node.kind() {
            "expression" | "expression_value" => {
                self.parse_and_insert(source, node);
            }
            _ => {}
        }

        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            self.walk_and_parse(source, child);
        }
    }

    fn parse_and_insert(&mut self, source: &str, node: Node<'_>) {
        if let Some(expr) = parse_expression_from_node(source, node) {
            self.expressions.insert(node.start_byte(), expr);
        }
    }
}

/// Parse a tree-sitter expression/expression_value node into an OXC `Expression`.
fn parse_expression_from_node(source: &str, node: Node<'_>) -> Option<Expression> {
    let raw = node.utf8_text(source.as_bytes()).ok()?;

    // For expression nodes with `{...}` delimiters, extract the inner content
    let (text, start_byte) = if node.kind() == "expression" {
        if let Some(content) = node.child_by_field_name("content") {
            let t = content.utf8_text(source.as_bytes()).ok()?;
            (t, content.start_byte())
        } else if raw.len() >= 2 && raw.starts_with('{') && raw.ends_with('}') {
            (&raw[1..raw.len() - 1], node.start_byte() + 1)
        } else {
            (raw, node.start_byte())
        }
    } else {
        (raw, node.start_byte())
    };

    let trimmed = text.trim();
    if trimmed.is_empty() {
        return None;
    }

    let leading = text.find(trimmed).unwrap_or(0);
    let abs = start_byte + leading;
    let (line, column) = crate::parse::line_column_at_offset(source, abs);
    crate::parse::parse_modern_expression_from_text(trimmed, abs, line, column)
}

// ---------------------------------------------------------------------------
// ParsedDocument — self-contained owning document (source + tree + expressions)
// ---------------------------------------------------------------------------

struct ParsedDocumentOwner {
    source: Arc<str>,
    tree: Tree,
    expressions: ExpressionCache,
}

/// The dependent data borrowing from the owner.
struct ParsedDocumentDependent<'a> {
    root: Root<'a>,
}

self_cell! {
    /// A fully parsed, self-contained document.
    ///
    /// Owns the source text, tree-sitter tree, and pre-parsed expression cache.
    /// Provides zero-copy wrapper access through `root()`.
    pub struct ParsedDocument {
        owner: ParsedDocumentOwner,

        #[covariant]
        dependent: ParsedDocumentDependent,
    }
}

impl std::fmt::Debug for ParsedDocument {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ParsedDocument")
            .field("source_len", &self.source().len())
            .field("expressions", &self.expressions().len())
            .finish()
    }
}

// SAFETY: ParsedDocument owns all its data (Arc<str>, Tree, ExpressionCache).
// The !Send/!Sync comes from self_cell's self-referential borrow, but the
// underlying data is fully owned and not shared across threads unsafely.
unsafe impl Send for ParsedDocument {}
unsafe impl Sync for ParsedDocument {}

impl ParsedDocument {
    /// Parse source into a fully self-contained document.
    pub fn parse(source: &str) -> Result<Self, CompileError> {
        let tree = {
            let mut parser = CstParser::new().configure(Language::Svelte)?;
            let st = SourceText::new(crate::primitives::SourceId::new(0), source, None);
            let doc = parser.parse(st)?;
            doc.tree
        };
        let expressions = ExpressionCache::from_tree(source, &tree);
        let source_arc: Arc<str> = Arc::from(source);

        Ok(ParsedDocument::new(
            ParsedDocumentOwner {
                source: source_arc,
                tree,
                expressions,
            },
            |owner| ParsedDocumentDependent {
                root: Root::new(&owner.source, owner.tree.root_node()),
            },
        ))
    }

    /// The source text.
    pub fn source(&self) -> &str {
        &self.borrow_owner().source
    }

    /// The root wrapper node.
    pub fn root(&self) -> &Root<'_> {
        &self.borrow_dependent().root
    }

    /// The pre-parsed expression cache.
    pub fn expressions(&self) -> &ExpressionCache {
        &self.borrow_owner().expressions
    }

    /// The underlying tree-sitter tree.
    pub fn tree(&self) -> &Tree {
        &self.borrow_owner().tree
    }
}

// ---------------------------------------------------------------------------
// Document — legacy borrowed document (kept for incremental parsing support)
// ---------------------------------------------------------------------------

/// A parsed tree-sitter document holding the source text, language, and
/// concrete syntax tree.
///
/// Use [`parse_svelte`] to create a `Document` from source text, or
/// [`CstParser`] for more control over parser reuse.
#[derive(Debug)]
pub struct Document<'src> {
    /// The language this document was parsed as.
    pub language: Language,
    /// The original source text.
    pub source: SourceText<'src>,
    /// The tree-sitter syntax tree.
    pub tree: Tree,
}

impl<'src> Document<'src> {
    /// Return the root tree-sitter node.
    pub fn root_node(&self) -> Node<'_> {
        self.tree.root_node()
    }

    /// Return the root node kind.
    pub fn root_kind(&self) -> &str {
        self.root_node().kind()
    }

    /// Return `true` if the CST contains parse errors.
    pub fn has_error(&self) -> bool {
        self.root_node().has_error()
    }

    /// Return the root node span in byte offsets.
    pub fn root_span(&self) -> Span {
        node_span(self.root_node())
    }

    /// Apply an edit to the stored tree so it can be reused for incremental reparsing.
    pub fn apply_edit(&mut self, edit: CstEdit) {
        self.tree.edit(&edit.into_input_edit());
    }

    /// Clone the tree for incremental parsing. The source text reference is
    /// preserved but the tree is cloned so `apply_edit` can be called on the
    /// copy without mutating the original.
    pub fn clone_for_incremental(&self) -> Document<'src> {
        Document {
            language: self.language,
            source: self.source,
            tree: self.tree.clone(),
        }
    }

    /// Return byte ranges that differ structurally between this document and a
    /// previously parsed document. Wraps [`Tree::changed_ranges`].
    pub fn changed_ranges(&self, old: &Document<'_>) -> Vec<std::ops::Range<usize>> {
        old.tree
            .changed_ranges(&self.tree)
            .map(|r| r.start_byte..r.end_byte)
            .collect()
    }
}

/// A row/column position in source text, used by [`CstEdit`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CstPoint {
    /// Zero-based line number.
    pub row: usize,
    /// Zero-based byte column within the line.
    pub column: usize,
}

/// Describes a text edit for incremental reparsing.
///
/// Records the byte range that was replaced and the resulting positions after
/// the edit. Use the convenience constructors [`CstEdit::replace`],
/// [`CstEdit::insert`], and [`CstEdit::delete`] to build edits from the old
/// source text.
///
/// # Example
///
/// ```
/// use svelte_syntax::CstEdit;
///
/// let old = "<div>Hello</div>";
/// let edit = CstEdit::replace(old, 5, 10, "World");
///
/// assert_eq!(edit.start_byte, 5);
/// assert_eq!(edit.new_end_byte, 10); // 5 + "World".len()
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CstEdit {
    /// Byte offset where the edit begins.
    pub start_byte: usize,
    /// Byte offset where the old text ended (before the edit).
    pub old_end_byte: usize,
    /// Byte offset where the new text ends (after the edit).
    pub new_end_byte: usize,
    /// Row/column position where the edit begins.
    pub start_position: CstPoint,
    /// Row/column position where the old text ended.
    pub old_end_position: CstPoint,
    /// Row/column position where the new text ends.
    pub new_end_position: CstPoint,
}

impl CstEdit {
    /// Create an edit that replaces `old_source[start_byte..old_end_byte]` with
    /// `new_text`. Positions are computed automatically from the old source.
    pub fn replace(
        old_source: &str,
        start_byte: usize,
        old_end_byte: usize,
        new_text: &str,
    ) -> Self {
        let start_position = byte_point_at_offset(old_source, start_byte);
        let old_end_position = byte_point_at_offset(old_source, old_end_byte);
        let new_end_byte = start_byte.saturating_add(new_text.len());
        let new_end_position = advance_point(start_position, new_text);

        Self {
            start_byte,
            old_end_byte,
            new_end_byte,
            start_position,
            old_end_position,
            new_end_position,
        }
    }

    /// Create an edit that inserts `new_text` at `start_byte` without removing
    /// any existing text.
    pub fn insert(old_source: &str, start_byte: usize, new_text: &str) -> Self {
        Self::replace(old_source, start_byte, start_byte, new_text)
    }

    /// Create an edit that deletes `old_source[start_byte..old_end_byte]`.
    pub fn delete(old_source: &str, start_byte: usize, old_end_byte: usize) -> Self {
        Self::replace(old_source, start_byte, old_end_byte, "")
    }

    fn into_input_edit(self) -> InputEdit {
        InputEdit {
            start_byte: self.start_byte,
            old_end_byte: self.old_end_byte,
            new_end_byte: self.new_end_byte,
            start_position: self.start_position.into_point(),
            old_end_position: self.old_end_position.into_point(),
            new_end_position: self.new_end_position.into_point(),
        }
    }
}

impl CstPoint {
    fn into_point(self) -> Point {
        Point {
            row: self.row,
            column: self.column,
        }
    }
}

/// Typestate marker for a parser before a language has been selected.
pub struct Unconfigured;
/// Typestate marker for a parser after a language has been selected.
pub struct Configured {
    language: Language,
}

/// Tree-sitter-backed CST parser with typestate for language selection.
///
/// Create a parser with [`CstParser::new`], configure it with
/// [`CstParser::configure`], then call [`parse`](CstParser::parse) or
/// [`parse_incremental`](CstParser::parse_incremental).
///
/// For a simpler one-shot API, use the free function [`parse_svelte`].
///
/// # Example
///
/// ```
/// use svelte_syntax::cst::{CstParser, Language};
/// use svelte_syntax::{SourceId, SourceText};
///
/// let mut parser = CstParser::new().configure(Language::Svelte)?;
/// let source = SourceText::new(SourceId::new(0), "<p>hi</p>", None);
/// let doc = parser.parse(source)?;
///
/// assert_eq!(doc.root_kind(), "document");
/// # Ok::<(), svelte_syntax::CompileError>(())
/// ```
pub struct CstParser<State> {
    parser: Parser,
    state: State,
}

impl CstParser<Unconfigured> {
    /// Create a parser with no configured language.
    pub fn new() -> Self {
        Self {
            parser: Parser::new(),
            state: Unconfigured,
        }
    }

    /// Configure the parser for a supported language.
    pub fn configure(mut self, language: Language) -> Result<CstParser<Configured>, CompileError> {
        let ts_lang = match language {
            Language::Svelte => tree_sitter_svelte::language(),
        };

        self.parser
            .set_language(&ts_lang)
            .map_err(|_| CompileError::internal("failed to configure tree-sitter language"))?;

        Ok(CstParser {
            parser: self.parser,
            state: Configured { language },
        })
    }
}

impl Default for CstParser<Unconfigured> {
    fn default() -> Self {
        Self::new()
    }
}

impl CstParser<Configured> {
    /// Parse source text into a CST document.
    pub fn parse<'src>(
        &mut self,
        source: SourceText<'src>,
    ) -> Result<Document<'src>, CompileError> {
        let tree = self
            .parser
            .parse(source.text, None)
            .ok_or_else(|| CompileError::internal("tree-sitter parser returned no syntax tree"))?;

        Ok(Document {
            language: self.state.language,
            source,
            tree,
        })
    }

    /// Parse source text using a previous tree plus edit information for incremental reparsing.
    pub fn parse_incremental<'src>(
        &mut self,
        source: SourceText<'src>,
        previous: &Document<'_>,
        edit: CstEdit,
    ) -> Result<Document<'src>, CompileError> {
        let mut previous_tree = previous.tree.clone();
        previous_tree.edit(&edit.into_input_edit());

        let tree = self
            .parser
            .parse(source.text, Some(&previous_tree))
            .ok_or_else(|| CompileError::internal("tree-sitter parser returned no syntax tree"))?;

        Ok(Document {
            language: self.state.language,
            source,
            tree,
        })
    }
}

/// Parse Svelte source into a tree-sitter CST document.
///
/// This is the simplest way to obtain a concrete syntax tree. For parser
/// reuse across multiple files, use [`CstParser`] directly.
///
/// # Example
///
/// ```
/// use svelte_syntax::{SourceId, SourceText, parse_svelte};
///
/// let source = SourceText::new(SourceId::new(0), "<div>hello</div>", None);
/// let cst = parse_svelte(source)?;
///
/// assert_eq!(cst.root_kind(), "document");
/// # Ok::<(), svelte_syntax::CompileError>(())
/// ```
pub fn parse_svelte<'src>(source: SourceText<'src>) -> Result<Document<'src>, CompileError> {
    let mut parser = CstParser::new().configure(Language::Svelte)?;
    parser.parse(source)
}

/// Parse Svelte source using an already-edited old tree for incremental reparsing.
/// Unlike `parse_svelte_incremental`, this expects the caller to have already
/// called `apply_edit` on the old document.
pub fn parse_svelte_with_old_tree<'src>(
    source: SourceText<'src>,
    edited_old: &Document<'_>,
) -> Result<Document<'src>, CompileError> {
    let ts_lang = match edited_old.language {
        Language::Svelte => tree_sitter_svelte::language(),
    };
    let mut parser = Parser::new();
    parser
        .set_language(&ts_lang)
        .map_err(|_| CompileError::internal("failed to configure tree-sitter language"))?;
    let tree = parser
        .parse(source.text, Some(&edited_old.tree))
        .ok_or_else(|| CompileError::internal("tree-sitter parser returned no syntax tree"))?;
    Ok(Document {
        language: edited_old.language,
        source,
        tree,
    })
}

/// Parse Svelte source into a tree-sitter CST using a previous CST and edit for incremental reparsing.
pub fn parse_svelte_incremental<'src>(
    source: SourceText<'src>,
    previous: &Document<'_>,
    edit: CstEdit,
) -> Result<Document<'src>, CompileError> {
    let mut parser = CstParser::new().configure(Language::Svelte)?;
    parser.parse_incremental(source, previous, edit)
}

fn node_span(node: Node<'_>) -> Span {
    let start = byte_pos_saturating(node.start_byte());
    let end = byte_pos_saturating(node.end_byte());
    Span::new(start, end)
}

fn byte_pos_saturating(offset: usize) -> BytePos {
    u32::try_from(offset)
        .map(BytePos::from)
        .unwrap_or_else(|_| BytePos::from(u32::MAX))
}

fn byte_point_at_offset(source: &str, offset: usize) -> CstPoint {
    let bounded = offset.min(source.len());
    let mut row = 0usize;
    let mut column = 0usize;

    for byte in source.as_bytes().iter().take(bounded) {
        if *byte == b'\n' {
            row += 1;
            column = 0;
        } else {
            column += 1;
        }
    }

    CstPoint { row, column }
}

fn advance_point(start: CstPoint, inserted_text: &str) -> CstPoint {
    let mut point = start;

    for byte in inserted_text.as_bytes() {
        if *byte == b'\n' {
            point.row += 1;
            point.column = 0;
        } else {
            point.column += 1;
        }
    }

    point
}

// ---------------------------------------------------------------------------
// Thin wrapper types — zero-copy views over tree-sitter nodes
// ---------------------------------------------------------------------------

/// Extract the text of a tree-sitter node from source.
fn node_text<'src>(source: &'src str, node: Node<'_>) -> &'src str {
    &source[node.start_byte()..node.end_byte()]
}

/// A thin wrapper around a tree-sitter node and source text.
/// All wrapper types share this layout: `(&str, Node)`.
macro_rules! define_wrapper {
    ($($(#[$meta:meta])* $name:ident),* $(,)?) => {
        $(
            $(#[$meta])*
            #[derive(Clone, Copy)]
            pub struct $name<'src> {
                source: &'src str,
                node: Node<'src>,
            }

            impl<'src> $name<'src> {
                /// Create from source text and a matching tree-sitter node.
                pub fn new(source: &'src str, node: Node<'src>) -> Self {
                    Self { source, node }
                }

                /// The underlying tree-sitter node.
                pub fn ts_node(&self) -> Node<'src> {
                    self.node
                }

                /// Byte offset of the start of this node.
                pub fn start(&self) -> usize {
                    self.node.start_byte()
                }

                /// Byte offset of the end of this node.
                pub fn end(&self) -> usize {
                    self.node.end_byte()
                }

                /// Span covering this node.
                pub fn span(&self) -> Span {
                    node_span(self.node)
                }

                /// The raw source text of this node.
                pub fn text(&self) -> &'src str {
                    node_text(self.source, self.node)
                }

                /// Whether this node has parse errors.
                pub fn has_error(&self) -> bool {
                    self.node.has_error()
                }
            }

            impl std::fmt::Debug for $name<'_> {
                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    f.debug_struct(stringify!($name))
                        .field("kind", &self.node.kind())
                        .field("range", &(self.start()..self.end()))
                        .finish()
                }
            }
        )*
    };
}

define_wrapper!(
    /// Root document node.
    Root,
    /// An HTML/Svelte element.
    Element,
    /// A text node.
    TextNode,
    /// An HTML comment.
    CommentNode,
    /// `{#if}...{:else if}...{:else}...{/if}`
    IfBlock,
    /// `{#each items as item}...{/each}`
    EachBlock,
    /// `{#await promise}...{:then}...{:catch}...{/await}`
    AwaitBlock,
    /// `{#key expression}...{/key}`
    KeyBlock,
    /// `{#snippet name(params)}...{/snippet}`
    SnippetBlock,
    /// `{expression}`
    ExpressionTag,
    /// `{@html expression}`
    HtmlTag,
    /// `{@const assignment}`
    ConstTag,
    /// `{@debug vars}`
    DebugTag,
    /// `{@render snippet()}`
    RenderTag,
    /// `{@attach handler}`
    AttachTag,
    /// An attribute on an element.
    AttributeNode,
    /// A start tag `<name ...>`.
    StartTag,
);

// --- Root accessors ---

impl<'src> Root<'src> {
    /// Iterate over top-level child nodes as `TemplateNode`s.
    pub fn children(&self) -> ChildIter<'src> {
        ChildIter::new(self.source, self.node)
    }
}

// --- Element accessors ---

impl<'src> Element<'src> {
    /// The element's tag name (e.g., "div", "Button", "svelte:head").
    pub fn name(&self) -> &'src str {
        // First child is start_tag or self_closing_tag
        let tag = self.node.child(0).expect("element must have a tag");
        if let Some(name_node) = tag.child_by_field_name("name") {
            node_text(self.source, name_node)
        } else {
            // Fallback: find first tag_name child
            let mut cursor = tag.walk();
            for child in tag.children(&mut cursor) {
                if child.kind() == "tag_name" {
                    return node_text(self.source, child);
                }
            }
            ""
        }
    }

    /// Whether this element uses self-closing syntax (`<br />`).
    pub fn is_self_closing(&self) -> bool {
        self.node.child(0)
            .is_some_and(|tag| tag.kind() == "self_closing_tag")
    }

    /// Whether this element has an explicit end tag.
    pub fn has_end_tag(&self) -> bool {
        let mut cursor = self.node.walk();
        self.node.children(&mut cursor).any(|c| c.kind() == "end_tag")
    }

    /// The start tag node.
    pub fn start_tag(&self) -> Option<StartTag<'src>> {
        let first = self.node.child(0)?;
        match first.kind() {
            "start_tag" | "self_closing_tag" => Some(StartTag::new(self.source, first)),
            _ => None,
        }
    }

    /// Iterate over attributes on this element.
    pub fn attributes(&self) -> AttributeIter<'src> {
        let tag = self.node.child(0).expect("element must have a tag");
        AttributeIter {
            source: self.source,
            cursor: tag.walk(),
            started: false,
        }
    }

    /// Iterate over child content nodes (between start and end tags).
    pub fn children(&self) -> ChildIter<'src> {
        ChildIter::new(self.source, self.node)
    }

    /// Whether this element's name indicates a component.
    pub fn is_component(&self) -> bool {
        is_component_name(self.name())
    }

    /// Classify this element into a `TemplateNode` variant based on its name.
    pub fn classify(&self) -> TemplateNode<'src> {
        classify_element(self.source, self.node)
    }
}

// --- StartTag accessors ---

impl<'src> StartTag<'src> {
    /// The tag name.
    pub fn name(&self) -> &'src str {
        if let Some(name_node) = self.node.child_by_field_name("name") {
            node_text(self.source, name_node)
        } else {
            ""
        }
    }

    /// Iterate over attributes on this start tag.
    pub fn attributes(&self) -> AttributeIter<'src> {
        AttributeIter {
            source: self.source,
            cursor: self.node.walk(),
            started: false,
        }
    }
}

// --- TextNode accessors ---

impl<'src> TextNode<'src> {
    /// The raw text content.
    pub fn raw(&self) -> &'src str {
        node_text(self.source, self.node)
    }

    /// Decoded text content (HTML entities resolved).
    pub fn data(&self) -> Cow<'src, str> {
        // For now, return raw. Entity decoding can be added later.
        Cow::Borrowed(self.raw())
    }
}

// --- CommentNode accessors ---

impl<'src> CommentNode<'src> {
    /// The comment content (without `<!--` and `-->`).
    pub fn data(&self) -> &'src str {
        let raw = self.raw();
        raw.strip_prefix("<!--")
            .and_then(|s| s.strip_suffix("-->"))
            .unwrap_or(raw)
    }

    fn raw(&self) -> &'src str {
        node_text(self.source, self.node)
    }
}

// --- Block accessors ---

impl<'src> IfBlock<'src> {
    /// The expression node for the test condition.
    pub fn test_node(&self) -> Option<Node<'src>> {
        self.node.child_by_field_name("expression")
    }

    /// The raw test expression text.
    pub fn test_text(&self) -> &'src str {
        self.test_node()
            .map(|n| node_text(self.source, n))
            .unwrap_or("")
    }

    /// The pre-parsed test expression from the cache.
    pub fn test_expression<'c>(&self, cache: &'c ExpressionCache) -> Option<&'c Expression> {
        self.test_node().and_then(|n| cache.get(n.start_byte()))
    }

    /// Iterate over consequent (then-branch) child nodes.
    pub fn consequent(&self) -> ChildIter<'src> {
        ChildIter::new(self.source, self.node)
    }

    /// The else clause, if any. Returns either an else fragment or an else-if block.
    pub fn alternate(&self) -> Option<Alternate<'src>> {
        if self.node.kind() == "else_if_clause" {
            // When wrapping an else_if_clause, the alternate is the next
            // sibling clause from the parent if_block, not a child of this node.
            let mut sibling = self.node.next_named_sibling();
            while let Some(s) = sibling {
                match s.kind() {
                    "else_clause" => return Some(Alternate::Else(ElseClause::new(self.source, s))),
                    "else_if_clause" => return Some(Alternate::ElseIf(IfBlock::new(self.source, s))),
                    _ => {}
                }
                sibling = s.next_named_sibling();
            }
            return None;
        }
        let mut cursor = self.node.walk();
        for child in self.node.children(&mut cursor) {
            match child.kind() {
                "else_clause" => return Some(Alternate::Else(ElseClause::new(self.source, child))),
                "else_if_clause" => return Some(Alternate::ElseIf(IfBlock::new(self.source, child))),
                _ => {}
            }
        }
        None
    }
}

impl<'src> EachBlock<'src> {
    /// The iterable expression node.
    pub fn expression_node(&self) -> Option<Node<'src>> {
        self.node.child_by_field_name("expression")
    }

    /// The pre-parsed iterable expression from the cache.
    pub fn expression<'c>(&self, cache: &'c ExpressionCache) -> Option<&'c Expression> {
        self.expression_node().and_then(|n| cache.get(n.start_byte()))
    }

    /// The binding pattern node.
    pub fn binding_node(&self) -> Option<Node<'src>> {
        self.node.child_by_field_name("binding")
    }

    /// The key expression node, if any.
    pub fn key_node(&self) -> Option<Node<'src>> {
        self.node.child_by_field_name("key")
    }

    /// The index identifier node, if any.
    pub fn index_node(&self) -> Option<Node<'src>> {
        self.node.child_by_field_name("index")
    }

    /// Iterate over body child nodes.
    pub fn body(&self) -> ChildIter<'src> {
        ChildIter::new(self.source, self.node)
    }

    /// The else (fallback) clause, if any.
    pub fn fallback(&self) -> Option<ElseClause<'src>> {
        let mut cursor = self.node.walk();
        for child in self.node.children(&mut cursor) {
            if child.kind() == "else_clause" {
                return Some(ElseClause::new(self.source, child));
            }
        }
        None
    }
}

impl<'src> AwaitBlock<'src> {
    /// The promise expression node.
    pub fn expression_node(&self) -> Option<Node<'src>> {
        self.node.child_by_field_name("expression")
    }

    /// The pre-parsed promise expression from the cache.
    pub fn expression<'c>(&self, cache: &'c ExpressionCache) -> Option<&'c Expression> {
        self.expression_node().and_then(|n| cache.get(n.start_byte()))
    }

    /// The pending (loading) body, if any.
    pub fn pending(&self) -> Option<ChildIter<'src>> {
        let mut cursor = self.node.walk();
        for child in self.node.children(&mut cursor) {
            if child.kind() == "await_pending" {
                return Some(ChildIter::new(self.source, child));
            }
        }
        None
    }

    /// The then branch children, if any.
    pub fn then_children(&self) -> Option<ChildIter<'src>> {
        // Check for shorthand form: {#await expr then value}...{/await}
        if let Some(shorthand) = self.node.child_by_field_name("shorthand") {
            if node_text(self.source, shorthand) == "then" {
                if let Some(children) = self.node.child_by_field_name("shorthand_children") {
                    return Some(ChildIter::new(self.source, children));
                }
            }
        }
        self.branch_children("then")
    }

    /// The catch branch children, if any.
    pub fn catch_children(&self) -> Option<ChildIter<'src>> {
        // Check for shorthand form: {#await expr catch error}...{/await}
        if let Some(shorthand) = self.node.child_by_field_name("shorthand") {
            if node_text(self.source, shorthand) == "catch" {
                if let Some(children) = self.node.child_by_field_name("shorthand_children") {
                    return Some(ChildIter::new(self.source, children));
                }
            }
        }
        self.branch_children("catch")
    }

    /// The then binding pattern text (e.g., "value" in `{:then value}`).
    pub fn then_binding_text(&self) -> Option<&'src str> {
        // Shorthand form: {#await expr then value}...{/await}
        if let Some(shorthand) = self.node.child_by_field_name("shorthand") {
            if node_text(self.source, shorthand) == "then" {
                return self.node.child_by_field_name("binding")
                    .map(|n| node_text(self.source, n));
            }
        }
        self.branch_binding("then")
    }

    /// The catch binding pattern text (e.g., "error" in `{:catch error}`).
    pub fn catch_binding_text(&self) -> Option<&'src str> {
        // Shorthand form: {#await expr catch error}...{/await}
        if let Some(shorthand) = self.node.child_by_field_name("shorthand") {
            if node_text(self.source, shorthand) == "catch" {
                return self.node.child_by_field_name("binding")
                    .map(|n| node_text(self.source, n));
            }
        }
        self.branch_binding("catch")
    }

    fn branch_binding(&self, kind_name: &str) -> Option<&'src str> {
        let mut cursor = self.node.walk();
        for child in self.node.children(&mut cursor) {
            if child.kind() == "await_branch" {
                let mut inner = child.walk();
                for c in child.children(&mut inner) {
                    if c.kind() == "branch_kind" && node_text(self.source, c) == kind_name {
                        return child.child_by_field_name("binding")
                            .or_else(|| child.child_by_field_name("expression"))
                            .map(|n| node_text(self.source, n));
                    }
                }
            }
        }
        None
    }

    fn branch_children(&self, kind_name: &str) -> Option<ChildIter<'src>> {
        let mut cursor = self.node.walk();
        for child in self.node.children(&mut cursor) {
            if child.kind() == "await_branch" {
                // Check branch_kind
                let mut inner = child.walk();
                for c in child.children(&mut inner) {
                    if c.kind() == "branch_kind" && node_text(self.source, c) == kind_name {
                        // Find await_branch_children
                        let mut inner2 = child.walk();
                        for c2 in child.children(&mut inner2) {
                            if c2.kind() == "await_branch_children" {
                                return Some(ChildIter::new(self.source, c2));
                            }
                        }
                    }
                }
            }
        }
        None
    }
}

impl<'src> KeyBlock<'src> {
    /// The key expression node.
    pub fn expression_node(&self) -> Option<Node<'src>> {
        self.node.child_by_field_name("expression")
    }

    /// The pre-parsed key expression from the cache.
    pub fn expression<'c>(&self, cache: &'c ExpressionCache) -> Option<&'c Expression> {
        self.expression_node().and_then(|n| cache.get(n.start_byte()))
    }

    /// Iterate over body child nodes.
    pub fn body(&self) -> ChildIter<'src> {
        ChildIter::new(self.source, self.node)
    }
}

impl<'src> SnippetBlock<'src> {
    /// The snippet name.
    pub fn name(&self) -> &'src str {
        let mut cursor = self.node.walk();
        for child in self.node.children(&mut cursor) {
            if child.kind() == "snippet_name" {
                return node_text(self.source, child);
            }
        }
        ""
    }

    /// The snippet parameters node, if any.
    pub fn parameters_node(&self) -> Option<Node<'src>> {
        let mut cursor = self.node.walk();
        for child in self.node.children(&mut cursor) {
            if child.kind() == "snippet_parameters" {
                return Some(child);
            }
        }
        None
    }

    /// The raw text of the parameters (e.g., "a, b" from `{#snippet name(a, b)}`).
    pub fn parameters_text(&self) -> Option<&'src str> {
        self.parameters_node().map(|n| node_text(self.source, n))
    }

    /// Iterate over body child nodes.
    pub fn body(&self) -> ChildIter<'src> {
        ChildIter::new(self.source, self.node)
    }
}

// --- Tag accessors ---

impl<'src> ExpressionTag<'src> {
    /// The expression content node (js or ts).
    pub fn content_node(&self) -> Option<Node<'src>> {
        self.node.child_by_field_name("content")
    }

    /// The raw expression text.
    pub fn content_text(&self) -> &'src str {
        self.content_node()
            .map(|n| node_text(self.source, n))
            .unwrap_or("")
    }

    /// The pre-parsed expression from the cache (keyed on the expression node itself).
    pub fn expression<'c>(&self, cache: &'c ExpressionCache) -> Option<&'c Expression> {
        cache.get(self.node.start_byte())
    }
}

impl<'src> HtmlTag<'src> {
    /// The expression node.
    pub fn expression_node(&self) -> Option<Node<'src>> {
        self.node.child_by_field_name("expression")
            .or_else(|| {
                let mut cursor = self.node.walk();
                self.node.children(&mut cursor)
                    .find(|c| c.kind() == "expression_value")
            })
    }

    /// The pre-parsed expression from the cache.
    pub fn expression<'c>(&self, cache: &'c ExpressionCache) -> Option<&'c Expression> {
        self.expression_node().and_then(|n| cache.get(n.start_byte()))
    }
}

impl<'src> ConstTag<'src> {
    /// The expression/declaration node.
    pub fn expression_node(&self) -> Option<Node<'src>> {
        let mut cursor = self.node.walk();
        self.node.children(&mut cursor)
            .find(|c| c.kind() == "expression_value")
    }

    /// The pre-parsed expression from the cache.
    pub fn expression<'c>(&self, cache: &'c ExpressionCache) -> Option<&'c Expression> {
        self.expression_node().and_then(|n| cache.get(n.start_byte()))
    }
}

impl<'src> DebugTag<'src> {
    /// The expression value node containing debug identifiers.
    pub fn expression_node(&self) -> Option<Node<'src>> {
        let mut cursor = self.node.walk();
        self.node.children(&mut cursor)
            .find(|c| c.kind() == "expression_value")
    }

    /// The pre-parsed expression from the cache.
    pub fn expression<'c>(&self, cache: &'c ExpressionCache) -> Option<&'c Expression> {
        self.expression_node().and_then(|n| cache.get(n.start_byte()))
    }
}

impl<'src> RenderTag<'src> {
    /// The expression node.
    pub fn expression_node(&self) -> Option<Node<'src>> {
        self.node.child_by_field_name("expression")
            .or_else(|| {
                let mut cursor = self.node.walk();
                self.node.children(&mut cursor)
                    .find(|c| c.kind() == "expression_value")
            })
    }

    /// The pre-parsed expression from the cache.
    pub fn expression<'c>(&self, cache: &'c ExpressionCache) -> Option<&'c Expression> {
        self.expression_node().and_then(|n| cache.get(n.start_byte()))
    }
}

impl<'src> AttachTag<'src> {
    /// The expression node.
    pub fn expression_node(&self) -> Option<Node<'src>> {
        let mut cursor = self.node.walk();
        self.node.children(&mut cursor)
            .find(|c| c.kind() == "expression_value" || c.kind() == "expression")
    }

    /// The pre-parsed expression from the cache.
    pub fn expression<'c>(&self, cache: &'c ExpressionCache) -> Option<&'c Expression> {
        self.expression_node().and_then(|n| cache.get(n.start_byte()))
    }
}

// --- AttributeNode accessors ---

impl<'src> AttributeNode<'src> {
    /// The attribute name.
    pub fn name(&self) -> &'src str {
        if let Some(name_node) = self.node.child_by_field_name("name") {
            node_text(self.source, name_node)
        } else {
            // Shorthand attribute — content is the name
            node_text(self.source, self.node)
        }
    }

    /// The attribute value node, if any.
    pub fn value_node(&self) -> Option<Node<'src>> {
        self.node.child_by_field_name("value")
    }

    /// Whether this is a shorthand attribute (`{identifier}`).
    pub fn is_shorthand(&self) -> bool {
        self.node.kind() == "shorthand_attribute"
    }

    /// Whether this is a spread attribute (`{...expr}`).
    pub fn is_spread(&self) -> bool {
        self.is_shorthand() && self.text().starts_with("{...")
    }

    /// Whether this is a directive (e.g., `bind:value`, `on:click`).
    pub fn is_directive(&self) -> bool {
        self.directive_prefix().is_some()
    }

    /// The directive prefix (e.g., "class" for `class:active`, "bind" for `bind:value`).
    pub fn directive_prefix(&self) -> Option<&'src str> {
        let name_node = self.node.child_by_field_name("name")?;
        let mut cursor = name_node.walk();
        for child in name_node.children(&mut cursor) {
            if child.kind() == "attribute_directive" {
                return Some(node_text(self.source, child));
            }
        }
        None
    }

    /// For directives, the identifier after the colon (e.g., "active" in `class:active`).
    pub fn directive_name(&self) -> Option<&'src str> {
        let name_node = self.node.child_by_field_name("name")?;
        let mut cursor = name_node.walk();
        for child in name_node.children(&mut cursor) {
            if child.kind() == "attribute_identifier" {
                return Some(node_text(self.source, child));
            }
        }
        None
    }

    /// Whether this is a `class:name` directive.
    pub fn is_class_directive(&self) -> bool {
        self.directive_prefix() == Some("class")
    }

    /// Whether this is a `bind:name` directive.
    pub fn is_bind_directive(&self) -> bool {
        self.directive_prefix() == Some("bind")
    }

    /// Whether this is a `style:name` directive.
    pub fn is_style_directive(&self) -> bool {
        self.directive_prefix() == Some("style")
    }

    /// Whether this wraps a shorthand_attribute child node (both `{name}` and `{...spread}`).
    pub fn has_shorthand_child(&self) -> bool {
        let mut cursor = self.node.walk();
        self.node.children(&mut cursor).any(|c| c.kind() == "shorthand_attribute")
    }

    /// The static text value of this attribute, if it's a simple quoted or bare value.
    pub fn static_value(&self) -> Option<&'src str> {
        let value = self.value_node()?;
        match value.kind() {
            "quoted_attribute_value" => {
                let mut cursor = value.walk();
                for child in value.children(&mut cursor) {
                    if child.kind() == "attribute_value" {
                        return Some(node_text(self.source, child));
                    }
                }
                None
            }
            "attribute_value" => Some(node_text(self.source, value)),
            _ => None,
        }
    }

    /// The value expression from the cache, if the value is an expression tag.
    pub fn value_expression<'c>(&self, cache: &'c ExpressionCache) -> Option<&'c Expression> {
        let value = self.value_node()?;
        match value.kind() {
            "expression" => cache.get(value.start_byte()),
            "quoted_attribute_value" => {
                let mut cursor = value.walk();
                for child in value.children(&mut cursor) {
                    if child.kind() == "expression" {
                        return cache.get(child.start_byte());
                    }
                }
                None
            }
            _ => None,
        }
    }

    /// Whether the value contains any expression (dynamic value).
    pub fn has_expression_value(&self) -> bool {
        let Some(value) = self.value_node() else { return false };
        match value.kind() {
            "expression" => true,
            "quoted_attribute_value" => {
                let mut cursor = value.walk();
                value.children(&mut cursor).any(|c| c.kind() == "expression")
            }
            _ => false,
        }
    }

    /// Whether the value contains mixed text and expressions.
    pub fn has_mixed_value(&self) -> bool {
        let Some(value) = self.value_node() else { return false };
        if value.kind() != "quoted_attribute_value" { return false; }
        let mut has_text = false;
        let mut has_expr = false;
        let mut cursor = value.walk();
        for child in value.children(&mut cursor) {
            match child.kind() {
                "attribute_value" => has_text = true,
                "expression" => has_expr = true,
                _ => {}
            }
        }
        has_text && has_expr
    }

    /// The source text that this attribute references.
    pub fn source_text(&self) -> &'src str {
        self.source
    }

    /// Iterate over value parts as `(is_expression: bool, text: &str, start_byte: usize)`.
    /// For quoted values like `"foo {bar} baz"`, yields text and expression parts.
    /// For expression values like `{expr}`, yields one expression part.
    /// For boolean (no value), yields nothing.
    pub fn value_parts(&self) -> Vec<AttributeValuePart<'src>> {
        let Some(value) = self.value_node() else { return vec![] };
        match value.kind() {
            "expression" => {
                vec![AttributeValuePart::Expression(
                    value.start_byte(),
                    node_text(self.source, value),
                )]
            }
            "quoted_attribute_value" => {
                let mut parts = Vec::new();
                let mut cursor = value.walk();
                for child in value.children(&mut cursor) {
                    match child.kind() {
                        "attribute_value" => {
                            parts.push(AttributeValuePart::Text(
                                node_text(self.source, child),
                            ));
                        }
                        "expression" => {
                            parts.push(AttributeValuePart::Expression(
                                child.start_byte(),
                                node_text(self.source, child),
                            ));
                        }
                        _ => {}
                    }
                }
                parts
            }
            _ => vec![],
        }
    }
}

/// A part of an attribute value (text or expression).
#[derive(Debug, Clone, Copy)]
pub enum AttributeValuePart<'src> {
    /// Static text content.
    Text(&'src str),
    /// An expression `{...}`. The usize is the start byte offset for cache lookup.
    Expression(usize, &'src str),
}

// --- ElseClause (not in define_wrapper since it's structural) ---

define_wrapper!(
    /// An else clause in a block.
    ElseClause,
);

impl<'src> ElseClause<'src> {
    /// Iterate over child nodes of this else clause.
    pub fn children(&self) -> ChildIter<'src> {
        ChildIter::new(self.source, self.node)
    }
}

// --- Alternate enum ---

/// The alternate branch of an if block.
#[derive(Debug, Clone, Copy)]
pub enum Alternate<'src> {
    Else(ElseClause<'src>),
    ElseIf(IfBlock<'src>),
}

// --- TemplateNode enum ---

/// A template node — discriminated by tree-sitter node kind.
#[derive(Debug, Clone, Copy)]
pub enum TemplateNode<'src> {
    Text(TextNode<'src>),
    Comment(CommentNode<'src>),
    ExpressionTag(ExpressionTag<'src>),
    HtmlTag(HtmlTag<'src>),
    ConstTag(ConstTag<'src>),
    DebugTag(DebugTag<'src>),
    RenderTag(RenderTag<'src>),
    AttachTag(AttachTag<'src>),
    IfBlock(IfBlock<'src>),
    EachBlock(EachBlock<'src>),
    AwaitBlock(AwaitBlock<'src>),
    KeyBlock(KeyBlock<'src>),
    SnippetBlock(SnippetBlock<'src>),
    // Element variants — all wrap Element but carry classification
    RegularElement(Element<'src>),
    Component(Element<'src>),
    SlotElement(Element<'src>),
    SvelteHead(Element<'src>),
    SvelteBody(Element<'src>),
    SvelteWindow(Element<'src>),
    SvelteDocument(Element<'src>),
    SvelteComponent(Element<'src>),
    SvelteElement(Element<'src>),
    SvelteSelf(Element<'src>),
    SvelteFragment(Element<'src>),
    SvelteBoundary(Element<'src>),
    TitleElement(Element<'src>),
}

impl<'src> TemplateNode<'src> {
    /// Byte offset of the start of this node.
    pub fn start(&self) -> usize {
        self.ts_node().start_byte()
    }

    /// Byte offset of the end of this node.
    pub fn end(&self) -> usize {
        self.ts_node().end_byte()
    }

    /// The underlying tree-sitter node.
    pub fn ts_node(&self) -> Node<'src> {
        match self {
            Self::Text(n) => n.ts_node(),
            Self::Comment(n) => n.ts_node(),
            Self::ExpressionTag(n) => n.ts_node(),
            Self::HtmlTag(n) => n.ts_node(),
            Self::ConstTag(n) => n.ts_node(),
            Self::DebugTag(n) => n.ts_node(),
            Self::RenderTag(n) => n.ts_node(),
            Self::AttachTag(n) => n.ts_node(),
            Self::IfBlock(n) => n.ts_node(),
            Self::EachBlock(n) => n.ts_node(),
            Self::AwaitBlock(n) => n.ts_node(),
            Self::KeyBlock(n) => n.ts_node(),
            Self::SnippetBlock(n) => n.ts_node(),
            Self::RegularElement(n)
            | Self::Component(n)
            | Self::SlotElement(n)
            | Self::SvelteHead(n)
            | Self::SvelteBody(n)
            | Self::SvelteWindow(n)
            | Self::SvelteDocument(n)
            | Self::SvelteComponent(n)
            | Self::SvelteElement(n)
            | Self::SvelteSelf(n)
            | Self::SvelteFragment(n)
            | Self::SvelteBoundary(n)
            | Self::TitleElement(n) => n.ts_node(),
        }
    }

    /// If this is any element variant, return the inner `Element`.
    pub fn as_element(&self) -> Option<&Element<'src>> {
        match self {
            Self::RegularElement(e)
            | Self::Component(e)
            | Self::SlotElement(e)
            | Self::SvelteHead(e)
            | Self::SvelteBody(e)
            | Self::SvelteWindow(e)
            | Self::SvelteDocument(e)
            | Self::SvelteComponent(e)
            | Self::SvelteElement(e)
            | Self::SvelteSelf(e)
            | Self::SvelteFragment(e)
            | Self::SvelteBoundary(e)
            | Self::TitleElement(e) => Some(e),
            _ => None,
        }
    }

    /// Whether this node is a component-like element (Component, SvelteComponent, etc.).
    pub fn is_component_like(&self) -> bool {
        matches!(
            self,
            Self::Component(_)
                | Self::SvelteComponent(_)
                | Self::SvelteSelf(_)
                | Self::SvelteFragment(_)
                | Self::SvelteBoundary(_)
                | Self::SvelteHead(_)
                | Self::SvelteBody(_)
                | Self::SvelteWindow(_)
                | Self::SvelteDocument(_)
                | Self::TitleElement(_)
        )
    }

    /// Whether this is a SvelteElement (`<svelte:element>`).
    pub fn is_svelte_element(&self) -> bool {
        matches!(self, Self::SvelteElement(_))
    }

    /// Visit all direct child fragments of this node.
    /// Calls `f` with a `ChildIter` for each child fragment (body, fallback, branches, etc.).
    pub fn for_each_child_iter<F>(&self, mut f: F)
    where
        F: FnMut(ChildIter<'src>),
    {
        match self {
            Self::RegularElement(el)
            | Self::Component(el)
            | Self::SlotElement(el)
            | Self::SvelteHead(el)
            | Self::SvelteBody(el)
            | Self::SvelteWindow(el)
            | Self::SvelteDocument(el)
            | Self::SvelteComponent(el)
            | Self::SvelteElement(el)
            | Self::SvelteSelf(el)
            | Self::SvelteFragment(el)
            | Self::SvelteBoundary(el)
            | Self::TitleElement(el) => {
                f(el.children());
            }
            Self::IfBlock(block) => {
                f(block.consequent());
                match block.alternate() {
                    Some(Alternate::Else(clause)) => f(clause.children()),
                    Some(Alternate::ElseIf(nested)) => {
                        TemplateNode::IfBlock(nested).for_each_child_iter(f);
                    }
                    None => {}
                }
            }
            Self::EachBlock(block) => {
                f(block.body());
                if let Some(clause) = block.fallback() {
                    f(clause.children());
                }
            }
            Self::AwaitBlock(block) => {
                if let Some(iter) = block.pending() {
                    f(iter);
                }
                if let Some(iter) = block.then_children() {
                    f(iter);
                }
                if let Some(iter) = block.catch_children() {
                    f(iter);
                }
            }
            Self::KeyBlock(block) => {
                f(block.body());
            }
            Self::SnippetBlock(block) => {
                f(block.body());
            }
            _ => {}
        }
    }

    /// Recursively walk all descendant template nodes depth-first.
    pub fn walk<F>(&self, f: &mut F)
    where
        F: FnMut(TemplateNode<'src>),
    {
        self.for_each_child_iter(|iter| {
            for child in iter {
                f(child);
                child.walk(f);
            }
        });
    }
}

impl<'src> Root<'src> {
    /// Recursively walk all descendant template nodes depth-first.
    pub fn walk<F>(&self, f: &mut F)
    where
        F: FnMut(TemplateNode<'src>),
    {
        for child in self.children() {
            f(child);
            child.walk(f);
        }
    }

    /// Check if any descendant matches a predicate.
    pub fn any<F>(&self, mut f: F) -> bool
    where
        F: FnMut(TemplateNode<'src>) -> bool,
    {
        let mut found = false;
        self.walk(&mut |node| {
            if !found && f(node) {
                found = true;
            }
        });
        found
    }
}

// --- Classify functions ---

/// Classify an `element` tree-sitter node into the appropriate `TemplateNode` variant.
fn classify_element<'src>(source: &'src str, node: Node<'src>) -> TemplateNode<'src> {
    let el = Element::new(source, node);
    let name = el.name();

    match name {
        "slot" => TemplateNode::SlotElement(el),
        "title" => TemplateNode::TitleElement(el),
        _ if name.starts_with("svelte:") => {
            match &name[7..] {
                "head" => TemplateNode::SvelteHead(el),
                "body" => TemplateNode::SvelteBody(el),
                "window" => TemplateNode::SvelteWindow(el),
                "document" => TemplateNode::SvelteDocument(el),
                "component" => TemplateNode::SvelteComponent(el),
                "element" => TemplateNode::SvelteElement(el),
                "self" => TemplateNode::SvelteSelf(el),
                "fragment" => TemplateNode::SvelteFragment(el),
                "boundary" => TemplateNode::SvelteBoundary(el),
                _ => TemplateNode::RegularElement(el),
            }
        }
        _ if is_component_name(name) => TemplateNode::Component(el),
        _ => TemplateNode::RegularElement(el),
    }
}

/// Classify any named tree-sitter node into a `TemplateNode`.
pub fn classify_node<'src>(source: &'src str, node: Node<'src>) -> Option<TemplateNode<'src>> {
    match node.kind() {
        "text" => Some(TemplateNode::Text(TextNode::new(source, node))),
        "comment" => Some(TemplateNode::Comment(CommentNode::new(source, node))),
        "expression" => Some(TemplateNode::ExpressionTag(ExpressionTag::new(source, node))),
        "html_tag" => Some(TemplateNode::HtmlTag(HtmlTag::new(source, node))),
        "const_tag" => Some(TemplateNode::ConstTag(ConstTag::new(source, node))),
        "debug_tag" => Some(TemplateNode::DebugTag(DebugTag::new(source, node))),
        "render_tag" => Some(TemplateNode::RenderTag(RenderTag::new(source, node))),
        "attach_tag" => Some(TemplateNode::AttachTag(AttachTag::new(source, node))),
        "if_block" => Some(TemplateNode::IfBlock(IfBlock::new(source, node))),
        "each_block" => Some(TemplateNode::EachBlock(EachBlock::new(source, node))),
        "await_block" => Some(TemplateNode::AwaitBlock(AwaitBlock::new(source, node))),
        "key_block" => Some(TemplateNode::KeyBlock(KeyBlock::new(source, node))),
        "snippet_block" => Some(TemplateNode::SnippetBlock(SnippetBlock::new(source, node))),
        "element" => Some(classify_element(source, node)),
        _ => None,
    }
}

// --- ChildIter ---

/// Iterator over child nodes that are template content (skipping structural nodes).
pub struct ChildIter<'src> {
    source: &'src str,
    cursor: TreeCursor<'src>,
    started: bool,
}

impl<'src> ChildIter<'src> {
    fn new(source: &'src str, parent: Node<'src>) -> Self {
        Self {
            source,
            cursor: parent.walk(),
            started: false,
        }
    }
}

/// Node kinds that are structural (not template content).
fn is_structural_kind(kind: &str) -> bool {
    matches!(
        kind,
        "block_open"
            | "block_close"
            | "block_end"
            | "block_keyword"
            | "block_sigil"
            | "branch_kind"
            | "start_tag"
            | "end_tag"
            | "self_closing_tag"
            | "else_clause"
            | "else_if_clause"
            | "await_branch"
            | "await_pending"
            | "await_branch_children"
            | "snippet_name"
            | "snippet_parameters"
            | "snippet_type_parameters"
            | "pattern"
            | "expression_value"
            | "shorthand_kind"
            | "raw_text"
    )
}

impl<'src> Iterator for ChildIter<'src> {
    type Item = TemplateNode<'src>;

    fn next(&mut self) -> Option<TemplateNode<'src>> {
        loop {
            let moved = if self.started {
                self.cursor.goto_next_sibling()
            } else {
                self.started = true;
                self.cursor.goto_first_child()
            };

            if !moved {
                return None;
            }

            let node = self.cursor.node();
            if !node.is_named() {
                continue;
            }

            // Skip children that are field-named (structural parts of parent:
            // expression, binding, key, etc.)
            if self.cursor.field_name().is_some() {
                continue;
            }

            let kind = node.kind();
            if is_structural_kind(kind) {
                continue;
            }

            if let Some(template_node) = classify_node(self.source, node) {
                return Some(template_node);
            }
        }
    }
}

// --- AttributeIter ---

/// Iterator over attribute nodes on a start tag.
pub struct AttributeIter<'src> {
    source: &'src str,
    cursor: TreeCursor<'src>,
    started: bool,
}

impl<'src> Iterator for AttributeIter<'src> {
    type Item = AttributeNode<'src>;

    fn next(&mut self) -> Option<AttributeNode<'src>> {
        loop {
            let moved = if self.started {
                self.cursor.goto_next_sibling()
            } else {
                self.started = true;
                self.cursor.goto_first_child()
            };

            if !moved {
                return None;
            }

            let node = self.cursor.node();
            match node.kind() {
                "attribute" | "shorthand_attribute" | "attach_tag" => {
                    return Some(AttributeNode::new(self.source, node));
                }
                _ => continue,
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::SourceId;

    #[test]
    fn parses_svelte_cst_document() {
        let source = SourceText::new(SourceId::new(1), "<div>Hello</div>", None);
        let cst = parse_svelte(source).expect("expected tree-sitter CST parse to succeed");

        assert!(!cst.root_kind().is_empty());
        assert!(cst.root_span().end.as_usize() >= cst.source.len());
    }

    #[test]
    fn cst_contains_attribute_nodes() {
        let source = SourceText::new(SourceId::new(2), "<div class='foo'></div>", None);
        let cst = parse_svelte(source).expect("expected cst parse to succeed");
        let sexp = cst.root_node().to_sexp();

        assert!(sexp.contains("(attribute"));
        assert!(sexp.contains("(attribute_name"));
    }

    #[test]
    fn cst_style_directive_shape() {
        let source = SourceText::new(SourceId::new(3), "<div style:color={myColor}></div>", None);
        let cst = parse_svelte(source).expect("expected cst parse to succeed");
        let sexp = cst.root_node().to_sexp();

        assert!(sexp.contains("attribute_directive"));
        assert!(sexp.contains("attribute_identifier"));
    }

    #[test]
    fn cst_if_block_shape() {
        let source = SourceText::new(SourceId::new(4), "{#if foo}bar{/if}", None);
        let cst = parse_svelte(source).expect("expected cst parse to succeed");
        let sexp = cst.root_node().to_sexp();

        assert!(sexp.contains("if_block"));
        assert!(sexp.contains("block_end"));
    }

    #[test]
    fn cst_breaks_unterminated_tags_before_block_branches() {
        let source = SourceText::new(
            SourceId::new(5),
            "{#if true}\n\t<input>\n{:else}\n{/if}\n\n{#await true}\n\t<input>\n{:then f}\n{/await}",
            None,
        );
        let cst = parse_svelte(source).expect("expected cst parse to succeed");
        let sexp = cst.root_node().to_sexp();

        assert!(sexp.matches("(else_clause").count() + sexp.matches("(await_branch").count() >= 2);
    }

    #[test]
    fn cst_directive_and_debug_tag_shapes() {
        let source = SourceText::new(
            SourceId::new(6),
            "<div let:x style:color={c} transition:fade={t} animate:flip={a} use:act={u}></div>{@debug x, y}",
            None,
        );
        let cst = parse_svelte(source).expect("expected cst parse to succeed");
        let sexp = cst.root_node().to_sexp();

        assert!(sexp.contains("attribute_name"));
        assert!(sexp.contains("debug_tag"));
        assert!(sexp.contains("expression_value"));
    }

    #[test]
    fn cst_malformed_snippet_headers_report_error_shape() {
        let source = SourceText::new(SourceId::new(7), "{#snippet children()hi{/snippet}", None);
        let cst = parse_svelte(source).expect("expected cst parse to succeed");
        let sexp = cst.root_node().to_sexp();
        assert!(
            cst.has_error(),
            "expected malformed snippet header CST error"
        );
        assert!(sexp.contains("(snippet_name"));

        let source = SourceText::new(SourceId::new(8), "{#snippet children(hi{/snippet}", None);
        let cst = parse_svelte(source).expect("expected cst parse to succeed");
        let sexp = cst.root_node().to_sexp();
        assert!(sexp.contains("(snippet_name"));
        assert!(sexp.contains("(snippet_parameters"));
    }

    #[test]
    fn incremental_parse_matches_fresh_parse_after_insert() {
        let before_text = "<div>Hello</div>";
        let after_text = "<div>Hello {name}</div>";
        let before = SourceText::new(SourceId::new(9), before_text, None);
        let after = SourceText::new(SourceId::new(10), after_text, None);

        let mut parser = CstParser::new()
            .configure(Language::Svelte)
            .expect("parser");
        let previous = parser.parse(before).expect("initial parse");
        let edit = CstEdit::insert(before_text, "<div>Hello".len(), " {name}");

        let incremental = parser
            .parse_incremental(after, &previous, edit)
            .expect("incremental parse");
        let fresh = parse_svelte(after).expect("fresh parse");

        assert_eq!(
            incremental.root_node().to_sexp(),
            fresh.root_node().to_sexp()
        );
    }

    #[test]
    fn document_apply_edit_keeps_tree_reusable() {
        let before_text = "<div>Hello</div>";
        let after_text = "<div>Hi</div>";
        let before = SourceText::new(SourceId::new(11), before_text, None);
        let after = SourceText::new(SourceId::new(12), after_text, None);

        let mut parser = CstParser::new()
            .configure(Language::Svelte)
            .expect("parser");
        let mut previous = parser.parse(before).expect("initial parse");
        let edit = CstEdit::replace(before_text, "<div>".len(), "<div>Hello".len(), "Hi");
        previous.apply_edit(edit.clone());

        let incremental = parser
            .parse_incremental(after, &previous, edit)
            .expect("incremental parse");
        let fresh = parse_svelte(after).expect("fresh parse");

        assert_eq!(
            incremental.root_node().to_sexp(),
            fresh.root_node().to_sexp()
        );
    }

    // --- Wrapper type tests ---

    fn parse_source(text: &str) -> Document<'_> {
        let source = SourceText::new(SourceId::new(100), text, None);
        parse_svelte(source).expect("parse")
    }

    #[test]
    fn wrapper_element_name_via_field() {
        let text = r#"<div class="foo">hello</div>"#;
        let doc = parse_source(text);
        let root = Root::new(text, doc.root_node());
        let children: Vec<_> = root.children().collect();
        assert_eq!(children.len(), 1);
        let TemplateNode::RegularElement(el) = &children[0] else {
            panic!("expected RegularElement");
        };
        assert_eq!(el.name(), "div");
        assert!(!el.is_self_closing());
        assert!(el.has_end_tag());
    }

    #[test]
    fn wrapper_self_closing_element() {
        let text = r#"<br />"#;
        let doc = parse_source(text);
        let root = Root::new(text, doc.root_node());
        let children: Vec<_> = root.children().collect();
        assert_eq!(children.len(), 1);
        let TemplateNode::RegularElement(el) = &children[0] else {
            panic!("expected RegularElement");
        };
        assert_eq!(el.name(), "br");
        assert!(el.is_self_closing());
    }

    #[test]
    fn wrapper_component_classification() {
        let text = r#"<Button>Click</Button>"#;
        let doc = parse_source(text);
        let root = Root::new(text, doc.root_node());
        let children: Vec<_> = root.children().collect();
        assert!(matches!(&children[0], TemplateNode::Component(el) if el.name() == "Button"));
    }

    #[test]
    fn wrapper_svelte_element_classification() {
        let text = r#"<svelte:head><title>Hi</title></svelte:head>"#;
        let doc = parse_source(text);
        let root = Root::new(text, doc.root_node());
        let children: Vec<_> = root.children().collect();
        assert!(matches!(&children[0], TemplateNode::SvelteHead(_)));
    }

    #[test]
    fn wrapper_if_block() {
        let text = r#"{#if visible}<p>Hello</p>{/if}"#;
        let doc = parse_source(text);
        let root = Root::new(text, doc.root_node());
        let children: Vec<_> = root.children().collect();
        assert_eq!(children.len(), 1);
        let TemplateNode::IfBlock(block) = &children[0] else {
            panic!("expected IfBlock");
        };
        assert!(block.test_node().is_some());
        let consequent: Vec<_> = block.consequent().collect();
        assert!(!consequent.is_empty());
    }

    #[test]
    fn wrapper_each_block() {
        let text = r#"{#each items as item}<li>{item}</li>{/each}"#;
        let doc = parse_source(text);
        let root = Root::new(text, doc.root_node());
        let children: Vec<_> = root.children().collect();
        assert_eq!(children.len(), 1);
        let TemplateNode::EachBlock(block) = &children[0] else {
            panic!("expected EachBlock");
        };
        assert!(block.expression_node().is_some());
        let body: Vec<_> = block.body().collect();
        assert!(!body.is_empty());
    }

    #[test]
    fn wrapper_text_node() {
        let text = r#"<div>hello world</div>"#;
        let doc = parse_source(text);
        let root = Root::new(text, doc.root_node());
        let children: Vec<_> = root.children().collect();
        let TemplateNode::RegularElement(el) = &children[0] else {
            panic!("expected element");
        };
        let inner: Vec<_> = el.children().collect();
        assert_eq!(inner.len(), 1);
        let TemplateNode::Text(t) = &inner[0] else {
            panic!("expected text");
        };
        assert_eq!(t.raw(), "hello world");
    }

    #[test]
    fn wrapper_attributes() {
        let text = r#"<div class="foo" id="bar">x</div>"#;
        let doc = parse_source(text);
        let root = Root::new(text, doc.root_node());
        let children: Vec<_> = root.children().collect();
        let TemplateNode::RegularElement(el) = &children[0] else {
            panic!("expected element");
        };
        let attrs: Vec<_> = el.attributes().collect();
        assert_eq!(attrs.len(), 2);
        assert_eq!(attrs[0].name(), "class");
        assert_eq!(attrs[1].name(), "id");
    }

    #[test]
    fn wrapper_expression_tag() {
        let text = r#"<p>{count}</p>"#;
        let doc = parse_source(text);
        let root = Root::new(text, doc.root_node());
        let children: Vec<_> = root.children().collect();
        let TemplateNode::RegularElement(el) = &children[0] else {
            panic!("expected element");
        };
        let inner: Vec<_> = el.children().collect();
        assert!(matches!(&inner[0], TemplateNode::ExpressionTag(_)));
    }

    #[test]
    fn wrapper_snippet_block() {
        let text = r#"{#snippet btn(text)}<button>{text}</button>{/snippet}"#;
        let doc = parse_source(text);
        let root = Root::new(text, doc.root_node());
        let children: Vec<_> = root.children().collect();
        let TemplateNode::SnippetBlock(block) = &children[0] else {
            panic!("expected SnippetBlock");
        };
        assert_eq!(block.name(), "btn");
        assert!(block.parameters_node().is_some());
    }

    #[test]
    fn wrapper_child_iter_skips_structural_nodes() {
        // Ensure ChildIter doesn't yield start_tag, end_tag, block_open, etc.
        let text = r#"{#if x}<div>A</div>{:else}<span>B</span>{/if}"#;
        let doc = parse_source(text);
        let root = Root::new(text, doc.root_node());
        let children: Vec<_> = root.children().collect();
        let TemplateNode::IfBlock(block) = &children[0] else {
            panic!("expected IfBlock");
        };
        // Consequent should have just the div
        let consequent: Vec<_> = block.consequent().collect();
        assert!(consequent.iter().all(|n| matches!(n, TemplateNode::RegularElement(_))));
    }

    // --- ParsedDocument tests ---

    #[test]
    fn attribute_directive_accessors() {
        let text = r#"<div class:active={isActive} bind:value={name} style:color="red" />"#;
        let doc = parse_source(text);
        let root = Root::new(text, doc.root_node());
        let children: Vec<_> = root.children().collect();
        let TemplateNode::RegularElement(el) = &children[0] else {
            panic!("expected element");
        };
        let attrs: Vec<_> = el.attributes().collect();
        assert_eq!(attrs.len(), 3);

        // class:active
        assert!(attrs[0].is_class_directive());
        assert_eq!(attrs[0].directive_prefix(), Some("class"));
        assert_eq!(attrs[0].directive_name(), Some("active"));

        // bind:value
        assert!(attrs[1].is_bind_directive());
        assert_eq!(attrs[1].directive_prefix(), Some("bind"));
        assert_eq!(attrs[1].directive_name(), Some("value"));

        // style:color
        assert!(attrs[2].is_style_directive());
        assert_eq!(attrs[2].directive_prefix(), Some("style"));
        assert_eq!(attrs[2].directive_name(), Some("color"));
        assert_eq!(attrs[2].static_value(), Some("red"));
    }

    #[test]
    fn attribute_static_and_expression_values() {
        let text = r#"<div class="foo" id={myId} />"#;
        let doc = ParsedDocument::parse(text).unwrap();
        let children: Vec<_> = doc.root().children().collect();
        let TemplateNode::RegularElement(el) = &children[0] else {
            panic!("expected element");
        };
        let attrs: Vec<_> = el.attributes().collect();
        assert_eq!(attrs.len(), 2);

        // class="foo" — static value
        assert_eq!(attrs[0].static_value(), Some("foo"));
        assert!(!attrs[0].has_expression_value());

        // id={myId} — expression value
        assert!(attrs[1].has_expression_value());
        let expr = attrs[1].value_expression(doc.expressions());
        assert!(expr.is_some(), "id expression should be cached");
    }

    #[test]
    fn attribute_spread_detection() {
        let text = r#"<div {...props} {shorthand} />"#;
        let doc = parse_source(text);
        let root = Root::new(text, doc.root_node());
        let children: Vec<_> = root.children().collect();
        let TemplateNode::RegularElement(el) = &children[0] else {
            panic!("expected element");
        };
        let attrs: Vec<_> = el.attributes().collect();
        assert_eq!(attrs.len(), 2);

        // {...props} is within an attribute wrapping a shorthand
        assert!(attrs[0].has_shorthand_child());
        // {shorthand} is also within an attribute wrapping a shorthand
        assert!(attrs[1].has_shorthand_child());
    }

    #[test]
    fn walk_visits_all_descendants() {
        let text = r#"<div><p>A</p><span>{x}</span></div>{#if y}<b>B</b>{/if}"#;
        let doc = parse_source(text);
        let root = Root::new(text, doc.root_node());
        let mut count = 0;
        root.walk(&mut |_| count += 1);
        // div, p, Text(A), span, ExpressionTag(x), if_block, b, Text(B)
        assert!(count >= 7, "expected at least 7 descendants, got {count}");
    }

    // --- ParsedDocument tests ---

    #[test]
    fn parsed_document_basic() {
        let doc = ParsedDocument::parse("<div>{count}</div>").unwrap();
        assert_eq!(doc.root().children().count(), 1);
        assert!(!doc.expressions().is_empty());
    }

    #[test]
    fn parsed_document_expression_cache() {
        let doc = ParsedDocument::parse("{#if visible}<p>Hello</p>{/if}").unwrap();
        let children: Vec<_> = doc.root().children().collect();
        let TemplateNode::IfBlock(block) = &children[0] else {
            panic!("expected IfBlock");
        };
        let expr = block.test_expression(doc.expressions());
        assert!(expr.is_some(), "test expression should be cached");
    }

    #[test]
    fn parsed_document_each_expression() {
        let doc = ParsedDocument::parse("{#each items as item}<li>{item}</li>{/each}").unwrap();
        let children: Vec<_> = doc.root().children().collect();
        let TemplateNode::EachBlock(block) = &children[0] else {
            panic!("expected EachBlock");
        };
        let expr = block.expression(doc.expressions());
        assert!(expr.is_some(), "each expression should be cached");
    }

    #[test]
    fn parsed_document_expression_tag() {
        let doc = ParsedDocument::parse("<p>{count + 1}</p>").unwrap();
        let children: Vec<_> = doc.root().children().collect();
        let TemplateNode::RegularElement(el) = &children[0] else {
            panic!("expected element");
        };
        let inner: Vec<_> = el.children().collect();
        let TemplateNode::ExpressionTag(tag) = &inner[0] else {
            panic!("expected ExpressionTag");
        };
        let expr = tag.expression(doc.expressions());
        assert!(expr.is_some(), "expression tag should be cached");
    }
}