treesitter-lang 1.0.1

Generate Tree-sitter grammars (grammar.js and grammar.json) and corpus tests from Rust.
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
# treesitter-lang — API Reference

> Complete reference for every public item in `treesitter-lang`, with examples.
> **Status: stable (1.0).** The surface below is the `1.0` contract; it follows
> [Semantic Versioning](#stability) and will not change in a breaking way before
> `2.0`. See [`../dev/ROADMAP.md`](../dev/ROADMAP.md).

<sub>Copyright &copy; 2026 <strong>James Gober</strong>.</sub>

## Table of contents

- [Overview](#overview)
- [Installation](#installation)
- [Quick start](#quick-start)
- [Concepts](#concepts)
  - [From Rust to tree-sitter](#from-rust-to-tree-sitter)
  - [Rules, names, and the start rule](#rules-names-and-the-start-rule)
  - [Tokens and extras](#tokens-and-extras)
  - [What validation checks](#what-validation-checks)
  - [Corpus tests from your own parser](#corpus-tests-from-your-own-parser)
- [`Rule`](#rule)
  - [`Rule::symbol`](#rulesymbol)
  - [`Rule::string`](#rulestring)
  - [`Rule::pattern`](#rulepattern)
  - [`Rule::blank`](#ruleblank)
  - [`Rule::seq`](#ruleseq)
  - [`Rule::choice`](#rulechoice)
  - [`Rule::optional`](#ruleoptional)
  - [`Rule::repeat`](#rulerepeat)
  - [`Rule::repeat1`](#rulerepeat1)
  - [`Rule::field`](#rulefield)
  - [`Rule::alias`](#rulealias)
  - [`Rule::token`](#ruletoken)
  - [`Rule::immediate`](#ruleimmediate)
  - [`Rule::prec`](#ruleprec)
  - [`Rule::prec_left`](#ruleprec_left)
  - [`Rule::prec_right`](#ruleprec_right)
  - [`Rule::prec_dynamic`](#ruleprec_dynamic)
- [`Grammar`](#grammar)
  - [`Grammar::new`](#grammarnew)
  - [`Grammar::rule`](#grammarrule)
  - [`Grammar::extra`](#grammarextra)
  - [`Grammar::external`](#grammarexternal)
  - [`Grammar::supertype`](#grammarsupertype)
  - [`Grammar::inline`](#grammarinline)
  - [`Grammar::conflict`](#grammarconflict)
  - [`Grammar::word`](#grammarword)
  - [`Grammar::to_js`](#grammarto_js)
  - [`Grammar::write_js`](#grammarwrite_js)
  - [`Grammar::to_json`](#grammarto_json)
  - [`Grammar::write_json`](#grammarwrite_json)
  - [`Grammar::sexp`](#grammarsexp)
  - [`Grammar::write_sexp`](#grammarwrite_sexp)
- [`Error`](#error)
- [Re-export: `syntax_lang`](#re-export-syntax_lang)
- [Feature flags](#feature-flags)
- [Guide: generating a grammar package](#guide-generating-a-grammar-package)
- [Guide: corpus tests from a hand-written parser](#guide-corpus-tests-from-a-hand-written-parser)
- [Stability](#stability)

---

## Overview

treesitter-lang builds [tree-sitter](https://tree-sitter.github.io/) grammars
in Rust. A [`Grammar`](#grammar) is a list of named [`Rule`](#rule)s plus
tree-sitter's grammar-level settings; it validates itself and emits
`grammar.js` or `grammar.json`, the input `tree-sitter generate` turns into a
parser. [`Grammar::sexp`](#grammarsexp) goes the other way: it renders a
[`syntax_lang::Node`](https://docs.rs/syntax-lang) tree the way tree-sitter
prints its own trees, so the trees a hand-written parser builds become
tree-sitter corpus tests.

| Item | Role |
|---|---|
| [`Rule`](#rule) | One rule expression: tree-sitter's rule language, one constructor per DSL function. |
| [`Grammar`](#grammar) | The named rules and grammar settings; validates and emits, and renders trees. |
| [`Error`](#error) | What validation found, or why a tree could not be rendered. |
| [`syntax_lang`](#re-export-syntax_lang) | The concrete-syntax-tree crate `sexp` reads, re-exported. |

The crate has one dependency, [`syntax-lang`](https://crates.io/crates/syntax-lang),
is `no_std`-compatible (it needs only `alloc`), and contains no `unsafe` code.

---

## Installation

```toml
[dependencies]
treesitter-lang = "1"
```

Or from the terminal:

```bash
cargo add treesitter-lang
```

A grammar is usually generated by a build step or a small program — an
example, an `xtask`, or a test that writes the files — so the crate can just
as well be a dev-dependency:

```toml
[dev-dependencies]
treesitter-lang = "1"
```

MSRV: Rust 1.85 (Rust 2024 edition).

---

## Quick start

Describe the language, emit `grammar.js`, and hand it to tree-sitter:

```rust
use treesitter_lang::{Grammar, Rule};

let e = || Rule::symbol("_expression");
let grammar = Grammar::new("calc")
    .rule("source_file", Rule::repeat(e()))
    .rule("_expression", Rule::choice([
        Rule::symbol("number"),
        Rule::symbol("sum"),
        Rule::symbol("product"),
    ]))
    .rule("sum", Rule::prec_left(1, Rule::seq([
        Rule::field("left", e()),
        Rule::string("+"),
        Rule::field("right", e()),
    ])))
    .rule("product", Rule::prec_left(2, Rule::seq([
        Rule::field("left", e()),
        Rule::string("*"),
        Rule::field("right", e()),
    ])))
    .rule("number", Rule::pattern(r"\d+"));

let js = grammar.to_js()?;
assert!(js.contains("    sum: $ => prec.left(1, seq(\n"));
// std::fs::write("tree-sitter-calc/grammar.js", js)?;
// then, in tree-sitter-calc/: tree-sitter generate
# Ok::<(), treesitter_lang::Error>(())
```

`to_js` produces the file a grammar author would have written by hand:

```js
/// <reference types="tree-sitter-cli/dsl" />
// @ts-check

module.exports = grammar({
  name: 'calc',

  rules: {
    source_file: $ => repeat($._expression),

    _expression: $ => choice($.number, $.sum, $.product),

    sum: $ => prec.left(1, seq(
      field('left', $._expression),
      '+',
      field('right', $._expression),
    )),

    product: $ => prec.left(2, seq(
      field('left', $._expression),
      '*',
      field('right', $._expression),
    )),

    number: $ => /\d+/,
  },
});
```

---

## Concepts

### From Rust to tree-sitter

Tree-sitter grammars are written in a small JavaScript DSL, `grammar.js`.
`tree-sitter generate` evaluates it into `src/grammar.json`, then compiles
that into a C parser. treesitter-lang produces either file:

| Output | Use it when |
|---|---|
| [`to_js`](#grammarto_js) — `grammar.js` | The grammar lives in a repository and is read, reviewed, and published like any tree-sitter grammar. |
| [`to_json`](#grammarto_json) — `grammar.json` | A build generates the parser directly, with no JavaScript runtime: `tree-sitter generate grammar.json`. |

The two agree exactly: both produce the same `parser.c`, and with
tree-sitter 0.25 or later the `grammar.json` this crate emits is
byte-identical to the `src/grammar.json` tree-sitter writes when it generates
from the emitted `grammar.js`. The CI suite checks this against the real
tree-sitter CLI on every change.

| tree-sitter | `grammar.json` loads | Same parser from both formats | `grammar.json` byte-identical |
|---|:---:|:---:|:---:|
| 0.25 – 0.27 | yes | yes | yes |
| 0.24 | yes | yes | all but the final, empty `reserved` field |
| 0.20, 0.22 | yes | not checked | — |

0.27 is checked in CI; the older versions were checked when the 0.2 release
was prepared.

Writing the grammar in Rust buys three things over writing `grammar.js` by
hand: rules can be generated from the same tables the language's own parser
uses (operator precedence, keyword lists); mistakes are reported by
[validation](#what-validation-checks) before tree-sitter runs; and the
grammar can be checked against the language's real parser through
[corpus tests](#corpus-tests-from-your-own-parser).

### Rules, names, and the start rule

A grammar is an ordered list of named rules. The **first rule is the start
rule**: every tree has it at the root. Names are identifiers — an ASCII letter
or `_`, then letters, digits, and `_` — and by tree-sitter convention
`snake_case`.

A name's first character decides how the rule's nodes appear in the tree:

| Name | Node in the tree |
|---|---|
| `expression` | Visible: a named node, `(expression ...)`. |
| `_expression` | Hidden: the rule matches as usual, but its node is left out and its children take its place. |

Hidden rules hold structure that is useful for writing the grammar but noise
in the tree — a choice between expression kinds, a list's separators. The
start rule must be visible.

Strings inside a rule (`Rule::string("+")`) become *anonymous* nodes: they
are in the tree, but tree-sitter's S-expressions leave them out. A rule whose
whole body is a string, pattern, or token is a *named token* and shows up as
`(name)`.

### Tokens and extras

Tree-sitter lexes text into tokens and parses tokens into trees. Every string
and pattern is a token. Between tokens, tree-sitter skips **extras** —
whitespace by default. [`Grammar::extra`](#grammarextra) sets them: usually
whitespace and a `comment` rule, which then appears in the tree wherever it
occurs.

Because extras may appear between any two tokens, `Rule::seq([a, b])` also
matches `a b` and `a /* comment */ b`. To match text with nothing in between,
make it one token: [`Rule::token`](#ruletoken) lexes its whole content as a
single token, and [`Rule::immediate`](#ruleimmediate) makes a token that
must follow the previous one directly.

### What validation checks

[`to_js`](#grammarto_js), [`to_json`](#grammarto_json), and their `write_`
forms validate the grammar first and refuse to emit one tree-sitter would
refuse — or, in a few cases, crash or hang on — returning the first problem
found as an [`Error`](#error):

| Check | Error |
|---|---|
| The grammar, rules, externals, fields, and aliases have identifier names; no rule or external is called `__proto__`. | [`InvalidName`](#error) |
| The grammar has at least one rule. | [`NoRules`](#error) |
| The start rule is visible. | [`HiddenStart`](#error) |
| No two rules share a name. | [`DuplicateRule`](#error) |
| Every symbol names a rule or an external — in rules, extras, `word`, `conflicts`, `inline`, and `supertypes`. | [`UndefinedSymbol`](#error) |
| No pattern is empty, and no string in a reachable rule. Every pattern is a regular expression JavaScript accepts, and — in reachable rules and the extras — one tree-sitter's own regular expression parser accepts (see [accepted patterns](#accepted-patterns)). | [`EmptyString`](#error) |
| No choice is empty. | [`EmptyChoice`](#error) |
| No symbol appears inside a token, or inside an extra that is not a lone symbol. | [`SymbolInToken`](#error) |
| No reachable rule that another rule (or an extra) refers to, and nothing a reachable `repeat` repeats, can match the empty string. | [`MatchesEmpty`](#error) |
| No reachable rules form a cycle in which each can be just the next, and no hidden rule is itself under a non-zero precedence (tree-sitter loops forever on it). | [`IndirectRecursion`](#error) |
| The word rule is a token. | [`WordNotToken`](#error) |
| A rule sharing an external's name is a token. | [`InvalidExternal`](#error) |
| An inlined rule is not the start rule, a token, or recursive through inlined rules alone. | [`InvalidInline`](#error) |
| A reachable supertype is not a token, is never itself, and produces a single node in each alternative. | [`InvalidSupertype`](#error) |

Two ideas from tree-sitter run through the table:

- **Reachability.** Tree-sitter drops rules that cannot be reached from the
  start rule or the extras before it builds the parser, so the checks that
  depend on how rules are used — empty strings, empty matches, cycles,
  supertype shapes, and tree-sitter's parse of each pattern — apply only to
  reachable rules. The checks `grammar.js` itself would trip on (names,
  symbols, tokens, JavaScript's parse of each pattern) apply to every rule.
- **Token rules.** A rule whose whole body is a string, a pattern, a
  [`token`](#ruletoken), or an [`immediate`](#ruleimmediate) token becomes a
  token of its own — unless it is the start rule, or another reachable rule
  uses the identical token (tree-sitter merges the two, and `token('x')` is
  the same token as `'x'`), or it is hidden (or a supertype) and its token is
  a bare string literal, which tree-sitter treats as that anonymous string.
  The word rule and a rule sharing an external's name must be token rules;
  an inlined rule and a reachable supertype must not.

Each check mirrors tree-sitter's behaviour, probed against its CLI, and the
whole was cross-checked by generating thousands of random grammars and
running each through both validation and `tree-sitter generate`. Some checks
are stricter than tree-sitter, because what they catch is always a mistake:
an empty choice (tree-sitter accepts it silently), an `inline` entry naming
no rule (tree-sitter only warns), and empty patterns and empty strings inside
tokens (tree-sitter accepts some, but they can only match nothing).

Validation does not build parse tables. What tree-sitter finds while building
them is reported by `tree-sitter generate`: ambiguities, which it explains by
naming the rules involved — resolve them with [precedence](#ruleprec) or
declare them with [`Grammar::conflict`](#grammarconflict) — and extras built
from rules whose end it cannot tell.

### Corpus tests from your own parser

Tree-sitter tests a grammar with *corpus files*: samples of source text, each
followed by the tree the parser should build, written as an S-expression.

```text
==================
Sum
==================

1 + 2

---

(source_file
  (sum
    (number)
    (number)))
```

A language built with the `-lang` family already has a parser that builds
[`syntax_lang::Node`](https://docs.rs/syntax-lang) trees. Name its node and
token kinds after the grammar's rules, and [`Grammar::sexp`](#grammarsexp)
renders its trees as the S-expressions above. Feed it the language's test
samples and write the results as corpus files: `tree-sitter test` then checks
the generated parser against the hand-written one, and a change to either
that makes them disagree fails the test. The
[guide below](#guide-corpus-tests-from-a-hand-written-parser) walks through
it.

---

## `Rule`

```rust,ignore
#[derive(Clone, Debug)]
pub struct Rule(/* private */);
```

A rule expression: what one rule of a grammar matches. Each constructor
corresponds to one function of tree-sitter's `grammar.js` DSL:

| Constructor | `grammar.js` | Matches |
|---|---|---|
| [`symbol`](#rulesymbol) | `$.name` | The rule (or external token) called `name`. |
| [`string`](#rulestring) | `'text'` | The exact text. |
| [`pattern`](#rulepattern) | `/regex/` | Text matching a regular expression. |
| [`blank`](#ruleblank) | `blank()` | Nothing. |
| [`seq`](#ruleseq) | `seq(a, b)` | Each rule in order. |
| [`choice`](#rulechoice) | `choice(a, b)` | Any one of the rules. |
| [`optional`](#ruleoptional) | `optional(a)` | The rule, or nothing. |
| [`repeat`](#rulerepeat) | `repeat(a)` | The rule zero or more times. |
| [`repeat1`](#rulerepeat1) | `repeat1(a)` | The rule one or more times. |
| [`field`](#rulefield) | `field('name', a)` | The rule, labelled as a field of its parent. |
| [`alias`](#rulealias) | `alias(a, $.name)` | The rule, appearing in the tree as `name`. |
| [`token`](#ruletoken) | `token(a)` | The rule, lexed as one token. |
| [`immediate`](#ruleimmediate) | `token.immediate(a)` | One token, with nothing before it. |
| [`prec`](#ruleprec), [`prec_left`](#ruleprec_left), [`prec_right`](#ruleprec_right), [`prec_dynamic`](#ruleprec_dynamic) | `prec(n, a)`, `prec.left`, `prec.right`, `prec.dynamic` | The rule, with a precedence. |

Rules are plain values. Build them, keep them in variables, and clone a piece
to use it in several places. Nothing is checked until the grammar is emitted,
so a rule may name a symbol defined later. Text arguments take
`impl Into<Cow<'static, str>>`: a string literal is stored without copying,
and a `String` built at run time is taken as is.

`Clone` and `Debug` recurse into nested rules, so a rule nested tens of
thousands of levels deep can exhaust the stack in them. Dropping, validating,
and emitting a rule are iterative and safe at any depth.

```rust
use treesitter_lang::{Grammar, Rule};

// A helper that builds a reusable rule shape.
fn comma_separated(item: Rule) -> Rule {
    Rule::seq([
        item.clone(),
        Rule::repeat(Rule::seq([Rule::string(","), item])),
    ])
}

let js = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::symbol("list")))
    .rule("list", Rule::seq([
        Rule::string("["),
        Rule::optional(comma_separated(Rule::symbol("number"))),
        Rule::string("]"),
    ]))
    .rule("number", Rule::pattern(r"\d+"))
    .to_js()?;
assert!(js.contains("optional(seq(\n        $.number,\n        repeat(seq(',', $.number)),\n      )),"));
# Ok::<(), treesitter_lang::Error>(())
```

### `Rule::symbol`

```rust,ignore
pub fn symbol(name: impl Into<Cow<'static, str>>) -> Rule
```

A reference to another rule, or to an external token, by name. Emitted as
`$.name`. Names are resolved when the grammar is emitted, so rules may refer
to each other in any order, including recursively. A name starting with `_`
refers to a hidden rule.

| Parameter | Meaning |
|---|---|
| `name` | The rule's name. A string literal is not copied; a `String` is moved in. |

An undefined name is reported as [`Error::UndefinedSymbol`](#error) when the
grammar is emitted.

```rust
use treesitter_lang::{Grammar, Rule};

// Recursion through a symbol: nested parentheses.
let js = Grammar::new("parens")
    .rule("source_file", Rule::repeat(Rule::symbol("group")))
    .rule("group", Rule::seq([
        Rule::string("("),
        Rule::repeat(Rule::symbol("group")),
        Rule::string(")"),
    ]))
    .to_js()?;
assert!(js.contains("group: $ => seq('(', repeat($.group), ')'),"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Error, Grammar, Rule};

// A typo is caught before tree-sitter runs.
let result = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::symbol("statment")))
    .rule("statement", Rule::string(";"))
    .to_js();
assert_eq!(
    result,
    Err(Error::UndefinedSymbol { symbol: "statment".into(), rule: "source_file".into() }),
);
```

### `Rule::string`

```rust,ignore
pub fn string(text: impl Into<Cow<'static, str>>) -> Rule
```

Exactly this text. Emitted as a single-quoted JavaScript string; quotes,
backslashes, control characters, and the JavaScript line separators U+2028
and U+2029 are escaped, so any text survives into `grammar.js` and back.

| Parameter | Meaning |
|---|---|
| `text` | The literal text. Any characters; must not be empty. |

Inside a larger rule a string is an anonymous token: present in the tree but
left out of S-expressions. As a rule's whole body it makes a named token. An
empty string is [`Error::EmptyString`](#error).

```rust
use treesitter_lang::{Grammar, Rule};

let js = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::choice([
        Rule::symbol("keyword"),
        Rule::string("it's"),
        Rule::string(r"C:\path"),
    ])))
    .rule("keyword", Rule::string("return"))
    .to_js()?;
assert!(js.contains(r"choice($.keyword, 'it\'s', 'C:\\path')"));
assert!(js.contains("keyword: $ => 'return',"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Grammar, Rule};

// Text built at run time.
let operators: Vec<String> = ["+", "-", "*"].iter().map(|s| s.to_string()).collect();
let js = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::choice(operators.into_iter().map(Rule::string))))
    .to_js()?;
assert!(js.contains("choice('+', '-', '*')"));
# Ok::<(), treesitter_lang::Error>(())
```

### `Rule::pattern`

```rust,ignore
pub fn pattern(regex: impl Into<Cow<'static, str>>) -> Rule
```

Text matching a regular expression, written as the source of a JavaScript
regular expression — what goes between the slashes of `/.../`. Use a raw
string (`r"\d+"`) so backslashes need no doubling. A `/` is written as `\/`
and a control character as `\n`, `\r`, `\t`, or `\xHH`, so the pattern fits
in a `/.../` literal; the regular expression is unchanged. `grammar.json`
records the pattern the same way, as tree-sitter would.

| Parameter | Meaning |
|---|---|
| `regex` | The pattern source; must not be empty, and must be one of the [accepted patterns](#accepted-patterns). |

An empty or invalid pattern is [`Error::EmptyString`](#error); for an invalid
one the error names the rule, says what is wrong, and gives the byte offset
in the pattern.

#### Accepted patterns

A pattern passes through two parsers on its way into a lexer, and validation
holds it to both:

1. **JavaScript.** `grammar.js` holds the pattern as a `/.../` literal with
   no flags, which the runtime that loads the file — Node.js, or
   tree-sitter's built-in QuickJS with `--js-runtime native` — parses under
   the web-compatible grammar of ECMAScript Annex B (B.1.2). This applies to
   every pattern, in every rule and extra: `grammar.js` evaluates them all.
2. **tree-sitter.** Tree-sitter reads the literal's source back, rewrites
   `\w`, `\s`, `\d`, `\W`, `\S`, and `\D` into bracketed classes — textually,
   so `\\D` becomes `\[^0-9]` — parses the result with the Rust
   `regex-syntax` crate (0.8), and refuses any assertion left in it. This
   applies to the patterns of rules reachable from the start rule and of the
   extras; tree-sitter never reads the others.

The two grammars differ, so the accepted patterns are those both accept. The
pattern then *means* what regex-syntax makes of it: JavaScript's reading only
decides whether `grammar.js` loads.

| Construct | Accepted | Refused |
|---|---|---|
| Characters | Any character. `/`, control characters, and line separators are escaped for you. | — |
| Escapes | `\` before any ASCII punctuation or space; `\t` `\n` `\r` `\f` `\v` `\a`; `\xHH`, `\uHHHH`, `\UHHHHHHHH`, `\x{H…}`, `\u{H…}` naming a Unicode scalar value; `\d` `\w` `\s` `\D` `\W` `\S`; `\p{…}`, `\pL`, `\P{…}`. | `\0`–`\9` (backreferences and octal escapes), `\c`, `\k`, `\e`, and other letters regex-syntax does not define; `\` before a non-ASCII character; surrogate escapes (`\uD83D`); `\p{}`. |
| Classes | `[…]` and `[^…]`; ranges in order; a leading `]` (`[]a]`) or `-`; nested classes, `&&`, `--`, and `~~` (regex-syntax set operations, which JavaScript reads as plain characters); `[:alpha:]` and the other ASCII classes inside a class. | A class unclosed in either reading (`[[a]` is closed for JavaScript but not for regex-syntax); a range out of order, by code point for regex-syntax and by UTF-16 code unit for JavaScript (`[😀-😁]`); a range ending in a class (`[a-\pL]`) or an assertion; `[]` and `[^]`. |
| Groups | `(…)`, `(?:…)`, `(?<name>…)` with a name of ASCII letters, digits, and `_`, not starting with a digit; modifier groups `(?i:…)`, `(?m:…)`, `(?s:…)`, `(?i-s:…)`. | Look-ahead and look-behind; `(?P<name>…)`; flags without a group, `(?i)`; repeated or empty names; unclosed or unmatched parentheses. |
| Repetition | `*`, `+`, `?`, `{n}`, `{n,}`, `{n,m}` with `n ≤ m < 2³²`, spaces allowed around the numbers, each optionally lazy (`?`). | A quantifier with nothing to repeat — at the start, after `(` or `\|`, after an assertion, or after another quantifier (`a**`, `\x{41}{2}`, which JavaScript reads as `x` repeated 41 times, then repeated again); a `{` that is not a whole quantifier (`{`, `a{`, `a{,3}`). |
| Assertions | Only inside a repetition of exactly zero, `(?:^){0}`, which compiles to nothing. | `^`, `$`, `\b`, `\B`, `\A`, `\z`, `\<`, `\>`, `\b{start}` and the other word boundaries. |
| Nesting | Up to 250 levels, as regex-syntax counts them: groups, repetitions, alternations, concatenations of two or more, classes and class operations. | Deeper. |

What validation does not check, all reported by `tree-sitter generate` or
the JavaScript runtime as before:

- The property names in `\p{…}` and `\P{…}`; regex-syntax knows them from
  Unicode tables this crate does not carry.
- Whether a non-ASCII character in a group name is a JavaScript identifier
  character (`ID_Start`, `ID_Continue`).
- Repeated group names in rules tree-sitter drops, where only JavaScript
  reads them: ES2025 allows repeats in different alternatives, and engines
  differ on exactly where.
- How long tree-sitter takes to expand a large counted repetition into its
  lexer: `a{100000}` is accepted, and takes tree-sitter a long time.
- Runtime differences in the JavaScript checked against: modifier groups
  (`(?i:…)`) are ES2025, verified with Node.js 24 — tree-sitter 0.27's
  QuickJS runtime refuses them, as may older Node.js releases.

Whatever a pattern holds, the literal `grammar.js` writes for it ends at its
own closing slash: a `[` that would open a character class running past the
end of the pattern is written `\[`, and an empty pattern or one starting
with `*` as `new RegExp('…')`. Validation refuses all of these first, so
valid patterns are written unchanged; this is a second line of defence.

```rust
use treesitter_lang::{Grammar, Rule};

let js = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::choice([
        Rule::symbol("float"),
        Rule::symbol("path"),
    ])))
    .rule("float", Rule::pattern(r"\d+\.\d+([eE][+-]?\d+)?"))
    .rule("path", Rule::pattern("[a-z]+(/[a-z]+)*"))
    .to_js()?;
assert!(js.contains(r"float: $ => /\d+\.\d+([eE][+-]?\d+)?/,"));
assert!(js.contains(r"path: $ => /[a-z]+(\/[a-z]+)*/,"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Grammar, Rule};

// grammar.json records what grammar.js holds between the slashes.
let json = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::pattern("a/b")))
    .to_json()?;
assert!(json.contains(r#""value": "a\\/b""#));
# Ok::<(), treesitter_lang::Error>(())
```

### `Rule::blank`

```rust,ignore
pub const fn blank() -> Rule
```

Matches nothing. Emitted as `blank()`. [`optional`](#ruleoptional) is
`choice(rule, blank())`; use `blank` directly for an explicit empty
alternative.

```rust
use treesitter_lang::{Grammar, Rule};

let js = Grammar::new("demo")
    .rule("source_file", Rule::seq([
        Rule::choice([Rule::string("+"), Rule::string("-"), Rule::blank()]),
        Rule::pattern(r"\d+"),
    ]))
    .to_js()?;
assert!(js.contains("choice('+', '-', blank())"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::Rule;

// `blank` is `const`, so it can initialize a constant.
const NOTHING: Rule = Rule::blank();
let _maybe_sign = Rule::choice([Rule::string("-"), NOTHING]);
```

### `Rule::seq`

```rust,ignore
pub fn seq(rules: impl IntoIterator<Item = Rule>) -> Rule
```

Each rule in order. [Extras](#tokens-and-extras) may appear between the
parts; to forbid that, wrap the sequence in [`token`](#ruletoken). An empty
sequence matches nothing: it is [`blank`](#ruleblank), and is emitted as
`blank()` (tree-sitter refuses an empty `seq()` inside a token, but not
`blank()`).

| Parameter | Meaning |
|---|---|
| `rules` | The parts, in order: an array, a `Vec`, or any iterator of rules. |

Short sequences of simple parts are emitted on one line; longer ones put each
part on its own line.

```rust
use treesitter_lang::{Grammar, Rule};

let js = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::symbol("assignment")))
    .rule("assignment", Rule::seq([
        Rule::field("name", Rule::symbol("identifier")),
        Rule::string("="),
        Rule::field("value", Rule::symbol("identifier")),
        Rule::string(";"),
    ]))
    .rule("identifier", Rule::pattern("[a-z]+"))
    .to_js()?;
assert!(js.contains("    assignment: $ => seq(\n      field('name', $.identifier),\n"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Grammar, Rule};

// Parts built from data: a fixed keyword sequence.
let words = ["end", "of", "file"];
let js = Grammar::new("demo")
    .rule("source_file", Rule::seq(words.map(Rule::string)))
    .to_js()?;
assert!(js.contains("source_file: $ => seq('end', 'of', 'file'),"));
# Ok::<(), treesitter_lang::Error>(())
```

### `Rule::choice`

```rust,ignore
pub fn choice(rules: impl IntoIterator<Item = Rule>) -> Rule
```

Any one of the rules. Ambiguity between alternatives is settled with
[precedence](#ruleprec) or [declared as a conflict](#grammarconflict). A
choice with no alternatives can never match and is
[`Error::EmptyChoice`](#error).

| Parameter | Meaning |
|---|---|
| `rules` | The alternatives: an array, a `Vec`, or any iterator of rules. At least one. |

```rust
use treesitter_lang::{Grammar, Rule};

let js = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::symbol("_literal")))
    .rule("_literal", Rule::choice([
        Rule::symbol("number"),
        Rule::symbol("boolean"),
    ]))
    .rule("number", Rule::pattern(r"\d+"))
    .rule("boolean", Rule::choice([Rule::string("true"), Rule::string("false")]))
    .to_js()?;
assert!(js.contains("_literal: $ => choice($.number, $.boolean),"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Error, Grammar, Rule};

// Alternatives filtered from a table; an empty result is caught.
let enabled: [&'static str; 0] = [];
let result = Grammar::new("demo")
    .rule("source_file", Rule::choice(enabled.map(Rule::string)))
    .to_js();
assert_eq!(result, Err(Error::EmptyChoice { rule: "source_file".into() }));
```

### `Rule::optional`

```rust,ignore
pub fn optional(rule: Rule) -> Rule
```

The rule, or nothing. The same as `choice([rule, blank()])`, which is how
tree-sitter records it in `grammar.json`; `grammar.js` shows it as
`optional(...)`.

| Parameter | Meaning |
|---|---|
| `rule` | What may be left out. |

A rule that other rules refer to must not be able to match nothing, so an
`optional` that covers a whole rule body belongs at the places that use the
rule instead (see [`Error::MatchesEmpty`](#error)).

```rust
use treesitter_lang::{Grammar, Rule};

let js = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::symbol("call")))
    .rule("call", Rule::seq([
        Rule::pattern("[a-z]+"),
        Rule::string("("),
        Rule::optional(Rule::symbol("arguments")),
        Rule::string(")"),
    ]))
    .rule("arguments", Rule::repeat1(Rule::pattern(r"\d+")))
    .to_js()?;
assert!(js.contains("optional($.arguments)"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Grammar, Rule};

let json = Grammar::new("demo")
    .rule("source_file", Rule::optional(Rule::string("x")))
    .to_json()?;
assert!(json.contains("\"type\": \"CHOICE\""));
assert!(json.contains("\"type\": \"BLANK\""));
# Ok::<(), treesitter_lang::Error>(())
```

### `Rule::repeat`

```rust,ignore
pub fn repeat(rule: Rule) -> Rule
```

The rule zero or more times. Because it can match nothing, it makes the rule
it is in able to match the empty string: right for the start rule, an
[`Error::MatchesEmpty`](#error) in a rule others refer to. Use
[`repeat1`](#rulerepeat1) there.

| Parameter | Meaning |
|---|---|
| `rule` | What repeats. |

```rust
use treesitter_lang::{Grammar, Rule};

let js = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::symbol("line")))
    .rule("line", Rule::seq([Rule::pattern("[^\n]+"), Rule::string("\n")]))
    .to_js()?;
assert!(js.contains("source_file: $ => repeat($.line),"));
assert!(js.contains(r"line: $ => seq(/[^\n]+/, '\n'),"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Error, Grammar, Rule};

// A block may be empty, so its body cannot be a bare `repeat`.
let result = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::symbol("block")))
    .rule("block", Rule::seq([Rule::string("{"), Rule::symbol("body"), Rule::string("}")]))
    .rule("body", Rule::repeat(Rule::pattern("[a-z]+")))
    .to_js();
assert_eq!(result, Err(Error::MatchesEmpty { rule: "body".into() }));
```

### `Rule::repeat1`

```rust,ignore
pub fn repeat1(rule: Rule) -> Rule
```

The rule one or more times.

| Parameter | Meaning |
|---|---|
| `rule` | What repeats. |

```rust
use treesitter_lang::{Grammar, Rule};

// The fix for the empty block above: `body` matches at least one word, and
// the block makes it optional.
let js = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::symbol("block")))
    .rule("block", Rule::seq([
        Rule::string("{"),
        Rule::optional(Rule::symbol("body")),
        Rule::string("}"),
    ]))
    .rule("body", Rule::repeat1(Rule::pattern("[a-z]+")))
    .to_js()?;
assert!(js.contains("body: $ => repeat1(/[a-z]+/),"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Grammar, Rule};

// A non-empty, comma-separated list.
let js = Grammar::new("demo")
    .rule("source_file", Rule::seq([
        Rule::pattern("[a-z]+"),
        Rule::repeat1(Rule::seq([Rule::string(","), Rule::pattern("[a-z]+")])),
    ]))
    .to_js()?;
assert!(js.contains("repeat1(seq(',', /[a-z]+/))"));
# Ok::<(), treesitter_lang::Error>(())
```

### `Rule::field`

```rust,ignore
pub fn field(name: impl Into<Cow<'static, str>>, rule: Rule) -> Rule
```

The rule, labelled as a field of the node it appears in. Fields let a tree
consumer ask for a child by role — "the condition", "the body" — rather than
by position. They do not change what is matched.

| Parameter | Meaning |
|---|---|
| `name` | The field name; an identifier, conventionally `snake_case`. |
| `rule` | The labelled part. |

An invalid name is [`Error::InvalidName`](#error).

```rust
use treesitter_lang::{Grammar, Rule};

let js = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::symbol("if_statement")))
    .rule("if_statement", Rule::seq([
        Rule::string("if"),
        Rule::field("condition", Rule::symbol("identifier")),
        Rule::field("consequence", Rule::symbol("block")),
    ]))
    .rule("block", Rule::seq([Rule::string("{"), Rule::string("}")]))
    .rule("identifier", Rule::pattern("[a-z]+"))
    .to_js()?;
assert!(js.contains("field('condition', $.identifier)"));
assert!(js.contains("field('consequence', $.block)"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Grammar, Rule};

// A field around several children: every child it matches carries the label.
let json = Grammar::new("demo")
    .rule("source_file", Rule::field("items", Rule::repeat(Rule::pattern("[a-z]+"))))
    .to_json()?;
assert!(json.contains("\"type\": \"FIELD\",\n      \"name\": \"items\","));
# Ok::<(), treesitter_lang::Error>(())
```

### `Rule::alias`

```rust,ignore
pub fn alias(rule: Rule, name: impl Into<Cow<'static, str>>) -> Rule
```

The rule, appearing in the tree as a named node called `name`. Use it to give
anonymous syntax a node of its own, or to show a rule under a different name
in one context. The name need not be a rule of the grammar.

| Parameter | Meaning |
|---|---|
| `rule` | What matches. |
| `name` | The node name it appears as; an identifier. |

```rust
use treesitter_lang::{Grammar, Rule};

// `...` gets a named node, `(spread)`.
let js = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::choice([
        Rule::alias(Rule::string("..."), "spread"),
        Rule::pattern("[a-z]+"),
    ])))
    .to_js()?;
assert!(js.contains("alias('...', $.spread)"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Grammar, Rule};

// An identifier that appears as `type_identifier` after a colon.
let js = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::symbol("declaration")))
    .rule("declaration", Rule::seq([
        Rule::symbol("identifier"),
        Rule::string(":"),
        Rule::alias(Rule::symbol("identifier"), "type_identifier"),
    ]))
    .rule("identifier", Rule::pattern("[a-z]+"))
    .to_js()?;
assert!(js.contains("alias($.identifier, $.type_identifier)"));
# Ok::<(), treesitter_lang::Error>(())
```

### `Rule::token`

```rust,ignore
pub fn token(rule: Rule) -> Rule
```

The rule, lexed as a single token: no extras inside it, and one leaf in the
tree for the whole match. The contents may only be strings, patterns, and
combinators over them — a [`symbol`](#rulesymbol) inside a token is
[`Error::SymbolInToken`](#error).

| Parameter | Meaning |
|---|---|
| `rule` | The token's lexical structure. |

```rust
use treesitter_lang::{Grammar, Rule};

// A comment runs to the end of the line, whatever it contains.
let js = Grammar::new("demo")
    .extra(Rule::pattern(r"\s"))
    .extra(Rule::symbol("comment"))
    .rule("source_file", Rule::repeat(Rule::pattern("[a-z]+")))
    .rule("comment", Rule::token(Rule::seq([Rule::string("//"), Rule::pattern(".*")])))
    .to_js()?;
assert!(js.contains("comment: $ => token(seq('//', /.*/)),"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Error, Grammar, Rule};

let result = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::symbol("version")))
    .rule("version", Rule::token(Rule::seq([Rule::symbol("digits"), Rule::string(".")])))
    .rule("digits", Rule::pattern(r"\d+"))
    .to_js();
assert_eq!(
    result,
    Err(Error::SymbolInToken { symbol: "digits".into(), rule: "version".into() }),
);
```

### `Rule::immediate`

```rust,ignore
pub fn immediate(rule: Rule) -> Rule
```

A token that must follow the previous token with nothing — not even an
extra — in between. Emitted as `token.immediate(...)`. The same content
restrictions as [`token`](#ruletoken) apply.

| Parameter | Meaning |
|---|---|
| `rule` | The token's lexical structure. |

```rust
use treesitter_lang::{Grammar, Rule};

// `x.y` is a member access; `x . y` is not.
let js = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::symbol("member")))
    .rule("member", Rule::seq([
        Rule::symbol("identifier"),
        Rule::immediate(Rule::string(".")),
        Rule::immediate(Rule::pattern("[a-z]+")),
    ]))
    .rule("identifier", Rule::pattern("[a-z]+"))
    .to_js()?;
assert!(js.contains("token.immediate('.')"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Grammar, Rule};

// String contents glued to the opening quote.
let json = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::symbol("string")))
    .rule("string", Rule::seq([
        Rule::string("\""),
        Rule::immediate(Rule::pattern("[^\"]*")),
        Rule::string("\""),
    ]))
    .to_json()?;
assert!(json.contains("\"type\": \"IMMEDIATE_TOKEN\""));
# Ok::<(), treesitter_lang::Error>(())
```

### `Rule::prec`

```rust,ignore
pub fn prec(level: i32, rule: Rule) -> Rule
```

The rule with a numeric precedence, emitted as `prec(level, ...)`. When the
parser generator finds two ways to proceed, the one with the higher
precedence wins. Inside a [`token`](#ruletoken), precedence chooses between
tokens that match the same text.

| Parameter | Meaning |
|---|---|
| `level` | The precedence. Higher binds tighter; the default is `0`; negative values are allowed. |
| `rule` | The rule it applies to. |

```rust
use treesitter_lang::{Grammar, Rule};

// Unary minus binds tighter than any binary operator.
let e = || Rule::symbol("_expression");
let js = Grammar::new("demo")
    .rule("source_file", Rule::repeat(e()))
    .rule("_expression", Rule::choice([
        Rule::symbol("number"),
        Rule::symbol("negation"),
        Rule::symbol("difference"),
    ]))
    .rule("negation", Rule::prec(3, Rule::seq([Rule::string("-"), e()])))
    .rule("difference", Rule::prec_left(1, Rule::seq([e(), Rule::string("-"), e()])))
    .rule("number", Rule::pattern(r"\d+"))
    .to_js()?;
assert!(js.contains("negation: $ => prec(3, seq('-', $._expression)),"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Grammar, Rule};

// Lexical precedence: `true` is a keyword even though it matches the
// identifier pattern too.
let js = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::choice([
        Rule::symbol("boolean"),
        Rule::symbol("identifier"),
    ])))
    .rule("boolean", Rule::token(Rule::prec(1, Rule::string("true"))))
    .rule("identifier", Rule::pattern("[a-z]+"))
    .to_js()?;
assert!(js.contains("boolean: $ => token(prec(1, 'true')),"));
# Ok::<(), treesitter_lang::Error>(())
```

### `Rule::prec_left`

```rust,ignore
pub fn prec_left(level: i32, rule: Rule) -> Rule
```

The rule with a precedence and left associativity, emitted as
`prec.left(level, ...)`: `a - b - c` groups as `(a - b) - c`.

| Parameter | Meaning |
|---|---|
| `level` | The precedence. |
| `rule` | The rule it applies to, usually a binary-operator sequence. |

```rust
use treesitter_lang::{Grammar, Rule};

// One alternative per operator, from an operator table.
let table = [("+", 1), ("-", 1), ("*", 2), ("/", 2)];
let e = || Rule::symbol("_expression");
let binary = Rule::choice(table.map(|(op, level)| {
    Rule::prec_left(level, Rule::seq([e(), Rule::string(op), e()]))
}));
let js = Grammar::new("calc")
    .rule("source_file", Rule::repeat(e()))
    .rule("_expression", Rule::choice([Rule::symbol("number"), Rule::symbol("binary")]))
    .rule("binary", binary)
    .rule("number", Rule::pattern(r"\d+"))
    .to_js()?;
assert!(js.contains("prec.left(2, seq($._expression, '/', $._expression)),"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Grammar, Rule};

let json = Grammar::new("demo")
    .rule("source_file", Rule::prec_left(-1, Rule::string("x")))
    .to_json()?;
assert!(json.contains("\"type\": \"PREC_LEFT\",\n      \"value\": -1,"));
# Ok::<(), treesitter_lang::Error>(())
```

### `Rule::prec_right`

```rust,ignore
pub fn prec_right(level: i32, rule: Rule) -> Rule
```

The rule with a precedence and right associativity, emitted as
`prec.right(level, ...)`: `a = b = c` groups as `a = (b = c)`.

| Parameter | Meaning |
|---|---|
| `level` | The precedence. |
| `rule` | The rule it applies to. |

```rust
use treesitter_lang::{Grammar, Rule};

let e = || Rule::symbol("_expression");
let js = Grammar::new("demo")
    .rule("source_file", Rule::repeat(e()))
    .rule("_expression", Rule::choice([
        Rule::symbol("identifier"),
        Rule::symbol("assignment"),
    ]))
    .rule("assignment", Rule::prec_right(0, Rule::seq([
        Rule::field("left", Rule::symbol("identifier")),
        Rule::string("="),
        Rule::field("right", e()),
    ])))
    .rule("identifier", Rule::pattern("[a-z]+"))
    .to_js()?;
assert!(js.contains("assignment: $ => prec.right(0, seq(\n"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Grammar, Rule};

// Exponentiation is right-associative and binds tightest.
let e = || Rule::symbol("_expression");
let js = Grammar::new("demo")
    .rule("source_file", Rule::repeat(e()))
    .rule("_expression", Rule::choice([Rule::symbol("number"), Rule::symbol("power")]))
    .rule("power", Rule::prec_right(4, Rule::seq([e(), Rule::string("**"), e()])))
    .rule("number", Rule::pattern(r"\d+"))
    .to_js()?;
assert!(js.contains("prec.right(4, seq($._expression, '**', $._expression))"));
# Ok::<(), treesitter_lang::Error>(())
```

### `Rule::prec_dynamic`

```rust,ignore
pub fn prec_dynamic(level: i32, rule: Rule) -> Rule
```

The rule with a dynamic precedence, emitted as `prec.dynamic(level, ...)`.
Dynamic precedence is applied while parsing, between the alternatives of a
[declared conflict](#grammarconflict) that are still alive at the end: the
parse with the higher total wins.

| Parameter | Meaning |
|---|---|
| `level` | The dynamic precedence. |
| `rule` | The rule it applies to. |

```rust
use treesitter_lang::{Grammar, Rule};

// `<a b>` reads both as a group of names and as a tuple of values; the
// conflict is declared and the group preferred at run time.
let js = Grammar::new("demo")
    .conflict(["_value", "group"])
    .rule("source_file", Rule::repeat(Rule::symbol("_value")))
    .rule("_value", Rule::choice([
        Rule::symbol("identifier"),
        Rule::symbol("group"),
        Rule::symbol("tuple"),
    ]))
    .rule("group", Rule::prec_dynamic(1, Rule::seq([
        Rule::string("<"),
        Rule::repeat1(Rule::symbol("identifier")),
        Rule::string(">"),
    ])))
    .rule("tuple", Rule::seq([
        Rule::string("<"),
        Rule::repeat1(Rule::symbol("_value")),
        Rule::string(">"),
    ]))
    .rule("identifier", Rule::pattern("[a-z]+"))
    .to_js()?;
assert!(js.contains("group: $ => prec.dynamic(1, seq('<', repeat1($.identifier), '>')),"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Grammar, Rule};

let json = Grammar::new("demo")
    .rule("source_file", Rule::prec_dynamic(2, Rule::string("x")))
    .to_json()?;
assert!(json.contains("\"type\": \"PREC_DYNAMIC\""));
# Ok::<(), treesitter_lang::Error>(())
```

---

## `Grammar`

```rust,ignore
#[derive(Clone, Debug)]
pub struct Grammar { /* private */ }
```

A tree-sitter grammar: a name, an ordered list of rules (the first is the
start rule), and the grammar-level settings — extras, externals, supertypes,
inlined rules, conflicts, and the word token. Build one by chaining: every
builder method takes the grammar by value and returns it. Nothing is checked
until it is emitted.

| Method | Purpose |
|---|---|
| [`new`](#grammarnew) | Start an empty grammar. |
| [`rule`](#grammarrule) | Add a named rule. |
| [`extra`](#grammarextra), [`external`](#grammarexternal), [`supertype`](#grammarsupertype), [`inline`](#grammarinline), [`conflict`](#grammarconflict), [`word`](#grammarword) | Grammar-level settings. |
| [`to_js`](#grammarto_js), [`write_js`](#grammarwrite_js) | Validate and emit `grammar.js`. |
| [`to_json`](#grammarto_json), [`write_json`](#grammarwrite_json) | Validate and emit `grammar.json`. |
| [`sexp`](#grammarsexp), [`write_sexp`](#grammarwrite_sexp) | Render a `syntax_lang` tree as tree-sitter's S-expression. |

`Grammar` is `Send + Sync`: build it once and share it between threads
rendering trees.

### `Grammar::new`

```rust,ignore
pub fn new(name: impl Into<Cow<'static, str>>) -> Grammar
```

Starts an empty grammar called `name`. The name is the language's name in
tree-sitter: the generated parser exports `tree_sitter_<name>()`, and the
package is conventionally `tree-sitter-<name>`.

| Parameter | Meaning |
|---|---|
| `name` | The language name, an identifier, conventionally lowercase. |

```rust
use treesitter_lang::{Grammar, Rule};

let js = Grammar::new("ini").rule("document", Rule::blank()).to_js()?;
assert!(js.contains("  name: 'ini',"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Error, Grammar, Rule};

// Hyphens belong in the package name, not the grammar name.
let result = Grammar::new("my-lang").rule("document", Rule::blank()).to_js();
assert_eq!(result, Err(Error::InvalidName { name: "my-lang".into() }));
```

### `Grammar::rule`

```rust,ignore
pub fn rule(self, name: impl Into<Cow<'static, str>>, rule: Rule) -> Grammar
```

Adds a rule called `name` matching `rule`. Rules are emitted in the order
they are added; the **first is the start rule** and must be visible
([`Error::HiddenStart`](#error)). Names must be identifiers and unique
([`Error::DuplicateRule`](#error)).

| Parameter | Meaning |
|---|---|
| `name` | The rule's name, which is also the name of its nodes. `_` first hides them. |
| `rule` | What the rule matches. |

```rust
use treesitter_lang::{Grammar, Rule};

let js = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::symbol("_item")))
    .rule("_item", Rule::choice([Rule::symbol("word"), Rule::symbol("number")]))
    .rule("word", Rule::pattern("[a-z]+"))
    .rule("number", Rule::pattern(r"\d+"))
    .to_js()?;
let order: Vec<usize> = ["source_file:", "_item:", "word:", "number:"]
    .iter()
    .map(|name| js.find(name).unwrap())
    .collect();
assert!(order.windows(2).all(|w| w[0] < w[1]));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Grammar, Rule};

// Keyword rules generated from a list.
let keywords = ["if", "else", "while", "return"];
let mut grammar = Grammar::new("demo").rule(
    "source_file",
    Rule::repeat(Rule::choice(keywords.map(|k| Rule::symbol(format!("{k}_keyword"))))),
);
for k in keywords {
    grammar = grammar.rule(format!("{k}_keyword"), Rule::string(k));
}
assert!(grammar.to_js()?.contains("return_keyword: $ => 'return',"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Error, Grammar, Rule};

let hidden_start = Grammar::new("demo").rule("_root", Rule::blank());
assert_eq!(hidden_start.to_js(), Err(Error::HiddenStart { name: "_root".into() }));

let duplicate = Grammar::new("demo")
    .rule("source_file", Rule::blank())
    .rule("source_file", Rule::string("x"));
assert_eq!(duplicate.to_js(), Err(Error::DuplicateRule { name: "source_file".into() }));
```

### `Grammar::extra`

```rust,ignore
pub fn extra(self, rule: Rule) -> Grammar
```

Adds an extra: something that may appear between any two tokens. Until this
is first called, tree-sitter's default applies — whitespace (`/\s/`) is the
only extra. **The first call replaces the default**, so add whitespace
yourself alongside a comment extra.

| Parameter | Meaning |
|---|---|
| `rule` | The extra: usually a pattern, or a symbol naming a rule. |

`grammar.js` leaves `extras` out while the default applies; `grammar.json`
always lists the extras, since that format has no implicit default.

```rust
use treesitter_lang::{Grammar, Rule};

let js = Grammar::new("demo")
    .extra(Rule::pattern(r"\s"))
    .extra(Rule::symbol("comment"))
    .rule("source_file", Rule::repeat(Rule::pattern("[a-z]+")))
    .rule("comment", Rule::token(Rule::seq([Rule::string(";"), Rule::pattern(".*")])))
    .to_js()?;
assert!(js.contains("  extras: $ => [\n    /\\s/,\n    $.comment,\n  ],\n"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Grammar, Rule};

// Line continuations count as whitespace too.
let js = Grammar::new("demo")
    .extra(Rule::pattern(r"\s"))
    .extra(Rule::pattern(r"\\\r?\n"))
    .rule("source_file", Rule::repeat(Rule::pattern("[a-z]+")))
    .to_js()?;
assert!(js.contains(r"    /\\\r?\n/,"));
# Ok::<(), treesitter_lang::Error>(())
```

### `Grammar::external`

```rust,ignore
pub fn external(self, name: impl Into<Cow<'static, str>>) -> Grammar
```

Declares an external token, lexed by a hand-written scanner in
`src/scanner.c` rather than by the generated lexer — for indentation,
heredocs, nested comments, anything a regular expression cannot match.
Rules refer to it with [`Rule::symbol`](#rulesymbol). Tree-sitter hands the
scanner the externals in declaration order, so keep the order in step with
the scanner's token enum.

| Parameter | Meaning |
|---|---|
| `name` | The token's name; an identifier. It may also name a rule that is a [token rule](#what-validation-checks), which then serves as the fallback when the scanner declines ([`InvalidExternal`](#error) otherwise). |

```rust
use treesitter_lang::{Grammar, Rule};

let js = Grammar::new("outline")
    .external("indent")
    .external("dedent")
    .external("newline")
    .rule("source_file", Rule::repeat(Rule::symbol("item")))
    .rule("item", Rule::seq([
        Rule::pattern("[a-z]+"),
        Rule::symbol("newline"),
        Rule::optional(Rule::seq([
            Rule::symbol("indent"),
            Rule::repeat1(Rule::symbol("item")),
            Rule::symbol("dedent"),
        ])),
    ]))
    .to_js()?;
assert!(js.contains("  externals: $ => [\n    $.indent,\n    $.dedent,\n    $.newline,\n  ],"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Grammar, Rule};

// A hidden external is lexed but never appears in the tree.
let json = Grammar::new("demo")
    .external("_line_break")
    .rule("source_file", Rule::repeat(Rule::seq([
        Rule::pattern("[a-z]+"),
        Rule::symbol("_line_break"),
    ])))
    .to_json()?;
assert!(json.contains("\"externals\": [\n    {\n      \"type\": \"SYMBOL\",\n      \"name\": \"_line_break\"\n    }\n  ]"));
# Ok::<(), treesitter_lang::Error>(())
```

### `Grammar::supertype`

```rust,ignore
pub fn supertype(self, name: impl Into<Cow<'static, str>>) -> Grammar
```

Marks a hidden rule as a supertype: a choice between other rules, like
`_expression` or `_statement`. It still does not appear in trees, but
tree-sitter records it in `node-types.json`, and queries can match on it —
`(_expression)` matches any expression.

| Parameter | Meaning |
|---|---|
| `name` | A rule's name, usually hidden; tree-sitter treats a supertype as hidden either way. When reachable, it must not be a token, never be itself, and produce a single node in each alternative ([`Error::InvalidSupertype`](#error)). |

```rust
use treesitter_lang::{Grammar, Rule};

let js = Grammar::new("demo")
    .supertype("_statement")
    .rule("source_file", Rule::repeat(Rule::symbol("_statement")))
    .rule("_statement", Rule::choice([Rule::symbol("break"), Rule::symbol("continue")]))
    .rule("break", Rule::string("break;"))
    .rule("continue", Rule::string("continue;"))
    .to_js()?;
assert!(js.contains("  supertypes: $ => [\n    $._statement,\n  ],"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Error, Grammar, Rule};

let result = Grammar::new("demo")
    .supertype("_expresion")
    .rule("source_file", Rule::blank())
    .to_js();
assert_eq!(
    result,
    Err(Error::UndefinedSymbol { symbol: "_expresion".into(), rule: "supertypes".into() }),
);
```

### `Grammar::inline`

```rust,ignore
pub fn inline(self, name: impl Into<Cow<'static, str>>) -> Grammar
```

Asks tree-sitter to inline a rule: substitute its body wherever it is used,
instead of giving it parse states of its own. Suits small hidden helpers used
in many places, and can resolve conflicts that exist only because the helper
is a separate rule. An inlined rule never appears in the tree.

| Parameter | Meaning |
|---|---|
| `name` | A rule's name ([`Error::UndefinedSymbol`](#error) otherwise; tree-sitter only warns, but a name that matches nothing is always a typo). Not the start rule, a token, or a rule that refers to itself through inlined rules alone ([`Error::InvalidInline`](#error)). Repeated entries are written once, as tree-sitter keeps them. |

```rust
use treesitter_lang::{Grammar, Rule};

let js = Grammar::new("demo")
    .inline("_name")
    .rule("source_file", Rule::repeat(Rule::symbol("_name")))
    .rule("_name", Rule::choice([Rule::symbol("identifier"), Rule::symbol("self")]))
    .rule("identifier", Rule::pattern("[a-z]+"))
    .rule("self", Rule::string("self"))
    .to_js()?;
assert!(js.contains("  inline: $ => [\n    $._name,\n  ],"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Grammar, Rule};

let json = Grammar::new("demo")
    .inline("_a")
    .inline("_b")
    .rule("source_file", Rule::repeat(Rule::choice([Rule::symbol("_a"), Rule::symbol("_b")])))
    .rule("_a", Rule::string("a"))
    .rule("_b", Rule::string("b"))
    .to_json()?;
assert!(json.contains("\"inline\": [\n    \"_a\",\n    \"_b\"\n  ]"));
# Ok::<(), treesitter_lang::Error>(())
```

### `Grammar::conflict`

```rust,ignore
pub fn conflict<N>(self, names: impl IntoIterator<Item = N>) -> Grammar
where
    N: Into<Cow<'static, str>>,
```

Declares an expected conflict between rules. When `tree-sitter generate`
finds an ambiguity that precedence does not settle, it stops and lists the
rules involved. Declaring the conflict tells it the ambiguity is intended: the
generated parser then explores the alternatives at run time and keeps the one
that succeeds (or, among several, the one with the higher
[dynamic precedence](#ruleprec_dynamic)).

| Parameter | Meaning |
|---|---|
| `names` | The conflicting rules, as tree-sitter named them. Each must be a rule or external ([`Error::UndefinedSymbol`](#error)). |

```rust
use treesitter_lang::{Grammar, Rule};

// `<a b>` is a group of names or a tuple of values.
let js = Grammar::new("demo")
    .conflict(["_value", "group"])
    .rule("source_file", Rule::repeat(Rule::symbol("_value")))
    .rule("_value", Rule::choice([
        Rule::symbol("identifier"),
        Rule::symbol("group"),
        Rule::symbol("tuple"),
    ]))
    .rule("group", Rule::seq([
        Rule::string("<"),
        Rule::repeat1(Rule::symbol("identifier")),
        Rule::string(">"),
    ]))
    .rule("tuple", Rule::seq([
        Rule::string("<"),
        Rule::repeat1(Rule::symbol("_value")),
        Rule::string(">"),
    ]))
    .rule("identifier", Rule::pattern("[a-z]+"))
    .to_js()?;
assert!(js.contains("  conflicts: $ => [\n    [$._value, $.group],\n  ],"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::Grammar;

// Several conflicts, with names known only at run time.
let pairs: Vec<[String; 2]> = vec![
    ["type".into(), "expression".into()],
    ["pattern".into(), "expression".into()],
];
let mut grammar = Grammar::new("demo");
for pair in pairs {
    grammar = grammar.conflict(pair);
}
# let _ = grammar;
```

### `Grammar::word`

```rust,ignore
pub fn word(self, name: impl Into<Cow<'static, str>>) -> Grammar
```

Names the word token: the identifier-like token keywords are carved out of.
With a word token, tree-sitter lexes a keyword by matching the word token and
then comparing the text with the keyword strings. The lexer gets smaller, and
keywords are no longer recognized inside longer identifiers (`if` in
`iffy`). Calling `word` again replaces the earlier choice.

| Parameter | Meaning |
|---|---|
| `name` | The identifier rule's name. Its body must be a string, a pattern, a [`token`](#ruletoken), or an [`immediate`](#ruleimmediate) token, with nothing wrapped around it — or the name must be an external. |

```rust
use treesitter_lang::{Grammar, Rule};

let js = Grammar::new("demo")
    .word("identifier")
    .rule("source_file", Rule::repeat(Rule::choice([
        Rule::seq([Rule::string("let"), Rule::symbol("identifier")]),
        Rule::symbol("identifier"),
    ])))
    .rule("identifier", Rule::pattern("[a-zA-Z_][a-zA-Z0-9_]*"))
    .to_js()?;
assert!(js.contains("  word: $ => $.identifier,\n"));
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Error, Grammar, Rule};

// Precedence around the pattern makes it a non-terminal in tree-sitter's eyes.
let result = Grammar::new("demo")
    .word("identifier")
    .rule("source_file", Rule::repeat(Rule::symbol("identifier")))
    .rule("identifier", Rule::prec(1, Rule::pattern("[a-z]+")))
    .to_js();
assert_eq!(result, Err(Error::WordNotToken { name: "identifier".into() }));
```

### `Grammar::to_js`

```rust,ignore
pub fn to_js(&self) -> Result<String, Error>
```

Validates the grammar and emits it as `grammar.js`. The output is formatted
as tree-sitter grammars are written by hand — two-space indentation, short
sequences on one line, trailing commas — and starts with the
`tree-sitter-cli/dsl` type reference, so it reads naturally and diffs
cleanly when committed. Settings appear in a fixed order: `name`, `extras`,
`externals`, `supertypes`, `inline`, `conflicts`, `word`, `rules`; empty
settings are left out.

**Errors.** The first problem [validation](#what-validation-checks) finds.

```rust
use treesitter_lang::{Grammar, Rule};

let js = Grammar::new("pairs")
    .rule("source_file", Rule::repeat(Rule::symbol("pair")))
    .rule("pair", Rule::seq([
        Rule::field("key", Rule::symbol("identifier")),
        Rule::string("="),
        Rule::field("value", Rule::choice([
            Rule::symbol("identifier"),
            Rule::symbol("number"),
        ])),
    ]))
    .rule("identifier", Rule::pattern("[a-z]+"))
    .rule("number", Rule::pattern(r"\d+"))
    .to_js()?;

assert_eq!(js, r#"/// <reference types="tree-sitter-cli/dsl" />
// @ts-check

module.exports = grammar({
  name: 'pairs',

  rules: {
    source_file: $ => repeat($.pair),

    pair: $ => seq(
      field('key', $.identifier),
      '=',
      field('value', choice($.identifier, $.number)),
    ),

    identifier: $ => /[a-z]+/,

    number: $ => /\d+/,
  },
});
"#);
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Grammar, Rule};

// Writing the file, as a build step would.
let dir = std::env::temp_dir().join("tree-sitter-pairs-doc");
std::fs::create_dir_all(&dir)?;
let grammar = Grammar::new("pairs").rule("source_file", Rule::repeat(Rule::pattern("[a-z]+")));
std::fs::write(dir.join("grammar.js"), grammar.to_js()?)?;
assert!(std::fs::read_to_string(dir.join("grammar.js"))?.contains("name: 'pairs'"));
# std::fs::remove_dir_all(&dir)?;
# Ok::<(), Box<dyn std::error::Error>>(())
```

### `Grammar::write_js`

```rust,ignore
pub fn write_js(&self, out: &mut String) -> Result<(), Error>
```

The same output as [`to_js`](#grammarto_js), appended to a buffer the
caller owns. Reuse one buffer to emit many grammars without reallocating.

| Parameter | Meaning |
|---|---|
| `out` | The buffer to append to. Existing contents are kept. |

**Errors.** As [`to_js`](#grammarto_js). On error nothing is appended.

```rust
use treesitter_lang::{Grammar, Rule};

// One buffer for several dialects.
let mut buffer = String::new();
for dialect in ["strict", "loose"] {
    buffer.clear();
    Grammar::new(dialect)
        .rule("source_file", Rule::repeat(Rule::pattern("[a-z]+")))
        .write_js(&mut buffer)?;
    assert!(buffer.contains(&format!("name: '{dialect}'")));
}
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Grammar, Rule};

// Appending after a license header.
let mut out = String::from("// SPDX-License-Identifier: MIT\n");
Grammar::new("demo")
    .rule("source_file", Rule::blank())
    .write_js(&mut out)?;
assert!(out.starts_with("// SPDX-License-Identifier: MIT\n/// <reference"));
# Ok::<(), treesitter_lang::Error>(())
```

### `Grammar::to_json`

```rust,ignore
pub fn to_json(&self) -> Result<String, Error>
```

Validates the grammar and emits it as `grammar.json`, the format
`tree-sitter generate` writes to `src/grammar.json` and accepts in place of
`grammar.js`. Both inputs produce the same parser, and with tree-sitter 0.25
or later the output is byte-identical to the file tree-sitter writes when it
generates from this grammar's [`to_js`](#grammarto_js) output — same
`$schema` line, field order, and layout, no trailing newline (see
[the compatibility table](#from-rust-to-tree-sitter)). Without any
[`extra`](#grammarextra), the default whitespace extra is written out.

**Errors.** The first problem [validation](#what-validation-checks) finds.

```rust
use treesitter_lang::{Grammar, Rule};

let json = Grammar::new("tiny")
    .rule("source_file", Rule::repeat(Rule::symbol("word")))
    .rule("word", Rule::pattern("[a-z]+"))
    .to_json()?;

assert_eq!(json, r#"{
  "$schema": "https://tree-sitter.github.io/tree-sitter/assets/schemas/grammar.schema.json",
  "name": "tiny",
  "rules": {
    "source_file": {
      "type": "REPEAT",
      "content": {
        "type": "SYMBOL",
        "name": "word"
      }
    },
    "word": {
      "type": "PATTERN",
      "value": "[a-z]+"
    }
  },
  "extras": [
    {
      "type": "PATTERN",
      "value": "\\s"
    }
  ],
  "conflicts": [],
  "precedences": [],
  "externals": [],
  "inline": [],
  "supertypes": [],
  "reserved": {}
}"#);
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Grammar, Rule};

// Strings are JSON-escaped; non-ASCII text is kept as is.
let json = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::choice([
        Rule::string("say \"hi\""),
        Rule::string("café"),
    ])))
    .to_json()?;
assert!(json.contains(r#""value": "say \"hi\"""#));
assert!(json.contains("\"value\": \"café\""));
# Ok::<(), treesitter_lang::Error>(())
```

### `Grammar::write_json`

```rust,ignore
pub fn write_json(&self, out: &mut String) -> Result<(), Error>
```

The same output as [`to_json`](#grammarto_json), appended to a buffer the
caller owns.

| Parameter | Meaning |
|---|---|
| `out` | The buffer to append to. Existing contents are kept. |

**Errors.** As [`to_json`](#grammarto_json). On error nothing is appended.

```rust
use treesitter_lang::{Grammar, Rule};

let grammar = Grammar::new("demo").rule("source_file", Rule::repeat(Rule::pattern("[a-z]+")));
let mut js = String::new();
let mut json = String::new();
grammar.write_js(&mut js)?;
grammar.write_json(&mut json)?;
assert!(js.len() < json.len());
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Error, Grammar, Rule};

let mut out = String::from("kept");
let broken = Grammar::new("demo").rule("source_file", Rule::string(""));
assert_eq!(
    broken.write_json(&mut out),
    Err(Error::EmptyString { rule: "source_file".into() }),
);
assert_eq!(out, "kept");
```

### `Grammar::sexp`

```rust,ignore
pub fn sexp<'n, K>(&self, tree: &Node<K>, name: impl Fn(&K) -> &'n str) -> Result<String, Error>
```

Renders a [`syntax_lang::Node`](https://docs.rs/syntax-lang) tree as the
S-expression tree-sitter prints for the same input, for writing corpus tests.
Each node and token is named by `name`, then shown the way tree-sitter shows
it:

| The name is… | Shown as |
|---|---|
| A visible rule that lexes a single token (a string, pattern, or `token`, possibly under `prec` or `field`) | A leaf, `(name)`; anything beneath it is part of the token. |
| A visible rule that names no other node (no symbol or alias in it) | `(name ...)` around only the extras, such as comments, beneath it. |
| Any other visible rule, or a name given by [`alias`](#rulealias) | `(name ...)` around its children; on a token, `(name)`. |
| A hidden rule (`_name`), an [inlined](#grammarinline) rule, or a [supertype](#grammarsupertype) | Not shown; its children take its place. |
| An [external](#grammarexternal) token | `(name)`, unless hidden. |
| Not in the grammar, on a token | Not shown: an anonymous token — punctuation, keywords written as strings, whitespace. |
| Not in the grammar, on a node | [`Error::UnknownNode`](#error). |

Children are indented two spaces per level, as `tree-sitter test` formats
them. Fields are not reconstructed — the tree does not record them, and
`tree-sitter test` ignores fields when the expected tree has none — and an
alias shows up only where the tree itself uses the aliased name.
Extras such as comments appear wherever the tree has them; tree-sitter puts
an extra inside the innermost node whose first and last tokens surround it,
so a parser whose trees are compared this way should place trivia the same
way. `sexp` does not validate the grammar.

| Parameter | Meaning |
|---|---|
| `tree` | The tree; its root is rendered like any other node. |
| `name` | Names a node or token kind, matching the grammar's rule names. Usually a method on the kind type. |

**Errors.** [`Error::UnknownNode`](#error) if a node's name is not a rule,
external, or alias name.

```rust
use treesitter_lang::{Grammar, Rule};
use treesitter_lang::syntax_lang::{Builder, Span, Token};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind { File, Sum, Number, Plus, Space }

impl Kind {
    fn name(&self) -> &'static str {
        match self {
            Kind::File => "source_file",
            Kind::Sum => "sum",
            Kind::Number => "number",
            Kind::Plus => "+",
            Kind::Space => " ",
        }
    }
}

let grammar = Grammar::new("calc")
    .rule("source_file", Rule::repeat(Rule::symbol("_expression")))
    .rule("_expression", Rule::choice([Rule::symbol("number"), Rule::symbol("sum")]))
    .rule("sum", Rule::prec_left(1, Rule::seq([
        Rule::symbol("_expression"),
        Rule::string("+"),
        Rule::symbol("_expression"),
    ])))
    .rule("number", Rule::pattern(r"\d+"));

// `1 + 2`, as a parser builds it.
let mut b = Builder::new();
b.start_node(Kind::File);
b.start_node(Kind::Sum);
b.token(Token::new(Kind::Number, Span::new(0, 1)));
b.token(Token::new(Kind::Space, Span::new(1, 2)));
b.token(Token::new(Kind::Plus, Span::new(2, 3)));
b.token(Token::new(Kind::Space, Span::new(3, 4)));
b.token(Token::new(Kind::Number, Span::new(4, 5)));
b.finish_node();
b.finish_node();
let tree = b.finish()?;

assert_eq!(grammar.sexp(&tree, Kind::name)?, "(source_file\n  (sum\n    (number)\n    (number)))");
# Ok::<(), Box<dyn std::error::Error>>(())
```

```rust
use treesitter_lang::{Error, Grammar, Rule};
use treesitter_lang::syntax_lang::{Element, Node, Span, Token};

let grammar = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::symbol("_group")))
    .rule("_group", Rule::seq([Rule::string("("), Rule::symbol("word"), Rule::string(")")]))
    .rule("word", Rule::pattern("[a-z]+"));

// A hidden rule's node is replaced by its children.
let tree = Node::new("source_file", vec![Element::Node(Node::new("_group", vec![
    Element::Token(Token::new("(", Span::new(0, 1))),
    Element::Token(Token::new("word", Span::new(1, 3))),
    Element::Token(Token::new(")", Span::new(3, 4))),
]))]);
assert_eq!(grammar.sexp(&tree, |k| *k)?, "(source_file\n  (word))");

// A node the grammar does not know is an error.
let stray = Node::new("source_file", vec![Element::Node(Node::new("block", vec![]))]);
assert_eq!(grammar.sexp(&stray, |k| *k), Err(Error::UnknownNode { name: "block".into() }));
# Ok::<(), Error>(())
```

### `Grammar::write_sexp`

```rust,ignore
pub fn write_sexp<'n, K>(
    &self,
    tree: &Node<K>,
    name: impl Fn(&K) -> &'n str,
    out: &mut String,
) -> Result<(), Error>
```

The same output as [`sexp`](#grammarsexp), appended to a buffer the caller
owns — reuse one buffer across a whole corpus.

| Parameter | Meaning |
|---|---|
| `tree` | The tree to render. |
| `name` | Names a node or token kind. |
| `out` | The buffer to append to. Existing contents are kept. |

**Errors.** As [`sexp`](#grammarsexp). On error nothing is appended.

```rust
use treesitter_lang::{Grammar, Rule};
use treesitter_lang::syntax_lang::{Element, Node, Span, Token};

let grammar = Grammar::new("words")
    .rule("source_file", Rule::repeat(Rule::symbol("word")))
    .rule("word", Rule::pattern("[a-z]+"));

let source = "hi there";
let tree = Node::new("source_file", vec![
    Element::Token(Token::new("word", Span::new(0, 2))),
    Element::Token(Token::new("space", Span::new(2, 3))),
    Element::Token(Token::new("word", Span::new(3, 8))),
]);

// A complete corpus entry.
let mut corpus = String::new();
corpus.push_str("==================\nTwo words\n==================\n\n");
corpus.push_str(source);
corpus.push_str("\n\n---\n\n");
grammar.write_sexp(&tree, |k| *k, &mut corpus)?;
corpus.push('\n');

assert_eq!(corpus, "==================\nTwo words\n==================\n\nhi there\n\n---\n\n\
                    (source_file\n  (word)\n  (word))\n");
# Ok::<(), treesitter_lang::Error>(())
```

```rust
use treesitter_lang::{Grammar, Rule};
use treesitter_lang::syntax_lang::{Element, Node, Span, Token};

// Names from a table, borrowed by the naming closure.
let names: Vec<String> = vec!["source_file".into(), "word".into()];
let grammar = Grammar::new("words")
    .rule("source_file", Rule::repeat(Rule::symbol("word")))
    .rule("word", Rule::pattern("[a-z]+"));
let tree = Node::new(0usize, vec![Element::Token(Token::new(1usize, Span::new(0, 2)))]);

let mut out = String::new();
grammar.write_sexp(&tree, |k| names[*k].as_str(), &mut out)?;
assert_eq!(out, "(source_file\n  (word))");
# Ok::<(), treesitter_lang::Error>(())
```

---

## `Error`

```rust,ignore
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
    InvalidName { name: String },
    NoRules,
    DuplicateRule { name: String },
    HiddenStart { name: String },
    UndefinedSymbol { symbol: String, rule: String },
    EmptyString { rule: String },
    EmptyChoice { rule: String },
    SymbolInToken { symbol: String, rule: String },
    MatchesEmpty { rule: String },
    IndirectRecursion { rule: String },
    WordNotToken { name: String },
    InvalidExternal { name: String },
    InvalidInline { name: String },
    InvalidSupertype { name: String },
    UnknownNode { name: String },
}
```

Why a grammar could not be emitted, or a tree could not be rendered.
Validation reports the first problem, checking in this order:

1. names (the grammar's, then each rule's, then each external's), the start
   rule, and duplicate rules;
2. every rule body in definition order, then the extras: symbols resolve and
   are not inside tokens, patterns and choices are not empty, patterns are
   regular expressions JavaScript accepts, field and alias names are
   identifiers;
3. the names in `word`, `conflicts`, `inline`, and `supertypes` resolve;
4. the rules reachable from the start rule and the extras: no cycle of rules
   that can each be just the next; then, in definition order, no empty
   strings, only patterns tree-sitter's regular expression parser accepts,
   and nothing that can match the empty string where tree-sitter needs a
   token; then the patterns in the extras;
5. the word token, externals sharing a rule's name, inlined rules, and
   supertypes.

Where a variant has a `rule` field, it names the rule the problem is in — or,
for a problem outside any rule, the grammar setting it is in: `extras`,
`word`, `conflicts`, `inline`, or `supertypes`. `Error` implements `Display`
and `core::error::Error`.

| Variant | Meaning | What to do |
|---|---|---|
| `InvalidName { name }` | A grammar, rule, external, field, or alias name is not an identifier, or a rule or external is called `__proto__`. | Rename: ASCII letter or `_`, then letters, digits, `_`. |
| `NoRules` | The grammar has no rules. | Add at least the start rule. |
| `DuplicateRule { name }` | Two rules share a name. | Rename one, or merge them with a `choice`. |
| `HiddenStart { name }` | The first rule's name starts with `_`. | Make the start rule visible. |
| `UndefinedSymbol { symbol, rule }` | A symbol names neither a rule nor an external. | Fix the typo, or define the rule or external. |
| `EmptyString { rule }` | A pattern is empty or is not one of the [accepted patterns](#accepted-patterns), or a string in a reachable rule is empty. For an invalid pattern, `rule` is the rule's name, `: `, then what is wrong and where: `` "number: unterminated character class at byte 0 of `[0-9`" ``. | Express "nothing" with `blank` or `optional`; fix an invalid pattern as the report says. |
| `EmptyChoice { rule }` | A choice has no alternatives. | Give it at least one. |
| `SymbolInToken { symbol, rule }` | A symbol appears inside `token`, `immediate`, or an extra that is not a lone symbol. | Inline the referenced rule's strings and patterns, or make the extra a symbol. |
| `MatchesEmpty { rule }` | A reachable rule another rule (or an extra) refers to can match the empty string, or something a `repeat` repeats can. | Make it match at least one token; put the `optional` at its uses, or use `repeat1`. |
| `IndirectRecursion { rule }` | Reachable rules form a cycle in which each can be just the next (`a` can be `b` alone, `b` can be `a` alone), or a hidden rule can be itself under a non-zero precedence. | Make one rule require more than the other, or merge them. |
| `WordNotToken { name }` | The `word` rule is not a token rule. | Make its body a bare string, pattern, or token used nowhere else. |
| `InvalidExternal { name }` | An external shares its name with a rule that is not a token rule. | Rename one of them, or make the rule a token. |
| `InvalidInline { name }` | An inlined rule is the start rule, an external, a token rule, or recursive through inlined rules alone. | Remove it from the inline list, or break the cycle. |
| `InvalidSupertype { name }` | A supertype is an external, or a reachable rule that is a token rule, is itself in an alternative, or produces several nodes in one. | Make it a choice of single symbols. |
| `UnknownNode { name }` | `sexp` met a node whose name is not a rule, external, or alias name. | Add the rule, or fix the naming function. |

```rust
use treesitter_lang::{Error, Grammar, Rule};

let result = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::symbol("block")))
    .rule("block", Rule::seq([Rule::string("{"), Rule::symbol("body"), Rule::string("}")]))
    .rule("body", Rule::optional(Rule::pattern("[a-z]+")))
    .to_js();

match result {
    Err(Error::MatchesEmpty { rule }) => assert_eq!(rule, "body"),
    other => panic!("unexpected {other:?}"),
}
```

```rust
use treesitter_lang::{Error, Grammar, Rule};

let result = Grammar::new("demo")
    .rule("source_file", Rule::repeat(Rule::symbol("number")))
    .rule("number", Rule::pattern("[0-9"))
    .to_js();

match result {
    Err(Error::EmptyString { rule }) => {
        assert_eq!(rule, "number: unterminated character class at byte 0 of `[0-9`");
        // The rule's name is everything before the first `: `.
        assert_eq!(rule.split_once(": ").map(|(name, _)| name), Some("number"));
    }
    other => panic!("unexpected {other:?}"),
}
```

```rust
use treesitter_lang::Error;

let e = Error::UndefinedSymbol { symbol: "item".into(), rule: "extras".into() };
assert_eq!(e.to_string(), "`extras` refers to undefined symbol `item`");

// A standard error: it boxes and propagates with `?`.
let boxed: Box<dyn std::error::Error> = Box::new(Error::NoRules);
assert!(boxed.to_string().contains("no rules"));
```

---

## Re-export: `syntax_lang`

```rust,ignore
pub use syntax_lang;
```

The [`syntax-lang`](https://docs.rs/syntax-lang) crate, re-exported whole.
[`Grammar::sexp`](#grammarsexp) reads its `Node`; building trees through the
re-export guarantees the same version this crate was compiled against, with
no separate dependency to keep in step.

```rust
use treesitter_lang::syntax_lang::{Element, Node, Span, Token};

let tree = Node::new("source_file", vec![Element::Token(Token::new("word", Span::new(0, 4)))]);
assert_eq!(tree.span(), Span::new(0, 4));
```

---

## Feature flags

| Feature | Default | Effect |
|---|---|---|
| `std` | yes | The standard library. Without it the crate is `no_std` and needs only `alloc`. Forwards to `syntax-lang/std`. |

---

## Guide: generating a grammar package

A tree-sitter grammar package is a directory holding `grammar.js`, the
generated parser under `src/`, and corpus tests under `test/corpus/`. The
grammar is best generated by a small program next to the language's own
code — an example or an `xtask` — so it is rebuilt whenever the language
changes:

```rust,no_run
use std::{fs, path::Path};
use treesitter_lang::{Grammar, Rule};

fn grammar() -> Grammar {
    Grammar::new("mini")
        .extra(Rule::pattern(r"\s"))
        .word("identifier")
        .rule("source_file", Rule::repeat(Rule::symbol("statement")))
        .rule("statement", Rule::seq([Rule::symbol("identifier"), Rule::string(";")]))
        .rule("identifier", Rule::pattern("[a-z_]+"))
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let dir = Path::new("tree-sitter-mini");
    fs::create_dir_all(dir)?;
    let mut buffer = String::new();
    grammar().write_js(&mut buffer)?;
    fs::write(dir.join("grammar.js"), &buffer)?;
    Ok(())
}
```

Then, in the package directory:

```bash
tree-sitter generate     # grammar.js -> src/parser.c, src/grammar.json, src/node-types.json
tree-sitter test         # run the corpus
```

`tree-sitter generate` evaluates `grammar.js` with Node.js by default, or
with its built-in JavaScript runtime given `--js-runtime native`. To skip
JavaScript altogether, emit [`grammar.json`](#grammarto_json) instead and run
`tree-sitter generate grammar.json`: it produces the same parser.

If generation stops on a conflict, it prints the ambiguous token sequence and
the rules involved. Settle it with [`prec`](#ruleprec),
[`prec_left`](#ruleprec_left), or [`prec_right`](#ruleprec_right) when one
reading is always right, or declare it with
[`Grammar::conflict`](#grammarconflict) when the parser must decide at run
time.

---

## Guide: corpus tests from a hand-written parser

The point of keeping the grammar in Rust is that it can be held to the
language's real parser. The steps:

1. **Name kinds after rules.** Give the kind type a method returning each
   kind's rule name. Node kinds and named tokens (identifiers, numbers,
   comments) use their rule names; punctuation and keywords that the grammar
   writes as strings use any name that is not a rule, such as their text.
2. **Place trivia as tree-sitter does.** Tree-sitter puts an extra (a
   comment, whitespace) inside the innermost node whose first and last
   tokens surround it, and outside any node that starts or ends there. A
   parser that holds trivia back until the next token is consumed, then
   attaches it to whichever node that token belongs to, matches.
3. **Render each sample.** Parse it, call [`write_sexp`](#grammarwrite_sexp),
   and write the entry: a `===` header with a title, the source, a `---`
   divider, and the S-expression.
4. **Run `tree-sitter test`.** It parses every sample with the generated
   parser and compares the trees.

```rust
use treesitter_lang::{Grammar, Rule};
use treesitter_lang::syntax_lang::{Element, Node, Span, Token};

let grammar = Grammar::new("lists")
    .extra(Rule::pattern(r"\s"))
    .rule("source_file", Rule::repeat(Rule::symbol("list")))
    .rule("list", Rule::seq([
        Rule::string("("),
        Rule::repeat(Rule::choice([Rule::symbol("atom"), Rule::symbol("list")])),
        Rule::string(")"),
    ]))
    .rule("atom", Rule::pattern("[a-z]+"));

// What a hand-written parser built for `(a (b))`.
let t = |kind, start, end| Element::Token(Token::new(kind, Span::new(start, end)));
let inner = Node::new("list", vec![t("(", 3, 4), t("atom", 4, 5), t(")", 5, 6)]);
let outer = Node::new("list", vec![
    t("(", 0, 1), t("atom", 1, 2), t(" ", 2, 3), Element::Node(inner), t(")", 6, 7),
]);
let tree = Node::new("source_file", vec![Element::Node(outer)]);

let mut entry = String::from("=====\nNested lists\n=====\n\n(a (b))\n\n---\n\n");
grammar.write_sexp(&tree, |k| *k, &mut entry)?;
assert!(entry.ends_with("---\n\n(source_file\n  (list\n    (atom)\n    (list\n      (atom))))"));
// std::fs::write("tree-sitter-lists/test/corpus/lists.txt", entry)?;
# Ok::<(), treesitter_lang::Error>(())
```

The [`corpus` example](../examples/corpus.rs) does this for a small
expression language with comments, using a complete hand-written lexer and
Pratt parser; the CI suite runs its corpus through `tree-sitter test` on
every change.

---

## Stability

As of `1.0.0` the public API is frozen. treesitter-lang follows
[Semantic Versioning](https://semver.org/); within the `1.x` series:

- The **surface** will not change in a breaking way: [`Rule`](#rule) and its
  seventeen constructors (`symbol`, `string`, `pattern`, `blank`, `seq`,
  `choice`, `optional`, `repeat`, `repeat1`, `field`, `alias`, `token`,
  `immediate`, `prec`, `prec_left`, `prec_right`, `prec_dynamic`) with
  `Clone` and `Debug`; [`Grammar`](#grammar) (`new`, `rule`, `extra`,
  `external`, `supertype`, `inline`, `conflict`, `word`, `to_js`, `write_js`,
  `to_json`, `write_json`, `sexp`, `write_sexp`) with `Clone`, `Debug`, `Send`,
  and `Sync`; [`Error`](#error), its variants and their fields, with `Clone`,
  `Debug`, `PartialEq`, `Eq`, `Display`, and `core::error::Error`; and the
  [`syntax_lang`](#re-export-syntax_lang) re-export. New constructors, builder
  methods, and error variants are minor additions.
- `Error` is `#[non_exhaustive]`, so failure modes can be added in a minor
  release: match it with a wildcard arm. The meaning of every existing
  variant is fixed.
- The **validation contract** holds: a grammar that validates is one
  `tree-sitter generate` loads, up to what only its parse tables reveal
  (conflicts, and extras whose end it cannot tell); and a grammar validation
  refuses is one tree-sitter refuses, crashes on, or hangs on — apart from the
  documented stricter checks. Checks may be refined in a minor release only
  to follow tree-sitter more closely; the stricter checks stay. (1.0.1
  brought patterns under this contract as a security fix: see below.)
- The **output contract** holds: `to_js` writes a `grammar.js` that describes
  exactly the grammar built, and `to_json` writes tree-sitter's
  `grammar.json` for it, generating the same parser. The `grammar.json`
  matches, byte for byte, the file the tree-sitter versions in the
  [compatibility table](#from-rust-to-tree-sitter) write; when tree-sitter
  changes its own format, a minor release may follow it.
- The **rendering rules** of [`sexp`](#grammarsexp) — which names are shown,
  spliced, or left out, and the two-space indentation — are fixed.
- `syntax-lang` is a **public dependency**: the re-exported crate and the
  tree type `sexp` takes come from `syntax-lang` 1. Moving to a new major
  version of it would be a major release here.
- MSRV (Rust 1.85) is a compatibility surface: raising it is a documented
  minor change, never a patch.

What is **not** promised: the exact layout of `grammar.js` (line breaks and
spacing may improve; what it describes may not change), which problem
validation reports first when a grammar has several, the `Display` wording of
`Error`, the `Debug` output of any type, and performance figures — the
benchmarks are tracked, but they are measurements, not guarantees.

**1.0.1 and patterns.** Until 1.0.1 a pattern was emitted unchecked, its
validity left to tree-sitter, and a pattern with an unclosed character class
could make the emitted `grammar.js` run text from the grammar's own strings
as code when tree-sitter evaluated it (ISSUES H06). 1.0.1 checks every
pattern against both parsers that read it (see
[accepted patterns](#accepted-patterns)) and writes every literal so that it
ends at its own closing slash. The patterns newly refused are ones the
JavaScript runtime or tree-sitter already refused, so no `grammar.js` that
loaded and generated stops validating. One workflow is affected: a grammar
emitted only as `grammar.json`, with a pattern JavaScript refuses but
tree-sitter's parser accepts (`a**`, `[😀-😁]`), validated before and is
refused now — both formats describe one grammar, and its `grammar.js` could
never load. The public surface is unchanged: the report travels in
[`Error::EmptyString`](#error).

Features planned for 1.1.0, all additive: named precedences (tree-sitter's
`precedences` field), reserved-word sets, anonymous aliases, and a
`Grammar::check` that validates without emitting. Pattern flags remain a
candidate.

See [`../dev/ROADMAP.md`](../dev/ROADMAP.md) and
[`../CHANGELOG.md`](../CHANGELOG.md).