tree-sitter-cli 0.26.8

CLI tool for developing, testing, and using Tree-sitter parsers
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
use std::{
    collections::HashSet,
    env, fs,
    path::{Path, PathBuf},
};

use anstyle::{AnsiColor, Color, Style};
use anyhow::{anyhow, Context, Result};
use clap::{crate_authors, Args, Command, FromArgMatches as _, Subcommand, ValueEnum};
use clap_complete::generate;
use dialoguer::{theme::ColorfulTheme, Confirm, FuzzySelect, Input, MultiSelect};
use heck::ToUpperCamelCase;
use log::{error, info, warn};
use regex::Regex;
use semver::Version as SemverVersion;
use tree_sitter::{ffi, Parser, Point};
use tree_sitter_cli::{
    fuzz::{
        fuzz_language_corpus, FuzzOptions, DEFAULT_EDIT_COUNT, DEFAULT_ITERATION_COUNT, EDIT_COUNT,
        ITERATION_COUNT, LOG_ENABLED, LOG_GRAPH_ENABLED, START_SEED,
    },
    highlight::{self, HighlightOptions},
    init::{generate_grammar_files, JsonConfigOpts, TREE_SITTER_JSON_SCHEMA},
    input::{get_input, get_tmp_source_file, CliInput},
    logger,
    parse::{self, ParseDebugType, ParseFileOptions, ParseOutput, ParseTheme},
    playground,
    query::{self, QueryFileOptions},
    tags::{self, TagsOptions},
    test::{self, TestOptions, TestStats, TestSummary},
    test_highlight, test_tags, util,
    version::{self, BumpLevel},
    wasm,
};
use tree_sitter_config::Config;
use tree_sitter_generate::OptLevel;
use tree_sitter_highlight::Highlighter;
use tree_sitter_loader::{self as loader, Bindings, TreeSitterJSON};
use tree_sitter_tags::TagsContext;

const BUILD_VERSION: &str = env!("CARGO_PKG_VERSION");
const BUILD_SHA: Option<&'static str> = option_env!("BUILD_SHA");
const DEFAULT_GENERATE_ABI_VERSION: usize = 15;

#[derive(Subcommand)]
#[command(about="Generates and tests parsers", author=crate_authors!("\n"), styles=get_styles())]
enum Commands {
    /// Generate a default config file
    InitConfig(InitConfig),
    /// Initialize a grammar repository
    Init(Init),
    /// Generate a parser
    Generate(Generate),
    /// Compile a parser
    Build(Build),
    /// Parse files
    Parse(Parse),
    /// Run a parser's tests
    Test(Test),
    /// Display or increment the version of a grammar
    Version(Version),
    /// Fuzz a parser
    Fuzz(Fuzz),
    /// Search files using a syntax tree query
    Query(Query),
    /// Highlight a file
    Highlight(Highlight),
    /// Generate a list of tags
    Tags(Tags),
    /// Start local playground for a parser in the browser
    Playground(Playground),
    /// Print info about all known language parsers
    DumpLanguages(DumpLanguages),
    /// Generate shell completions
    Complete(Complete),
}

#[derive(Args)]
struct InitConfig;

#[derive(Args)]
#[command(alias = "i")]
struct Init {
    /// Update outdated files
    #[arg(long, short)]
    pub update: bool,
    /// The path to the tree-sitter grammar directory
    #[arg(long, short = 'p')]
    pub grammar_path: Option<PathBuf>,
}

#[derive(Args)]
#[command(alias = "gen", alias = "g")]
struct Generate {
    /// The path to the grammar file
    #[arg(index = 1)]
    pub grammar_path: Option<PathBuf>,
    /// Show debug log during generation
    #[arg(long, short)]
    pub log: bool,
    #[arg(
        long = "abi",
        value_name = "VERSION",
        env = "TREE_SITTER_ABI_VERSION",
        help = format!(concat!(
                    "Select the language ABI version to generate (default {}).\n",
                    "Use --abi=latest to generate the newest supported version ({}).",
                    ),
                DEFAULT_GENERATE_ABI_VERSION,
                tree_sitter::LANGUAGE_VERSION,
                )
    )]
    pub abi_version: Option<String>,
    /// Only generate `grammar.json` and `node-types.json`
    #[arg(long)]
    pub no_parser: bool,
    /// Deprecated: use the `build` command
    #[arg(long, short = 'b')]
    pub build: bool,
    /// Deprecated: use the `build` command
    #[arg(long, short = '0')]
    pub debug_build: bool,
    /// Deprecated: use the `build` command
    #[arg(long, value_name = "PATH")]
    pub libdir: Option<PathBuf>,
    /// The path to output the generated source files
    #[arg(long, short, value_name = "DIRECTORY")]
    pub output: Option<PathBuf>,
    /// Produce a report of the states for the given rule, use `-` to report every rule
    #[arg(long, conflicts_with = "json", conflicts_with = "json_summary")]
    pub report_states_for_rule: Option<String>,
    /// Deprecated: use --json-summary
    #[arg(
        long,
        conflicts_with = "json_summary",
        conflicts_with = "report_states_for_rule"
    )]
    pub json: bool,
    /// Report conflicts in a JSON format
    #[arg(
        long,
        conflicts_with = "json",
        conflicts_with = "report_states_for_rule"
    )]
    pub json_summary: bool,
    /// The name or path of the JavaScript runtime to use for generating parsers
    #[cfg(not(feature = "qjs-rt"))]
    #[arg(
        long,
        value_name = "EXECUTABLE",
        env = "TREE_SITTER_JS_RUNTIME",
        default_value = "node"
    )]
    pub js_runtime: Option<String>,

    #[cfg(feature = "qjs-rt")]
    #[arg(
        long,
        value_name = "EXECUTABLE",
        env = "TREE_SITTER_JS_RUNTIME",
        default_value = "node"
    )]
    /// The name or path of the JavaScript runtime to use for generating parsers, specify `native`
    /// to use the native `QuickJS` runtime
    pub js_runtime: Option<String>,

    /// Disable optimizations when generating the parser. Currently, this only affects
    /// the merging of compatible parse states.
    #[arg(long)]
    pub disable_optimizations: bool,
}

#[derive(Args)]
#[command(alias = "b")]
struct Build {
    /// Build a Wasm module instead of a dynamic library
    #[arg(short, long)]
    pub wasm: bool,
    /// The path to output the compiled file
    #[arg(short, long)]
    pub output: Option<PathBuf>,
    /// The path to the grammar directory
    #[arg(index = 1, num_args = 1)]
    pub path: Option<PathBuf>,
    /// Make the parser reuse the same allocator as the library
    #[arg(long)]
    pub reuse_allocator: bool,
    /// Compile a parser in debug mode
    #[arg(long, short = '0')]
    pub debug: bool,
}

#[derive(Args)]
#[command(alias = "p")]
struct Parse {
    /// The path to a file with paths to source file(s)
    #[arg(long = "paths")]
    pub paths_file: Option<PathBuf>,
    /// The source file(s) to use
    #[arg(num_args=1..)]
    pub paths: Option<Vec<PathBuf>>,
    /// The path to the tree-sitter grammar directory, implies --rebuild
    #[arg(long, short = 'p', conflicts_with = "rebuild")]
    pub grammar_path: Option<PathBuf>,
    /// The path to the parser's dynamic library
    #[arg(long, short = 'l')]
    pub lib_path: Option<PathBuf>,
    /// If `--lib-path` is used, the name of the language used to extract the
    /// library's language function
    #[arg(long)]
    pub lang_name: Option<String>,
    /// Select a language by the scope instead of a file extension
    #[arg(long)]
    pub scope: Option<String>,
    /// Show parsing debug log
    #[arg(long, short = 'd')] // TODO: Rework once clap adds `default_missing_value_t`
    #[allow(clippy::option_option)]
    pub debug: Option<Option<ParseDebugType>>,
    /// Compile a parser in debug mode
    #[arg(long, short = '0')]
    pub debug_build: bool,
    /// Produce the log.html file with debug graphs
    #[arg(long, short = 'D')]
    pub debug_graph: bool,
    /// Compile parsers to Wasm instead of native dynamic libraries
    #[arg(long, hide = cfg!(not(feature = "wasm")))]
    pub wasm: bool,
    /// Output the parse data with graphviz dot
    #[arg(long = "dot")]
    pub output_dot: bool,
    /// Output the parse data in XML format
    #[arg(long = "xml", short = 'x')]
    pub output_xml: bool,
    /// Output the parse data in a pretty-printed CST format
    #[arg(long = "cst", short = 'c')]
    pub output_cst: bool,
    /// Show parsing statistics
    #[arg(long, short, conflicts_with = "json", conflicts_with = "json_summary")]
    pub stat: bool,
    /// Interrupt the parsing process by timeout (µs)
    #[arg(long)]
    pub timeout: Option<u64>,
    /// Measure execution time
    #[arg(long, short)]
    pub time: bool,
    /// Suppress main output
    #[arg(long, short)]
    pub quiet: bool,
    #[allow(clippy::doc_markdown)]
    /// Apply edits in the format: \"row,col|position delcount insert_text\", can be supplied
    /// multiple times
    #[arg(
        long,
        num_args = 1..,
    )]
    pub edits: Option<Vec<String>>,
    /// The encoding of the input files
    #[arg(long)]
    pub encoding: Option<Encoding>,
    /// Open `log.html` in the default browser, if `--debug-graph` is supplied
    #[arg(long)]
    pub open_log: bool,
    /// Deprecated: use --json-summary
    #[arg(long, conflicts_with = "json_summary", conflicts_with = "stat")]
    pub json: bool,
    /// Output parsing results in a JSON format
    #[arg(long, short = 'j', conflicts_with = "json", conflicts_with = "stat")]
    pub json_summary: bool,
    /// The path to an alternative config.json file
    #[arg(long)]
    pub config_path: Option<PathBuf>,
    /// Parse the contents of a specific test
    #[arg(long, short = 'n')]
    #[clap(conflicts_with = "paths", conflicts_with = "paths_file")]
    pub test_number: Option<u32>,
    /// Force rebuild the parser
    #[arg(short, long)]
    pub rebuild: bool,
    /// Omit ranges in the output
    #[arg(long)]
    pub no_ranges: bool,
}

#[derive(ValueEnum, Clone)]
pub enum Encoding {
    Utf8,
    Utf16LE,
    Utf16BE,
}

#[derive(Args)]
#[command(alias = "t")]
struct Test {
    /// Only run corpus test cases whose name matches the given regex
    #[arg(long, short)]
    pub include: Option<Regex>,
    /// Only run corpus test cases whose name does not match the given regex
    #[arg(long, short)]
    pub exclude: Option<Regex>,
    /// Only run corpus test cases from a given filename
    #[arg(long)]
    pub file_name: Option<String>,
    /// The path to the tree-sitter grammar directory, implies --rebuild
    #[arg(long, short = 'p', conflicts_with = "rebuild")]
    pub grammar_path: Option<PathBuf>,
    /// The path to the parser's dynamic library
    #[arg(long, short = 'l')]
    pub lib_path: Option<PathBuf>,
    /// If `--lib-path` is used, the name of the language used to extract the
    /// library's language function
    #[arg(long)]
    pub lang_name: Option<String>,
    /// Update all syntax trees in corpus files with current parser output
    #[arg(long, short)]
    pub update: bool,
    /// Show parsing debug log
    #[arg(long, short = 'd')]
    pub debug: bool,
    /// Compile a parser in debug mode
    #[arg(long, short = '0')]
    pub debug_build: bool,
    /// Produce the log.html file with debug graphs
    #[arg(long, short = 'D')]
    pub debug_graph: bool,
    /// Compile parsers to Wasm instead of native dynamic libraries
    #[arg(long, hide = cfg!(not(feature = "wasm")))]
    pub wasm: bool,
    /// Open `log.html` in the default browser, if `--debug-graph` is supplied
    #[arg(long)]
    pub open_log: bool,
    /// The path to an alternative config.json file
    #[arg(long)]
    pub config_path: Option<PathBuf>,
    /// Force showing fields in test diffs
    #[arg(long)]
    pub show_fields: bool,
    /// Show parsing statistics
    #[arg(long)]
    pub stat: Option<TestStats>,
    /// Force rebuild the parser
    #[arg(short, long)]
    pub rebuild: bool,
    /// Show only the pass-fail overview tree
    #[arg(long)]
    pub overview_only: bool,
    /// Output the test summary in a JSON format
    #[arg(long)]
    pub json_summary: bool,
}

#[derive(Args)]
#[command(alias = "publish")]
/// Display or increment the version of a grammar
struct Version {
    /// The version to bump to
    #[arg(
        conflicts_with = "bump",
        long_help = "\
        The version to bump to\n\
        \n\
        Examples:\n    \
            tree-sitter version: display the current version\n    \
            tree-sitter version <version>: bump to specified version\n    \
            tree-sitter version --bump <level>: automatic bump"
    )]
    pub version: Option<SemverVersion>,
    /// The path to the tree-sitter grammar directory
    #[arg(long, short = 'p')]
    pub grammar_path: Option<PathBuf>,
    /// Automatically bump from the current version
    #[arg(long, value_enum, conflicts_with = "version")]
    pub bump: Option<BumpLevel>,
}

#[derive(Args)]
#[command(alias = "f")]
struct Fuzz {
    /// List of test names to skip
    #[arg(long, short)]
    pub skip: Option<Vec<String>>,
    /// Subdirectory to the language
    #[arg(long)]
    pub subdir: Option<PathBuf>,
    /// The path to the tree-sitter grammar directory, implies --rebuild
    #[arg(long, short = 'p', conflicts_with = "rebuild")]
    pub grammar_path: Option<PathBuf>,
    /// The path to the parser's dynamic library
    #[arg(long)]
    pub lib_path: Option<PathBuf>,
    /// If `--lib-path` is used, the name of the language used to extract the
    /// library's language function
    #[arg(long)]
    pub lang_name: Option<String>,
    #[arg(
        long,
        help=format!("Maximum number of edits to perform per fuzz test (Default: {DEFAULT_EDIT_COUNT})")
    )]
    pub edits: Option<usize>,
    #[arg(
        long,
        help=format!("Number of fuzzing iterations to run per test (Default: {DEFAULT_ITERATION_COUNT})")
    )]
    pub iterations: Option<usize>,
    /// Only fuzz corpus test cases whose name matches the given regex
    #[arg(long, short)]
    pub include: Option<Regex>,
    /// Only fuzz corpus test cases whose name does not match the given regex
    #[arg(long, short)]
    pub exclude: Option<Regex>,
    /// Enable logging of graphs and input
    #[arg(long)]
    pub log_graphs: bool,
    /// Enable parser logging
    #[arg(long, short)]
    pub log: bool,
    /// Force rebuild the parser
    #[arg(short, long)]
    pub rebuild: bool,
}

#[derive(Args)]
#[command(alias = "q")]
struct Query {
    /// Path to a file with queries
    #[arg(index = 1, required = true)]
    query_path: PathBuf,
    /// The path to the tree-sitter grammar directory, implies --rebuild
    #[arg(long, short = 'p', conflicts_with = "rebuild")]
    pub grammar_path: Option<PathBuf>,
    /// The path to the parser's dynamic library
    #[arg(long, short = 'l')]
    pub lib_path: Option<PathBuf>,
    /// If `--lib-path` is used, the name of the language used to extract the
    /// library's language function
    #[arg(long)]
    pub lang_name: Option<String>,
    /// Measure execution time
    #[arg(long, short)]
    pub time: bool,
    /// Suppress main output
    #[arg(long, short)]
    pub quiet: bool,
    /// The path to a file with paths to source file(s)
    #[arg(long = "paths")]
    pub paths_file: Option<PathBuf>,
    /// The source file(s) to use
    #[arg(index = 2, num_args=1..)]
    pub paths: Option<Vec<PathBuf>>,
    /// The range of byte offsets in which the query will be executed
    #[arg(long)]
    pub byte_range: Option<String>,
    /// The range of rows in which the query will be executed
    #[arg(long)]
    pub row_range: Option<String>,
    /// The range of byte offsets in which the query will be executed. Only the matches that are fully contained within the provided
    /// byte range will be returned.
    #[arg(long)]
    pub containing_byte_range: Option<String>,
    /// The range of rows in which the query will be executed. Only the matches that are fully contained within the provided row range
    /// will be returned.
    #[arg(long)]
    pub containing_row_range: Option<String>,
    /// Select a language by the scope instead of a file extension
    #[arg(long)]
    pub scope: Option<String>,
    /// Order by captures instead of matches
    #[arg(long, short)]
    pub captures: bool,
    /// Whether to run query tests or not
    #[arg(long)]
    pub test: bool,
    /// The path to an alternative config.json file
    #[arg(long)]
    pub config_path: Option<PathBuf>,
    /// Query the contents of a specific test
    #[arg(long, short = 'n')]
    #[clap(conflicts_with = "paths", conflicts_with = "paths_file")]
    pub test_number: Option<u32>,
    /// Force rebuild the parser
    #[arg(short, long)]
    pub rebuild: bool,
}

#[derive(Args)]
#[command(alias = "hi")]
struct Highlight {
    /// Generate highlighting as an HTML document
    #[arg(long, short = 'H')]
    pub html: bool,
    /// When generating HTML, use css classes rather than inline styles
    #[arg(long)]
    pub css_classes: bool,
    /// Check that highlighting captures conform strictly to standards
    #[arg(long)]
    pub check: bool,
    /// The path to a file with captures
    #[arg(long)]
    pub captures_path: Option<PathBuf>,
    /// The paths to files with queries
    #[arg(long, num_args = 1..)]
    pub query_paths: Option<Vec<PathBuf>>,
    /// Select a language by the scope instead of a file extension
    #[arg(long)]
    pub scope: Option<String>,
    /// Measure execution time
    #[arg(long, short)]
    pub time: bool,
    /// Suppress main output
    #[arg(long, short)]
    pub quiet: bool,
    /// The path to a file with paths to source file(s)
    #[arg(long = "paths")]
    pub paths_file: Option<PathBuf>,
    /// The source file(s) to use
    #[arg(num_args = 1..)]
    pub paths: Option<Vec<PathBuf>>,
    /// The path to the tree-sitter grammar directory, implies --rebuild
    #[arg(long, short = 'p', conflicts_with = "rebuild")]
    pub grammar_path: Option<PathBuf>,
    /// The path to an alternative config.json file
    #[arg(long)]
    pub config_path: Option<PathBuf>,
    /// Highlight the contents of a specific test
    #[arg(long, short = 'n')]
    #[clap(conflicts_with = "paths", conflicts_with = "paths_file")]
    pub test_number: Option<u32>,
    /// Force rebuild the parser
    #[arg(short, long)]
    pub rebuild: bool,
}

#[derive(Args)]
struct Tags {
    /// Select a language by the scope instead of a file extension
    #[arg(long)]
    pub scope: Option<String>,
    /// Measure execution time
    #[arg(long, short)]
    pub time: bool,
    /// Suppress main output
    #[arg(long, short)]
    pub quiet: bool,
    /// The path to a file with paths to source file(s)
    #[arg(long = "paths")]
    pub paths_file: Option<PathBuf>,
    /// The source file(s) to use
    #[arg(num_args = 1..)]
    pub paths: Option<Vec<PathBuf>>,
    /// The path to the tree-sitter grammar directory, implies --rebuild
    #[arg(long, short = 'p', conflicts_with = "rebuild")]
    pub grammar_path: Option<PathBuf>,
    /// The path to an alternative config.json file
    #[arg(long)]
    pub config_path: Option<PathBuf>,
    /// Generate tags from the contents of a specific test
    #[arg(long, short = 'n')]
    #[clap(conflicts_with = "paths", conflicts_with = "paths_file")]
    pub test_number: Option<u32>,
    /// Force rebuild the parser
    #[arg(short, long)]
    pub rebuild: bool,
}

#[derive(Args)]
#[command(alias = "play", alias = "pg", alias = "web-ui")]
struct Playground {
    /// Don't open in default browser
    #[arg(long, short)]
    pub quiet: bool,
    /// Path to the directory containing the grammar and Wasm files
    #[arg(long)]
    pub grammar_path: Option<PathBuf>,
    /// Export playground files to specified directory instead of serving them
    #[arg(long, short)]
    pub export: Option<PathBuf>,
}

#[derive(Args)]
#[command(alias = "langs")]
struct DumpLanguages {
    /// The path to an alternative config.json file
    #[arg(long)]
    pub config_path: Option<PathBuf>,
}

#[derive(Args)]
#[command(alias = "comp")]
struct Complete {
    /// The shell to generate completions for
    #[arg(long, short, value_enum)]
    pub shell: Shell,
}

#[derive(ValueEnum, Clone)]
pub enum Shell {
    Bash,
    Elvish,
    Fish,
    PowerShell,
    Zsh,
    Nushell,
}

/// Complete `action` if the wasm feature is enabled, otherwise return an error
macro_rules! checked_wasm {
    ($action:block) => {
        #[cfg(feature = "wasm")]
        {
            $action
        }
        #[cfg(not(feature = "wasm"))]
        {
            Err(anyhow!("--wasm flag specified, but this build of tree-sitter-cli does not include the wasm feature"))?;
        }
    };
}

impl InitConfig {
    fn run() -> Result<()> {
        if let Ok(Some(config_path)) = Config::find_config_file() {
            return Err(anyhow!(
                "Remove your existing config file first: {}",
                config_path.to_string_lossy()
            ));
        }
        let mut config = Config::initial()?;
        config.add(tree_sitter_loader::Config::initial())?;
        config.add(tree_sitter_cli::highlight::ThemeConfig::default())?;
        config.save()?;
        info!(
            "Saved initial configuration to {}",
            config.location.display()
        );
        Ok(())
    }
}

impl Init {
    fn run(self, current_dir: &Path) -> Result<()> {
        let configure_json = !current_dir.join("tree-sitter.json").exists();

        let (language_name, json_config_opts) = if configure_json {
            let mut opts = JsonConfigOpts::default();

            let name = || {
                Input::<String>::with_theme(&ColorfulTheme::default())
                    .with_prompt("Parser name")
                    .validate_with(|input: &String| {
                        if input.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') {
                            Ok(())
                        } else {
                            Err("The name must be lowercase and contain only letters, digits, and underscores")
                        }
                    })
                    .interact_text()
            };

            let camelcase_name = |name: &str| {
                Input::<String>::with_theme(&ColorfulTheme::default())
                    .with_prompt("CamelCase name")
                    .default(name.to_upper_camel_case())
                    .validate_with(|input: &String| {
                        if input
                            .chars()
                            .all(|c| c.is_ascii_alphabetic() || c.is_ascii_digit() || c == '_')
                        {
                            Ok(())
                        } else {
                            Err("The name must contain only letters, digits, and underscores")
                        }
                    })
                    .interact_text()
            };

            let title = |name: &str| {
                Input::<String>::with_theme(&ColorfulTheme::default())
                    .with_prompt("Title (human-readable name)")
                    .default(name.to_upper_camel_case())
                    .interact_text()
            };

            let description = |name: &str| {
                Input::<String>::with_theme(&ColorfulTheme::default())
                    .with_prompt("Description")
                    .default(format!(
                        "{} grammar for tree-sitter",
                        name.to_upper_camel_case()
                    ))
                    .show_default(false)
                    .allow_empty(true)
                    .interact_text()
            };

            let repository = |name: &str| {
                Input::<String>::with_theme(&ColorfulTheme::default())
                    .with_prompt("Repository URL")
                    .allow_empty(true)
                    .default(format!("https://github.com/tree-sitter/tree-sitter-{name}"))
                    .show_default(false)
                    .interact_text()
            };

            let funding = || {
                Input::<String>::with_theme(&ColorfulTheme::default())
                    .with_prompt("Funding URL")
                    .allow_empty(true)
                    .interact_text()
                    .map(|e| Some(e.trim().to_string()))
            };

            let scope = |name: &str| {
                Input::<String>::with_theme(&ColorfulTheme::default())
                    .with_prompt("TextMate scope")
                    .default(format!("source.{name}"))
                    .validate_with(|input: &String| {
                        if input.starts_with("source.") || input.starts_with("text.") {
                            Ok(())
                        } else {
                            Err("The scope must start with 'source.' or 'text.'")
                        }
                    })
                    .interact_text()
            };

            let file_types = |name: &str| {
                Input::<String>::with_theme(&ColorfulTheme::default())
                    .with_prompt("File types (space-separated)")
                    .default(name.to_string())
                    .interact_text()
                    .map(|ft| {
                        let mut set = HashSet::new();
                        for ext in ft.split(' ') {
                            let ext = ext.trim();
                            if !ext.is_empty() {
                                set.insert(ext.to_string());
                            }
                        }
                        set.into_iter().collect::<Vec<_>>()
                    })
            };

            let initial_version = || {
                Input::<SemverVersion>::with_theme(&ColorfulTheme::default())
                    .with_prompt("Version")
                    .default(SemverVersion::new(0, 1, 0))
                    .interact_text()
            };

            let license = || {
                Input::<String>::with_theme(&ColorfulTheme::default())
                    .with_prompt("License")
                    .default("MIT".to_string())
                    .allow_empty(true)
                    .interact()
            };

            let author = || {
                Input::<String>::with_theme(&ColorfulTheme::default())
                    .with_prompt("Author name")
                    .interact_text()
            };

            let email = || {
                Input::<String>::with_theme(&ColorfulTheme::default())
                    .with_prompt("Author email")
                    .allow_empty(true)
                    .interact_text()
                    .map(|e| (!e.trim().is_empty()).then_some(e))
            };

            let url = || {
                Input::<String>::with_theme(&ColorfulTheme::default())
                    .with_prompt("Author URL")
                    .allow_empty(true)
                    .interact_text()
                    .map(|e| Some(e.trim().to_string()))
            };

            let namespace = || {
                Input::<String>::with_theme(&ColorfulTheme::default())
                    .with_prompt("Package namespace")
                    .default("io.github.tree-sitter".to_string())
                    .allow_empty(true)
                    .interact()
            };

            let bindings = || {
                let languages = Bindings::default().languages();

                let enabled = MultiSelect::new()
                    .with_prompt("Bindings")
                    .items_checked(&languages)
                    .interact()?
                    .into_iter()
                    .map(|i| languages[i].0);

                let out = Bindings::with_enabled_languages(enabled)
                    .expect("unexpected unsupported language");
                anyhow::Ok(out)
            };

            let choices = [
                "name",
                "camelcase",
                "title",
                "description",
                "repository",
                "funding",
                "scope",
                "file_types",
                "version",
                "license",
                "author",
                "email",
                "url",
                "namespace",
                "bindings",
                "exit",
            ];

            macro_rules! set_choice {
                ($choice:expr) => {
                    match $choice {
                        "name" => opts.name = name()?,
                        "camelcase" => opts.camelcase = camelcase_name(&opts.name)?,
                        "title" => opts.title = title(&opts.name)?,
                        "description" => opts.description = description(&opts.name)?,
                        "repository" => opts.repository = Some(repository(&opts.name)?),
                        "funding" => opts.funding = funding()?,
                        "scope" => opts.scope = scope(&opts.name)?,
                        "file_types" => opts.file_types = file_types(&opts.name)?,
                        "version" => opts.version = initial_version()?,
                        "license" => opts.license = license()?,
                        "author" => opts.author = author()?,
                        "email" => opts.email = email()?,
                        "url" => opts.url = url()?,
                        "namespace" => opts.namespace = Some(namespace()?),
                        "bindings" => opts.bindings = bindings()?,
                        "exit" => break,
                        _ => unreachable!(),
                    }
                };
            }

            // Initial configuration
            for choice in choices.iter().take(choices.len() - 1) {
                set_choice!(*choice);
            }

            // Loop for editing the configuration
            loop {
                info!(
                    "Your current configuration:\n{}",
                    serde_json::to_string_pretty(&opts)?
                );

                if Confirm::with_theme(&ColorfulTheme::default())
                    .with_prompt("Does the config above look correct?")
                    .interact()?
                {
                    break;
                }

                let idx = FuzzySelect::with_theme(&ColorfulTheme::default())
                    .with_prompt("Which field would you like to change?")
                    .items(&choices)
                    .interact()?;

                set_choice!(choices[idx]);
            }

            (opts.name.clone(), Some(opts))
        } else {
            let old_config = fs::read_to_string(current_dir.join("tree-sitter.json"))
                .with_context(|| "Failed to read tree-sitter.json")?;

            let mut json = serde_json::from_str::<TreeSitterJSON>(&old_config)?;
            if json.schema.is_none() {
                json.schema = Some(TREE_SITTER_JSON_SCHEMA.to_string());
            }

            let new_config = format!("{}\n", serde_json::to_string_pretty(&json)?);
            // Write the re-serialized config back, as newly added optional boolean fields
            // will be included with explicit `false`s rather than implict `null`s
            if self.update && !old_config.trim().eq(new_config.trim()) {
                info!("Updating tree-sitter.json");
                fs::write(
                    current_dir.join("tree-sitter.json"),
                    serde_json::to_string_pretty(&json)?,
                )
                .with_context(|| "Failed to write tree-sitter.json")?;
            }

            (json.grammars.swap_remove(0).name, None)
        };

        generate_grammar_files(
            current_dir,
            &language_name,
            self.update,
            json_config_opts.as_ref(),
        )?;

        Ok(())
    }
}

impl Generate {
    fn run(self, mut loader: loader::Loader, current_dir: &Path) -> Result<()> {
        if self.log {
            logger::enable_debug();
        }
        let abi_version =
            self.abi_version
                .as_ref()
                .map_or(DEFAULT_GENERATE_ABI_VERSION, |version| {
                    if version == "latest" {
                        tree_sitter::LANGUAGE_VERSION
                    } else {
                        version.parse().expect("invalid abi version flag")
                    }
                });

        let json_summary = if self.json {
            warn!("--json is deprecated, use --json-summary instead");
            true
        } else {
            self.json_summary
        };

        if let Err(err) = tree_sitter_generate::generate_parser_in_directory(
            current_dir,
            self.output.as_deref(),
            self.grammar_path.as_deref(),
            abi_version,
            self.report_states_for_rule.as_deref(),
            self.js_runtime.as_deref(),
            !self.no_parser,
            if self.disable_optimizations {
                OptLevel::empty()
            } else {
                OptLevel::default()
            },
        ) {
            if json_summary {
                eprintln!("{}", serde_json::to_string_pretty(&err)?);
                // Exit early to prevent errors from being printed a second time in the caller
                std::process::exit(1);
            } else {
                // Removes extra context associated with the error
                Err(anyhow!(err.to_string())).with_context(|| "Error when generating parser")?;
            }
        }
        if self.build {
            warn!("--build is deprecated, use the `build` command");
            if let Some(path) = self.libdir {
                loader = loader::Loader::with_parser_lib_path(path);
            }
            loader.debug_build(self.debug_build);
            loader.languages_at_path(current_dir)?;
        }
        Ok(())
    }
}

impl Build {
    fn run(self, mut loader: loader::Loader, current_dir: &Path) -> Result<()> {
        let grammar_path = current_dir.join(self.path.unwrap_or_default());

        loader.debug_build(self.debug);

        if self.wasm {
            let output_path = self.output.map(|path| current_dir.join(path));
            wasm::compile_language_to_wasm(&loader, &grammar_path, current_dir, output_path)?;
        } else {
            let output_path = if let Some(ref path) = self.output {
                let path = Path::new(path);
                let full_path = if path.is_absolute() {
                    path.to_path_buf()
                } else {
                    current_dir.join(path)
                };
                let parent_path = full_path
                    .parent()
                    .context("Output path must have a parent")?;
                let name = full_path
                    .file_name()
                    .context("Ouput path must have a filename")?;
                fs::create_dir_all(parent_path).context("Failed to create output path")?;
                let mut canon_path = parent_path.canonicalize().context("Invalid output path")?;
                canon_path.push(name);
                canon_path
            } else {
                let file_name = grammar_path
                    .file_stem()
                    .unwrap()
                    .to_str()
                    .unwrap()
                    .strip_prefix("tree-sitter-")
                    .unwrap_or("parser");
                current_dir
                    .join(file_name)
                    .with_extension(env::consts::DLL_EXTENSION)
            };

            let flags: &[&str] = match (self.reuse_allocator, self.debug) {
                (true, true) => &["TREE_SITTER_REUSE_ALLOCATOR", "TREE_SITTER_DEBUG"],
                (true, false) => &["TREE_SITTER_REUSE_ALLOCATOR"],
                (false, true) => &["TREE_SITTER_DEBUG"],
                (false, false) => &[],
            };

            loader.force_rebuild(true);

            loader
                .compile_parser_at_path(&grammar_path, output_path, flags)
                .context("Failed to compile parser")?;
        }
        Ok(())
    }
}

impl Parse {
    fn run(self, mut loader: loader::Loader, current_dir: &Path) -> Result<()> {
        let config = Config::load(self.config_path)?;
        let color = env::var("NO_COLOR").map_or(true, |v| v != "1");
        let json_summary = if self.json {
            warn!("--json is deprecated, use --json-summary instead");
            true
        } else {
            self.json_summary
        };
        let output = if self.output_dot {
            ParseOutput::Dot
        } else if self.output_xml {
            ParseOutput::Xml
        } else if self.output_cst {
            ParseOutput::Cst
        } else if self.quiet || json_summary {
            ParseOutput::Quiet
        } else {
            ParseOutput::Normal
        };

        let parse_theme = if color {
            config
                .get::<parse::Config>()
                .with_context(|| "Failed to parse CST theme")?
                .parse_theme
                .unwrap_or_default()
                .into()
        } else {
            ParseTheme::empty()
        };

        let encoding = self.encoding.map(|e| match e {
            Encoding::Utf8 => ffi::TSInputEncodingUTF8,
            Encoding::Utf16LE => ffi::TSInputEncodingUTF16LE,
            Encoding::Utf16BE => ffi::TSInputEncodingUTF16BE,
        });

        let time = self.time;
        let edits = self.edits.unwrap_or_default();
        let cancellation_flag = util::cancel_on_signal();
        let mut parser = Parser::new();

        loader.debug_build(self.debug_build);
        loader.force_rebuild(self.rebuild || self.grammar_path.is_some());

        if self.wasm {
            checked_wasm!({
                let engine = tree_sitter::wasmtime::Engine::default();
                parser
                    .set_wasm_store(tree_sitter::WasmStore::new(&engine).unwrap())
                    .unwrap();
                loader.use_wasm(&engine);
            });
        }

        let timeout = self.timeout.unwrap_or_default();

        let mut has_error = false;
        let loader_config = config.get()?;
        loader.find_all_languages(&loader_config)?;

        let should_track_stats = self.stat;
        let mut stats = parse::ParseStats::default();
        let debug: ParseDebugType = match self.debug {
            None => ParseDebugType::Quiet,
            Some(None) => ParseDebugType::Normal,
            Some(Some(specifier)) => specifier,
        };

        let mut options = ParseFileOptions {
            edits: &edits
                .iter()
                .map(std::string::String::as_str)
                .collect::<Vec<&str>>(),
            output,
            print_time: time,
            timeout,
            stats: &mut stats,
            debug,
            debug_graph: self.debug_graph,
            cancellation_flag: Some(&cancellation_flag),
            encoding,
            open_log: self.open_log,
            no_ranges: self.no_ranges,
            parse_theme: &parse_theme,
        };

        let mut update_stats = |stats: &mut parse::ParseStats| {
            let parse_result = stats.parse_summaries.last().unwrap();
            if should_track_stats || json_summary {
                stats.cumulative_stats.total_parses += 1;
                if parse_result.successful {
                    stats.cumulative_stats.successful_parses += 1;
                }
                if let (Some(duration), Some(bytes)) = (parse_result.duration, parse_result.bytes) {
                    stats.cumulative_stats.total_bytes += bytes;
                    stats.cumulative_stats.total_duration += duration;
                }
            }

            has_error |= !parse_result.successful;
        };

        if self.lib_path.is_none() && self.lang_name.is_some() {
            warn!("--lang-name` specified without --lib-path. This argument will be ignored.");
        }
        let lib_info = get_lib_info(self.lib_path.as_ref(), self.lang_name.as_ref(), current_dir);

        let input = get_input(
            self.paths_file.as_deref(),
            self.paths,
            self.test_number,
            &cancellation_flag,
        )?;
        match input {
            CliInput::Paths(paths) => {
                let max_path_length = paths
                    .iter()
                    .map(|p| p.to_string_lossy().chars().count())
                    .max()
                    .unwrap_or(0);
                options.stats.source_count = paths.len();

                for path in &paths {
                    let path = Path::new(&path);
                    let language = loader
                        .select_language(
                            Some(path),
                            current_dir,
                            self.scope.as_deref(),
                            lib_info.as_ref(),
                        )
                        .with_context(|| {
                            anyhow!("Failed to load language for path \"{}\"", path.display())
                        })?;

                    parse::parse_file_at_path(
                        &mut parser,
                        &language,
                        path,
                        &path.display().to_string(),
                        max_path_length,
                        &mut options,
                    )?;
                    update_stats(options.stats);
                }
            }

            CliInput::Test {
                name,
                contents,
                languages: language_names,
            } => {
                let path = get_tmp_source_file(&contents)?;
                let languages = loader.languages_at_path(current_dir)?;

                let language = if let Some(ref lib_path) = self.lib_path {
                    &loader
                        .select_language(
                            None,
                            current_dir,
                            self.scope.as_deref(),
                            lib_info.as_ref(),
                        )
                        .with_context(|| {
                            anyhow!(
                                "Failed to load language for path \"{}\"",
                                lib_path.display()
                            )
                        })?
                } else {
                    &languages
                        .iter()
                        .find(|(_, n)| language_names.contains(&Box::from(n.as_str())))
                        .or_else(|| languages.first())
                        .map(|(l, _)| l.clone())
                        .ok_or_else(|| anyhow!("No language found"))?
                };

                parse::parse_file_at_path(
                    &mut parser,
                    language,
                    &path,
                    &name,
                    name.chars().count(),
                    &mut options,
                )?;
                update_stats(&mut stats);
                fs::remove_file(path)?;
            }

            CliInput::Stdin(contents) => {
                // Place user input and parser output on separate lines
                println!();

                let path = get_tmp_source_file(&contents)?;
                let name = "stdin";
                let language = loader.select_language(
                    None,
                    current_dir,
                    self.scope.as_deref(),
                    lib_info.as_ref(),
                )?;

                parse::parse_file_at_path(
                    &mut parser,
                    &language,
                    &path,
                    name,
                    name.chars().count(),
                    &mut options,
                )?;
                update_stats(&mut stats);
                fs::remove_file(path)?;
            }
        }

        if should_track_stats {
            println!("\n{}", stats.cumulative_stats);
        }
        if json_summary {
            println!("{}", serde_json::to_string_pretty(&stats)?);
        }

        if has_error {
            return Err(anyhow!(""));
        }

        Ok(())
    }
}

/// In case an error is encountered, prints out the contents of `test_summary` and
/// propagates the error
fn check_test(
    test_result: Result<()>,
    test_summary: &TestSummary,
    json_summary: bool,
) -> Result<()> {
    if let Err(e) = test_result {
        if json_summary {
            let json_summary = serde_json::to_string_pretty(test_summary)
                .expect("Failed to encode summary to JSON");
            println!("{json_summary}");
        } else {
            println!("{test_summary}");
        }

        Err(e)?;
    }

    Ok(())
}

impl Test {
    fn run(self, mut loader: loader::Loader, current_dir: &Path) -> Result<()> {
        let config = Config::load(self.config_path)?;
        let color = env::var("NO_COLOR").map_or(true, |v| v != "1");
        let stat = self.stat.unwrap_or_default();

        loader.debug_build(self.debug_build);
        loader.force_rebuild(self.rebuild || self.grammar_path.is_some());

        let mut parser = Parser::new();

        if self.wasm {
            checked_wasm!({
                let engine = tree_sitter::wasmtime::Engine::default();
                parser
                    .set_wasm_store(tree_sitter::WasmStore::new(&engine).unwrap())
                    .unwrap();
                loader.use_wasm(&engine);
            });
        }

        if self.lib_path.is_none() && self.lang_name.is_some() {
            warn!("--lang-name` specified without --lib-path. This argument will be ignored.");
        }
        let languages = loader.languages_at_path(current_dir)?;
        let language = if let Some(ref lib_path) = self.lib_path {
            let lib_info =
                get_lib_info(self.lib_path.as_ref(), self.lang_name.as_ref(), current_dir);
            &loader
                .select_language(None, current_dir, None, lib_info.as_ref())
                .with_context(|| {
                    anyhow!(
                        "Failed to load language for path \"{}\"",
                        lib_path.display()
                    )
                })?
        } else {
            &languages
                .first()
                .ok_or_else(|| anyhow!("No language found"))?
                .0
        };
        parser.set_language(language)?;

        let test_dir = current_dir.join("test");
        let mut test_summary = TestSummary::new(
            color,
            stat,
            self.update,
            self.overview_only,
            self.json_summary,
        );

        // Run the corpus tests. Look for them in `test/corpus`.
        let test_corpus_dir = test_dir.join("corpus");
        if test_corpus_dir.is_dir() {
            let opts = TestOptions {
                path: test_corpus_dir,
                debug: self.debug,
                debug_graph: self.debug_graph,
                include: self.include,
                exclude: self.exclude,
                file_name: self.file_name,
                update: self.update,
                open_log: self.open_log,
                languages: languages.iter().map(|(l, n)| (n.as_str(), l)).collect(),
                color,
                show_fields: self.show_fields,
                overview_only: self.overview_only,
            };

            check_test(
                test::run_tests_at_path(&mut parser, &opts, &mut test_summary),
                &test_summary,
                self.json_summary,
            )?;
            test_summary.test_num = 1;
        }

        // Check that all of the queries are valid.
        let query_dir = current_dir.join("queries");
        check_test(
            test::check_queries_at_path(language, &query_dir),
            &test_summary,
            self.json_summary,
        )?;
        test_summary.test_num = 1;

        // Run the syntax highlighting tests.
        let test_highlight_dir = test_dir.join("highlight");
        if test_highlight_dir.is_dir() {
            let mut highlighter = Highlighter::new();
            highlighter.parser = parser;
            check_test(
                test_highlight::test_highlights(
                    &loader,
                    &config.get()?,
                    &mut highlighter,
                    &test_highlight_dir,
                    &mut test_summary,
                ),
                &test_summary,
                self.json_summary,
            )?;
            parser = highlighter.parser;
            test_summary.test_num = 1;
        }

        let test_tag_dir = test_dir.join("tags");
        if test_tag_dir.is_dir() {
            let mut tags_context = TagsContext::new();
            tags_context.parser = parser;
            check_test(
                test_tags::test_tags(
                    &loader,
                    &config.get()?,
                    &mut tags_context,
                    &test_tag_dir,
                    &mut test_summary,
                ),
                &test_summary,
                self.json_summary,
            )?;
            test_summary.test_num = 1;
        }

        // For the rest of the queries, find their tests and run them
        for entry in walkdir::WalkDir::new(&query_dir)
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_type().is_file())
        {
            let stem = entry
                .path()
                .file_stem()
                .map(|s| s.to_str().unwrap_or_default())
                .unwrap_or_default();
            if stem != "highlights" && stem != "tags" {
                let entries = walkdir::WalkDir::new(test_dir.join(stem))
                    .into_iter()
                    .filter_map(|e| {
                        let entry = e.ok()?;
                        if entry.file_type().is_file() {
                            Some(entry)
                        } else {
                            None
                        }
                    })
                    .collect::<Vec<_>>();
                if !entries.is_empty() {
                    test_summary.query_results.add_group(stem);
                }

                test_summary.test_num = 1;
                let opts = QueryFileOptions::default();
                for entry in &entries {
                    let path = entry.path();
                    check_test(
                        query::query_file_at_path(
                            language,
                            path,
                            &path.display().to_string(),
                            path,
                            &opts,
                            Some(&mut test_summary),
                        ),
                        &test_summary,
                        self.json_summary,
                    )?;
                }
                if !entries.is_empty() {
                    test_summary.query_results.pop_traversal();
                }
            }
        }
        test_summary.test_num = 1;

        if self.json_summary {
            let json_summary = serde_json::to_string_pretty(&test_summary)
                .expect("Failed to encode test summary to JSON");
            println!("{json_summary}");
        } else {
            println!("{test_summary}");
        }

        Ok(())
    }
}

impl Version {
    fn run(self, current_dir: PathBuf) -> Result<()> {
        Ok(version::Version::new(self.version, current_dir, self.bump).run()?)
    }
}

impl Fuzz {
    fn run(self, mut loader: loader::Loader, current_dir: &Path) -> Result<()> {
        loader.sanitize_build(true);
        loader.force_rebuild(self.rebuild || self.grammar_path.is_some());

        if self.lib_path.is_none() && self.lang_name.is_some() {
            warn!("--lang-name` specified without --lib-path. This argument will be ignored.");
        }
        let languages = loader.languages_at_path(current_dir)?;
        let (language, language_name) = if let Some(ref lib_path) = self.lib_path {
            let lib_info = get_lib_info(Some(lib_path), self.lang_name.as_ref(), current_dir)
                .with_context(|| anyhow!("No language name found for {}", lib_path.display()))?;
            let lang_name = lib_info.1.to_string();
            &(
                loader
                    .select_language(None, current_dir, None, Some(&lib_info))
                    .with_context(|| {
                        anyhow!(
                            "Failed to load language for path \"{}\"",
                            lib_path.display()
                        )
                    })?,
                lang_name,
            )
        } else {
            languages
                .first()
                .ok_or_else(|| anyhow!("No language found"))?
        };

        let mut fuzz_options = FuzzOptions {
            skipped: self.skip,
            subdir: self.subdir,
            edits: self.edits.unwrap_or(*EDIT_COUNT),
            iterations: self.iterations.unwrap_or(*ITERATION_COUNT),
            include: self.include,
            exclude: self.exclude,
            log_graphs: self.log_graphs || *LOG_GRAPH_ENABLED,
            log: self.log || *LOG_ENABLED,
        };

        fuzz_language_corpus(
            language,
            language_name,
            *START_SEED,
            current_dir,
            &mut fuzz_options,
        );
        Ok(())
    }
}

impl Query {
    fn run(self, mut loader: loader::Loader, current_dir: &Path) -> Result<()> {
        let config = Config::load(self.config_path)?;
        let loader_config = config.get()?;
        loader.force_rebuild(self.rebuild || self.grammar_path.is_some());
        loader.find_all_languages(&loader_config)?;
        let query_path = Path::new(&self.query_path);

        let byte_range = parse_range(&self.byte_range, |x| x)?;
        let point_range = parse_range(&self.row_range, |row| Point::new(row, 0))?;
        let containing_byte_range = parse_range(&self.containing_byte_range, |x| x)?;
        let containing_point_range =
            parse_range(&self.containing_row_range, |row| Point::new(row, 0))?;

        let cancellation_flag = util::cancel_on_signal();

        if self.lib_path.is_none() && self.lang_name.is_some() {
            warn!("--lang-name specified without --lib-path. This argument will be ignored.");
        }
        let lib_info = get_lib_info(self.lib_path.as_ref(), self.lang_name.as_ref(), current_dir);

        let input = get_input(
            self.paths_file.as_deref(),
            self.paths,
            self.test_number,
            &cancellation_flag,
        )?;

        match input {
            CliInput::Paths(paths) => {
                let language = loader.select_language(
                    Some(Path::new(&paths[0])),
                    current_dir,
                    self.scope.as_deref(),
                    lib_info.as_ref(),
                )?;

                let opts = QueryFileOptions {
                    ordered_captures: self.captures,
                    byte_range,
                    point_range,
                    containing_byte_range,
                    containing_point_range,
                    quiet: self.quiet,
                    print_time: self.time,
                    stdin: false,
                };
                for path in paths {
                    query::query_file_at_path(
                        &language,
                        &path,
                        &path.display().to_string(),
                        query_path,
                        &opts,
                        None,
                    )?;
                }
            }
            CliInput::Test {
                name,
                contents,
                languages: language_names,
            } => {
                let path = get_tmp_source_file(&contents)?;
                let languages = loader.languages_at_path(current_dir)?;
                let language = if let Some(ref lib_path) = self.lib_path {
                    &loader
                        .select_language(None, current_dir, None, lib_info.as_ref())
                        .with_context(|| {
                            anyhow!(
                                "Failed to load language for path \"{}\"",
                                lib_path.display()
                            )
                        })?
                } else {
                    &languages
                        .iter()
                        .find(|(_, n)| language_names.contains(&Box::from(n.as_str())))
                        .or_else(|| languages.first())
                        .map(|(l, _)| l.clone())
                        .ok_or_else(|| anyhow!("No language found"))?
                };
                let opts = QueryFileOptions {
                    ordered_captures: self.captures,
                    byte_range,
                    point_range,
                    containing_byte_range,
                    containing_point_range,
                    quiet: self.quiet,
                    print_time: self.time,
                    stdin: true,
                };
                query::query_file_at_path(language, &path, &name, query_path, &opts, None)?;
                fs::remove_file(path)?;
            }
            CliInput::Stdin(contents) => {
                // Place user input and query output on separate lines
                println!();

                let path = get_tmp_source_file(&contents)?;
                let language =
                    loader.select_language(None, current_dir, None, lib_info.as_ref())?;
                let opts = QueryFileOptions {
                    ordered_captures: self.captures,
                    byte_range,
                    point_range,
                    containing_byte_range,
                    containing_point_range,
                    quiet: self.quiet,
                    print_time: self.time,
                    stdin: true,
                };
                query::query_file_at_path(&language, &path, "stdin", query_path, &opts, None)?;
                fs::remove_file(path)?;
            }
        }

        Ok(())
    }
}

impl Highlight {
    fn run(self, mut loader: loader::Loader, current_dir: &Path) -> Result<()> {
        let config = Config::load(self.config_path)?;
        let theme_config: tree_sitter_cli::highlight::ThemeConfig = config.get()?;
        loader.configure_highlights(&theme_config.theme.highlight_names);
        let loader_config = config.get()?;
        loader.find_all_languages(&loader_config)?;
        loader.force_rebuild(self.rebuild || self.grammar_path.is_some());
        let languages = loader.languages_at_path(current_dir)?;

        let cancellation_flag = util::cancel_on_signal();

        let (mut language, mut language_configuration) = (None, None);
        if let Some(scope) = self.scope.as_deref() {
            if let Some((lang, lang_config)) = loader.language_configuration_for_scope(scope)? {
                language = Some(lang);
                language_configuration = Some(lang_config);
            }
            if language.is_none() {
                return Err(anyhow!("Unknown scope '{scope}'"));
            }
        }

        let options = HighlightOptions {
            theme: theme_config.theme,
            check: self.check,
            captures_path: self.captures_path,
            inline_styles: !self.css_classes,
            html: self.html,
            quiet: self.quiet,
            print_time: self.time,
            cancellation_flag: cancellation_flag.clone(),
        };

        let input = get_input(
            self.paths_file.as_deref(),
            self.paths,
            self.test_number,
            &cancellation_flag,
        )?;
        match input {
            CliInput::Paths(paths) => {
                let print_name = paths.len() > 1;
                for path in paths {
                    let (language, language_config) =
                        match (language.clone(), language_configuration) {
                            (Some(l), Some(lc)) => (l, lc),
                            _ => {
                                if let Some((lang, lang_config)) =
                                    loader.language_configuration_for_file_name(&path)?
                                {
                                    (lang, lang_config)
                                } else {
                                    warn!(
                                        "{}",
                                        util::lang_not_found_for_path(&path, &loader_config)
                                    );
                                    continue;
                                }
                            }
                        };

                    if let Some(highlight_config) =
                        language_config.highlight_config(language, self.query_paths.as_deref())?
                    {
                        highlight::highlight(
                            &loader,
                            &path,
                            &path.display().to_string(),
                            highlight_config,
                            print_name,
                            &options,
                        )?;
                    } else {
                        warn!(
                            "No syntax highlighting config found for path {}",
                            path.display()
                        );
                    }
                }
            }

            CliInput::Test {
                name,
                contents,
                languages: language_names,
            } => {
                let path = get_tmp_source_file(&contents)?;

                let language = languages
                    .iter()
                    .find(|(_, n)| language_names.contains(&Box::from(n.as_str())))
                    .or_else(|| languages.first())
                    .map(|(l, _)| l.clone())
                    .ok_or_else(|| anyhow!("No language found in current path"))?;
                let language_config = loader
                    .get_language_configuration_in_current_path()
                    .ok_or_else(|| anyhow!("No language configuration found in current path"))?;

                if let Some(highlight_config) =
                    language_config.highlight_config(language, self.query_paths.as_deref())?
                {
                    highlight::highlight(&loader, &path, &name, highlight_config, false, &options)?;
                } else {
                    warn!("No syntax highlighting config found for test {name}");
                }
                fs::remove_file(path)?;
            }

            CliInput::Stdin(contents) => {
                // Place user input and highlight output on separate lines
                println!();

                let path = get_tmp_source_file(&contents)?;

                let (language, language_config) =
                    if let (Some(l), Some(lc)) = (language.clone(), language_configuration) {
                        (l, lc)
                    } else {
                        let language = languages
                            .first()
                            .map(|(l, _)| l.clone())
                            .ok_or_else(|| anyhow!("No language found in current path"))?;
                        let language_configuration = loader
                            .get_language_configuration_in_current_path()
                            .ok_or_else(|| {
                                anyhow!("No language configuration found in current path")
                            })?;
                        (language, language_configuration)
                    };

                if let Some(highlight_config) =
                    language_config.highlight_config(language, self.query_paths.as_deref())?
                {
                    highlight::highlight(
                        &loader,
                        &path,
                        "stdin",
                        highlight_config,
                        false,
                        &options,
                    )?;
                } else {
                    warn!(
                        "No syntax highlighting config found for path {}",
                        current_dir.display()
                    );
                }
                fs::remove_file(path)?;
            }
        }

        Ok(())
    }
}

impl Tags {
    fn run(self, mut loader: loader::Loader, current_dir: &Path) -> Result<()> {
        let config = Config::load(self.config_path)?;
        let loader_config = config.get()?;
        loader.find_all_languages(&loader_config)?;
        loader.force_rebuild(self.rebuild || self.grammar_path.is_some());

        let cancellation_flag = util::cancel_on_signal();

        let (mut language, mut language_configuration) = (None, None);
        if let Some(scope) = self.scope.as_deref() {
            if let Some((lang, lang_config)) = loader.language_configuration_for_scope(scope)? {
                language = Some(lang);
                language_configuration = Some(lang_config);
            }
            if language.is_none() {
                return Err(anyhow!("Unknown scope '{scope}'"));
            }
        }

        let options = TagsOptions {
            scope: self.scope,
            quiet: self.quiet,
            print_time: self.time,
            cancellation_flag: cancellation_flag.clone(),
        };

        let input = get_input(
            self.paths_file.as_deref(),
            self.paths,
            self.test_number,
            &cancellation_flag,
        )?;
        match input {
            CliInput::Paths(paths) => {
                let indent = paths.len() > 1;
                for path in paths {
                    let (language, language_config) =
                        match (language.clone(), language_configuration) {
                            (Some(l), Some(lc)) => (l, lc),
                            _ => {
                                if let Some((lang, lang_config)) =
                                    loader.language_configuration_for_file_name(&path)?
                                {
                                    (lang, lang_config)
                                } else {
                                    warn!(
                                        "{}",
                                        util::lang_not_found_for_path(&path, &loader_config)
                                    );
                                    continue;
                                }
                            }
                        };

                    if let Some(tags_config) = language_config.tags_config(language)? {
                        tags::generate_tags(
                            &path,
                            &path.display().to_string(),
                            tags_config,
                            indent,
                            &options,
                        )?;
                    } else {
                        warn!("No tags config found for path {}", path.display());
                    }
                }
            }

            CliInput::Test {
                name,
                contents,
                languages: language_names,
            } => {
                let path = get_tmp_source_file(&contents)?;

                let languages = loader.languages_at_path(current_dir)?;
                let language = languages
                    .iter()
                    .find(|(_, n)| language_names.contains(&Box::from(n.as_str())))
                    .or_else(|| languages.first())
                    .map(|(l, _)| l.clone())
                    .ok_or_else(|| anyhow!("No language found in current path"))?;
                let language_config = loader
                    .get_language_configuration_in_current_path()
                    .ok_or_else(|| anyhow!("No language configuration found in current path"))?;

                if let Some(tags_config) = language_config.tags_config(language)? {
                    tags::generate_tags(&path, &name, tags_config, false, &options)?;
                } else {
                    warn!("No tags config found for test {name}");
                }
                fs::remove_file(path)?;
            }

            CliInput::Stdin(contents) => {
                // Place user input and tags output on separate lines
                println!();

                let path = get_tmp_source_file(&contents)?;

                let (language, language_config) =
                    if let (Some(l), Some(lc)) = (language.clone(), language_configuration) {
                        (l, lc)
                    } else {
                        let languages = loader.languages_at_path(current_dir)?;
                        let language = languages
                            .first()
                            .map(|(l, _)| l.clone())
                            .ok_or_else(|| anyhow!("No language found in current path"))?;
                        let language_configuration = loader
                            .get_language_configuration_in_current_path()
                            .ok_or_else(|| {
                                anyhow!("No language configuration found in current path")
                            })?;
                        (language, language_configuration)
                    };

                if let Some(tags_config) = language_config.tags_config(language)? {
                    tags::generate_tags(&path, "stdin", tags_config, false, &options)?;
                } else {
                    warn!("No tags config found for path {}", current_dir.display());
                }
                fs::remove_file(path)?;
            }
        }

        Ok(())
    }
}

impl Playground {
    fn run(self, current_dir: &Path) -> Result<()> {
        let grammar_path = self.grammar_path.as_deref().map_or(current_dir, Path::new);

        if let Some(export_path) = self.export {
            playground::export(grammar_path, &export_path)?;
        } else {
            let open_in_browser = !self.quiet;
            playground::serve(grammar_path, open_in_browser)?;
        }

        Ok(())
    }
}

impl DumpLanguages {
    fn run(self, mut loader: loader::Loader) -> Result<()> {
        let config = Config::load(self.config_path)?;
        let loader_config = config.get()?;
        loader.find_all_languages(&loader_config)?;
        for (configuration, language_path) in loader.get_all_language_configurations() {
            info!(
                concat!(
                    "name: {}\n",
                    "scope: {}\n",
                    "parser: {:?}\n",
                    "highlights: {:?}\n",
                    "file_types: {:?}\n",
                    "content_regex: {:?}\n",
                    "injection_regex: {:?}\n",
                ),
                configuration.language_name,
                configuration.scope.as_ref().unwrap_or(&String::new()),
                language_path,
                configuration.highlights_filenames,
                configuration.file_types,
                configuration.content_regex,
                configuration.injection_regex,
            );
        }
        Ok(())
    }
}

impl Complete {
    fn run(self, cli: &mut Command) {
        let name = cli.get_name().to_string();
        let mut stdout = std::io::stdout();

        match self.shell {
            Shell::Bash => generate(clap_complete::shells::Bash, cli, &name, &mut stdout),
            Shell::Elvish => generate(clap_complete::shells::Elvish, cli, &name, &mut stdout),
            Shell::Fish => generate(clap_complete::shells::Fish, cli, &name, &mut stdout),
            Shell::PowerShell => {
                generate(clap_complete::shells::PowerShell, cli, &name, &mut stdout);
            }
            Shell::Zsh => generate(clap_complete::shells::Zsh, cli, &name, &mut stdout),
            Shell::Nushell => generate(clap_complete_nushell::Nushell, cli, &name, &mut stdout),
        }
    }
}

fn main() {
    let result = run();
    if let Err(err) = &result {
        // Ignore BrokenPipe errors
        if let Some(error) = err.downcast_ref::<std::io::Error>() {
            if error.kind() == std::io::ErrorKind::BrokenPipe {
                return;
            }
        }
        if !err.to_string().is_empty() {
            error!("{err:?}");
        }
        std::process::exit(1);
    }
}

fn run() -> Result<()> {
    logger::init();

    let version = BUILD_SHA.map_or_else(
        || BUILD_VERSION.to_string(),
        |build_sha| format!("{BUILD_VERSION} ({build_sha})"),
    );

    let cli = Command::new("tree-sitter")
        .help_template(concat!(
            "\n",
            "{before-help}{name} {version}\n",
            "{author-with-newline}{about-with-newline}\n",
            "{usage-heading} {usage}\n",
            "\n",
            "{all-args}{after-help}\n",
            "\n"
        ))
        .version(version)
        .subcommand_required(true)
        .arg_required_else_help(true)
        .disable_help_subcommand(true)
        .disable_colored_help(false);
    let mut cli = Commands::augment_subcommands(cli);

    let command = Commands::from_arg_matches(&cli.clone().get_matches())?;

    let current_dir = match &command {
        Commands::Init(Init { grammar_path, .. })
        | Commands::Parse(Parse { grammar_path, .. })
        | Commands::Test(Test { grammar_path, .. })
        | Commands::Version(Version { grammar_path, .. })
        | Commands::Fuzz(Fuzz { grammar_path, .. })
        | Commands::Query(Query { grammar_path, .. })
        | Commands::Highlight(Highlight { grammar_path, .. })
        | Commands::Tags(Tags { grammar_path, .. })
        | Commands::Playground(Playground { grammar_path, .. }) => grammar_path,
        Commands::Build(_)
        | Commands::Generate(_)
        | Commands::InitConfig(_)
        | Commands::DumpLanguages(_)
        | Commands::Complete(_) => &None,
    }
    .as_ref()
    .map_or_else(|| env::current_dir().unwrap(), |p| p.clone());

    let loader = loader::Loader::new()?;

    match command {
        Commands::InitConfig(_) => InitConfig::run()?,
        Commands::Init(init_options) => init_options.run(&current_dir)?,
        Commands::Generate(generate_options) => generate_options.run(loader, &current_dir)?,
        Commands::Build(build_options) => build_options.run(loader, &current_dir)?,
        Commands::Parse(parse_options) => parse_options.run(loader, &current_dir)?,
        Commands::Test(test_options) => test_options.run(loader, &current_dir)?,
        Commands::Version(version_options) => version_options.run(current_dir)?,
        Commands::Fuzz(fuzz_options) => fuzz_options.run(loader, &current_dir)?,
        Commands::Query(query_options) => query_options.run(loader, &current_dir)?,
        Commands::Highlight(highlight_options) => highlight_options.run(loader, &current_dir)?,
        Commands::Tags(tags_options) => tags_options.run(loader, &current_dir)?,
        Commands::Playground(playground_options) => playground_options.run(&current_dir)?,
        Commands::DumpLanguages(dump_options) => dump_options.run(loader)?,
        Commands::Complete(complete_options) => complete_options.run(&mut cli),
    }

    Ok(())
}

#[must_use]
const fn get_styles() -> clap::builder::Styles {
    clap::builder::Styles::styled()
        .usage(
            Style::new()
                .bold()
                .fg_color(Some(Color::Ansi(AnsiColor::Yellow))),
        )
        .header(
            Style::new()
                .bold()
                .fg_color(Some(Color::Ansi(AnsiColor::Yellow))),
        )
        .literal(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Green))))
        .invalid(
            Style::new()
                .bold()
                .fg_color(Some(Color::Ansi(AnsiColor::Red))),
        )
        .error(
            Style::new()
                .bold()
                .fg_color(Some(Color::Ansi(AnsiColor::Red))),
        )
        .valid(
            Style::new()
                .bold()
                .fg_color(Some(Color::Ansi(AnsiColor::Green))),
        )
        .placeholder(Style::new().fg_color(Some(Color::Ansi(AnsiColor::White))))
}

/// Utility to extract the shared library path and language function name from user-provided
/// arguments if present.
fn get_lib_info<'a>(
    lib_path: Option<&'a PathBuf>,
    language_name: Option<&'a String>,
    current_dir: &Path,
) -> Option<(PathBuf, &'a str)> {
    if let Some(lib_path) = lib_path {
        let absolute_lib_path = if lib_path.is_absolute() {
            lib_path.clone()
        } else {
            current_dir.join(lib_path)
        };
        // Use the user-specified name if present, otherwise try to derive it from
        // the lib path
        match (
            language_name.map(|s| s.as_str()),
            lib_path.file_stem().and_then(|s| s.to_str()),
        ) {
            (Some(name), _) | (None, Some(name)) => Some((absolute_lib_path, name)),
            _ => None,
        }
    } else {
        None
    }
}

/// Parse a range string of the form "start:end" into an optional Range<T>.
fn parse_range<T>(
    range_str: &Option<String>,
    make: impl Fn(usize) -> T,
) -> Result<Option<std::ops::Range<T>>> {
    if let Some(range) = range_str.as_ref() {
        let err_msg = format!("Invalid range '{range}', expected 'start:end'");
        let mut parts = range.split(':');

        let Some(part) = parts.next() else {
            Err(anyhow!(err_msg))?
        };
        let Ok(start) = part.parse::<usize>() else {
            Err(anyhow!(err_msg))?
        };

        let Some(part) = parts.next() else {
            Err(anyhow!(err_msg))?
        };
        let Ok(end) = part.parse::<usize>() else {
            Err(anyhow!(err_msg))?
        };

        Ok(Some(make(start)..make(end)))
    } else {
        Ok(None)
    }
}