typst_syntax/
ast.rs

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
2189
2190
2191
2192
2193
2194
2195
//! A typed layer over the untyped syntax tree.
//!
//! The AST is rooted in the [`Markup`] node.

use std::num::NonZeroUsize;
use std::ops::Deref;

use ecow::EcoString;
use unscanny::Scanner;

use crate::{is_newline, Span, SyntaxKind, SyntaxNode};

/// A typed AST node.
pub trait AstNode<'a>: Sized {
    /// Convert a node into its typed variant.
    fn from_untyped(node: &'a SyntaxNode) -> Option<Self>;

    /// A reference to the underlying syntax node.
    fn to_untyped(self) -> &'a SyntaxNode;

    /// The source code location.
    fn span(self) -> Span {
        self.to_untyped().span()
    }
}

macro_rules! node {
    ($(#[$attr:meta])* $name:ident) => {
        #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
        #[repr(transparent)]
        $(#[$attr])*
        pub struct $name<'a>(&'a SyntaxNode);

        impl<'a> AstNode<'a> for $name<'a> {
            #[inline]
            fn from_untyped(node: &'a SyntaxNode) -> Option<Self> {
                if node.kind() == SyntaxKind::$name {
                    Some(Self(node))
                } else {
                    Option::None
                }
            }

            #[inline]
            fn to_untyped(self) -> &'a SyntaxNode {
                self.0
            }
        }

        impl Default for $name<'_> {
            #[inline]
            fn default() -> Self {
                static PLACEHOLDER: SyntaxNode
                    = SyntaxNode::placeholder(SyntaxKind::$name);
                Self(&PLACEHOLDER)
            }
        }
    };
}

node! {
    /// The syntactical root capable of representing a full parsed document.
    Markup
}

impl<'a> Markup<'a> {
    /// The expressions.
    pub fn exprs(self) -> impl DoubleEndedIterator<Item = Expr<'a>> {
        let mut was_stmt = false;
        self.0
            .children()
            .filter(move |node| {
                // Ignore newline directly after statements without semicolons.
                let kind = node.kind();
                let keep = !was_stmt || node.kind() != SyntaxKind::Space;
                was_stmt = kind.is_stmt();
                keep
            })
            .filter_map(Expr::cast_with_space)
    }
}

/// An expression in markup, math or code.
#[derive(Debug, Copy, Clone, Hash)]
pub enum Expr<'a> {
    /// Plain text without markup.
    Text(Text<'a>),
    /// Whitespace in markup or math. Has at most one newline in markup, as more
    /// indicate a paragraph break.
    Space(Space<'a>),
    /// A forced line break: `\`.
    Linebreak(Linebreak<'a>),
    /// A paragraph break, indicated by one or multiple blank lines.
    Parbreak(Parbreak<'a>),
    /// An escape sequence: `\#`, `\u{1F5FA}`.
    Escape(Escape<'a>),
    /// A shorthand for a unicode codepoint. For example, `~` for non-breaking
    /// space or `-?` for a soft hyphen.
    Shorthand(Shorthand<'a>),
    /// A smart quote: `'` or `"`.
    SmartQuote(SmartQuote<'a>),
    /// Strong content: `*Strong*`.
    Strong(Strong<'a>),
    /// Emphasized content: `_Emphasized_`.
    Emph(Emph<'a>),
    /// Raw text with optional syntax highlighting: `` `...` ``.
    Raw(Raw<'a>),
    /// A hyperlink: `https://typst.org`.
    Link(Link<'a>),
    /// A label: `<intro>`.
    Label(Label<'a>),
    /// A reference: `@target`, `@target[..]`.
    Ref(Ref<'a>),
    /// A section heading: `= Introduction`.
    Heading(Heading<'a>),
    /// An item in a bullet list: `- ...`.
    List(ListItem<'a>),
    /// An item in an enumeration (numbered list): `+ ...` or `1. ...`.
    Enum(EnumItem<'a>),
    /// An item in a term list: `/ Term: Details`.
    Term(TermItem<'a>),
    /// A mathematical equation: `$x$`, `$ x^2 $`.
    Equation(Equation<'a>),
    /// The contents of a mathematical equation: `x^2 + 1`.
    Math(Math<'a>),
    /// An identifier in math: `pi`.
    MathIdent(MathIdent<'a>),
    /// A shorthand for a unicode codepoint in math: `a <= b`.
    MathShorthand(MathShorthand<'a>),
    /// An alignment point in math: `&`.
    MathAlignPoint(MathAlignPoint<'a>),
    /// Matched delimiters in math: `[x + y]`.
    MathDelimited(MathDelimited<'a>),
    /// A base with optional attachments in math: `a_1^2`.
    MathAttach(MathAttach<'a>),
    /// Grouped math primes
    MathPrimes(MathPrimes<'a>),
    /// A fraction in math: `x/2`.
    MathFrac(MathFrac<'a>),
    /// A root in math: `√x`, `∛x` or `∜x`.
    MathRoot(MathRoot<'a>),
    /// An identifier: `left`.
    Ident(Ident<'a>),
    /// The `none` literal.
    None(None<'a>),
    /// The `auto` literal.
    Auto(Auto<'a>),
    /// A boolean: `true`, `false`.
    Bool(Bool<'a>),
    /// An integer: `120`.
    Int(Int<'a>),
    /// A floating-point number: `1.2`, `10e-4`.
    Float(Float<'a>),
    /// A numeric value with a unit: `12pt`, `3cm`, `2em`, `90deg`, `50%`.
    Numeric(Numeric<'a>),
    /// A quoted string: `"..."`.
    Str(Str<'a>),
    /// A code block: `{ let x = 1; x + 2 }`.
    Code(CodeBlock<'a>),
    /// A content block: `[*Hi* there!]`.
    Content(ContentBlock<'a>),
    /// A grouped expression: `(1 + 2)`.
    Parenthesized(Parenthesized<'a>),
    /// An array: `(1, "hi", 12cm)`.
    Array(Array<'a>),
    /// A dictionary: `(thickness: 3pt, pattern: dashed)`.
    Dict(Dict<'a>),
    /// A unary operation: `-x`.
    Unary(Unary<'a>),
    /// A binary operation: `a + b`.
    Binary(Binary<'a>),
    /// A field access: `properties.age`.
    FieldAccess(FieldAccess<'a>),
    /// An invocation of a function or method: `f(x, y)`.
    FuncCall(FuncCall<'a>),
    /// A closure: `(x, y) => z`.
    Closure(Closure<'a>),
    /// A let binding: `let x = 1`.
    Let(LetBinding<'a>),
    /// A destructuring assignment: `(x, y) = (1, 2)`.
    DestructAssign(DestructAssignment<'a>),
    /// A set rule: `set text(...)`.
    Set(SetRule<'a>),
    /// A show rule: `show heading: it => emph(it.body)`.
    Show(ShowRule<'a>),
    /// A contextual expression: `context text.lang`.
    Contextual(Contextual<'a>),
    /// An if-else conditional: `if x { y } else { z }`.
    Conditional(Conditional<'a>),
    /// A while loop: `while x { y }`.
    While(WhileLoop<'a>),
    /// A for loop: `for x in y { z }`.
    For(ForLoop<'a>),
    /// A module import: `import "utils.typ": a, b, c`.
    Import(ModuleImport<'a>),
    /// A module include: `include "chapter1.typ"`.
    Include(ModuleInclude<'a>),
    /// A break from a loop: `break`.
    Break(LoopBreak<'a>),
    /// A continue in a loop: `continue`.
    Continue(LoopContinue<'a>),
    /// A return from a function: `return`, `return x + 1`.
    Return(FuncReturn<'a>),
}

impl<'a> Expr<'a> {
    fn cast_with_space(node: &'a SyntaxNode) -> Option<Self> {
        match node.kind() {
            SyntaxKind::Space => node.cast().map(Self::Space),
            _ => Self::from_untyped(node),
        }
    }
}

impl<'a> AstNode<'a> for Expr<'a> {
    fn from_untyped(node: &'a SyntaxNode) -> Option<Self> {
        match node.kind() {
            SyntaxKind::Linebreak => node.cast().map(Self::Linebreak),
            SyntaxKind::Parbreak => node.cast().map(Self::Parbreak),
            SyntaxKind::Text => node.cast().map(Self::Text),
            SyntaxKind::Escape => node.cast().map(Self::Escape),
            SyntaxKind::Shorthand => node.cast().map(Self::Shorthand),
            SyntaxKind::SmartQuote => node.cast().map(Self::SmartQuote),
            SyntaxKind::Strong => node.cast().map(Self::Strong),
            SyntaxKind::Emph => node.cast().map(Self::Emph),
            SyntaxKind::Raw => node.cast().map(Self::Raw),
            SyntaxKind::Link => node.cast().map(Self::Link),
            SyntaxKind::Label => node.cast().map(Self::Label),
            SyntaxKind::Ref => node.cast().map(Self::Ref),
            SyntaxKind::Heading => node.cast().map(Self::Heading),
            SyntaxKind::ListItem => node.cast().map(Self::List),
            SyntaxKind::EnumItem => node.cast().map(Self::Enum),
            SyntaxKind::TermItem => node.cast().map(Self::Term),
            SyntaxKind::Equation => node.cast().map(Self::Equation),
            SyntaxKind::Math => node.cast().map(Self::Math),
            SyntaxKind::MathIdent => node.cast().map(Self::MathIdent),
            SyntaxKind::MathShorthand => node.cast().map(Self::MathShorthand),
            SyntaxKind::MathAlignPoint => node.cast().map(Self::MathAlignPoint),
            SyntaxKind::MathDelimited => node.cast().map(Self::MathDelimited),
            SyntaxKind::MathAttach => node.cast().map(Self::MathAttach),
            SyntaxKind::MathPrimes => node.cast().map(Self::MathPrimes),
            SyntaxKind::MathFrac => node.cast().map(Self::MathFrac),
            SyntaxKind::MathRoot => node.cast().map(Self::MathRoot),
            SyntaxKind::Ident => node.cast().map(Self::Ident),
            SyntaxKind::None => node.cast().map(Self::None),
            SyntaxKind::Auto => node.cast().map(Self::Auto),
            SyntaxKind::Bool => node.cast().map(Self::Bool),
            SyntaxKind::Int => node.cast().map(Self::Int),
            SyntaxKind::Float => node.cast().map(Self::Float),
            SyntaxKind::Numeric => node.cast().map(Self::Numeric),
            SyntaxKind::Str => node.cast().map(Self::Str),
            SyntaxKind::CodeBlock => node.cast().map(Self::Code),
            SyntaxKind::ContentBlock => node.cast().map(Self::Content),
            SyntaxKind::Parenthesized => node.cast().map(Self::Parenthesized),
            SyntaxKind::Array => node.cast().map(Self::Array),
            SyntaxKind::Dict => node.cast().map(Self::Dict),
            SyntaxKind::Unary => node.cast().map(Self::Unary),
            SyntaxKind::Binary => node.cast().map(Self::Binary),
            SyntaxKind::FieldAccess => node.cast().map(Self::FieldAccess),
            SyntaxKind::FuncCall => node.cast().map(Self::FuncCall),
            SyntaxKind::Closure => node.cast().map(Self::Closure),
            SyntaxKind::LetBinding => node.cast().map(Self::Let),
            SyntaxKind::DestructAssignment => node.cast().map(Self::DestructAssign),
            SyntaxKind::SetRule => node.cast().map(Self::Set),
            SyntaxKind::ShowRule => node.cast().map(Self::Show),
            SyntaxKind::Contextual => node.cast().map(Self::Contextual),
            SyntaxKind::Conditional => node.cast().map(Self::Conditional),
            SyntaxKind::WhileLoop => node.cast().map(Self::While),
            SyntaxKind::ForLoop => node.cast().map(Self::For),
            SyntaxKind::ModuleImport => node.cast().map(Self::Import),
            SyntaxKind::ModuleInclude => node.cast().map(Self::Include),
            SyntaxKind::LoopBreak => node.cast().map(Self::Break),
            SyntaxKind::LoopContinue => node.cast().map(Self::Continue),
            SyntaxKind::FuncReturn => node.cast().map(Self::Return),
            _ => Option::None,
        }
    }

    fn to_untyped(self) -> &'a SyntaxNode {
        match self {
            Self::Text(v) => v.to_untyped(),
            Self::Space(v) => v.to_untyped(),
            Self::Linebreak(v) => v.to_untyped(),
            Self::Parbreak(v) => v.to_untyped(),
            Self::Escape(v) => v.to_untyped(),
            Self::Shorthand(v) => v.to_untyped(),
            Self::SmartQuote(v) => v.to_untyped(),
            Self::Strong(v) => v.to_untyped(),
            Self::Emph(v) => v.to_untyped(),
            Self::Raw(v) => v.to_untyped(),
            Self::Link(v) => v.to_untyped(),
            Self::Label(v) => v.to_untyped(),
            Self::Ref(v) => v.to_untyped(),
            Self::Heading(v) => v.to_untyped(),
            Self::List(v) => v.to_untyped(),
            Self::Enum(v) => v.to_untyped(),
            Self::Term(v) => v.to_untyped(),
            Self::Equation(v) => v.to_untyped(),
            Self::Math(v) => v.to_untyped(),
            Self::MathIdent(v) => v.to_untyped(),
            Self::MathShorthand(v) => v.to_untyped(),
            Self::MathAlignPoint(v) => v.to_untyped(),
            Self::MathDelimited(v) => v.to_untyped(),
            Self::MathAttach(v) => v.to_untyped(),
            Self::MathPrimes(v) => v.to_untyped(),
            Self::MathFrac(v) => v.to_untyped(),
            Self::MathRoot(v) => v.to_untyped(),
            Self::Ident(v) => v.to_untyped(),
            Self::None(v) => v.to_untyped(),
            Self::Auto(v) => v.to_untyped(),
            Self::Bool(v) => v.to_untyped(),
            Self::Int(v) => v.to_untyped(),
            Self::Float(v) => v.to_untyped(),
            Self::Numeric(v) => v.to_untyped(),
            Self::Str(v) => v.to_untyped(),
            Self::Code(v) => v.to_untyped(),
            Self::Content(v) => v.to_untyped(),
            Self::Array(v) => v.to_untyped(),
            Self::Dict(v) => v.to_untyped(),
            Self::Parenthesized(v) => v.to_untyped(),
            Self::Unary(v) => v.to_untyped(),
            Self::Binary(v) => v.to_untyped(),
            Self::FieldAccess(v) => v.to_untyped(),
            Self::FuncCall(v) => v.to_untyped(),
            Self::Closure(v) => v.to_untyped(),
            Self::Let(v) => v.to_untyped(),
            Self::DestructAssign(v) => v.to_untyped(),
            Self::Set(v) => v.to_untyped(),
            Self::Show(v) => v.to_untyped(),
            Self::Contextual(v) => v.to_untyped(),
            Self::Conditional(v) => v.to_untyped(),
            Self::While(v) => v.to_untyped(),
            Self::For(v) => v.to_untyped(),
            Self::Import(v) => v.to_untyped(),
            Self::Include(v) => v.to_untyped(),
            Self::Break(v) => v.to_untyped(),
            Self::Continue(v) => v.to_untyped(),
            Self::Return(v) => v.to_untyped(),
        }
    }
}

impl Expr<'_> {
    /// Can this expression be embedded into markup with a hash?
    pub fn hash(self) -> bool {
        matches!(
            self,
            Self::Ident(_)
                | Self::None(_)
                | Self::Auto(_)
                | Self::Bool(_)
                | Self::Int(_)
                | Self::Float(_)
                | Self::Numeric(_)
                | Self::Str(_)
                | Self::Code(_)
                | Self::Content(_)
                | Self::Array(_)
                | Self::Dict(_)
                | Self::Parenthesized(_)
                | Self::FieldAccess(_)
                | Self::FuncCall(_)
                | Self::Let(_)
                | Self::Set(_)
                | Self::Show(_)
                | Self::Contextual(_)
                | Self::Conditional(_)
                | Self::While(_)
                | Self::For(_)
                | Self::Import(_)
                | Self::Include(_)
                | Self::Break(_)
                | Self::Continue(_)
                | Self::Return(_)
        )
    }

    /// Is this a literal?
    pub fn is_literal(self) -> bool {
        matches!(
            self,
            Self::None(_)
                | Self::Auto(_)
                | Self::Bool(_)
                | Self::Int(_)
                | Self::Float(_)
                | Self::Numeric(_)
                | Self::Str(_)
        )
    }
}

impl Default for Expr<'_> {
    fn default() -> Self {
        Expr::None(None::default())
    }
}

node! {
    /// Plain text without markup.
    Text
}

impl<'a> Text<'a> {
    /// Get the text.
    pub fn get(self) -> &'a EcoString {
        self.0.text()
    }
}

node! {
    /// Whitespace in markup or math. Has at most one newline in markup, as more
    /// indicate a paragraph break.
    Space
}

node! {
    /// A forced line break: `\`.
    Linebreak
}

node! {
    /// A paragraph break, indicated by one or multiple blank lines.
    Parbreak
}

node! {
    /// An escape sequence: `\#`, `\u{1F5FA}`.
    Escape
}

impl Escape<'_> {
    /// Get the escaped character.
    pub fn get(self) -> char {
        let mut s = Scanner::new(self.0.text());
        s.expect('\\');
        if s.eat_if("u{") {
            let hex = s.eat_while(char::is_ascii_hexdigit);
            u32::from_str_radix(hex, 16)
                .ok()
                .and_then(std::char::from_u32)
                .unwrap_or_default()
        } else {
            s.eat().unwrap_or_default()
        }
    }
}

node! {
    /// A shorthand for a unicode codepoint. For example, `~` for a non-breaking
    /// space or `-?` for a soft hyphen.
    Shorthand
}

impl Shorthand<'_> {
    /// A list of all shorthands in markup mode.
    pub const LIST: &'static [(&'static str, char)] = &[
        ("...", '…'),
        ("~", '\u{00A0}'),
        ("-", '\u{2212}'), // Only before a digit
        ("--", '\u{2013}'),
        ("---", '\u{2014}'),
        ("-?", '\u{00AD}'),
    ];

    /// Get the shorthanded character.
    pub fn get(self) -> char {
        let text = self.0.text();
        Self::LIST
            .iter()
            .find(|&&(s, _)| s == text)
            .map_or_else(char::default, |&(_, c)| c)
    }
}

node! {
    /// A smart quote: `'` or `"`.
    SmartQuote
}

impl SmartQuote<'_> {
    /// Whether this is a double quote.
    pub fn double(self) -> bool {
        self.0.text() == "\""
    }
}

node! {
    /// Strong content: `*Strong*`.
    Strong
}

impl<'a> Strong<'a> {
    /// The contents of the strong node.
    pub fn body(self) -> Markup<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }
}

node! {
    /// Emphasized content: `_Emphasized_`.
    Emph
}

impl<'a> Emph<'a> {
    /// The contents of the emphasis node.
    pub fn body(self) -> Markup<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }
}

node! {
    /// Raw text with optional syntax highlighting: `` `...` ``.
    Raw
}

impl<'a> Raw<'a> {
    /// The lines in the raw block.
    pub fn lines(self) -> impl DoubleEndedIterator<Item = Text<'a>> {
        self.0.children().filter_map(SyntaxNode::cast)
    }

    /// An optional identifier specifying the language to syntax-highlight in.
    pub fn lang(self) -> Option<RawLang<'a>> {
        // Only blocky literals are supposed to contain a language.
        let delim: RawDelim = self.0.cast_first_match()?;
        if delim.0.len() < 3 {
            return Option::None;
        }

        self.0.cast_first_match()
    }

    /// Whether the raw text should be displayed in a separate block.
    pub fn block(self) -> bool {
        self.0
            .cast_first_match()
            .is_some_and(|delim: RawDelim| delim.0.len() >= 3)
            && self.0.children().any(|e| {
                e.kind() == SyntaxKind::RawTrimmed && e.text().chars().any(is_newline)
            })
    }
}

node! {
    /// A language tag at the start of raw element: ``typ ``.
    RawLang
}

impl<'a> RawLang<'a> {
    /// Get the language tag.
    pub fn get(self) -> &'a EcoString {
        self.0.text()
    }
}

node! {
    /// A raw delimiter in single or 3+ backticks: `` ` ``.
    RawDelim
}

node! {
    /// A hyperlink: `https://typst.org`.
    Link
}

impl<'a> Link<'a> {
    /// Get the URL.
    pub fn get(self) -> &'a EcoString {
        self.0.text()
    }
}

node! {
    /// A label: `<intro>`.
    Label
}

impl<'a> Label<'a> {
    /// Get the label's text.
    pub fn get(self) -> &'a str {
        self.0.text().trim_start_matches('<').trim_end_matches('>')
    }
}

node! {
    /// A reference: `@target`, `@target[..]`.
    Ref
}

impl<'a> Ref<'a> {
    /// Get the target.
    pub fn target(self) -> &'a str {
        self.0
            .children()
            .find(|node| node.kind() == SyntaxKind::RefMarker)
            .map(|node| node.text().trim_start_matches('@'))
            .unwrap_or_default()
    }

    /// Get the supplement.
    pub fn supplement(self) -> Option<ContentBlock<'a>> {
        self.0.cast_last_match()
    }
}

node! {
    /// A section heading: `= Introduction`.
    Heading
}

impl<'a> Heading<'a> {
    /// The contents of the heading.
    pub fn body(self) -> Markup<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// The section depth (number of equals signs).
    pub fn depth(self) -> NonZeroUsize {
        self.0
            .children()
            .find(|node| node.kind() == SyntaxKind::HeadingMarker)
            .and_then(|node| node.len().try_into().ok())
            .unwrap_or(NonZeroUsize::new(1).unwrap())
    }
}

node! {
    /// An item in a bullet list: `- ...`.
    ListItem
}

impl<'a> ListItem<'a> {
    /// The contents of the list item.
    pub fn body(self) -> Markup<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }
}

node! {
    /// An item in an enumeration (numbered list): `+ ...` or `1. ...`.
    EnumItem
}

impl<'a> EnumItem<'a> {
    /// The explicit numbering, if any: `23.`.
    pub fn number(self) -> Option<usize> {
        self.0.children().find_map(|node| match node.kind() {
            SyntaxKind::EnumMarker => node.text().trim_end_matches('.').parse().ok(),
            _ => Option::None,
        })
    }

    /// The contents of the list item.
    pub fn body(self) -> Markup<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }
}

node! {
    /// An item in a term list: `/ Term: Details`.
    TermItem
}

impl<'a> TermItem<'a> {
    /// The term described by the item.
    pub fn term(self) -> Markup<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// The description of the term.
    pub fn description(self) -> Markup<'a> {
        self.0.cast_last_match().unwrap_or_default()
    }
}

node! {
    /// A mathematical equation: `$x$`, `$ x^2 $`.
    Equation
}

impl<'a> Equation<'a> {
    /// The contained math.
    pub fn body(self) -> Math<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// Whether the equation should be displayed as a separate block.
    pub fn block(self) -> bool {
        let is_space = |node: Option<&SyntaxNode>| {
            node.map(SyntaxNode::kind) == Some(SyntaxKind::Space)
        };
        is_space(self.0.children().nth(1)) && is_space(self.0.children().nth_back(1))
    }
}

node! {
    /// The contents of a mathematical equation: `x^2 + 1`.
    Math
}

impl<'a> Math<'a> {
    /// The expressions the mathematical content consists of.
    pub fn exprs(self) -> impl DoubleEndedIterator<Item = Expr<'a>> {
        self.0.children().filter_map(Expr::cast_with_space)
    }
}

node! {
    /// An identifier in math: `pi`.
    MathIdent
}

impl<'a> MathIdent<'a> {
    /// Get the identifier.
    pub fn get(self) -> &'a EcoString {
        self.0.text()
    }

    /// Get the identifier as a string slice.
    pub fn as_str(self) -> &'a str {
        self.get()
    }
}

impl Deref for MathIdent<'_> {
    type Target = str;

    /// Dereference to a string. Note that this shortens the lifetime, so you
    /// may need to use [`get()`](Self::get) instead in some situations.
    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

node! {
    /// A shorthand for a unicode codepoint in math: `a <= b`.
    MathShorthand
}

impl MathShorthand<'_> {
    /// A list of all shorthands in math mode.
    pub const LIST: &'static [(&'static str, char)] = &[
        ("...", '…'),
        ("-", '−'),
        ("'", '′'),
        ("*", '∗'),
        ("~", '∼'),
        ("!=", '≠'),
        (":=", '≔'),
        ("::=", '⩴'),
        ("=:", '≕'),
        ("<<", '≪'),
        ("<<<", '⋘'),
        (">>", '≫'),
        (">>>", '⋙'),
        ("<=", '≤'),
        (">=", '≥'),
        ("->", '→'),
        ("-->", '⟶'),
        ("|->", '↦'),
        (">->", '↣'),
        ("->>", '↠'),
        ("<-", '←'),
        ("<--", '⟵'),
        ("<-<", '↢'),
        ("<<-", '↞'),
        ("<->", '↔'),
        ("<-->", '⟷'),
        ("~>", '⇝'),
        ("~~>", '⟿'),
        ("<~", '⇜'),
        ("<~~", '⬳'),
        ("=>", '⇒'),
        ("|=>", '⤇'),
        ("==>", '⟹'),
        ("<==", '⟸'),
        ("<=>", '⇔'),
        ("<==>", '⟺'),
        ("[|", '⟦'),
        ("|]", '⟧'),
        ("||", '‖'),
    ];

    /// Get the shorthanded character.
    pub fn get(self) -> char {
        let text = self.0.text();
        Self::LIST
            .iter()
            .find(|&&(s, _)| s == text)
            .map_or_else(char::default, |&(_, c)| c)
    }
}

node! {
    /// An alignment point in math: `&`.
    MathAlignPoint
}

node! {
    /// Matched delimiters in math: `[x + y]`.
    MathDelimited
}

impl<'a> MathDelimited<'a> {
    /// The opening delimiter.
    pub fn open(self) -> Expr<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// The contents, including the delimiters.
    pub fn body(self) -> Math<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// The closing delimiter.
    pub fn close(self) -> Expr<'a> {
        self.0.cast_last_match().unwrap_or_default()
    }
}

node! {
    /// A base with optional attachments in math: `a_1^2`.
    MathAttach
}

impl<'a> MathAttach<'a> {
    /// The base, to which things are attached.
    pub fn base(self) -> Expr<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// The bottom attachment.
    pub fn bottom(self) -> Option<Expr<'a>> {
        self.0
            .children()
            .skip_while(|node| !matches!(node.kind(), SyntaxKind::Underscore))
            .find_map(SyntaxNode::cast)
    }

    /// The top attachment.
    pub fn top(self) -> Option<Expr<'a>> {
        self.0
            .children()
            .skip_while(|node| !matches!(node.kind(), SyntaxKind::Hat))
            .find_map(SyntaxNode::cast)
    }

    /// Extract attached primes if present.
    pub fn primes(self) -> Option<MathPrimes<'a>> {
        self.0
            .children()
            .skip_while(|node| node.cast::<Expr<'_>>().is_none())
            .nth(1)
            .and_then(|n| n.cast())
    }
}

node! {
    /// Grouped primes in math: `a'''`.
    MathPrimes
}

impl MathPrimes<'_> {
    /// The number of grouped primes.
    pub fn count(self) -> usize {
        self.0
            .children()
            .filter(|node| matches!(node.kind(), SyntaxKind::Prime))
            .count()
    }
}

node! {
    /// A fraction in math: `x/2`
    MathFrac
}

impl<'a> MathFrac<'a> {
    /// The numerator.
    pub fn num(self) -> Expr<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// The denominator.
    pub fn denom(self) -> Expr<'a> {
        self.0.cast_last_match().unwrap_or_default()
    }
}

node! {
    /// A root in math: `√x`, `∛x` or `∜x`.
    MathRoot
}

impl<'a> MathRoot<'a> {
    /// The index of the root.
    pub fn index(self) -> Option<usize> {
        match self.0.children().next().map(|node| node.text().as_str()) {
            Some("∜") => Some(4),
            Some("∛") => Some(3),
            Some("√") => Option::None,
            _ => Option::None,
        }
    }

    /// The radicand.
    pub fn radicand(self) -> Expr<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }
}

node! {
    /// An identifier: `it`.
    Ident
}

impl<'a> Ident<'a> {
    /// Get the identifier.
    pub fn get(self) -> &'a EcoString {
        self.0.text()
    }

    /// Get the identifier as a string slice.
    pub fn as_str(self) -> &'a str {
        self.get()
    }
}

impl Deref for Ident<'_> {
    type Target = str;

    /// Dereference to a string. Note that this shortens the lifetime, so you
    /// may need to use [`get()`](Self::get) instead in some situations.
    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

node! {
    /// The `none` literal.
    None
}

node! {
    /// The `auto` literal.
    Auto
}

node! {
    /// A boolean: `true`, `false`.
    Bool
}

impl Bool<'_> {
    /// Get the boolean value.
    pub fn get(self) -> bool {
        self.0.text() == "true"
    }
}

node! {
    /// An integer: `120`.
    Int
}

impl Int<'_> {
    /// Get the integer value.
    pub fn get(self) -> i64 {
        let text = self.0.text();
        if let Some(rest) = text.strip_prefix("0x") {
            i64::from_str_radix(rest, 16)
        } else if let Some(rest) = text.strip_prefix("0o") {
            i64::from_str_radix(rest, 8)
        } else if let Some(rest) = text.strip_prefix("0b") {
            i64::from_str_radix(rest, 2)
        } else {
            text.parse()
        }
        .unwrap_or_default()
    }
}

node! {
    /// A floating-point number: `1.2`, `10e-4`.
    Float
}

impl Float<'_> {
    /// Get the floating-point value.
    pub fn get(self) -> f64 {
        self.0.text().parse().unwrap_or_default()
    }
}

node! {
    /// A numeric value with a unit: `12pt`, `3cm`, `2em`, `90deg`, `50%`.
    Numeric
}

impl Numeric<'_> {
    /// Get the numeric value and unit.
    pub fn get(self) -> (f64, Unit) {
        let text = self.0.text();
        let count = text
            .chars()
            .rev()
            .take_while(|c| matches!(c, 'a'..='z' | '%'))
            .count();

        let split = text.len() - count;
        let value = text[..split].parse().unwrap_or_default();
        let unit = match &text[split..] {
            "pt" => Unit::Pt,
            "mm" => Unit::Mm,
            "cm" => Unit::Cm,
            "in" => Unit::In,
            "deg" => Unit::Deg,
            "rad" => Unit::Rad,
            "em" => Unit::Em,
            "fr" => Unit::Fr,
            "%" => Unit::Percent,
            _ => Unit::Percent,
        };

        (value, unit)
    }
}

/// Unit of a numeric value.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Unit {
    /// Points.
    Pt,
    /// Millimeters.
    Mm,
    /// Centimeters.
    Cm,
    /// Inches.
    In,
    /// Radians.
    Rad,
    /// Degrees.
    Deg,
    /// Font-relative: `1em` is the same as the font size.
    Em,
    /// Fractions: `fr`.
    Fr,
    /// Percentage: `%`.
    Percent,
}

node! {
    /// A quoted string: `"..."`.
    Str
}

impl Str<'_> {
    /// Get the string value with resolved escape sequences.
    pub fn get(self) -> EcoString {
        let text = self.0.text();
        let unquoted = &text[1..text.len() - 1];
        if !unquoted.contains('\\') {
            return unquoted.into();
        }

        let mut out = EcoString::with_capacity(unquoted.len());
        let mut s = Scanner::new(unquoted);

        while let Some(c) = s.eat() {
            if c != '\\' {
                out.push(c);
                continue;
            }

            let start = s.locate(-1);
            match s.eat() {
                Some('\\') => out.push('\\'),
                Some('"') => out.push('"'),
                Some('n') => out.push('\n'),
                Some('r') => out.push('\r'),
                Some('t') => out.push('\t'),
                Some('u') if s.eat_if('{') => {
                    let sequence = s.eat_while(char::is_ascii_hexdigit);
                    s.eat_if('}');

                    match u32::from_str_radix(sequence, 16)
                        .ok()
                        .and_then(std::char::from_u32)
                    {
                        Some(c) => out.push(c),
                        Option::None => out.push_str(s.from(start)),
                    }
                }
                _ => out.push_str(s.from(start)),
            }
        }

        out
    }
}

node! {
    /// A code block: `{ let x = 1; x + 2 }`.
    CodeBlock
}

impl<'a> CodeBlock<'a> {
    /// The contained code.
    pub fn body(self) -> Code<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }
}

node! {
    /// The body of a code block.
    Code
}

impl<'a> Code<'a> {
    /// The list of expressions contained in the code.
    pub fn exprs(self) -> impl DoubleEndedIterator<Item = Expr<'a>> {
        self.0.children().filter_map(SyntaxNode::cast)
    }
}

node! {
    /// A content block: `[*Hi* there!]`.
    ContentBlock
}

impl<'a> ContentBlock<'a> {
    /// The contained markup.
    pub fn body(self) -> Markup<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }
}

node! {
    /// A grouped expression: `(1 + 2)`.
    Parenthesized
}

impl<'a> Parenthesized<'a> {
    /// The wrapped expression.
    ///
    /// Should only be accessed if this is contained in an `Expr`.
    pub fn expr(self) -> Expr<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// The wrapped pattern.
    ///
    /// Should only be accessed if this is contained in a `Pattern`.
    pub fn pattern(self) -> Pattern<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }
}

node! {
    /// An array: `(1, "hi", 12cm)`.
    Array
}

impl<'a> Array<'a> {
    /// The array's items.
    pub fn items(self) -> impl DoubleEndedIterator<Item = ArrayItem<'a>> {
        self.0.children().filter_map(SyntaxNode::cast)
    }
}

/// An item in an array.
#[derive(Debug, Copy, Clone, Hash)]
pub enum ArrayItem<'a> {
    /// A bare expression: `12`.
    Pos(Expr<'a>),
    /// A spread expression: `..things`.
    Spread(Spread<'a>),
}

impl<'a> AstNode<'a> for ArrayItem<'a> {
    fn from_untyped(node: &'a SyntaxNode) -> Option<Self> {
        match node.kind() {
            SyntaxKind::Spread => node.cast().map(Self::Spread),
            _ => node.cast().map(Self::Pos),
        }
    }

    fn to_untyped(self) -> &'a SyntaxNode {
        match self {
            Self::Pos(v) => v.to_untyped(),
            Self::Spread(v) => v.to_untyped(),
        }
    }
}

node! {
    /// A dictionary: `(thickness: 3pt, pattern: dashed)`.
    Dict
}

impl<'a> Dict<'a> {
    /// The dictionary's items.
    pub fn items(self) -> impl DoubleEndedIterator<Item = DictItem<'a>> {
        self.0.children().filter_map(SyntaxNode::cast)
    }
}

/// An item in an dictionary expression.
#[derive(Debug, Copy, Clone, Hash)]
pub enum DictItem<'a> {
    /// A named pair: `thickness: 3pt`.
    Named(Named<'a>),
    /// A keyed pair: `"spacy key": true`.
    Keyed(Keyed<'a>),
    /// A spread expression: `..things`.
    Spread(Spread<'a>),
}

impl<'a> AstNode<'a> for DictItem<'a> {
    fn from_untyped(node: &'a SyntaxNode) -> Option<Self> {
        match node.kind() {
            SyntaxKind::Named => node.cast().map(Self::Named),
            SyntaxKind::Keyed => node.cast().map(Self::Keyed),
            SyntaxKind::Spread => node.cast().map(Self::Spread),
            _ => Option::None,
        }
    }

    fn to_untyped(self) -> &'a SyntaxNode {
        match self {
            Self::Named(v) => v.to_untyped(),
            Self::Keyed(v) => v.to_untyped(),
            Self::Spread(v) => v.to_untyped(),
        }
    }
}

node! {
    /// A named pair: `thickness: 3pt`.
    Named
}

impl<'a> Named<'a> {
    /// The name: `thickness`.
    pub fn name(self) -> Ident<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// The right-hand side of the pair: `3pt`.
    ///
    /// This should only be accessed if this `Named` is contained in a
    /// `DictItem`, `Arg`, or `Param`.
    pub fn expr(self) -> Expr<'a> {
        self.0.cast_last_match().unwrap_or_default()
    }

    /// The right-hand side of the pair as a pattern.
    ///
    /// This should only be accessed if this `Named` is contained in a
    /// `Destructuring`.
    pub fn pattern(self) -> Pattern<'a> {
        self.0.cast_last_match().unwrap_or_default()
    }
}

node! {
    /// A keyed pair: `"spacy key": true`.
    Keyed
}

impl<'a> Keyed<'a> {
    /// The key: `"spacy key"`.
    pub fn key(self) -> Expr<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// The right-hand side of the pair: `true`.
    ///
    /// This should only be accessed if this `Keyed` is contained in a
    /// `DictItem`.
    pub fn expr(self) -> Expr<'a> {
        self.0.cast_last_match().unwrap_or_default()
    }
}

node! {
    /// A spread: `..x` or `..x.at(0)`.
    Spread
}

impl<'a> Spread<'a> {
    /// The spread expression.
    ///
    /// This should only be accessed if this `Spread` is contained in an
    /// `ArrayItem`, `DictItem`, or `Arg`.
    pub fn expr(self) -> Expr<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// The sink identifier, if present.
    ///
    /// This should only be accessed if this `Spread` is contained in a
    /// `Param` or binding `DestructuringItem`.
    pub fn sink_ident(self) -> Option<Ident<'a>> {
        self.0.cast_first_match()
    }

    /// The sink expressions, if present.
    ///
    /// This should only be accessed if this `Spread` is contained in a
    /// `DestructuringItem`.
    pub fn sink_expr(self) -> Option<Expr<'a>> {
        self.0.cast_first_match()
    }
}

node! {
    /// A unary operation: `-x`.
    Unary
}

impl<'a> Unary<'a> {
    /// The operator: `-`.
    pub fn op(self) -> UnOp {
        self.0
            .children()
            .find_map(|node| UnOp::from_kind(node.kind()))
            .unwrap_or(UnOp::Pos)
    }

    /// The expression to operate on: `x`.
    pub fn expr(self) -> Expr<'a> {
        self.0.cast_last_match().unwrap_or_default()
    }
}

/// A unary operator.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum UnOp {
    /// The plus operator: `+`.
    Pos,
    /// The negation operator: `-`.
    Neg,
    /// The boolean `not`.
    Not,
}

impl UnOp {
    /// Try to convert the token into a unary operation.
    pub fn from_kind(token: SyntaxKind) -> Option<Self> {
        Some(match token {
            SyntaxKind::Plus => Self::Pos,
            SyntaxKind::Minus => Self::Neg,
            SyntaxKind::Not => Self::Not,
            _ => return Option::None,
        })
    }

    /// The precedence of this operator.
    pub fn precedence(self) -> usize {
        match self {
            Self::Pos | Self::Neg => 7,
            Self::Not => 4,
        }
    }

    /// The string representation of this operation.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Pos => "+",
            Self::Neg => "-",
            Self::Not => "not",
        }
    }
}

node! {
    /// A binary operation: `a + b`.
    Binary
}

impl<'a> Binary<'a> {
    /// The binary operator: `+`.
    pub fn op(self) -> BinOp {
        let mut not = false;
        self.0
            .children()
            .find_map(|node| match node.kind() {
                SyntaxKind::Not => {
                    not = true;
                    Option::None
                }
                SyntaxKind::In if not => Some(BinOp::NotIn),
                _ => BinOp::from_kind(node.kind()),
            })
            .unwrap_or(BinOp::Add)
    }

    /// The left-hand side of the operation: `a`.
    pub fn lhs(self) -> Expr<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// The right-hand side of the operation: `b`.
    pub fn rhs(self) -> Expr<'a> {
        self.0.cast_last_match().unwrap_or_default()
    }
}

/// A binary operator.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum BinOp {
    /// The addition operator: `+`.
    Add,
    /// The subtraction operator: `-`.
    Sub,
    /// The multiplication operator: `*`.
    Mul,
    /// The division operator: `/`.
    Div,
    /// The short-circuiting boolean `and`.
    And,
    /// The short-circuiting boolean `or`.
    Or,
    /// The equality operator: `==`.
    Eq,
    /// The inequality operator: `!=`.
    Neq,
    /// The less-than operator: `<`.
    Lt,
    /// The less-than or equal operator: `<=`.
    Leq,
    /// The greater-than operator: `>`.
    Gt,
    /// The greater-than or equal operator: `>=`.
    Geq,
    /// The assignment operator: `=`.
    Assign,
    /// The containment operator: `in`.
    In,
    /// The inverse containment operator: `not in`.
    NotIn,
    /// The add-assign operator: `+=`.
    AddAssign,
    /// The subtract-assign operator: `-=`.
    SubAssign,
    /// The multiply-assign operator: `*=`.
    MulAssign,
    /// The divide-assign operator: `/=`.
    DivAssign,
}

impl BinOp {
    /// Try to convert the token into a binary operation.
    pub fn from_kind(token: SyntaxKind) -> Option<Self> {
        Some(match token {
            SyntaxKind::Plus => Self::Add,
            SyntaxKind::Minus => Self::Sub,
            SyntaxKind::Star => Self::Mul,
            SyntaxKind::Slash => Self::Div,
            SyntaxKind::And => Self::And,
            SyntaxKind::Or => Self::Or,
            SyntaxKind::EqEq => Self::Eq,
            SyntaxKind::ExclEq => Self::Neq,
            SyntaxKind::Lt => Self::Lt,
            SyntaxKind::LtEq => Self::Leq,
            SyntaxKind::Gt => Self::Gt,
            SyntaxKind::GtEq => Self::Geq,
            SyntaxKind::Eq => Self::Assign,
            SyntaxKind::In => Self::In,
            SyntaxKind::PlusEq => Self::AddAssign,
            SyntaxKind::HyphEq => Self::SubAssign,
            SyntaxKind::StarEq => Self::MulAssign,
            SyntaxKind::SlashEq => Self::DivAssign,
            _ => return Option::None,
        })
    }

    /// The precedence of this operator.
    pub fn precedence(self) -> usize {
        match self {
            Self::Mul => 6,
            Self::Div => 6,
            Self::Add => 5,
            Self::Sub => 5,
            Self::Eq => 4,
            Self::Neq => 4,
            Self::Lt => 4,
            Self::Leq => 4,
            Self::Gt => 4,
            Self::Geq => 4,
            Self::In => 4,
            Self::NotIn => 4,
            Self::And => 3,
            Self::Or => 2,
            Self::Assign => 1,
            Self::AddAssign => 1,
            Self::SubAssign => 1,
            Self::MulAssign => 1,
            Self::DivAssign => 1,
        }
    }

    /// The associativity of this operator.
    pub fn assoc(self) -> Assoc {
        match self {
            Self::Add => Assoc::Left,
            Self::Sub => Assoc::Left,
            Self::Mul => Assoc::Left,
            Self::Div => Assoc::Left,
            Self::And => Assoc::Left,
            Self::Or => Assoc::Left,
            Self::Eq => Assoc::Left,
            Self::Neq => Assoc::Left,
            Self::Lt => Assoc::Left,
            Self::Leq => Assoc::Left,
            Self::Gt => Assoc::Left,
            Self::Geq => Assoc::Left,
            Self::In => Assoc::Left,
            Self::NotIn => Assoc::Left,
            Self::Assign => Assoc::Right,
            Self::AddAssign => Assoc::Right,
            Self::SubAssign => Assoc::Right,
            Self::MulAssign => Assoc::Right,
            Self::DivAssign => Assoc::Right,
        }
    }

    /// The string representation of this operation.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Add => "+",
            Self::Sub => "-",
            Self::Mul => "*",
            Self::Div => "/",
            Self::And => "and",
            Self::Or => "or",
            Self::Eq => "==",
            Self::Neq => "!=",
            Self::Lt => "<",
            Self::Leq => "<=",
            Self::Gt => ">",
            Self::Geq => ">=",
            Self::In => "in",
            Self::NotIn => "not in",
            Self::Assign => "=",
            Self::AddAssign => "+=",
            Self::SubAssign => "-=",
            Self::MulAssign => "*=",
            Self::DivAssign => "/=",
        }
    }
}

/// The associativity of a binary operator.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Assoc {
    /// Left-associative: `a + b + c` is equivalent to `(a + b) + c`.
    Left,
    /// Right-associative: `a = b = c` is equivalent to `a = (b = c)`.
    Right,
}

node! {
    /// A field access: `properties.age`.
    FieldAccess
}

impl<'a> FieldAccess<'a> {
    /// The expression to access the field on.
    pub fn target(self) -> Expr<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// The name of the field.
    pub fn field(self) -> Ident<'a> {
        self.0.cast_last_match().unwrap_or_default()
    }
}

node! {
    /// An invocation of a function or method: `f(x, y)`.
    FuncCall
}

impl<'a> FuncCall<'a> {
    /// The function to call.
    pub fn callee(self) -> Expr<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// The arguments to the function.
    pub fn args(self) -> Args<'a> {
        self.0.cast_last_match().unwrap_or_default()
    }
}

node! {
    /// A function call's argument list: `(12pt, y)`.
    Args
}

impl<'a> Args<'a> {
    /// The positional and named arguments.
    pub fn items(self) -> impl DoubleEndedIterator<Item = Arg<'a>> {
        self.0.children().filter_map(SyntaxNode::cast)
    }

    /// Whether there is a comma at the end.
    pub fn trailing_comma(self) -> bool {
        self.0
            .children()
            .rev()
            .skip(1)
            .find(|n| !n.kind().is_trivia())
            .is_some_and(|n| n.kind() == SyntaxKind::Comma)
    }
}

/// An argument to a function call.
#[derive(Debug, Copy, Clone, Hash)]
pub enum Arg<'a> {
    /// A positional argument: `12`.
    Pos(Expr<'a>),
    /// A named argument: `draw: false`.
    Named(Named<'a>),
    /// A spread argument: `..things`.
    Spread(Spread<'a>),
}

impl<'a> AstNode<'a> for Arg<'a> {
    fn from_untyped(node: &'a SyntaxNode) -> Option<Self> {
        match node.kind() {
            SyntaxKind::Named => node.cast().map(Self::Named),
            SyntaxKind::Spread => node.cast().map(Self::Spread),
            _ => node.cast().map(Self::Pos),
        }
    }

    fn to_untyped(self) -> &'a SyntaxNode {
        match self {
            Self::Pos(v) => v.to_untyped(),
            Self::Named(v) => v.to_untyped(),
            Self::Spread(v) => v.to_untyped(),
        }
    }
}

node! {
    /// A closure: `(x, y) => z`.
    Closure
}

impl<'a> Closure<'a> {
    /// The name of the closure.
    ///
    /// This only exists if you use the function syntax sugar: `let f(x) = y`.
    pub fn name(self) -> Option<Ident<'a>> {
        self.0.children().next()?.cast()
    }

    /// The parameter bindings.
    pub fn params(self) -> Params<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// The body of the closure.
    pub fn body(self) -> Expr<'a> {
        self.0.cast_last_match().unwrap_or_default()
    }
}

node! {
    /// A closure's parameters: `(x, y)`.
    Params
}

impl<'a> Params<'a> {
    /// The parameter bindings.
    pub fn children(self) -> impl DoubleEndedIterator<Item = Param<'a>> {
        self.0.children().filter_map(SyntaxNode::cast)
    }
}

/// A parameter to a closure.
#[derive(Debug, Copy, Clone, Hash)]
pub enum Param<'a> {
    /// A positional parameter: `x`.
    Pos(Pattern<'a>),
    /// A named parameter with a default value: `draw: false`.
    Named(Named<'a>),
    /// An argument sink: `..args` or `..`.
    Spread(Spread<'a>),
}

impl<'a> AstNode<'a> for Param<'a> {
    fn from_untyped(node: &'a SyntaxNode) -> Option<Self> {
        match node.kind() {
            SyntaxKind::Named => node.cast().map(Self::Named),
            SyntaxKind::Spread => node.cast().map(Self::Spread),
            _ => node.cast().map(Self::Pos),
        }
    }

    fn to_untyped(self) -> &'a SyntaxNode {
        match self {
            Self::Pos(v) => v.to_untyped(),
            Self::Named(v) => v.to_untyped(),
            Self::Spread(v) => v.to_untyped(),
        }
    }
}

/// The kind of a pattern.
#[derive(Debug, Copy, Clone, Hash)]
pub enum Pattern<'a> {
    /// A single expression: `x`.
    Normal(Expr<'a>),
    /// A placeholder: `_`.
    Placeholder(Underscore<'a>),
    /// A parenthesized pattern.
    Parenthesized(Parenthesized<'a>),
    /// A destructuring pattern: `(x, _, ..y)`.
    Destructuring(Destructuring<'a>),
}

impl<'a> AstNode<'a> for Pattern<'a> {
    fn from_untyped(node: &'a SyntaxNode) -> Option<Self> {
        match node.kind() {
            SyntaxKind::Underscore => node.cast().map(Self::Placeholder),
            SyntaxKind::Parenthesized => node.cast().map(Self::Parenthesized),
            SyntaxKind::Destructuring => node.cast().map(Self::Destructuring),
            _ => node.cast().map(Self::Normal),
        }
    }

    fn to_untyped(self) -> &'a SyntaxNode {
        match self {
            Self::Normal(v) => v.to_untyped(),
            Self::Placeholder(v) => v.to_untyped(),
            Self::Parenthesized(v) => v.to_untyped(),
            Self::Destructuring(v) => v.to_untyped(),
        }
    }
}

impl<'a> Pattern<'a> {
    /// Returns a list of all new bindings introduced by the pattern.
    pub fn bindings(self) -> Vec<Ident<'a>> {
        match self {
            Self::Normal(Expr::Ident(ident)) => vec![ident],
            Self::Parenthesized(v) => v.pattern().bindings(),
            Self::Destructuring(v) => v.bindings(),
            _ => vec![],
        }
    }
}

impl Default for Pattern<'_> {
    fn default() -> Self {
        Self::Normal(Expr::default())
    }
}

node! {
    /// An underscore: `_`
    Underscore
}

node! {
    /// A destructuring pattern: `x` or `(x, _, ..y)`.
    Destructuring
}

impl<'a> Destructuring<'a> {
    /// The items of the destructuring.
    pub fn items(self) -> impl DoubleEndedIterator<Item = DestructuringItem<'a>> {
        self.0.children().filter_map(SyntaxNode::cast)
    }

    /// Returns a list of all new bindings introduced by the destructuring.
    pub fn bindings(self) -> Vec<Ident<'a>> {
        self.items()
            .flat_map(|binding| match binding {
                DestructuringItem::Pattern(pattern) => pattern.bindings(),
                DestructuringItem::Named(named) => named.pattern().bindings(),
                DestructuringItem::Spread(spread) => {
                    spread.sink_ident().into_iter().collect()
                }
            })
            .collect()
    }
}

/// The kind of an element in a destructuring pattern.
#[derive(Debug, Copy, Clone, Hash)]
pub enum DestructuringItem<'a> {
    /// A sub-pattern: `x`.
    Pattern(Pattern<'a>),
    /// A renamed destructuring: `x: y`.
    Named(Named<'a>),
    /// A destructuring sink: `..y` or `..`.
    Spread(Spread<'a>),
}

impl<'a> AstNode<'a> for DestructuringItem<'a> {
    fn from_untyped(node: &'a SyntaxNode) -> Option<Self> {
        match node.kind() {
            SyntaxKind::Named => node.cast().map(Self::Named),
            SyntaxKind::Spread => node.cast().map(Self::Spread),
            _ => node.cast().map(Self::Pattern),
        }
    }

    fn to_untyped(self) -> &'a SyntaxNode {
        match self {
            Self::Pattern(v) => v.to_untyped(),
            Self::Named(v) => v.to_untyped(),
            Self::Spread(v) => v.to_untyped(),
        }
    }
}

node! {
    /// A let binding: `let x = 1`.
    LetBinding
}

/// The kind of a let binding, either a normal one or a closure.
#[derive(Debug)]
pub enum LetBindingKind<'a> {
    /// A normal binding: `let x = 1`.
    Normal(Pattern<'a>),
    /// A closure binding: `let f(x) = 1`.
    Closure(Ident<'a>),
}

impl<'a> LetBindingKind<'a> {
    /// Returns a list of all new bindings introduced by the let binding.
    pub fn bindings(self) -> Vec<Ident<'a>> {
        match self {
            LetBindingKind::Normal(pattern) => pattern.bindings(),
            LetBindingKind::Closure(ident) => vec![ident],
        }
    }
}

impl<'a> LetBinding<'a> {
    /// The kind of the let binding.
    pub fn kind(self) -> LetBindingKind<'a> {
        match self.0.cast_first_match::<Pattern>() {
            Some(Pattern::Normal(Expr::Closure(closure))) => {
                LetBindingKind::Closure(closure.name().unwrap_or_default())
            }
            pattern => LetBindingKind::Normal(pattern.unwrap_or_default()),
        }
    }

    /// The expression the binding is initialized with.
    pub fn init(self) -> Option<Expr<'a>> {
        match self.kind() {
            LetBindingKind::Normal(Pattern::Normal(_) | Pattern::Parenthesized(_)) => {
                self.0.children().filter_map(SyntaxNode::cast).nth(1)
            }
            LetBindingKind::Normal(_) => self.0.cast_first_match(),
            LetBindingKind::Closure(_) => self.0.cast_first_match(),
        }
    }
}

node! {
    /// An assignment expression `(x, y) = (1, 2)`.
    DestructAssignment
}

impl<'a> DestructAssignment<'a> {
    /// The pattern of the assignment.
    pub fn pattern(self) -> Pattern<'a> {
        self.0.cast_first_match::<Pattern>().unwrap_or_default()
    }

    /// The expression that is assigned.
    pub fn value(self) -> Expr<'a> {
        self.0.cast_last_match().unwrap_or_default()
    }
}

node! {
    /// A set rule: `set text(...)`.
    SetRule
}

impl<'a> SetRule<'a> {
    /// The function to set style properties for.
    pub fn target(self) -> Expr<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// The style properties to set.
    pub fn args(self) -> Args<'a> {
        self.0.cast_last_match().unwrap_or_default()
    }

    /// A condition under which the set rule applies.
    pub fn condition(self) -> Option<Expr<'a>> {
        self.0
            .children()
            .skip_while(|child| child.kind() != SyntaxKind::If)
            .find_map(SyntaxNode::cast)
    }
}

node! {
    /// A show rule: `show heading: it => emph(it.body)`.
    ShowRule
}

impl<'a> ShowRule<'a> {
    /// Defines which nodes the show rule applies to.
    pub fn selector(self) -> Option<Expr<'a>> {
        self.0
            .children()
            .rev()
            .skip_while(|child| child.kind() != SyntaxKind::Colon)
            .find_map(SyntaxNode::cast)
    }

    /// The transformation recipe.
    pub fn transform(self) -> Expr<'a> {
        self.0.cast_last_match().unwrap_or_default()
    }
}

node! {
    /// A contextual expression: `context text.lang`.
    Contextual
}

impl<'a> Contextual<'a> {
    /// The expression which depends on the context.
    pub fn body(self) -> Expr<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }
}

node! {
    /// An if-else conditional: `if x { y } else { z }`.
    Conditional
}

impl<'a> Conditional<'a> {
    /// The condition which selects the body to evaluate.
    pub fn condition(self) -> Expr<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// The expression to evaluate if the condition is true.
    pub fn if_body(self) -> Expr<'a> {
        self.0
            .children()
            .filter_map(SyntaxNode::cast)
            .nth(1)
            .unwrap_or_default()
    }

    /// The expression to evaluate if the condition is false.
    pub fn else_body(self) -> Option<Expr<'a>> {
        self.0.children().filter_map(SyntaxNode::cast).nth(2)
    }
}

node! {
    /// A while loop: `while x { y }`.
    WhileLoop
}

impl<'a> WhileLoop<'a> {
    /// The condition which selects whether to evaluate the body.
    pub fn condition(self) -> Expr<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// The expression to evaluate while the condition is true.
    pub fn body(self) -> Expr<'a> {
        self.0.cast_last_match().unwrap_or_default()
    }
}

node! {
    /// A for loop: `for x in y { z }`.
    ForLoop
}

impl<'a> ForLoop<'a> {
    /// The pattern to assign to.
    pub fn pattern(self) -> Pattern<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// The expression to iterate over.
    pub fn iterable(self) -> Expr<'a> {
        self.0
            .children()
            .skip_while(|&c| c.kind() != SyntaxKind::In)
            .find_map(SyntaxNode::cast)
            .unwrap_or_default()
    }

    /// The expression to evaluate for each iteration.
    pub fn body(self) -> Expr<'a> {
        self.0.cast_last_match().unwrap_or_default()
    }
}

node! {
    /// A module import: `import "utils.typ": a, b, c`.
    ModuleImport
}

impl<'a> ModuleImport<'a> {
    /// The module or path from which the items should be imported.
    pub fn source(self) -> Expr<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// The items to be imported.
    pub fn imports(self) -> Option<Imports<'a>> {
        self.0.children().find_map(|node| match node.kind() {
            SyntaxKind::Star => Some(Imports::Wildcard),
            SyntaxKind::ImportItems => node.cast().map(Imports::Items),
            _ => Option::None,
        })
    }

    /// The name this module was assigned to, if it was renamed with `as`
    /// (`renamed` in `import "..." as renamed`).
    pub fn new_name(self) -> Option<Ident<'a>> {
        self.0
            .children()
            .skip_while(|child| child.kind() != SyntaxKind::As)
            .find_map(SyntaxNode::cast)
    }
}

/// The items that ought to be imported from a file.
#[derive(Debug, Copy, Clone, Hash)]
pub enum Imports<'a> {
    /// All items in the scope of the file should be imported.
    Wildcard,
    /// The specified items from the file should be imported.
    Items(ImportItems<'a>),
}

node! {
    /// Items to import from a module: `a, b, c`.
    ImportItems
}

impl<'a> ImportItems<'a> {
    /// Returns an iterator over the items to import from the module.
    pub fn iter(self) -> impl DoubleEndedIterator<Item = ImportItem<'a>> {
        self.0.children().filter_map(|child| match child.kind() {
            SyntaxKind::RenamedImportItem => child.cast().map(ImportItem::Renamed),
            SyntaxKind::ImportItemPath => child.cast().map(ImportItem::Simple),
            _ => Option::None,
        })
    }
}

node! {
    /// A path to a submodule's imported name: `a.b.c`.
    ImportItemPath
}

impl<'a> ImportItemPath<'a> {
    /// An iterator over the path's components.
    pub fn iter(self) -> impl DoubleEndedIterator<Item = Ident<'a>> {
        self.0.children().filter_map(SyntaxNode::cast)
    }

    /// The name of the imported item. This is the last segment in the path.
    pub fn name(self) -> Ident<'a> {
        self.iter().last().unwrap_or_default()
    }
}

/// An imported item, potentially renamed to another identifier.
#[derive(Debug, Copy, Clone, Hash)]
pub enum ImportItem<'a> {
    /// A non-renamed import (the item's name in the scope is the same as its
    /// name).
    Simple(ImportItemPath<'a>),
    /// A renamed import (the item was bound to a different name in the scope
    /// than the one it was defined as).
    Renamed(RenamedImportItem<'a>),
}

impl<'a> ImportItem<'a> {
    /// The path to the imported item.
    pub fn path(self) -> ImportItemPath<'a> {
        match self {
            Self::Simple(path) => path,
            Self::Renamed(renamed_item) => renamed_item.path(),
        }
    }

    /// The original name of the imported item, at its source. This will be the
    /// equal to the bound name if the item wasn't renamed with 'as'.
    pub fn original_name(self) -> Ident<'a> {
        match self {
            Self::Simple(path) => path.name(),
            Self::Renamed(renamed_item) => renamed_item.original_name(),
        }
    }

    /// The name which this import item was bound to. Corresponds to the new
    /// name, if it was renamed; otherwise, it's just its original name.
    pub fn bound_name(self) -> Ident<'a> {
        match self {
            Self::Simple(path) => path.name(),
            Self::Renamed(renamed_item) => renamed_item.new_name(),
        }
    }
}

node! {
    /// A renamed import item: `a as d`
    RenamedImportItem
}

impl<'a> RenamedImportItem<'a> {
    /// The path to the imported item.
    pub fn path(self) -> ImportItemPath<'a> {
        self.0.cast_first_match().unwrap_or_default()
    }

    /// The original name of the imported item (`a` in `a as d` or `c.b.a as d`).
    pub fn original_name(self) -> Ident<'a> {
        self.path().name()
    }

    /// The new name of the imported item (`d` in `a as d`).
    pub fn new_name(self) -> Ident<'a> {
        self.0
            .children()
            .filter_map(SyntaxNode::cast)
            .last()
            .unwrap_or_default()
    }
}

node! {
    /// A module include: `include "chapter1.typ"`.
    ModuleInclude
}

impl<'a> ModuleInclude<'a> {
    /// The module or path from which the content should be included.
    pub fn source(self) -> Expr<'a> {
        self.0.cast_last_match().unwrap_or_default()
    }
}

node! {
    /// A break from a loop: `break`.
    LoopBreak
}

node! {
    /// A continue in a loop: `continue`.
    LoopContinue
}

node! {
    /// A return from a function: `return`, `return x + 1`.
    FuncReturn
}

impl<'a> FuncReturn<'a> {
    /// The expression to return.
    pub fn body(self) -> Option<Expr<'a>> {
        self.0.cast_last_match()
    }
}

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

    #[test]
    fn test_expr_default() {
        assert!(Expr::default().to_untyped().cast::<Expr>().is_some());
    }
}