wdl-ast 0.26.1

An abstract syntax tree for Workflow Description Language (WDL) documents
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
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
//! V1 AST representation for task definitions.

use rowan::NodeOrToken;
use wdl_grammar::SyntaxTokenExt;

use super::BoundDecl;
use super::Decl;
use super::Expr;
use super::LiteralBoolean;
use super::LiteralFloat;
use super::LiteralInteger;
use super::LiteralString;
use super::OpenHeredoc;
use super::Placeholder;
use super::StructDefinition;
use super::TaskKeyword;
use super::WorkflowDefinition;
use crate::AstNode;
use crate::AstToken;
use crate::Comment;
use crate::Documented;
use crate::Ident;
use crate::SyntaxKind;
use crate::SyntaxNode;
use crate::SyntaxToken;
use crate::TreeNode;
use crate::TreeToken;
use crate::v1::CommandKeyword;
use crate::v1::MetaKeyword;
use crate::v1::ParameterMetaKeyword;
use crate::v1::RequirementsKeyword;

pub mod common;
pub mod requirements;
pub mod runtime;

/// The set of all valid task fields and their descriptions for the implicit
/// `task` variable.
pub const TASK_FIELDS: &[(&str, &str)] = &[
    (TASK_FIELD_NAME, "The task name."),
    (
        TASK_FIELD_ID,
        "A String with the unique ID of the task. The execution engine may choose the format for \
         this ID, but it is suggested to include at least the following information:\nThe task \
         name\nThe task alias, if it differs from the task name\nThe index of the task instance, \
         if it is within a scatter statement",
    ),
    (
        TASK_FIELD_CONTAINER,
        "The URI String of the container in which the task is executing, or None if the task is \
         being executed in the host environment.",
    ),
    (
        TASK_FIELD_CPU,
        "The allocated number of cpus as a Float. Must be greater than 0.",
    ),
    (
        TASK_FIELD_MEMORY,
        "The allocated memory in bytes as an Int. Must be greater than 0.",
    ),
    (
        TASK_FIELD_GPU,
        "An Array[String] with one specification per allocated GPU. The specification is \
         execution engine-specific. If no GPUs were allocated, then the value must be an empty \
         array.",
    ),
    (
        TASK_FIELD_FPGA,
        "An Array[String] with one specification per allocated FPGA. The specification is \
         execution engine-specific. If no FPGAs were allocated, then the value must be an empty \
         array.",
    ),
    (
        TASK_FIELD_DISKS,
        "A Map[String, Int] with one entry for each disk mount point. The key is the mount point \
         and the value is the initial amount of disk space allocated, in bytes. The execution \
         engine must, at a minimum, provide one entry for each disk mount point requested, but \
         may provide more. The amount of disk space available for a given mount point may \
         increase during the lifetime of the task (e.g., autoscaling volumes provided by some \
         cloud services).",
    ),
    (
        TASK_FIELD_ATTEMPT,
        "The current task attempt. The value must be 0 the first time the task is executed, and \
         incremented by 1 each time the task is retried (if any).",
    ),
    (
        TASK_FIELD_PREVIOUS,
        "An Object containing the resource requirements from the previous task attempt. Available \
         in requirements, hints, runtime, output, and command sections. All constituent members \
         are optional and `None` on the first attempt.",
    ),
    (
        TASK_FIELD_END_TIME,
        "An Int? whose value is the time by which the task must be completed, as a Unix time \
         stamp. A value of 0 means that the execution engine does not impose a time limit. A \
         value of None means that the execution engine cannot determine whether the runtime of \
         the task is limited. A positive value is a guarantee that the task will be preempted at \
         the specified time, but is not a guarantee that the task won't be preempted earlier.",
    ),
    (
        TASK_FIELD_RETURN_CODE,
        "An Int? whose value is initially None and is set to the value of the command's return \
         code. The value is only guaranteed to be defined in the output section.",
    ),
    (
        TASK_FIELD_META,
        "An Object containing a copy of the task's meta section, or the empty Object if there is \
         no meta section or if it is empty.",
    ),
    (
        TASK_FIELD_PARAMETER_META,
        "An Object containing a copy of the task's parameter_meta section, or the empty Object if \
         there is no parameter_meta section or if it is empty.",
    ),
    (
        TASK_FIELD_EXT,
        "An Object containing execution engine-specific attributes, or the empty Object if there \
         aren't any. Members of ext should be considered optional. It is recommended to only \
         access a member of ext using string interpolation to avoid an error if it is not defined.",
    ),
];

/// The set of all valid runtime section keys and their descriptions.
pub const RUNTIME_KEYS: &[(&str, &str)] = &[
    (
        TASK_REQUIREMENT_CONTAINER,
        "Specifies the container image (e.g., Docker, Singularity) to use for the task.",
    ),
    (
        TASK_REQUIREMENT_CPU,
        "The number of CPU cores required for the task.",
    ),
    (
        TASK_REQUIREMENT_MEMORY,
        "The amount of memory required, specified as a string with units (e.g., '2 GiB').",
    ),
    (
        TASK_REQUIREMENT_DISKS,
        "Specifies the disk requirements for the task.",
    ),
    (TASK_REQUIREMENT_GPU, "Specifies GPU requirements."),
];

/// The set of all valid requirements section keys and their descriptions.
pub const REQUIREMENTS_KEY: &[(&str, &str)] = &[
    (
        TASK_REQUIREMENT_CONTAINER,
        "Specifies a list of allowed container images. Use `*` to allow any POSIX environment.",
    ),
    (
        TASK_REQUIREMENT_CPU,
        "The minimum number of CPU cores required.",
    ),
    (
        TASK_REQUIREMENT_MEMORY,
        "The minimum amount of memory required.",
    ),
    (TASK_REQUIREMENT_GPU, "The minimum GPU requirements."),
    (TASK_REQUIREMENT_FPGA, "The minimum FPGA requirements."),
    (TASK_REQUIREMENT_DISKS, "The minimum disk requirements."),
    (
        TASK_REQUIREMENT_MAX_RETRIES,
        "The maximum number of times the task can be retried.",
    ),
    (
        TASK_REQUIREMENT_RETURN_CODES,
        "A list of acceptable return codes from the command.",
    ),
];

/// The set of all valid task hints section keys and their descriptions.
pub const TASK_HINT_KEYS: &[(&str, &str)] = &[
    (
        TASK_HINT_DISKS,
        "A hint to the execution engine to mount disks with specific attributes. The value of \
         this hint can be a String with a specification that applies to all mount points, or a \
         Map with the key being the mount point and the value being a String with the \
         specification for that mount point.",
    ),
    (
        TASK_HINT_GPU,
        "A hint to the execution engine to provision hardware accelerators with specific \
         attributes. Accelerator specifications are left intentionally vague as they are \
         primarily intended to be used in the context of a specific compute environment.",
    ),
    (
        TASK_HINT_FPGA,
        "A hint to the execution engine to provision hardware accelerators with specific \
         attributes. Accelerator specifications are left intentionally vague as they are \
         primarily intended to be used in the context of a specific compute environment.",
    ),
    (
        TASK_HINT_INPUTS,
        "Provides input-specific hints. Each key must refer to a parameter defined in the task's \
         input section. A key may also used dotted notation to refer to a specific member of a \
         struct input.",
    ),
    (
        TASK_HINT_LOCALIZATION_OPTIONAL,
        "A hint to the execution engine about whether the File inputs for this task need to be \
         localized prior to executing the task. The value of this hint is a Boolean for which \
         true indicates that the contents of the File inputs may be streamed on demand.",
    ),
    (
        TASK_HINT_MAX_CPU,
        "A hint to the execution engine that the task expects to use no more than the specified \
         number of CPUs. The value of this hint has the same specification as requirements.cpu.",
    ),
    (
        TASK_HINT_MAX_MEMORY,
        "A hint to the execution engine that the task expects to use no more than the specified \
         amount of memory. The value of this hint has the same specification as \
         requirements.memory.",
    ),
    (
        TASK_HINT_OUTPUTS,
        "Provides output-specific hints. Each key must refer to a parameter defined in the task's \
         output section. A key may also use dotted notation to refer to a specific member of a \
         struct output.",
    ),
    (
        TASK_HINT_SHORT_TASK,
        "A hint to the execution engine about the expected duration of this task. The value of \
         this hint is a Boolean for which true indicates that that this task is not expected to \
         take long to execute, which the execution engine can interpret as permission to optimize \
         the execution of the task.",
    ),
    (
        TASK_HINT_CACHEABLE,
        "A hint to the execution engine that the task's execution result is cacheable. The value \
         of this hint is a Boolean for which true indicates that the execution result is \
         cacheable and false indicates it is not. The default value of the hint depends on the \
         engine's configuration.",
    ),
];

/// The name of the `name` task variable field.
pub const TASK_FIELD_NAME: &str = "name";
/// The name of the `id` task variable field.
pub const TASK_FIELD_ID: &str = "id";
/// The name of the `container` task variable field.
pub const TASK_FIELD_CONTAINER: &str = "container";
/// The name of the `cpu` task variable field.
pub const TASK_FIELD_CPU: &str = "cpu";
/// The name of the `memory` task variable field.
pub const TASK_FIELD_MEMORY: &str = "memory";
/// The name of the `attempt` task variable field.
pub const TASK_FIELD_ATTEMPT: &str = "attempt";
/// The name of the `previous` task variable field.
pub const TASK_FIELD_PREVIOUS: &str = "previous";
/// The name of the `gpu` task variable field.
pub const TASK_FIELD_GPU: &str = "gpu";
/// The name of the `fpga` task variable field.
pub const TASK_FIELD_FPGA: &str = "fpga";
/// The name of the `disks` task variable field.
pub const TASK_FIELD_DISKS: &str = "disks";
/// The name of the `end_time` task variable field.
pub const TASK_FIELD_END_TIME: &str = "end_time";
/// The name of the `return_code` task variable field.
pub const TASK_FIELD_RETURN_CODE: &str = "return_code";
/// The name of the `meta` task variable field.
pub const TASK_FIELD_META: &str = "meta";
/// The name of the `parameter_meta` task variable field.
pub const TASK_FIELD_PARAMETER_META: &str = "parameter_meta";
/// The name of the `ext` task variable field.
pub const TASK_FIELD_EXT: &str = "ext";
/// The name of the `max_retries` task variable field.
pub const TASK_FIELD_MAX_RETRIES: &str = "max_retries";

/// The name of the `container` task requirement.
pub const TASK_REQUIREMENT_CONTAINER: &str = "container";
/// The alias of the `container` task requirement (i.e. `docker`).
pub const TASK_REQUIREMENT_CONTAINER_ALIAS: &str = "docker";
/// The name of the `cpu` task requirement.
pub const TASK_REQUIREMENT_CPU: &str = "cpu";
/// The name of the `disks` task requirement.
pub const TASK_REQUIREMENT_DISKS: &str = "disks";
/// The name of the `gpu` task requirement.
pub const TASK_REQUIREMENT_GPU: &str = "gpu";
/// The name of the `fpga` task requirement.
pub const TASK_REQUIREMENT_FPGA: &str = "fpga";
/// The name of the `max_retries` task requirement.
pub const TASK_REQUIREMENT_MAX_RETRIES: &str = "max_retries";
/// The alias of the `max_retries` task requirement (i.e. `maxRetries``).
pub const TASK_REQUIREMENT_MAX_RETRIES_ALIAS: &str = "maxRetries";
/// The name of the `memory` task requirement.
pub const TASK_REQUIREMENT_MEMORY: &str = "memory";
/// The name of the `return_codes` task requirement.
pub const TASK_REQUIREMENT_RETURN_CODES: &str = "return_codes";
/// The alias of the `return_codes` task requirement (i.e. `returnCodes`).
pub const TASK_REQUIREMENT_RETURN_CODES_ALIAS: &str = "returnCodes";

/// The name of the `disks` task hint.
pub const TASK_HINT_DISKS: &str = "disks";
/// The name of the `gpu` task hint.
pub const TASK_HINT_GPU: &str = "gpu";
/// The name of the `fpga` task hint.
pub const TASK_HINT_FPGA: &str = "fpga";
/// The name of the `inputs` task hint.
pub const TASK_HINT_INPUTS: &str = "inputs";
/// The name of the `localization_optional` task hint.
pub const TASK_HINT_LOCALIZATION_OPTIONAL: &str = "localization_optional";
/// The alias of the `localization_optional` task hint (i.e.
/// `localizationOptional`).
pub const TASK_HINT_LOCALIZATION_OPTIONAL_ALIAS: &str = "localizationOptional";
/// The name of the `max_cpu` task hint.
pub const TASK_HINT_MAX_CPU: &str = "max_cpu";
/// The alias of the `max_cpu` task hint (i.e. `maxCpu`).
pub const TASK_HINT_MAX_CPU_ALIAS: &str = "maxCpu";
/// The name of the `max_memory` task hint.
pub const TASK_HINT_MAX_MEMORY: &str = "max_memory";
/// The alias of the `max_memory` task hin (e.g. `maxMemory`).
pub const TASK_HINT_MAX_MEMORY_ALIAS: &str = "maxMemory";
/// The name of the `outputs` task hint.
pub const TASK_HINT_OUTPUTS: &str = "outputs";
/// The name of the `short_task` task hint.
pub const TASK_HINT_SHORT_TASK: &str = "short_task";
/// The alias of the `short_task` task hint (e.g. `shortTask`).
pub const TASK_HINT_SHORT_TASK_ALIAS: &str = "shortTask";
/// The name of the `cacheable` task hint.
pub const TASK_HINT_CACHEABLE: &str = "cacheable";

/// Unescapes command text.
fn unescape_command_text(s: &str, heredoc: bool, buffer: &mut String) {
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '\\' => match chars.peek() {
                Some('\\') | Some('~') => {
                    buffer.push(chars.next().unwrap());
                }
                Some('>') if heredoc => {
                    buffer.push(chars.next().unwrap());
                }
                Some('$') | Some('}') if !heredoc => {
                    buffer.push(chars.next().unwrap());
                }
                _ => {
                    buffer.push('\\');
                }
            },
            _ => {
                buffer.push(c);
            }
        }
    }
}

/// Represents a task definition.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TaskDefinition<N: TreeNode = SyntaxNode>(N);

impl<N: TreeNode> TaskDefinition<N> {
    /// Gets the name of the task.
    pub fn name(&self) -> Ident<N::Token> {
        self.token().expect("task should have a name")
    }

    /// Gets the `task` keyword of the task definition.
    pub fn keyword(&self) -> TaskKeyword<N::Token> {
        self.token().expect("task should have a keyword")
    }

    /// Gets the items of the task.
    pub fn items(&self) -> impl Iterator<Item = TaskItem<N>> + use<'_, N> {
        TaskItem::children(&self.0)
    }

    /// Gets the input section of the task.
    pub fn input(&self) -> Option<InputSection<N>> {
        self.child()
    }

    /// Gets the output section of the task.
    pub fn output(&self) -> Option<OutputSection<N>> {
        self.child()
    }

    /// Gets the command section of the task.
    pub fn command(&self) -> Option<CommandSection<N>> {
        self.child()
    }

    /// Gets the requirements sections of the task.
    pub fn requirements(&self) -> Option<RequirementsSection<N>> {
        self.child()
    }

    /// Gets the hints section of the task.
    pub fn hints(&self) -> Option<TaskHintsSection<N>> {
        self.child()
    }

    /// Gets the runtime section of the task.
    pub fn runtime(&self) -> Option<RuntimeSection<N>> {
        self.child()
    }

    /// Gets the metadata section of the task.
    pub fn metadata(&self) -> Option<MetadataSection<N>> {
        self.child()
    }

    /// Gets the parameter section of the task.
    pub fn parameter_metadata(&self) -> Option<ParameterMetadataSection<N>> {
        self.child()
    }

    /// Gets the private declarations of the task.
    pub fn declarations(&self) -> impl Iterator<Item = BoundDecl<N>> + use<'_, N> {
        self.children()
    }
}

impl<N: TreeNode> AstNode<N> for TaskDefinition<N> {
    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::TaskDefinitionNode
    }

    fn cast(inner: N) -> Option<Self> {
        match inner.kind() {
            SyntaxKind::TaskDefinitionNode => Some(Self(inner)),
            _ => None,
        }
    }

    fn inner(&self) -> &N {
        &self.0
    }
}

impl Documented<SyntaxNode> for TaskDefinition<SyntaxNode> {
    fn doc_comments(&self) -> Option<Vec<Comment<<SyntaxNode as TreeNode>::Token>>> {
        Some(crate::doc_comments::<SyntaxNode>(self.keyword().inner().preceding_trivia()).collect())
    }
}

/// Represents an item in a task definition.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TaskItem<N: TreeNode = SyntaxNode> {
    /// The item is an input section.
    Input(InputSection<N>),
    /// The item is an output section.
    Output(OutputSection<N>),
    /// The item is a command section.
    Command(CommandSection<N>),
    /// The item is a requirements section.
    Requirements(RequirementsSection<N>),
    /// The item is a task hints section.
    Hints(TaskHintsSection<N>),
    /// The item is a runtime section.
    Runtime(RuntimeSection<N>),
    /// The item is a metadata section.
    Metadata(MetadataSection<N>),
    /// The item is a parameter meta section.
    ParameterMetadata(ParameterMetadataSection<N>),
    /// The item is a private bound declaration.
    Declaration(BoundDecl<N>),
}

impl<N: TreeNode> TaskItem<N> {
    /// Returns whether or not the given syntax kind can be cast to
    /// [`TaskItem`].
    pub fn can_cast(kind: SyntaxKind) -> bool {
        matches!(
            kind,
            SyntaxKind::InputSectionNode
                | SyntaxKind::OutputSectionNode
                | SyntaxKind::CommandSectionNode
                | SyntaxKind::RequirementsSectionNode
                | SyntaxKind::TaskHintsSectionNode
                | SyntaxKind::RuntimeSectionNode
                | SyntaxKind::MetadataSectionNode
                | SyntaxKind::ParameterMetadataSectionNode
                | SyntaxKind::BoundDeclNode
        )
    }

    /// Casts the given node to [`TaskItem`].
    ///
    /// Returns `None` if the node cannot be cast.
    pub fn cast(inner: N) -> Option<Self> {
        match inner.kind() {
            SyntaxKind::InputSectionNode => Some(Self::Input(
                InputSection::cast(inner).expect("input section to cast"),
            )),
            SyntaxKind::OutputSectionNode => Some(Self::Output(
                OutputSection::cast(inner).expect("output section to cast"),
            )),
            SyntaxKind::CommandSectionNode => Some(Self::Command(
                CommandSection::cast(inner).expect("command section to cast"),
            )),
            SyntaxKind::RequirementsSectionNode => Some(Self::Requirements(
                RequirementsSection::cast(inner).expect("requirements section to cast"),
            )),
            SyntaxKind::RuntimeSectionNode => Some(Self::Runtime(
                RuntimeSection::cast(inner).expect("runtime section to cast"),
            )),
            SyntaxKind::MetadataSectionNode => Some(Self::Metadata(
                MetadataSection::cast(inner).expect("metadata section to cast"),
            )),
            SyntaxKind::ParameterMetadataSectionNode => Some(Self::ParameterMetadata(
                ParameterMetadataSection::cast(inner).expect("parameter metadata section to cast"),
            )),
            SyntaxKind::TaskHintsSectionNode => Some(Self::Hints(
                TaskHintsSection::cast(inner).expect("task hints section to cast"),
            )),
            SyntaxKind::BoundDeclNode => Some(Self::Declaration(
                BoundDecl::cast(inner).expect("bound decl to cast"),
            )),
            _ => None,
        }
    }

    /// Gets a reference to the inner node.
    pub fn inner(&self) -> &N {
        match self {
            Self::Input(element) => element.inner(),
            Self::Output(element) => element.inner(),
            Self::Command(element) => element.inner(),
            Self::Requirements(element) => element.inner(),
            Self::Hints(element) => element.inner(),
            Self::Runtime(element) => element.inner(),
            Self::Metadata(element) => element.inner(),
            Self::ParameterMetadata(element) => element.inner(),
            Self::Declaration(element) => element.inner(),
        }
    }

    /// Attempts to get a reference to the inner [`InputSection`].
    ///
    /// * If `self` is a [`TaskItem::Input`], then a reference to the inner
    ///   [`InputSection`] is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn as_input_section(&self) -> Option<&InputSection<N>> {
        match self {
            Self::Input(s) => Some(s),
            _ => None,
        }
    }

    /// Consumes `self` and attempts to return the inner [`InputSection`].
    ///
    /// * If `self` is a [`TaskItem::Input`], then the inner [`InputSection`] is
    ///   returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn into_input_section(self) -> Option<InputSection<N>> {
        match self {
            Self::Input(s) => Some(s),
            _ => None,
        }
    }

    /// Attempts to get a reference to the inner [`OutputSection`].
    ///
    /// * If `self` is a [`TaskItem::Output`], then a reference to the inner
    ///   [`OutputSection`] is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn as_output_section(&self) -> Option<&OutputSection<N>> {
        match self {
            Self::Output(s) => Some(s),
            _ => None,
        }
    }

    /// Consumes `self` and attempts to return the inner [`OutputSection`].
    ///
    /// * If `self` is a [`TaskItem::Output`], then the inner [`OutputSection`]
    ///   is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn into_output_section(self) -> Option<OutputSection<N>> {
        match self {
            Self::Output(s) => Some(s),
            _ => None,
        }
    }

    /// Attempts to get a reference to the inner [`CommandSection`].
    ///
    /// * If `self` is a [`TaskItem::Command`], then a reference to the inner
    ///   [`CommandSection`] is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn as_command_section(&self) -> Option<&CommandSection<N>> {
        match self {
            Self::Command(s) => Some(s),
            _ => None,
        }
    }

    /// Consumes `self` and attempts to return the inner [`CommandSection`].
    ///
    /// * If `self` is a [`TaskItem::Command`], then the inner
    ///   [`CommandSection`] is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn into_command_section(self) -> Option<CommandSection<N>> {
        match self {
            Self::Command(s) => Some(s),
            _ => None,
        }
    }

    /// Attempts to get a reference to the inner [`RequirementsSection`].
    ///
    /// * If `self` is a [`TaskItem::Requirements`], then a reference to the
    ///   inner [`RequirementsSection`] is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn as_requirements_section(&self) -> Option<&RequirementsSection<N>> {
        match self {
            Self::Requirements(s) => Some(s),
            _ => None,
        }
    }

    /// Consumes `self` and attempts to return the inner
    /// [`RequirementsSection`].
    ///
    /// * If `self` is a [`TaskItem::Requirements`], then the inner
    ///   [`RequirementsSection`] is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn into_requirements_section(self) -> Option<RequirementsSection<N>> {
        match self {
            Self::Requirements(s) => Some(s),
            _ => None,
        }
    }

    /// Attempts to get a reference to the inner [`TaskHintsSection`].
    ///
    /// * If `self` is a [`TaskItem::Hints`], then a reference to the inner
    ///   [`TaskHintsSection`] is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn as_hints_section(&self) -> Option<&TaskHintsSection<N>> {
        match self {
            Self::Hints(s) => Some(s),
            _ => None,
        }
    }

    /// Consumes `self` and attempts to return the inner [`TaskHintsSection`].
    ///
    /// * If `self` is a [`TaskItem::Hints`], then the inner
    ///   [`TaskHintsSection`] is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn into_hints_section(self) -> Option<TaskHintsSection<N>> {
        match self {
            Self::Hints(s) => Some(s),
            _ => None,
        }
    }

    /// Attempts to get a reference to the inner [`RuntimeSection`].
    ///
    /// * If `self` is a [`TaskItem::Runtime`], then a reference to the inner
    ///   [`RuntimeSection`] is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn as_runtime_section(&self) -> Option<&RuntimeSection<N>> {
        match self {
            Self::Runtime(s) => Some(s),
            _ => None,
        }
    }

    /// Consumes `self` and attempts to return the inner [`RuntimeSection`].
    ///
    /// * If `self` is a [`TaskItem::Runtime`], then the inner
    ///   [`RuntimeSection`] is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn into_runtime_section(self) -> Option<RuntimeSection<N>> {
        match self {
            Self::Runtime(s) => Some(s),
            _ => None,
        }
    }

    /// Attempts to get a reference to the inner [`MetadataSection`].
    ///
    /// * If `self` is a [`TaskItem::Metadata`], then a reference to the inner
    ///   [`MetadataSection`] is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn as_metadata_section(&self) -> Option<&MetadataSection<N>> {
        match self {
            Self::Metadata(s) => Some(s),
            _ => None,
        }
    }

    /// Consumes `self` and attempts to return the inner [`MetadataSection`].
    ///
    /// * If `self` is a [`TaskItem::Metadata`], then the inner
    ///   [`MetadataSection`] is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn into_metadata_section(self) -> Option<MetadataSection<N>> {
        match self {
            Self::Metadata(s) => Some(s),
            _ => None,
        }
    }

    /// Attempts to get a reference to the inner [`ParameterMetadataSection`].
    ///
    /// * If `self` is a [`TaskItem::ParameterMetadata`], then a reference to
    ///   the inner [`ParameterMetadataSection`] is returned wrapped in
    ///   [`Some`].
    /// * Else, [`None`] is returned.
    pub fn as_parameter_metadata_section(&self) -> Option<&ParameterMetadataSection<N>> {
        match self {
            Self::ParameterMetadata(s) => Some(s),
            _ => None,
        }
    }

    /// Consumes `self` and attempts to return the inner
    /// [`ParameterMetadataSection`].
    ///
    /// * If `self` is a [`TaskItem::ParameterMetadata`], then the inner
    ///   [`ParameterMetadataSection`] is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn into_parameter_metadata_section(self) -> Option<ParameterMetadataSection<N>> {
        match self {
            Self::ParameterMetadata(s) => Some(s),
            _ => None,
        }
    }

    /// Attempts to get a reference to the inner [`BoundDecl`].
    ///
    /// * If `self` is a [`TaskItem::Declaration`], then a reference to the
    ///   inner [`BoundDecl`] is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn as_declaration(&self) -> Option<&BoundDecl<N>> {
        match self {
            Self::Declaration(d) => Some(d),
            _ => None,
        }
    }

    /// Consumes `self` and attempts to return the inner [`BoundDecl`].
    ///
    /// * If `self` is a [`TaskItem::Declaration`], then the inner [`BoundDecl`]
    ///   is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn into_declaration(self) -> Option<BoundDecl<N>> {
        match self {
            Self::Declaration(d) => Some(d),
            _ => None,
        }
    }

    /// Finds the first child that can be cast to a [`TaskItem`].
    pub fn child(node: &N) -> Option<Self> {
        node.children().find_map(Self::cast)
    }

    /// Finds all children that can be cast to a [`TaskItem`].
    pub fn children(node: &N) -> impl Iterator<Item = Self> + use<'_, N> {
        node.children().filter_map(Self::cast)
    }
}

/// Represents the parent of a section.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SectionParent<N: TreeNode = SyntaxNode> {
    /// The parent is a task.
    Task(TaskDefinition<N>),
    /// The parent is a workflow.
    Workflow(WorkflowDefinition<N>),
    /// The parent is a struct.
    Struct(StructDefinition<N>),
}

impl<N: TreeNode> SectionParent<N> {
    /// Returns whether or not the given syntax kind can be cast to
    /// [`SectionParent`].
    pub fn can_cast(kind: SyntaxKind) -> bool {
        matches!(
            kind,
            SyntaxKind::TaskDefinitionNode
                | SyntaxKind::WorkflowDefinitionNode
                | SyntaxKind::StructDefinitionNode
        )
    }

    /// Casts the given node to [`SectionParent`].
    ///
    /// Returns `None` if the node cannot be cast.
    pub fn cast(inner: N) -> Option<Self> {
        match inner.kind() {
            SyntaxKind::TaskDefinitionNode => Some(Self::Task(
                TaskDefinition::cast(inner).expect("task definition to cast"),
            )),
            SyntaxKind::WorkflowDefinitionNode => Some(Self::Workflow(
                WorkflowDefinition::cast(inner).expect("workflow definition to cast"),
            )),
            SyntaxKind::StructDefinitionNode => Some(Self::Struct(
                StructDefinition::cast(inner).expect("struct definition to cast"),
            )),
            _ => None,
        }
    }

    /// Gets a reference to the inner node.
    pub fn inner(&self) -> &N {
        match self {
            Self::Task(element) => element.inner(),
            Self::Workflow(element) => element.inner(),
            Self::Struct(element) => element.inner(),
        }
    }

    /// Gets the name of the section parent.
    pub fn name(&self) -> Ident<N::Token> {
        match self {
            Self::Task(t) => t.name(),
            Self::Workflow(w) => w.name(),
            Self::Struct(s) => s.name(),
        }
    }

    /// Attempts to get a reference to the inner [`TaskDefinition`].
    ///
    /// * If `self` is a [`SectionParent::Task`], then a reference to the inner
    ///   [`TaskDefinition`] is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn as_task(&self) -> Option<&TaskDefinition<N>> {
        match self {
            Self::Task(task) => Some(task),
            _ => None,
        }
    }

    /// Consumes `self` and attempts to return the inner [`TaskDefinition`].
    ///
    /// * If `self` is a [`SectionParent::Task`], then the inner
    ///   [`TaskDefinition`] is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn into_task(self) -> Option<TaskDefinition<N>> {
        match self {
            Self::Task(task) => Some(task),
            _ => None,
        }
    }

    /// Unwraps to a task definition.
    ///
    /// # Panics
    ///
    /// Panics if it is not a task definition.
    pub fn unwrap_task(self) -> TaskDefinition<N> {
        match self {
            Self::Task(task) => task,
            _ => panic!("not a task definition"),
        }
    }

    /// Attempts to get a reference to the inner [`WorkflowDefinition`].
    ///
    /// * If `self` is a [`SectionParent::Workflow`], then a reference to the
    ///   inner [`WorkflowDefinition`] is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn as_workflow(&self) -> Option<&WorkflowDefinition<N>> {
        match self {
            Self::Workflow(workflow) => Some(workflow),
            _ => None,
        }
    }

    /// Consumes `self` and attempts to return the inner [`WorkflowDefinition`].
    ///
    /// * If `self` is a [`SectionParent::Workflow`], then the inner
    ///   [`WorkflowDefinition`] is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn into_workflow(self) -> Option<WorkflowDefinition<N>> {
        match self {
            Self::Workflow(workflow) => Some(workflow),
            _ => None,
        }
    }

    /// Unwraps to a workflow definition.
    ///
    /// # Panics
    ///
    /// Panics if it is not a workflow definition.
    pub fn unwrap_workflow(self) -> WorkflowDefinition<N> {
        match self {
            Self::Workflow(workflow) => workflow,
            _ => panic!("not a workflow definition"),
        }
    }

    /// Attempts to get a reference to the inner [`StructDefinition`].
    ///
    /// * If `self` is a [`SectionParent::Struct`], then a reference to the
    ///   inner [`StructDefinition`] is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn as_struct(&self) -> Option<&StructDefinition<N>> {
        match self {
            Self::Struct(r#struct) => Some(r#struct),
            _ => None,
        }
    }

    /// Consumes `self` and attempts to return the inner [`StructDefinition`].
    ///
    /// * If `self` is a [`SectionParent::Struct`], then the inner
    ///   [`StructDefinition`] is returned wrapped in [`Some`].
    /// * Else, [`None`] is returned.
    pub fn into_struct(self) -> Option<StructDefinition<N>> {
        match self {
            Self::Struct(r#struct) => Some(r#struct),
            _ => None,
        }
    }

    /// Unwraps to a struct definition.
    ///
    /// # Panics
    ///
    /// Panics if it is not a struct definition.
    pub fn unwrap_struct(self) -> StructDefinition<N> {
        match self {
            Self::Struct(def) => def,
            _ => panic!("not a struct definition"),
        }
    }

    /// Finds the first child that can be cast to a [`SectionParent`].
    pub fn child(node: &N) -> Option<Self> {
        node.children().find_map(Self::cast)
    }

    /// Finds all children that can be cast to a [`SectionParent`].
    pub fn children(node: &N) -> impl Iterator<Item = Self> + use<'_, N> {
        node.children().filter_map(Self::cast)
    }
}

/// Represents an input section in a task or workflow definition.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InputSection<N: TreeNode = SyntaxNode>(N);

impl<N: TreeNode> InputSection<N> {
    /// Gets the declarations of the input section.
    pub fn declarations(&self) -> impl Iterator<Item = Decl<N>> + use<'_, N> {
        Decl::children(&self.0)
    }

    /// Gets the parent of the input section.
    pub fn parent(&self) -> SectionParent<N> {
        SectionParent::cast(self.0.parent().expect("should have a parent"))
            .expect("parent should cast")
    }
}

impl<N: TreeNode> AstNode<N> for InputSection<N> {
    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::InputSectionNode
    }

    fn cast(inner: N) -> Option<Self> {
        match inner.kind() {
            SyntaxKind::InputSectionNode => Some(Self(inner)),
            _ => None,
        }
    }

    fn inner(&self) -> &N {
        &self.0
    }
}

/// Represents an output section in a task or workflow definition.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OutputSection<N: TreeNode = SyntaxNode>(N);

impl<N: TreeNode> OutputSection<N> {
    /// Gets the declarations of the output section.
    pub fn declarations(&self) -> impl Iterator<Item = BoundDecl<N>> + use<'_, N> {
        self.children()
    }

    /// Gets the parent of the output section.
    pub fn parent(&self) -> SectionParent<N> {
        SectionParent::cast(self.0.parent().expect("should have a parent"))
            .expect("parent should cast")
    }
}

impl<N: TreeNode> AstNode<N> for OutputSection<N> {
    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::OutputSectionNode
    }

    fn cast(inner: N) -> Option<Self> {
        match inner.kind() {
            SyntaxKind::OutputSectionNode => Some(Self(inner)),
            _ => None,
        }
    }

    fn inner(&self) -> &N {
        &self.0
    }
}

/// A command part stripped of leading whitespace.
///
/// Placeholders are not changed and are copied as is.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum StrippedCommandPart<N: TreeNode = SyntaxNode> {
    /// A text part.
    Text(String),
    /// A placeholder part.
    Placeholder(Placeholder<N>),
}

/// Represents a command section in a task definition.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CommandSection<N: TreeNode = SyntaxNode>(N);

impl<N: TreeNode> CommandSection<N> {
    /// Gets whether or not the command section is a heredoc command.
    pub fn is_heredoc(&self) -> bool {
        self.token::<OpenHeredoc<N::Token>>().is_some()
    }

    /// Gets the parts of the command.
    pub fn parts(&self) -> impl Iterator<Item = CommandPart<N>> + use<'_, N> {
        self.0.children_with_tokens().filter_map(CommandPart::cast)
    }

    /// Counts the leading whitespace of the command.
    ///
    /// If the command has mixed indentation, this will return None.
    pub fn count_whitespace(&self) -> Option<usize> {
        let mut min_leading_spaces = usize::MAX;
        let mut min_leading_tabs = usize::MAX;
        let mut parsing_leading_whitespace = false; // init to false so that the first line is skipped

        let mut leading_spaces = 0;
        let mut leading_tabs = 0;
        for part in self.parts() {
            match part {
                CommandPart::Text(text) => {
                    for c in text.text().chars() {
                        match c {
                            ' ' if parsing_leading_whitespace => {
                                leading_spaces += 1;
                            }
                            '\t' if parsing_leading_whitespace => {
                                leading_tabs += 1;
                            }
                            '\n' => {
                                parsing_leading_whitespace = true;
                                leading_spaces = 0;
                                leading_tabs = 0;
                            }
                            '\r' => {}
                            _ => {
                                if parsing_leading_whitespace {
                                    parsing_leading_whitespace = false;
                                    if leading_spaces == 0 && leading_tabs == 0 {
                                        min_leading_spaces = 0;
                                        min_leading_tabs = 0;
                                        continue;
                                    }
                                    if leading_spaces < min_leading_spaces && leading_spaces > 0 {
                                        min_leading_spaces = leading_spaces;
                                    }
                                    if leading_tabs < min_leading_tabs && leading_tabs > 0 {
                                        min_leading_tabs = leading_tabs;
                                    }
                                }
                            }
                        }
                    }
                    // The last line is intentionally skipped.
                }
                CommandPart::Placeholder(_) => {
                    if parsing_leading_whitespace {
                        parsing_leading_whitespace = false;
                        if leading_spaces == 0 && leading_tabs == 0 {
                            min_leading_spaces = 0;
                            min_leading_tabs = 0;
                            continue;
                        }
                        if leading_spaces < min_leading_spaces && leading_spaces > 0 {
                            min_leading_spaces = leading_spaces;
                        }
                        if leading_tabs < min_leading_tabs && leading_tabs > 0 {
                            min_leading_tabs = leading_tabs;
                        }
                    }
                }
            }
        }

        // Check for no indentation or all whitespace, in which case we're done
        if (min_leading_spaces == 0 && min_leading_tabs == 0)
            || (min_leading_spaces == usize::MAX && min_leading_tabs == usize::MAX)
        {
            return Some(0);
        }

        // Check for mixed indentation
        if (min_leading_spaces > 0 && min_leading_spaces != usize::MAX)
            && (min_leading_tabs > 0 && min_leading_tabs != usize::MAX)
        {
            return None;
        }

        // Exactly one of the two will be equal to usize::MAX because it never appeared.
        // The other will be the number of leading spaces or tabs to strip.
        let final_leading_whitespace = if min_leading_spaces < min_leading_tabs {
            min_leading_spaces
        } else {
            min_leading_tabs
        };

        Some(final_leading_whitespace)
    }

    /// Strips leading whitespace from the command.
    ///
    /// If the command has mixed indentation, this will return `None`.
    pub fn strip_whitespace(&self) -> Option<Vec<StrippedCommandPart<N>>> {
        let mut result = Vec::new();
        let heredoc = self.is_heredoc();
        for part in self.parts() {
            match part {
                CommandPart::Text(text) => {
                    let mut s = String::new();
                    unescape_command_text(text.text(), heredoc, &mut s);
                    result.push(StrippedCommandPart::Text(s));
                }
                CommandPart::Placeholder(p) => {
                    result.push(StrippedCommandPart::Placeholder(p));
                }
            }
        }

        // Trim the first line
        let mut whole_first_line_trimmed = false;
        if let Some(StrippedCommandPart::Text(text)) = result.first_mut() {
            let end_of_first_line = text.find('\n').map(|p| p + 1).unwrap_or(text.len());
            let line = &text[..end_of_first_line];
            let len = line.len() - line.trim_start().len();
            whole_first_line_trimmed = len == line.len();
            text.replace_range(..len, "");
        }

        // Trim the last line
        if let Some(StrippedCommandPart::Text(text)) = result.last_mut() {
            if let Some(index) = text.rfind(|c| !matches!(c, ' ' | '\t')) {
                text.truncate(index + 1);
            } else {
                text.clear();
            }

            if text.ends_with('\n') {
                text.pop();
            }

            if text.ends_with('\r') {
                text.pop();
            }
        }

        // Return immediately if command contains mixed indentation
        let num_stripped_chars = self.count_whitespace()?;

        // If there is no leading whitespace, we're done
        if num_stripped_chars == 0 {
            return Some(result);
        }

        // Finally, strip the leading whitespace on each line
        // This is done in place using the `replace_range` method; the method will
        // internally do moves without allocations
        let mut strip_leading_whitespace = whole_first_line_trimmed;
        for part in &mut result {
            match part {
                StrippedCommandPart::Text(text) => {
                    let mut offset = 0;
                    while let Some(next) = text[offset..].find('\n') {
                        let next = next + offset;
                        if offset > 0 {
                            strip_leading_whitespace = true;
                        }

                        if !strip_leading_whitespace {
                            offset = next + 1;
                            continue;
                        }

                        let line = &text[offset..next];
                        let line = line.strip_suffix('\r').unwrap_or(line);
                        let len = line.len().min(num_stripped_chars);
                        text.replace_range(offset..offset + len, "");
                        offset = next + 1 - len;
                    }

                    // Replace any remaining text
                    if strip_leading_whitespace || offset > 0 {
                        let line = &text[offset..];
                        let line = line.strip_suffix('\r').unwrap_or(line);
                        let len = line.len().min(num_stripped_chars);
                        text.replace_range(offset..offset + len, "");
                    }
                }
                StrippedCommandPart::Placeholder(_) => {
                    strip_leading_whitespace = false;
                }
            }
        }

        Some(result)
    }

    /// Gets the parent of the command section.
    pub fn parent(&self) -> SectionParent<N> {
        SectionParent::cast(self.0.parent().expect("should have a parent"))
            .expect("parent should cast")
    }

    /// Gets the `command` keyword.
    pub fn keyword(&self) -> CommandKeyword<N::Token> {
        self.token()
            .expect("CommandSection must have CommandKeyword")
    }
}

impl<N: TreeNode> AstNode<N> for CommandSection<N> {
    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::CommandSectionNode
    }

    fn cast(inner: N) -> Option<Self> {
        match inner.kind() {
            SyntaxKind::CommandSectionNode => Some(Self(inner)),
            _ => None,
        }
    }

    fn inner(&self) -> &N {
        &self.0
    }
}

/// Represents a textual part of a command.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CommandText<T: TreeToken = SyntaxToken>(T);

impl<T: TreeToken> CommandText<T> {
    /// Unescapes the command text to the given buffer.
    ///
    /// When `heredoc` is true, only heredoc escape sequences are allowed.
    ///
    /// Otherwise, brace command sequences are accepted.
    pub fn unescape_to(&self, heredoc: bool, buffer: &mut String) {
        unescape_command_text(self.text(), heredoc, buffer);
    }
}

impl<T: TreeToken> AstToken<T> for CommandText<T> {
    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::LiteralCommandText
    }

    fn cast(inner: T) -> Option<Self> {
        match inner.kind() {
            SyntaxKind::LiteralCommandText => Some(Self(inner)),
            _ => None,
        }
    }

    fn inner(&self) -> &T {
        &self.0
    }
}

/// Represents a part of a command.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CommandPart<N: TreeNode = SyntaxNode> {
    /// A textual part of the command.
    Text(CommandText<N::Token>),
    /// A placeholder encountered in the command.
    Placeholder(Placeholder<N>),
}

impl<N: TreeNode> CommandPart<N> {
    /// Unwraps the command part into text.
    ///
    /// # Panics
    ///
    /// Panics if the command part is not text.
    pub fn unwrap_text(self) -> CommandText<N::Token> {
        match self {
            Self::Text(text) => text,
            _ => panic!("not string text"),
        }
    }

    /// Unwraps the command part into a placeholder.
    ///
    /// # Panics
    ///
    /// Panics if the command part is not a placeholder.
    pub fn unwrap_placeholder(self) -> Placeholder<N> {
        match self {
            Self::Placeholder(p) => p,
            _ => panic!("not a placeholder"),
        }
    }

    /// Casts the given [`NodeOrToken`] to [`CommandPart`].
    ///
    /// Returns `None` if it cannot case cannot be cast.
    fn cast(element: NodeOrToken<N, N::Token>) -> Option<Self> {
        match element {
            NodeOrToken::Node(n) => Some(Self::Placeholder(Placeholder::cast(n)?)),
            NodeOrToken::Token(t) => Some(Self::Text(CommandText::cast(t)?)),
        }
    }
}

/// Represents a requirements section in a task definition.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RequirementsSection<N: TreeNode = SyntaxNode>(N);

impl<N: TreeNode> RequirementsSection<N> {
    /// Gets the items in the requirements section.
    pub fn items(&self) -> impl Iterator<Item = RequirementsItem<N>> + use<'_, N> {
        self.children()
    }

    /// Gets the parent of the requirements section.
    pub fn parent(&self) -> SectionParent<N> {
        SectionParent::cast(self.0.parent().expect("should have a parent"))
            .expect("parent should cast")
    }

    /// Gets the `container` item as a
    /// [`Container`](requirements::item::Container) (if it exists).
    pub fn container(&self) -> Option<requirements::item::Container<N>> {
        // NOTE: validation should ensure that, at most, one `container` item exists in
        // the `requirements` section.
        self.child()
    }

    /// Gets the `requirements` keyword.
    pub fn keyword(&self) -> RequirementsKeyword<N::Token> {
        self.token()
            .expect("RequirementsSection must have RequirementsKeyword")
    }
}

impl<N: TreeNode> AstNode<N> for RequirementsSection<N> {
    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::RequirementsSectionNode
    }

    fn cast(inner: N) -> Option<Self> {
        match inner.kind() {
            SyntaxKind::RequirementsSectionNode => Some(Self(inner)),
            _ => None,
        }
    }

    fn inner(&self) -> &N {
        &self.0
    }
}

/// Represents an item in a requirements section.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RequirementsItem<N: TreeNode = SyntaxNode>(N);

impl<N: TreeNode> RequirementsItem<N> {
    /// Gets the name of the requirements item.
    pub fn name(&self) -> Ident<N::Token> {
        self.token().expect("expected an item name")
    }

    /// Gets the expression of the requirements item.
    pub fn expr(&self) -> Expr<N> {
        Expr::child(&self.0).expect("expected an item expression")
    }

    /// Consumes `self` and attempts to cast the requirements item to a
    /// [`Container`](requirements::item::Container).
    pub fn into_container(self) -> Option<requirements::item::Container<N>> {
        requirements::item::Container::try_from(self).ok()
    }
}

impl<N: TreeNode> AstNode<N> for RequirementsItem<N> {
    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::RequirementsItemNode
    }

    fn cast(inner: N) -> Option<Self> {
        match inner.kind() {
            SyntaxKind::RequirementsItemNode => Some(Self(inner)),
            _ => None,
        }
    }

    fn inner(&self) -> &N {
        &self.0
    }
}

/// Represents a hints section in a task definition.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TaskHintsSection<N: TreeNode = SyntaxNode>(N);

impl<N: TreeNode> TaskHintsSection<N> {
    /// Gets the items in the hints section.
    pub fn items(&self) -> impl Iterator<Item = TaskHintsItem<N>> + use<'_, N> {
        self.children()
    }

    /// Gets the parent of the hints section.
    pub fn parent(&self) -> TaskDefinition<N> {
        TaskDefinition::cast(self.0.parent().expect("should have a parent"))
            .expect("parent should cast")
    }
}

impl<N: TreeNode> AstNode<N> for TaskHintsSection<N> {
    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::TaskHintsSectionNode
    }

    fn cast(inner: N) -> Option<Self> {
        match inner.kind() {
            SyntaxKind::TaskHintsSectionNode => Some(Self(inner)),
            _ => None,
        }
    }

    fn inner(&self) -> &N {
        &self.0
    }
}

/// Represents an item in a task hints section.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TaskHintsItem<N: TreeNode = SyntaxNode>(N);

impl<N: TreeNode> TaskHintsItem<N> {
    /// Gets the name of the hints item.
    pub fn name(&self) -> Ident<N::Token> {
        self.token().expect("expected an item name")
    }

    /// Gets the expression of the hints item.
    pub fn expr(&self) -> Expr<N> {
        Expr::child(&self.0).expect("expected an item expression")
    }
}

impl<N: TreeNode> AstNode<N> for TaskHintsItem<N> {
    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::TaskHintsItemNode
    }

    fn cast(inner: N) -> Option<Self> {
        match inner.kind() {
            SyntaxKind::TaskHintsItemNode => Some(Self(inner)),
            _ => None,
        }
    }

    fn inner(&self) -> &N {
        &self.0
    }
}

/// Represents a runtime section in a task definition.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RuntimeSection<N: TreeNode = SyntaxNode>(N);

impl<N: TreeNode> RuntimeSection<N> {
    /// Gets the items in the runtime section.
    pub fn items(&self) -> impl Iterator<Item = RuntimeItem<N>> + use<'_, N> {
        self.children()
    }

    /// Gets the parent of the runtime section.
    pub fn parent(&self) -> SectionParent<N> {
        SectionParent::cast(self.0.parent().expect("should have a parent"))
            .expect("parent should cast")
    }

    /// Gets the `container` item as a [`Container`](runtime::item::Container)
    /// (if it exists).
    pub fn container(&self) -> Option<runtime::item::Container<N>> {
        // NOTE: validation should ensure that, at most, one `container`/`docker` item
        // exists in the `runtime` section.
        self.child()
    }
}

impl<N: TreeNode> AstNode<N> for RuntimeSection<N> {
    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::RuntimeSectionNode
    }

    fn cast(inner: N) -> Option<Self> {
        match inner.kind() {
            SyntaxKind::RuntimeSectionNode => Some(Self(inner)),
            _ => None,
        }
    }

    fn inner(&self) -> &N {
        &self.0
    }
}

/// Represents an item in a runtime section.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RuntimeItem<N: TreeNode = SyntaxNode>(N);

impl<N: TreeNode> RuntimeItem<N> {
    /// Gets the name of the runtime item.
    pub fn name(&self) -> Ident<N::Token> {
        self.token().expect("expected an item name")
    }

    /// Gets the expression of the runtime item.
    pub fn expr(&self) -> Expr<N> {
        Expr::child(&self.0).expect("expected an item expression")
    }

    /// Consumes `self` and attempts to cast the runtime item to a
    /// [`Container`](runtime::item::Container).
    pub fn into_container(self) -> Option<runtime::item::Container<N>> {
        runtime::item::Container::try_from(self).ok()
    }
}

impl<N: TreeNode> AstNode<N> for RuntimeItem<N> {
    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::RuntimeItemNode
    }

    fn cast(inner: N) -> Option<Self> {
        match inner.kind() {
            SyntaxKind::RuntimeItemNode => Some(Self(inner)),
            _ => None,
        }
    }

    fn inner(&self) -> &N {
        &self.0
    }
}

/// Represents a metadata section in a task or workflow definition.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MetadataSection<N: TreeNode = SyntaxNode>(N);

impl<N: TreeNode> MetadataSection<N> {
    /// Gets the items of the metadata section.
    pub fn items(&self) -> impl Iterator<Item = MetadataObjectItem<N>> + use<'_, N> {
        self.children()
    }

    /// Gets the parent of the metadata section.
    pub fn parent(&self) -> SectionParent<N> {
        SectionParent::cast(self.0.parent().expect("should have a parent"))
            .expect("parent should cast")
    }

    /// Gets the `meta` keyword.
    pub fn keyword(&self) -> MetaKeyword<N::Token> {
        self.token().expect("MetadataSection must have MetaKeyword")
    }
}

impl<N: TreeNode> AstNode<N> for MetadataSection<N> {
    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::MetadataSectionNode
    }

    fn cast(inner: N) -> Option<Self> {
        match inner.kind() {
            SyntaxKind::MetadataSectionNode => Some(Self(inner)),
            _ => None,
        }
    }

    fn inner(&self) -> &N {
        &self.0
    }
}

/// Represents a metadata object item.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MetadataObjectItem<N: TreeNode = SyntaxNode>(N);

impl<N: TreeNode> MetadataObjectItem<N> {
    /// Gets the name of the item.
    pub fn name(&self) -> Ident<N::Token> {
        self.token().expect("expected a name")
    }

    /// Gets the value of the item.
    pub fn value(&self) -> MetadataValue<N> {
        self.child().expect("expected a value")
    }
}

impl<N: TreeNode> AstNode<N> for MetadataObjectItem<N> {
    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::MetadataObjectItemNode
    }

    fn cast(inner: N) -> Option<Self> {
        match inner.kind() {
            SyntaxKind::MetadataObjectItemNode => Some(Self(inner)),
            _ => None,
        }
    }

    fn inner(&self) -> &N {
        &self.0
    }
}

/// Represents a metadata value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MetadataValue<N: TreeNode = SyntaxNode> {
    /// The value is a literal boolean.
    Boolean(LiteralBoolean<N>),
    /// The value is a literal integer.
    Integer(LiteralInteger<N>),
    /// The value is a literal float.
    Float(LiteralFloat<N>),
    /// The value is a literal string.
    String(LiteralString<N>),
    /// The value is a literal null.
    Null(LiteralNull<N>),
    /// The value is a metadata object.
    Object(MetadataObject<N>),
    /// The value is a metadata array.
    Array(MetadataArray<N>),
}

impl<N: TreeNode> MetadataValue<N> {
    /// Unwraps the metadata value into a boolean.
    ///
    /// # Panics
    ///
    /// Panics if the metadata value is not a boolean.
    pub fn unwrap_boolean(self) -> LiteralBoolean<N> {
        match self {
            Self::Boolean(b) => b,
            _ => panic!("not a boolean"),
        }
    }

    /// Unwraps the metadata value into an integer.
    ///
    /// # Panics
    ///
    /// Panics if the metadata value is not an integer.
    pub fn unwrap_integer(self) -> LiteralInteger<N> {
        match self {
            Self::Integer(i) => i,
            _ => panic!("not an integer"),
        }
    }

    /// Unwraps the metadata value into a float.
    ///
    /// # Panics
    ///
    /// Panics if the metadata value is not a float.
    pub fn unwrap_float(self) -> LiteralFloat<N> {
        match self {
            Self::Float(f) => f,
            _ => panic!("not a float"),
        }
    }

    /// Unwraps the metadata value into a string.
    ///
    /// # Panics
    ///
    /// Panics if the metadata value is not a string.
    pub fn unwrap_string(self) -> LiteralString<N> {
        match self {
            Self::String(s) => s,
            _ => panic!("not a string"),
        }
    }

    /// Unwraps the metadata value into a null.
    ///
    /// # Panics
    ///
    /// Panics if the metadata value is not a null.
    pub fn unwrap_null(self) -> LiteralNull<N> {
        match self {
            Self::Null(n) => n,
            _ => panic!("not a null"),
        }
    }

    /// Unwraps the metadata value into an object.
    ///
    /// # Panics
    ///
    /// Panics if the metadata value is not an object.
    pub fn unwrap_object(self) -> MetadataObject<N> {
        match self {
            Self::Object(o) => o,
            _ => panic!("not an object"),
        }
    }

    /// Unwraps the metadata value into an array.
    ///
    /// # Panics
    ///
    /// Panics if the metadata value is not an array.
    pub fn unwrap_array(self) -> MetadataArray<N> {
        match self {
            Self::Array(a) => a,
            _ => panic!("not an array"),
        }
    }
}

impl<N: TreeNode> AstNode<N> for MetadataValue<N> {
    fn can_cast(kind: SyntaxKind) -> bool {
        matches!(
            kind,
            SyntaxKind::LiteralBooleanNode
                | SyntaxKind::LiteralIntegerNode
                | SyntaxKind::LiteralFloatNode
                | SyntaxKind::LiteralStringNode
                | SyntaxKind::LiteralNullNode
                | SyntaxKind::MetadataObjectNode
                | SyntaxKind::MetadataArrayNode
        )
    }

    fn cast(inner: N) -> Option<Self> {
        match inner.kind() {
            SyntaxKind::LiteralBooleanNode => Some(Self::Boolean(LiteralBoolean(inner))),
            SyntaxKind::LiteralIntegerNode => Some(Self::Integer(LiteralInteger(inner))),
            SyntaxKind::LiteralFloatNode => Some(Self::Float(LiteralFloat(inner))),
            SyntaxKind::LiteralStringNode => Some(Self::String(LiteralString(inner))),
            SyntaxKind::LiteralNullNode => Some(Self::Null(LiteralNull(inner))),
            SyntaxKind::MetadataObjectNode => Some(Self::Object(MetadataObject(inner))),
            SyntaxKind::MetadataArrayNode => Some(Self::Array(MetadataArray(inner))),
            _ => None,
        }
    }

    fn inner(&self) -> &N {
        match self {
            Self::Boolean(b) => &b.0,
            Self::Integer(i) => &i.0,
            Self::Float(f) => &f.0,
            Self::String(s) => &s.0,
            Self::Null(n) => &n.0,
            Self::Object(o) => &o.0,
            Self::Array(a) => &a.0,
        }
    }
}

/// Represents a literal null.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LiteralNull<N: TreeNode = SyntaxNode>(N);

impl<N: TreeNode> AstNode<N> for LiteralNull<N> {
    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::LiteralNullNode
    }

    fn cast(inner: N) -> Option<Self> {
        match inner.kind() {
            SyntaxKind::LiteralNullNode => Some(Self(inner)),
            _ => None,
        }
    }

    fn inner(&self) -> &N {
        &self.0
    }
}

/// Represents a metadata object.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MetadataObject<N: TreeNode = SyntaxNode>(N);

impl<N: TreeNode> MetadataObject<N> {
    /// Gets the items of the metadata object.
    pub fn items(&self) -> impl Iterator<Item = MetadataObjectItem<N>> + use<'_, N> {
        self.children()
    }
}

impl<N: TreeNode> AstNode<N> for MetadataObject<N> {
    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::MetadataObjectNode
    }

    fn cast(inner: N) -> Option<Self> {
        match inner.kind() {
            SyntaxKind::MetadataObjectNode => Some(Self(inner)),
            _ => None,
        }
    }

    fn inner(&self) -> &N {
        &self.0
    }
}

/// Represents a metadata array.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MetadataArray<N: TreeNode = SyntaxNode>(N);

impl<N: TreeNode> MetadataArray<N> {
    /// Gets the elements of the metadata array.
    pub fn elements(&self) -> impl Iterator<Item = MetadataValue<N>> + use<'_, N> {
        self.children()
    }
}

impl<N: TreeNode> AstNode<N> for MetadataArray<N> {
    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::MetadataArrayNode
    }

    fn cast(inner: N) -> Option<Self> {
        match inner.kind() {
            SyntaxKind::MetadataArrayNode => Some(Self(inner)),
            _ => None,
        }
    }

    fn inner(&self) -> &N {
        &self.0
    }
}

/// Represents a parameter metadata section in a task or workflow definition.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParameterMetadataSection<N: TreeNode = SyntaxNode>(N);

impl<N: TreeNode> ParameterMetadataSection<N> {
    /// Gets the items of the parameter metadata section.
    pub fn items(&self) -> impl Iterator<Item = MetadataObjectItem<N>> + use<'_, N> {
        self.children()
    }

    /// Gets the parent of the parameter metadata section.
    pub fn parent(&self) -> SectionParent<N> {
        SectionParent::cast(self.0.parent().expect("should have a parent"))
            .expect("parent should cast")
    }

    /// Gets the `parameter_meta` keyword.
    pub fn keyword(&self) -> ParameterMetaKeyword<N::Token> {
        self.token()
            .expect("ParameterMetadataSection must have ParameterMetaKeyword")
    }
}

impl<N: TreeNode> AstNode<N> for ParameterMetadataSection<N> {
    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::ParameterMetadataSectionNode
    }

    fn cast(inner: N) -> Option<Self> {
        match inner.kind() {
            SyntaxKind::ParameterMetadataSectionNode => Some(Self(inner)),
            _ => None,
        }
    }

    fn inner(&self) -> &N {
        &self.0
    }
}

#[cfg(test)]
mod test {
    use pretty_assertions::assert_eq;

    use super::*;
    use crate::Document;

    #[test]
    fn tasks() {
        let (document, diagnostics) = Document::parse(
            r#"
version 1.2

task test {
    input {
        String name
    }

    output {
        String greeting = stdout()
    }

    command <<<
        printf "hello, ~{name}!
    >>>

    requirements {
        container: "baz/qux"
    }

    hints {
        foo: "bar"
    }

    runtime {
        container: "foo/bar"
    }

    meta {
        description: "a test"
        foo: null
    }

    parameter_meta {
        name: {
            help: "a name to greet"
        }
    }

    String x = "private"
}
"#,
            None,
        );

        assert!(diagnostics.is_empty());
        let ast = document.ast();
        let ast = ast.as_v1().expect("should be a V1 AST");
        let tasks: Vec<_> = ast.tasks().collect();
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].name().text(), "test");

        // Task input
        let input = tasks[0].input().expect("should have an input section");
        assert_eq!(input.parent().unwrap_task().name().text(), "test");
        let decls: Vec<_> = input.declarations().collect();
        assert_eq!(decls.len(), 1);
        assert_eq!(
            decls[0].clone().unwrap_unbound_decl().ty().to_string(),
            "String"
        );
        assert_eq!(decls[0].clone().unwrap_unbound_decl().name().text(), "name");

        // Task output
        let output = tasks[0].output().expect("should have an output section");
        assert_eq!(output.parent().unwrap_task().name().text(), "test");
        let decls: Vec<_> = output.declarations().collect();
        assert_eq!(decls.len(), 1);
        assert_eq!(decls[0].ty().to_string(), "String");
        assert_eq!(decls[0].name().text(), "greeting");
        assert_eq!(decls[0].expr().unwrap_call().target().text(), "stdout");

        // Task command
        let command = tasks[0].command().expect("should have a command section");
        assert_eq!(command.parent().name().text(), "test");
        assert!(command.is_heredoc());
        let parts: Vec<_> = command.parts().collect();
        assert_eq!(parts.len(), 3);
        assert_eq!(
            parts[0].clone().unwrap_text().text(),
            "\n        printf \"hello, "
        );
        assert_eq!(
            parts[1]
                .clone()
                .unwrap_placeholder()
                .expr()
                .unwrap_name_ref()
                .name()
                .text(),
            "name"
        );
        assert_eq!(parts[2].clone().unwrap_text().text(), "!\n    ");

        // Task requirements
        let requirements = tasks[0]
            .requirements()
            .expect("should have a requirements section");
        assert_eq!(requirements.parent().name().text(), "test");
        let items: Vec<_> = requirements.items().collect();
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].name().text(), TASK_REQUIREMENT_CONTAINER);
        assert_eq!(
            items[0]
                .expr()
                .unwrap_literal()
                .unwrap_string()
                .text()
                .unwrap()
                .text(),
            "baz/qux"
        );

        // Task hints
        let hints = tasks[0].hints().expect("should have a hints section");
        assert_eq!(hints.parent().name().text(), "test");
        let items: Vec<_> = hints.items().collect();
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].name().text(), "foo");
        assert_eq!(
            items[0]
                .expr()
                .unwrap_literal()
                .unwrap_string()
                .text()
                .unwrap()
                .text(),
            "bar"
        );

        // Task runtimes
        let runtime = tasks[0].runtime().expect("should have a runtime section");
        assert_eq!(runtime.parent().name().text(), "test");
        let items: Vec<_> = runtime.items().collect();
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].name().text(), TASK_REQUIREMENT_CONTAINER);
        assert_eq!(
            items[0]
                .expr()
                .unwrap_literal()
                .unwrap_string()
                .text()
                .unwrap()
                .text(),
            "foo/bar"
        );

        // Task metadata
        let metadata = tasks[0].metadata().expect("should have a metadata section");
        assert_eq!(metadata.parent().unwrap_task().name().text(), "test");
        let items: Vec<_> = metadata.items().collect();
        assert_eq!(items.len(), 2);
        assert_eq!(items[0].name().text(), "description");
        assert_eq!(
            items[0].value().unwrap_string().text().unwrap().text(),
            "a test"
        );

        // Second metadata
        assert_eq!(items[1].name().text(), "foo");
        items[1].value().unwrap_null();

        // Task parameter metadata
        let param_meta = tasks[0]
            .parameter_metadata()
            .expect("should have a parameter metadata section");
        assert_eq!(param_meta.parent().unwrap_task().name().text(), "test");
        let items: Vec<_> = param_meta.items().collect();
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].name().text(), "name");
        let items: Vec<_> = items[0].value().unwrap_object().items().collect();
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].name().text(), "help");
        assert_eq!(
            items[0].value().unwrap_string().text().unwrap().text(),
            "a name to greet"
        );

        // Task declarations
        let decls: Vec<_> = tasks[0].declarations().collect();
        assert_eq!(decls.len(), 1);

        // First task declaration
        assert_eq!(decls[0].ty().to_string(), "String");
        assert_eq!(decls[0].name().text(), "x");
        assert_eq!(
            decls[0]
                .expr()
                .unwrap_literal()
                .unwrap_string()
                .text()
                .unwrap()
                .text(),
            "private"
        );
    }

    #[test]
    fn whitespace_stripping_without_interpolation() {
        let (document, diagnostics) = Document::parse(
            r#"
version 1.2

task test {
    command <<<
        echo "hello"
        echo "world"
        echo \
            "goodbye"
    >>>
}
"#,
            None,
        );

        assert!(diagnostics.is_empty());
        let ast = document.ast();
        let ast = ast.as_v1().expect("should be a V1 AST");
        let tasks: Vec<_> = ast.tasks().collect();
        assert_eq!(tasks.len(), 1);

        let command = tasks[0].command().expect("should have a command section");

        let stripped = command.strip_whitespace().unwrap();

        assert_eq!(stripped.len(), 1);
        let text = match &stripped[0] {
            StrippedCommandPart::Text(text) => text,
            _ => panic!("expected text"),
        };
        assert_eq!(
            text,
            "echo \"hello\"\necho \"world\"\necho \\\n    \"goodbye\""
        );
    }

    #[test]
    fn whitespace_stripping_with_interpolation() {
        let (document, diagnostics) = Document::parse(
            r#"
version 1.2

task test {
    input {
        String name
        Boolean flag
    }

    command <<<
        echo "hello, ~{
if flag
then name
               else "Jerry"
    }!"
    >>>
}
    "#,
            None,
        );

        assert!(diagnostics.is_empty());
        let ast = document.ast();
        let ast = ast.as_v1().expect("should be a V1 AST");
        let tasks: Vec<_> = ast.tasks().collect();
        assert_eq!(tasks.len(), 1);

        let command = tasks[0].command().expect("should have a command section");

        let stripped = command.strip_whitespace().unwrap();
        assert_eq!(stripped.len(), 3);
        let text = match &stripped[0] {
            StrippedCommandPart::Text(text) => text,
            _ => panic!("expected text"),
        };
        assert_eq!(text, "echo \"hello, ");

        let _placeholder = match &stripped[1] {
            StrippedCommandPart::Placeholder(p) => p,
            _ => panic!("expected placeholder"),
        };
        // not testing anything with the placeholder, just making sure it's there

        let text = match &stripped[2] {
            StrippedCommandPart::Text(text) => text,
            _ => panic!("expected text"),
        };
        assert_eq!(text, "!\"");
    }

    #[test]
    fn whitespace_stripping_when_interpolation_starts_line() {
        let (document, diagnostics) = Document::parse(
            r#"
version 1.2

task test {
    input {
      Int placeholder
    }

    command <<<
            # other weird whitespace
      ~{placeholder} "$trailing_pholder" ~{placeholder}
      ~{placeholder} somecommand.py "$leading_pholder"
    >>>
}
"#,
            None,
        );

        assert!(diagnostics.is_empty());
        let ast = document.ast();
        let ast = ast.as_v1().expect("should be a V1 AST");
        let tasks: Vec<_> = ast.tasks().collect();
        assert_eq!(tasks.len(), 1);

        let command = tasks[0].command().expect("should have a command section");

        let stripped = command.strip_whitespace().unwrap();
        assert_eq!(stripped.len(), 7);
        let text = match &stripped[0] {
            StrippedCommandPart::Text(text) => text,
            _ => panic!("expected text"),
        };
        assert_eq!(text, "      # other weird whitespace\n");

        let _placeholder = match &stripped[1] {
            StrippedCommandPart::Placeholder(p) => p,
            _ => panic!("expected placeholder"),
        };
        // not testing anything with the placeholder, just making sure it's there

        let text = match &stripped[2] {
            StrippedCommandPart::Text(text) => text,
            _ => panic!("expected text"),
        };
        assert_eq!(text, " \"$trailing_pholder\" ");

        let _placeholder = match &stripped[3] {
            StrippedCommandPart::Placeholder(p) => p,
            _ => panic!("expected placeholder"),
        };
        // not testing anything with the placeholder, just making sure it's there

        let text = match &stripped[4] {
            StrippedCommandPart::Text(text) => text,
            _ => panic!("expected text"),
        };
        assert_eq!(text, "\n");

        let _placeholder = match &stripped[5] {
            StrippedCommandPart::Placeholder(p) => p,
            _ => panic!("expected placeholder"),
        };
        // not testing anything with the placeholder, just making sure it's there

        let text = match &stripped[6] {
            StrippedCommandPart::Text(text) => text,
            _ => panic!("expected text"),
        };
        assert_eq!(text, " somecommand.py \"$leading_pholder\"");
    }

    #[test]
    fn whitespace_stripping_when_command_is_empty() {
        let (document, diagnostics) = Document::parse(
            r#"
version 1.2

task test {
    command <<<>>>
}
    "#,
            None,
        );

        assert!(diagnostics.is_empty());
        let ast = document.ast();
        let ast = ast.as_v1().expect("should be a V1 AST");
        let tasks: Vec<_> = ast.tasks().collect();
        assert_eq!(tasks.len(), 1);

        let command = tasks[0].command().expect("should have a command section");

        let stripped = command.strip_whitespace().unwrap();
        assert_eq!(stripped.len(), 0);
    }

    #[test]
    fn whitespace_stripping_when_command_is_one_line_of_whitespace() {
        let (document, diagnostics) = Document::parse(
            r#"
version 1.2

task test {
    command <<<     >>>
}
    "#,
            None,
        );

        assert!(diagnostics.is_empty());
        let ast = document.ast();
        let ast = ast.as_v1().expect("should be a V1 AST");
        let tasks: Vec<_> = ast.tasks().collect();
        assert_eq!(tasks.len(), 1);

        let command = tasks[0].command().expect("should have a command section");

        let stripped = command.strip_whitespace().unwrap();
        assert_eq!(stripped.len(), 1);
        let text = match &stripped[0] {
            StrippedCommandPart::Text(text) => text,
            _ => panic!("expected text"),
        };
        assert_eq!(text, "");
    }

    #[test]
    fn whitespace_stripping_when_command_is_one_newline() {
        let (document, diagnostics) = Document::parse(
            r#"
version 1.2

task test {
    command <<<
    >>>
}
    "#,
            None,
        );

        assert!(diagnostics.is_empty());
        let ast = document.ast();
        let ast = ast.as_v1().expect("should be a V1 AST");
        let tasks: Vec<_> = ast.tasks().collect();
        assert_eq!(tasks.len(), 1);

        let command = tasks[0].command().expect("should have a command section");

        let stripped = command.strip_whitespace().unwrap();
        assert_eq!(stripped.len(), 1);
        let text = match &stripped[0] {
            StrippedCommandPart::Text(text) => text,
            _ => panic!("expected text"),
        };
        assert_eq!(text, "");
    }

    #[test]
    fn whitespace_stripping_when_command_is_a_blank_line() {
        let (document, diagnostics) = Document::parse(
            r#"
version 1.2

task test {
    command <<<

    >>>
}
    "#,
            None,
        );

        assert!(diagnostics.is_empty());
        let ast = document.ast();
        let ast = ast.as_v1().expect("should be a V1 AST");
        let tasks: Vec<_> = ast.tasks().collect();
        assert_eq!(tasks.len(), 1);

        let command = tasks[0].command().expect("should have a command section");

        let stripped = command.strip_whitespace().unwrap();
        assert_eq!(stripped.len(), 1);
        let text = match &stripped[0] {
            StrippedCommandPart::Text(text) => text,
            _ => panic!("expected text"),
        };
        assert_eq!(text, "");
    }

    #[test]
    fn whitespace_stripping_when_command_is_a_blank_line_with_spaces() {
        let (document, diagnostics) = Document::parse(
            r#"
version 1.2

task test {
    command <<<
    
    >>>
}
    "#,
            None,
        );

        assert!(diagnostics.is_empty());
        let ast = document.ast();
        let ast = ast.as_v1().expect("should be a V1 AST");
        let tasks: Vec<_> = ast.tasks().collect();
        assert_eq!(tasks.len(), 1);

        let command = tasks[0].command().expect("should have a command section");

        let stripped = command.strip_whitespace().unwrap();
        assert_eq!(stripped.len(), 1);
        let text = match &stripped[0] {
            StrippedCommandPart::Text(text) => text,
            _ => panic!("expected text"),
        };
        assert_eq!(text, "    ");
    }

    #[test]
    fn whitespace_stripping_with_mixed_indentation() {
        let (document, diagnostics) = Document::parse(
            r#"
version 1.2

task test {
    command <<<
        echo "hello"
			echo "world"
        echo \
            "goodbye"
    >>>
        }"#,
            None,
        );

        assert!(diagnostics.is_empty());
        let ast = document.ast();
        let ast = ast.as_v1().expect("should be a V1 AST");
        let tasks: Vec<_> = ast.tasks().collect();
        assert_eq!(tasks.len(), 1);

        let command = tasks[0].command().expect("should have a command section");

        let stripped = command.strip_whitespace();
        assert!(stripped.is_none());
    }

    #[test]
    fn whitespace_stripping_with_funky_indentation() {
        let (document, diagnostics) = Document::parse(
            r#"
version 1.2

task test {
    command <<<
    echo "hello"
        echo "world"
    echo \
            "goodbye"
                >>>
        }"#,
            None,
        );

        assert!(diagnostics.is_empty());
        let ast = document.ast();
        let ast = ast.as_v1().expect("should be a V1 AST");
        let tasks: Vec<_> = ast.tasks().collect();
        assert_eq!(tasks.len(), 1);

        let command = tasks[0].command().expect("should have a command section");

        let stripped = command.strip_whitespace().unwrap();
        assert_eq!(stripped.len(), 1);
        let text = match &stripped[0] {
            StrippedCommandPart::Text(text) => text,
            _ => panic!("expected text"),
        };
        assert_eq!(
            text,
            "echo \"hello\"\n    echo \"world\"\necho \\\n        \"goodbye\""
        );
    }

    /// Regression test for issue [#268](https://github.com/stjude-rust-labs/wdl/issues/268).
    #[test]
    fn whitespace_stripping_with_content_on_first_line() {
        let (document, diagnostics) = Document::parse(
            r#"
version 1.2

task test {
    command <<<      weird stuff $firstlinelint
            # other weird whitespace
      somecommand.py $line120 ~{placeholder}
    >>>
        }"#,
            None,
        );

        assert!(diagnostics.is_empty());
        let ast = document.ast();
        let ast = ast.as_v1().expect("should be a V1 AST");
        let tasks: Vec<_> = ast.tasks().collect();
        assert_eq!(tasks.len(), 1);

        let command = tasks[0].command().expect("should have a command section");

        let stripped = command.strip_whitespace().unwrap();
        assert_eq!(stripped.len(), 3);
        let text = match &stripped[0] {
            StrippedCommandPart::Text(text) => text,
            _ => panic!("expected text"),
        };
        assert_eq!(
            text,
            "weird stuff $firstlinelint\n      # other weird whitespace\nsomecommand.py $line120 "
        );

        let _placeholder = match &stripped[1] {
            StrippedCommandPart::Placeholder(p) => p,
            _ => panic!("expected placeholder"),
        };
        // not testing anything with the placeholder, just making sure it's there

        let text = match &stripped[2] {
            StrippedCommandPart::Text(text) => text,
            _ => panic!("expected text"),
        };
        assert_eq!(text, "");
    }

    #[test]
    fn whitespace_stripping_on_windows() {
        let (document, diagnostics) = Document::parse(
            "version 1.2\r\ntask test {\r\n    command <<<\r\n        echo \"hello\"\r\n    \
             >>>\r\n}\r\n",
            None,
        );

        assert!(diagnostics.is_empty());
        let ast = document.ast();
        let ast = ast.as_v1().expect("should be a V1 AST");
        let tasks: Vec<_> = ast.tasks().collect();
        assert_eq!(tasks.len(), 1);

        let command = tasks[0].command().expect("should have a command section");
        let stripped = command.strip_whitespace().unwrap();
        assert_eq!(stripped.len(), 1);
        let text = match &stripped[0] {
            StrippedCommandPart::Text(text) => text,
            _ => panic!("expected text"),
        };
        assert_eq!(text, "echo \"hello\"");
    }
}