1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
#![doc = include_str!("./README.md")]

pub mod ffi;
mod util;

#[cfg(unix)]
use std::os::unix::io::AsRawFd;
#[cfg(windows)]
use std::os::windows::io::AsRawHandle;

use std::{
    char, error,
    ffi::CStr,
    fmt::{self, Write},
    hash, iter,
    marker::PhantomData,
    mem::MaybeUninit,
    num::NonZeroU16,
    ops::{self, Deref},
    os::raw::{c_char, c_void},
    ptr::{self, NonNull},
    slice, str,
    sync::atomic::AtomicUsize,
    u16,
};

#[cfg(feature = "wasm")]
mod wasm_language;
#[cfg(feature = "wasm")]
pub use wasm_language::*;

/// The latest ABI version that is supported by the current version of the
/// library.
///
/// When Languages are generated by the Tree-sitter CLI, they are
/// assigned an ABI version number that corresponds to the current CLI version.
/// The Tree-sitter library is generally backwards-compatible with languages
/// generated using older CLI versions, but is not forwards-compatible.
#[doc(alias = "TREE_SITTER_LANGUAGE_VERSION")]
pub const LANGUAGE_VERSION: usize = ffi::TREE_SITTER_LANGUAGE_VERSION as usize;

/// The earliest ABI version that is supported by the current version of the
/// library.
#[doc(alias = "TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION")]
pub const MIN_COMPATIBLE_LANGUAGE_VERSION: usize =
    ffi::TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION as usize;

pub const ARRAY_HEADER: &str = include_str!("../src/array.h");
pub const PARSER_HEADER: &str = include_str!("../src/parser.h");

/// An opaque object that defines how to parse a particular language. The code for each
/// `Language` is generated by the Tree-sitter CLI.
#[doc(alias = "TSLanguage")]
#[derive(Debug, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct Language(*const ffi::TSLanguage);

pub struct LanguageRef<'a>(*const ffi::TSLanguage, PhantomData<&'a ()>);

/// A tree that represents the syntactic structure of a source code file.
#[doc(alias = "TSTree")]
pub struct Tree(NonNull<ffi::TSTree>);

/// A position in a multi-line text document, in terms of rows and columns.
///
/// Rows and columns are zero-based.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Point {
    pub row: usize,
    pub column: usize,
}

/// A range of positions in a multi-line text document, both in terms of bytes and of
/// rows and columns.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Range {
    pub start_byte: usize,
    pub end_byte: usize,
    pub start_point: Point,
    pub end_point: Point,
}

/// A summary of a change to a text document.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct InputEdit {
    pub start_byte: usize,
    pub old_end_byte: usize,
    pub new_end_byte: usize,
    pub start_position: Point,
    pub old_end_position: Point,
    pub new_end_position: Point,
}

/// A single node within a syntax [`Tree`].
#[doc(alias = "TSNode")]
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Node<'tree>(ffi::TSNode, PhantomData<&'tree ()>);

/// A stateful object that this is used to produce a [`Tree`] based on some source code.
#[doc(alias = "TSParser")]
pub struct Parser(NonNull<ffi::TSParser>);

/// A stateful object that is used to look up symbols valid in a specific parse state
#[doc(alias = "TSLookaheadIterator")]
pub struct LookaheadIterator(NonNull<ffi::TSLookaheadIterator>);
struct LookaheadNamesIterator<'a>(&'a mut LookaheadIterator);

/// A type of log message.
#[derive(Debug, PartialEq, Eq)]
pub enum LogType {
    Parse,
    Lex,
}

type FieldId = NonZeroU16;

/// A callback that receives log messages during parser.
type Logger<'a> = Box<dyn FnMut(LogType, &str) + 'a>;

/// A stateful object for walking a syntax [`Tree`] efficiently.
#[doc(alias = "TSTreeCursor")]
pub struct TreeCursor<'cursor>(ffi::TSTreeCursor, PhantomData<&'cursor ()>);

/// A set of patterns that match nodes in a syntax tree.
#[doc(alias = "TSQuery")]
#[derive(Debug)]
#[allow(clippy::type_complexity)]
pub struct Query {
    ptr: NonNull<ffi::TSQuery>,
    capture_names: Box<[&'static str]>,
    capture_quantifiers: Box<[Box<[CaptureQuantifier]>]>,
    text_predicates: Box<[Box<[TextPredicateCapture]>]>,
    property_settings: Box<[Box<[QueryProperty]>]>,
    property_predicates: Box<[Box<[(QueryProperty, bool)]>]>,
    general_predicates: Box<[Box<[QueryPredicate]>]>,
}

/// A quantifier for captures
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum CaptureQuantifier {
    Zero,
    ZeroOrOne,
    ZeroOrMore,
    One,
    OneOrMore,
}

impl From<ffi::TSQuantifier> for CaptureQuantifier {
    fn from(value: ffi::TSQuantifier) -> Self {
        match value {
            ffi::TSQuantifierZero => Self::Zero,
            ffi::TSQuantifierZeroOrOne => Self::ZeroOrOne,
            ffi::TSQuantifierZeroOrMore => Self::ZeroOrMore,
            ffi::TSQuantifierOne => Self::One,
            ffi::TSQuantifierOneOrMore => Self::OneOrMore,
            _ => panic!("Unrecognized quantifier: {value}"),
        }
    }
}

/// A stateful object for executing a [`Query`] on a syntax [`Tree`].
#[doc(alias = "TSQueryCursor")]
pub struct QueryCursor {
    ptr: NonNull<ffi::TSQueryCursor>,
}

/// A key-value pair associated with a particular pattern in a [`Query`].
#[derive(Debug, PartialEq, Eq)]
pub struct QueryProperty {
    pub key: Box<str>,
    pub value: Option<Box<str>>,
    pub capture_id: Option<usize>,
}

#[derive(Debug, PartialEq, Eq)]
pub enum QueryPredicateArg {
    Capture(u32),
    String(Box<str>),
}

/// A key-value pair associated with a particular pattern in a [`Query`].
#[derive(Debug, PartialEq, Eq)]
pub struct QueryPredicate {
    pub operator: Box<str>,
    pub args: Box<[QueryPredicateArg]>,
}

/// A match of a [`Query`] to a particular set of [`Node`]s.
pub struct QueryMatch<'cursor, 'tree> {
    pub pattern_index: usize,
    pub captures: &'cursor [QueryCapture<'tree>],
    id: u32,
    cursor: *mut ffi::TSQueryCursor,
}

/// A sequence of [`QueryMatch`]es associated with a given [`QueryCursor`].
pub struct QueryMatches<'query, 'cursor, T: TextProvider<I>, I: AsRef<[u8]>> {
    ptr: *mut ffi::TSQueryCursor,
    query: &'query Query,
    text_provider: T,
    buffer1: Vec<u8>,
    buffer2: Vec<u8>,
    _phantom: PhantomData<(&'cursor (), I)>,
}

/// A sequence of [`QueryCapture`]s associated with a given [`QueryCursor`].
pub struct QueryCaptures<'query, 'cursor, T: TextProvider<I>, I: AsRef<[u8]>> {
    ptr: *mut ffi::TSQueryCursor,
    query: &'query Query,
    text_provider: T,
    buffer1: Vec<u8>,
    buffer2: Vec<u8>,
    _phantom: PhantomData<(&'cursor (), I)>,
}

pub trait TextProvider<I>
where
    I: AsRef<[u8]>,
{
    type I: Iterator<Item = I>;
    fn text(&mut self, node: Node) -> Self::I;
}

/// A particular [`Node`] that has been captured with a particular name within a [`Query`].
#[derive(Clone, Copy, Debug)]
#[repr(C)]
pub struct QueryCapture<'tree> {
    pub node: Node<'tree>,
    pub index: u32,
}

/// An error that occurred when trying to assign an incompatible [`Language`] to a [`Parser`].
#[derive(Debug, PartialEq, Eq)]
pub struct LanguageError {
    version: usize,
}

/// An error that occurred in [`Parser::set_included_ranges`].
#[derive(Debug, PartialEq, Eq)]
pub struct IncludedRangesError(pub usize);

/// An error that occurred when trying to create a [`Query`].
#[derive(Debug, PartialEq, Eq)]
pub struct QueryError {
    pub row: usize,
    pub column: usize,
    pub offset: usize,
    pub message: String,
    pub kind: QueryErrorKind,
}

#[derive(Debug, PartialEq, Eq)]
pub enum QueryErrorKind {
    Syntax,
    NodeType,
    Field,
    Capture,
    Predicate,
    Structure,
    Language,
}

#[derive(Debug)]
/// The first item is the capture index
/// The next is capture specific, depending on what item is expected
/// The first bool is if the capture is positive
/// The last item is a bool signifying whether or not it's meant to match
/// any or all captures
enum TextPredicateCapture {
    EqString(u32, Box<str>, bool, bool),
    EqCapture(u32, u32, bool, bool),
    MatchString(u32, regex::bytes::Regex, bool, bool),
    AnyString(u32, Box<[Box<str>]>, bool),
}

// TODO: Remove this struct at at some point. If `core::str::lossy::Utf8Lossy`
// is ever stabilized.
pub struct LossyUtf8<'a> {
    bytes: &'a [u8],
    in_replacement: bool,
}

impl Language {
    /// Get the ABI version number that indicates which version of the Tree-sitter CLI
    /// that was used to generate this [`Language`].
    #[doc(alias = "ts_language_version")]
    #[must_use]
    pub fn version(&self) -> usize {
        unsafe { ffi::ts_language_version(self.0) as usize }
    }

    /// Get the number of distinct node types in this language.
    #[doc(alias = "ts_language_symbol_count")]
    #[must_use]
    pub fn node_kind_count(&self) -> usize {
        unsafe { ffi::ts_language_symbol_count(self.0) as usize }
    }

    /// Get the number of valid states in this language.
    #[doc(alias = "ts_language_state_count")]
    #[must_use]
    pub fn parse_state_count(&self) -> usize {
        unsafe { ffi::ts_language_state_count(self.0) as usize }
    }

    /// Get the name of the node kind for the given numerical id.
    #[doc(alias = "ts_language_symbol_name")]
    #[must_use]
    pub fn node_kind_for_id(&self, id: u16) -> Option<&'static str> {
        let ptr = unsafe { ffi::ts_language_symbol_name(self.0, id) };
        (!ptr.is_null()).then(|| unsafe { CStr::from_ptr(ptr) }.to_str().unwrap())
    }

    /// Get the numeric id for the given node kind.
    #[doc(alias = "ts_language_symbol_for_name")]
    #[must_use]
    pub fn id_for_node_kind(&self, kind: &str, named: bool) -> u16 {
        unsafe {
            ffi::ts_language_symbol_for_name(
                self.0,
                kind.as_bytes().as_ptr().cast::<c_char>(),
                kind.len() as u32,
                named,
            )
        }
    }

    /// Check if the node type for the given numerical id is named (as opposed
    /// to an anonymous node type).
    #[must_use]
    pub fn node_kind_is_named(&self, id: u16) -> bool {
        unsafe { ffi::ts_language_symbol_type(self.0, id) == ffi::TSSymbolTypeRegular }
    }

    #[doc(alias = "ts_language_symbol_type")]
    #[must_use]
    pub fn node_kind_is_visible(&self, id: u16) -> bool {
        unsafe { ffi::ts_language_symbol_type(self.0, id) <= ffi::TSSymbolTypeAnonymous }
    }

    /// Get the number of distinct field names in this language.
    #[doc(alias = "ts_language_field_count")]
    #[must_use]
    pub fn field_count(&self) -> usize {
        unsafe { ffi::ts_language_field_count(self.0) as usize }
    }

    /// Get the field names for the given numerical id.
    #[doc(alias = "ts_language_field_name_for_id")]
    #[must_use]
    pub fn field_name_for_id(&self, field_id: u16) -> Option<&'static str> {
        let ptr = unsafe { ffi::ts_language_field_name_for_id(self.0, field_id) };
        (!ptr.is_null()).then(|| unsafe { CStr::from_ptr(ptr) }.to_str().unwrap())
    }

    /// Get the numerical id for the given field name.
    #[doc(alias = "ts_language_field_id_for_name")]
    #[must_use]
    pub fn field_id_for_name(&self, field_name: impl AsRef<[u8]>) -> Option<FieldId> {
        let field_name = field_name.as_ref();
        let id = unsafe {
            ffi::ts_language_field_id_for_name(
                self.0,
                field_name.as_ptr().cast::<c_char>(),
                field_name.len() as u32,
            )
        };
        FieldId::new(id)
    }

    /// Get the next parse state. Combine this with
    /// [`lookahead_iterator`](Language::lookahead_iterator) to
    /// generate completion suggestions or valid symbols in error nodes.
    ///
    /// Example:
    /// ```
    /// let state = language.next_state(node.parse_state(), node.grammar_id());
    /// ```
    #[doc(alias = "ts_language_next_state")]
    #[must_use]
    pub fn next_state(&self, state: u16, id: u16) -> u16 {
        unsafe { ffi::ts_language_next_state(self.0, state, id) }
    }

    /// Create a new lookahead iterator for this language and parse state.
    ///
    /// This returns `None` if state is invalid for this language.
    ///
    /// Iterating [`LookaheadIterator`] will yield valid symbols in the given
    /// parse state. Newly created lookahead iterators will return the `ERROR`
    /// symbol from [`LookaheadIterator::current_symbol`].
    ///
    /// Lookahead iterators can be useful to generate suggestions and improve
    /// syntax error diagnostics. To get symbols valid in an ERROR node, use the
    /// lookahead iterator on its first leaf node state. For `MISSING` nodes, a
    /// lookahead iterator created on the previous non-extra leaf node may be
    /// appropriate.
    #[doc(alias = "ts_lookahead_iterator_new")]
    #[must_use]
    pub fn lookahead_iterator(&self, state: u16) -> Option<LookaheadIterator> {
        let ptr = unsafe { ffi::ts_lookahead_iterator_new(self.0, state) };
        (!ptr.is_null()).then(|| unsafe { LookaheadIterator::from_raw(ptr) })
    }
}

impl Clone for Language {
    fn clone(&self) -> Self {
        unsafe { Self(ffi::ts_language_copy(self.0)) }
    }
}

impl Drop for Language {
    fn drop(&mut self) {
        unsafe { ffi::ts_language_delete(self.0) }
    }
}

impl<'a> Deref for LanguageRef<'a> {
    type Target = Language;

    fn deref(&self) -> &Self::Target {
        unsafe { &*(std::ptr::addr_of!(self.0).cast::<Language>()) }
    }
}

impl Default for Parser {
    fn default() -> Self {
        Self::new()
    }
}

impl Parser {
    /// Create a new parser.
    #[doc(alias = "ts_parser_new")]
    #[must_use]
    pub fn new() -> Self {
        unsafe {
            let parser = ffi::ts_parser_new();
            Self(NonNull::new_unchecked(parser))
        }
    }

    /// Set the language that the parser should use for parsing.
    ///
    /// Returns a Result indicating whether or not the language was successfully
    /// assigned. True means assignment succeeded. False means there was a version
    /// mismatch: the language was generated with an incompatible version of the
    /// Tree-sitter CLI. Check the language's version using [`Language::version`]
    /// and compare it to this library's [`LANGUAGE_VERSION`](LANGUAGE_VERSION) and
    /// [`MIN_COMPATIBLE_LANGUAGE_VERSION`](MIN_COMPATIBLE_LANGUAGE_VERSION) constants.
    #[doc(alias = "ts_parser_set_language")]
    pub fn set_language(&mut self, language: &Language) -> Result<(), LanguageError> {
        let version = language.version();
        if (MIN_COMPATIBLE_LANGUAGE_VERSION..=LANGUAGE_VERSION).contains(&version) {
            unsafe {
                ffi::ts_parser_set_language(self.0.as_ptr(), language.0);
            }
            Ok(())
        } else {
            Err(LanguageError { version })
        }
    }

    /// Get the parser's current language.
    #[doc(alias = "ts_parser_language")]
    #[must_use]
    pub fn language(&self) -> Option<Language> {
        let ptr = unsafe { ffi::ts_parser_language(self.0.as_ptr()) };
        (!ptr.is_null()).then(|| Language(ptr))
    }

    /// Get the parser's current logger.
    #[doc(alias = "ts_parser_logger")]
    #[must_use]
    pub fn logger(&self) -> Option<&Logger> {
        let logger = unsafe { ffi::ts_parser_logger(self.0.as_ptr()) };
        unsafe { logger.payload.cast::<Logger>().as_ref() }
    }

    /// Set the logging callback that a parser should use during parsing.
    #[doc(alias = "ts_parser_set_logger")]
    pub fn set_logger(&mut self, logger: Option<Logger>) {
        let prev_logger = unsafe { ffi::ts_parser_logger(self.0.as_ptr()) };
        if !prev_logger.payload.is_null() {
            drop(unsafe { Box::from_raw(prev_logger.payload.cast::<Logger>()) });
        }

        let c_logger;
        if let Some(logger) = logger {
            let container = Box::new(logger);

            unsafe extern "C" fn log(
                payload: *mut c_void,
                c_log_type: ffi::TSLogType,
                c_message: *const c_char,
            ) {
                let callback = payload.cast::<Logger>().as_mut().unwrap();
                if let Ok(message) = CStr::from_ptr(c_message).to_str() {
                    let log_type = if c_log_type == ffi::TSLogTypeParse {
                        LogType::Parse
                    } else {
                        LogType::Lex
                    };
                    callback(log_type, message);
                }
            }

            let raw_container = Box::into_raw(container);

            c_logger = ffi::TSLogger {
                payload: raw_container.cast::<c_void>(),
                log: Some(log),
            };
        } else {
            c_logger = ffi::TSLogger {
                payload: ptr::null_mut(),
                log: None,
            };
        }

        unsafe { ffi::ts_parser_set_logger(self.0.as_ptr(), c_logger) };
    }

    /// Set the destination to which the parser should write debugging graphs
    /// during parsing. The graphs are formatted in the DOT language. You may want
    /// to pipe these graphs directly to a `dot(1)` process in order to generate
    /// SVG output.
    #[doc(alias = "ts_parser_print_dot_graphs")]
    pub fn print_dot_graphs(
        &mut self,
        #[cfg(not(windows))] file: &impl AsRawFd,
        #[cfg(windows)] file: &impl AsRawHandle,
    ) {
        #[cfg(not(windows))]
        {
            let fd = file.as_raw_fd();
            unsafe {
                ffi::ts_parser_print_dot_graphs(self.0.as_ptr(), ffi::_ts_dup(fd));
            }
        }

        #[cfg(windows)]
        {
            let handle = file.as_raw_handle();
            unsafe {
                ffi::ts_parser_print_dot_graphs(self.0.as_ptr(), ffi::_ts_dup(handle));
            }
        }
    }

    /// Stop the parser from printing debugging graphs while parsing.
    #[doc(alias = "ts_parser_print_dot_graphs")]
    pub fn stop_printing_dot_graphs(&mut self) {
        unsafe { ffi::ts_parser_print_dot_graphs(self.0.as_ptr(), -1) }
    }

    /// Parse a slice of UTF8 text.
    ///
    /// # Arguments:
    /// * `text` The UTF8-encoded text to parse.
    /// * `old_tree` A previous syntax tree parsed from the same document.
    ///   If the text of the document has changed since `old_tree` was
    ///   created, then you must edit `old_tree` to match the new text using
    ///   [`Tree::edit`].
    ///
    /// Returns a [`Tree`] if parsing succeeded, or `None` if:
    ///  * The parser has not yet had a language assigned with [`Parser::set_language`]
    ///  * The timeout set with [`Parser::set_timeout_micros`] expired
    ///  * The cancellation flag set with [`Parser::set_cancellation_flag`] was flipped
    #[doc(alias = "ts_parser_parse")]
    pub fn parse(&mut self, text: impl AsRef<[u8]>, old_tree: Option<&Tree>) -> Option<Tree> {
        let bytes = text.as_ref();
        let len = bytes.len();
        self.parse_with(
            &mut |i, _| (i < len).then(|| &bytes[i..]).unwrap_or_default(),
            old_tree,
        )
    }

    /// Parse a slice of UTF16 text.
    ///
    /// # Arguments:
    /// * `text` The UTF16-encoded text to parse.
    /// * `old_tree` A previous syntax tree parsed from the same document.
    ///   If the text of the document has changed since `old_tree` was
    ///   created, then you must edit `old_tree` to match the new text using
    ///   [`Tree::edit`].
    pub fn parse_utf16(
        &mut self,
        input: impl AsRef<[u16]>,
        old_tree: Option<&Tree>,
    ) -> Option<Tree> {
        let code_points = input.as_ref();
        let len = code_points.len();
        self.parse_utf16_with(
            &mut |i, _| (i < len).then(|| &code_points[i..]).unwrap_or_default(),
            old_tree,
        )
    }

    /// Parse UTF8 text provided in chunks by a callback.
    ///
    /// # Arguments:
    /// * `callback` A function that takes a byte offset and position and
    ///   returns a slice of UTF8-encoded text starting at that byte offset
    ///   and position. The slices can be of any length. If the given position
    ///   is at the end of the text, the callback should return an empty slice.
    /// * `old_tree` A previous syntax tree parsed from the same document.
    ///   If the text of the document has changed since `old_tree` was
    ///   created, then you must edit `old_tree` to match the new text using
    ///   [`Tree::edit`].
    pub fn parse_with<T: AsRef<[u8]>, F: FnMut(usize, Point) -> T>(
        &mut self,
        callback: &mut F,
        old_tree: Option<&Tree>,
    ) -> Option<Tree> {
        // A pointer to this payload is passed on every call to the `read` C function.
        // The payload contains two things:
        // 1. A reference to the rust `callback`.
        // 2. The text that was returned from the previous call to `callback`.
        //    This allows the callback to return owned values like vectors.
        let mut payload: (&mut F, Option<T>) = (callback, None);

        // This C function is passed to Tree-sitter as the input callback.
        unsafe extern "C" fn read<T: AsRef<[u8]>, F: FnMut(usize, Point) -> T>(
            payload: *mut c_void,
            byte_offset: u32,
            position: ffi::TSPoint,
            bytes_read: *mut u32,
        ) -> *const c_char {
            let (callback, text) = payload.cast::<(&mut F, Option<T>)>().as_mut().unwrap();
            *text = Some(callback(byte_offset as usize, position.into()));
            let slice = text.as_ref().unwrap().as_ref();
            *bytes_read = slice.len() as u32;
            slice.as_ptr().cast::<c_char>()
        }

        let c_input = ffi::TSInput {
            payload: std::ptr::addr_of_mut!(payload).cast::<c_void>(),
            read: Some(read::<T, F>),
            encoding: ffi::TSInputEncodingUTF8,
        };

        let c_old_tree = old_tree.map_or(ptr::null_mut(), |t| t.0.as_ptr());
        unsafe {
            let c_new_tree = ffi::ts_parser_parse(self.0.as_ptr(), c_old_tree, c_input);
            NonNull::new(c_new_tree).map(Tree)
        }
    }

    /// Parse UTF16 text provided in chunks by a callback.
    ///
    /// # Arguments:
    /// * `callback` A function that takes a code point offset and position and
    ///   returns a slice of UTF16-encoded text starting at that byte offset
    ///   and position. The slices can be of any length. If the given position
    ///   is at the end of the text, the callback should return an empty slice.
    /// * `old_tree` A previous syntax tree parsed from the same document.
    ///   If the text of the document has changed since `old_tree` was
    ///   created, then you must edit `old_tree` to match the new text using
    ///   [`Tree::edit`].
    pub fn parse_utf16_with<T: AsRef<[u16]>, F: FnMut(usize, Point) -> T>(
        &mut self,
        callback: &mut F,
        old_tree: Option<&Tree>,
    ) -> Option<Tree> {
        // A pointer to this payload is passed on every call to the `read` C function.
        // The payload contains two things:
        // 1. A reference to the rust `callback`.
        // 2. The text that was returned from the previous call to `callback`.
        //    This allows the callback to return owned values like vectors.
        let mut payload: (&mut F, Option<T>) = (callback, None);

        // This C function is passed to Tree-sitter as the input callback.
        unsafe extern "C" fn read<T: AsRef<[u16]>, F: FnMut(usize, Point) -> T>(
            payload: *mut c_void,
            byte_offset: u32,
            position: ffi::TSPoint,
            bytes_read: *mut u32,
        ) -> *const c_char {
            let (callback, text) = payload.cast::<(&mut F, Option<T>)>().as_mut().unwrap();
            *text = Some(callback(
                (byte_offset / 2) as usize,
                Point {
                    row: position.row as usize,
                    column: position.column as usize / 2,
                },
            ));
            let slice = text.as_ref().unwrap().as_ref();
            *bytes_read = slice.len() as u32 * 2;
            slice.as_ptr().cast::<c_char>()
        }

        let c_input = ffi::TSInput {
            payload: std::ptr::addr_of_mut!(payload).cast::<c_void>(),
            read: Some(read::<T, F>),
            encoding: ffi::TSInputEncodingUTF16,
        };

        let c_old_tree = old_tree.map_or(ptr::null_mut(), |t| t.0.as_ptr());
        unsafe {
            let c_new_tree = ffi::ts_parser_parse(self.0.as_ptr(), c_old_tree, c_input);
            NonNull::new(c_new_tree).map(Tree)
        }
    }

    /// Instruct the parser to start the next parse from the beginning.
    ///
    /// If the parser previously failed because of a timeout or a cancellation, then by default, it
    /// will resume where it left off on the next call to [`parse`](Parser::parse) or other parsing
    /// functions. If you don't want to resume, and instead intend to use this parser to parse some
    /// other document, you must call `reset` first.
    #[doc(alias = "ts_parser_reset")]
    pub fn reset(&mut self) {
        unsafe { ffi::ts_parser_reset(self.0.as_ptr()) }
    }

    /// Get the duration in microseconds that parsing is allowed to take.
    ///
    /// This is set via [`set_timeout_micros`](Parser::set_timeout_micros).
    #[doc(alias = "ts_parser_timeout_micros")]
    #[must_use]
    pub fn timeout_micros(&self) -> u64 {
        unsafe { ffi::ts_parser_timeout_micros(self.0.as_ptr()) }
    }

    /// Set the maximum duration in microseconds that parsing should be allowed to
    /// take before halting.
    ///
    /// If parsing takes longer than this, it will halt early, returning `None`.
    /// See [`parse`](Parser::parse) for more information.
    #[doc(alias = "ts_parser_set_timeout_micros")]
    pub fn set_timeout_micros(&mut self, timeout_micros: u64) {
        unsafe { ffi::ts_parser_set_timeout_micros(self.0.as_ptr(), timeout_micros) }
    }

    /// Set the ranges of text that the parser should include when parsing.
    ///
    /// By default, the parser will always include entire documents. This function
    /// allows you to parse only a *portion* of a document but still return a syntax
    /// tree whose ranges match up with the document as a whole. You can also pass
    /// multiple disjoint ranges.
    ///
    /// If `ranges` is empty, then the entire document will be parsed. Otherwise,
    /// the given ranges must be ordered from earliest to latest in the document,
    /// and they must not overlap. That is, the following must hold for all
    /// `i` < `length - 1`:
    /// ```text
    ///     ranges[i].end_byte <= ranges[i + 1].start_byte
    /// ```
    /// If this requirement is not satisfied, method will return [`IncludedRangesError`]
    /// error with an offset in the passed ranges slice pointing to a first incorrect range.
    #[doc(alias = "ts_parser_set_included_ranges")]
    pub fn set_included_ranges(&mut self, ranges: &[Range]) -> Result<(), IncludedRangesError> {
        let ts_ranges = ranges
            .iter()
            .copied()
            .map(std::convert::Into::into)
            .collect::<Vec<_>>();
        let result = unsafe {
            ffi::ts_parser_set_included_ranges(
                self.0.as_ptr(),
                ts_ranges.as_ptr(),
                ts_ranges.len() as u32,
            )
        };

        if result {
            Ok(())
        } else {
            let mut prev_end_byte = 0;
            for (i, range) in ranges.iter().enumerate() {
                if range.start_byte < prev_end_byte || range.end_byte < range.start_byte {
                    return Err(IncludedRangesError(i));
                }
                prev_end_byte = range.end_byte;
            }
            Err(IncludedRangesError(0))
        }
    }

    /// Get the ranges of text that the parser will include when parsing.
    #[doc(alias = "ts_parser_included_ranges")]
    #[must_use]
    pub fn included_ranges(&self) -> Vec<Range> {
        let mut count = 0u32;
        unsafe {
            let ptr =
                ffi::ts_parser_included_ranges(self.0.as_ptr(), std::ptr::addr_of_mut!(count));
            let ranges = slice::from_raw_parts(ptr, count as usize);
            let result = ranges
                .iter()
                .copied()
                .map(std::convert::Into::into)
                .collect();
            result
        }
    }

    /// Get the parser's current cancellation flag pointer.
    ///
    /// # Safety
    ///
    /// It uses FFI
    #[doc(alias = "ts_parser_cancellation_flag")]
    #[must_use]
    pub unsafe fn cancellation_flag(&self) -> Option<&AtomicUsize> {
        ffi::ts_parser_cancellation_flag(self.0.as_ptr())
            .cast::<AtomicUsize>()
            .as_ref()
    }

    /// Set the parser's current cancellation flag pointer.
    ///
    /// If a pointer is assigned, then the parser will periodically read from
    /// this pointer during parsing. If it reads a non-zero value, it will halt early,
    /// returning `None`. See [`parse`](Parser::parse) for more information.
    ///
    /// # Safety
    ///
    /// It uses FFI
    #[doc(alias = "ts_parser_set_cancellation_flag")]
    pub unsafe fn set_cancellation_flag(&mut self, flag: Option<&AtomicUsize>) {
        if let Some(flag) = flag {
            ffi::ts_parser_set_cancellation_flag(
                self.0.as_ptr(),
                (flag as *const AtomicUsize).cast::<usize>(),
            );
        } else {
            ffi::ts_parser_set_cancellation_flag(self.0.as_ptr(), ptr::null());
        }
    }
}

impl Drop for Parser {
    fn drop(&mut self) {
        self.stop_printing_dot_graphs();
        self.set_logger(None);
        unsafe { ffi::ts_parser_delete(self.0.as_ptr()) }
    }
}

impl Tree {
    /// Get the root node of the syntax tree.
    #[doc(alias = "ts_tree_root_node")]
    #[must_use]
    pub fn root_node(&self) -> Node {
        Node::new(unsafe { ffi::ts_tree_root_node(self.0.as_ptr()) }).unwrap()
    }

    /// Get the root node of the syntax tree, but with its position shifted
    /// forward by the given offset.
    #[doc(alias = "ts_tree_root_node_with_offset")]
    #[must_use]
    pub fn root_node_with_offset(&self, offset_bytes: usize, offset_extent: Point) -> Node {
        Node::new(unsafe {
            ffi::ts_tree_root_node_with_offset(
                self.0.as_ptr(),
                offset_bytes as u32,
                offset_extent.into(),
            )
        })
        .unwrap()
    }

    /// Get the language that was used to parse the syntax tree.
    #[doc(alias = "ts_tree_language")]
    #[must_use]
    pub fn language(&self) -> LanguageRef {
        LanguageRef(
            unsafe { ffi::ts_tree_language(self.0.as_ptr()) },
            PhantomData,
        )
    }

    /// Edit the syntax tree to keep it in sync with source code that has been
    /// edited.
    ///
    /// You must describe the edit both in terms of byte offsets and in terms of
    /// row/column coordinates.
    #[doc(alias = "ts_tree_edit")]
    pub fn edit(&mut self, edit: &InputEdit) {
        let edit = edit.into();
        unsafe { ffi::ts_tree_edit(self.0.as_ptr(), &edit) };
    }

    /// Create a new [`TreeCursor`] starting from the root of the tree.
    #[must_use]
    pub fn walk(&self) -> TreeCursor {
        self.root_node().walk()
    }

    /// Compare this old edited syntax tree to a new syntax tree representing the same
    /// document, returning a sequence of ranges whose syntactic structure has changed.
    ///
    /// For this to work correctly, this syntax tree must have been edited such that its
    /// ranges match up to the new tree. Generally, you'll want to call this method right
    /// after calling one of the [`Parser::parse`] functions. Call it on the old tree that
    /// was passed to parse, and pass the new tree that was returned from `parse`.
    #[doc(alias = "ts_tree_get_changed_ranges")]
    #[must_use]
    pub fn changed_ranges(&self, other: &Self) -> impl ExactSizeIterator<Item = Range> {
        let mut count = 0u32;
        unsafe {
            let ptr = ffi::ts_tree_get_changed_ranges(
                self.0.as_ptr(),
                other.0.as_ptr(),
                std::ptr::addr_of_mut!(count),
            );
            util::CBufferIter::new(ptr, count as usize).map(std::convert::Into::into)
        }
    }

    /// Get the included ranges that were used to parse the syntax tree.
    #[doc(alias = "ts_tree_included_ranges")]
    #[must_use]
    pub fn included_ranges(&self) -> Vec<Range> {
        let mut count = 0u32;
        unsafe {
            let ptr = ffi::ts_tree_included_ranges(self.0.as_ptr(), std::ptr::addr_of_mut!(count));
            let ranges = slice::from_raw_parts(ptr, count as usize);
            let result = ranges
                .iter()
                .copied()
                .map(std::convert::Into::into)
                .collect();
            (FREE_FN)(ptr.cast::<c_void>());
            result
        }
    }

    /// Print a graph of the tree to the given file descriptor.
    /// The graph is formatted in the DOT language. You may want to pipe this graph
    /// directly to a `dot(1)` process in order to generate SVG output.
    #[doc(alias = "ts_tree_print_dot_graph")]
    pub fn print_dot_graph(
        &self,
        #[cfg(unix)] file: &impl AsRawFd,
        #[cfg(windows)] file: &impl AsRawHandle,
    ) {
        #[cfg(unix)]
        {
            let fd = file.as_raw_fd();
            unsafe { ffi::ts_tree_print_dot_graph(self.0.as_ptr(), fd) }
        }

        #[cfg(windows)]
        {
            let handle = file.as_raw_handle();
            unsafe { ffi::ts_tree_print_dot_graph(self.0.as_ptr(), handle as i32) }
        }
    }
}

impl fmt::Debug for Tree {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{{Tree {:?}}}", self.root_node())
    }
}

impl Drop for Tree {
    fn drop(&mut self) {
        unsafe { ffi::ts_tree_delete(self.0.as_ptr()) }
    }
}

impl Clone for Tree {
    fn clone(&self) -> Self {
        unsafe { Self(NonNull::new_unchecked(ffi::ts_tree_copy(self.0.as_ptr()))) }
    }
}

impl<'tree> Node<'tree> {
    fn new(node: ffi::TSNode) -> Option<Self> {
        (!node.id.is_null()).then_some(Node(node, PhantomData))
    }

    /// Get a numeric id for this node that is unique.
    ///
    /// Within a given syntax tree, no two nodes have the same id. However, if
    /// a new tree is created based on an older tree, and a node from the old
    /// tree is reused in the process, then that node will have the same id in
    /// both trees.
    #[must_use]
    pub fn id(&self) -> usize {
        self.0.id as usize
    }

    /// Get this node's type as a numerical id.
    #[doc(alias = "ts_node_symbol")]
    #[must_use]
    pub fn kind_id(&self) -> u16 {
        unsafe { ffi::ts_node_symbol(self.0) }
    }

    /// Get the node's type as a numerical id as it appears in the grammar
    /// ignoring aliases.
    #[doc(alias = "ts_node_grammar_symbol")]
    #[must_use]
    pub fn grammar_id(&self) -> u16 {
        unsafe { ffi::ts_node_grammar_symbol(self.0) }
    }

    /// Get this node's type as a string.
    #[doc(alias = "ts_node_type")]
    #[must_use]
    pub fn kind(&self) -> &'static str {
        unsafe { CStr::from_ptr(ffi::ts_node_type(self.0)) }
            .to_str()
            .unwrap()
    }

    /// Get this node's symbol name as it appears in the grammar ignoring
    /// aliases as a string.
    #[doc(alias = "ts_node_grammar_type")]
    #[must_use]
    pub fn grammar_name(&self) -> &'static str {
        unsafe { CStr::from_ptr(ffi::ts_node_grammar_type(self.0)) }
            .to_str()
            .unwrap()
    }

    /// Get the [`Language`] that was used to parse this node's syntax tree.
    #[doc(alias = "ts_node_language")]
    #[must_use]
    pub fn language(&self) -> LanguageRef {
        LanguageRef(unsafe { ffi::ts_node_language(self.0) }, PhantomData)
    }

    /// Check if this node is *named*.
    ///
    /// Named nodes correspond to named rules in the grammar, whereas *anonymous* nodes
    /// correspond to string literals in the grammar.
    #[doc(alias = "ts_node_is_named")]
    #[must_use]
    pub fn is_named(&self) -> bool {
        unsafe { ffi::ts_node_is_named(self.0) }
    }

    /// Check if this node is *extra*.
    ///
    /// Extra nodes represent things like comments, which are not required the grammar,
    /// but can appear anywhere.
    #[doc(alias = "ts_node_is_extra")]
    #[must_use]
    pub fn is_extra(&self) -> bool {
        unsafe { ffi::ts_node_is_extra(self.0) }
    }

    /// Check if this node has been edited.
    #[doc(alias = "ts_node_has_changes")]
    #[must_use]
    pub fn has_changes(&self) -> bool {
        unsafe { ffi::ts_node_has_changes(self.0) }
    }

    /// Check if this node represents a syntax error or contains any syntax errors anywhere
    /// within it.
    #[doc(alias = "ts_node_has_error")]
    #[must_use]
    pub fn has_error(&self) -> bool {
        unsafe { ffi::ts_node_has_error(self.0) }
    }

    /// Check if this node represents a syntax error.
    ///
    /// Syntax errors represent parts of the code that could not be incorporated into a
    /// valid syntax tree.
    #[doc(alias = "ts_node_is_error")]
    #[must_use]
    pub fn is_error(&self) -> bool {
        unsafe { ffi::ts_node_is_error(self.0) }
    }

    /// Get this node's parse state.
    #[doc(alias = "ts_node_parse_state")]
    #[must_use]
    pub fn parse_state(&self) -> u16 {
        unsafe { ffi::ts_node_parse_state(self.0) }
    }

    /// Get the parse state after this node.
    #[doc(alias = "ts_node_next_parse_state")]
    #[must_use]
    pub fn next_parse_state(&self) -> u16 {
        unsafe { ffi::ts_node_next_parse_state(self.0) }
    }

    /// Check if this node is *missing*.
    ///
    /// Missing nodes are inserted by the parser in order to recover from certain kinds of
    /// syntax errors.
    #[doc(alias = "ts_node_is_missing")]
    #[must_use]
    pub fn is_missing(&self) -> bool {
        unsafe { ffi::ts_node_is_missing(self.0) }
    }

    /// Get the byte offsets where this node starts.
    #[doc(alias = "ts_node_start_byte")]
    #[must_use]
    pub fn start_byte(&self) -> usize {
        unsafe { ffi::ts_node_start_byte(self.0) as usize }
    }

    /// Get the byte offsets where this node end.
    #[doc(alias = "ts_node_end_byte")]
    #[must_use]
    pub fn end_byte(&self) -> usize {
        unsafe { ffi::ts_node_end_byte(self.0) as usize }
    }

    /// Get the byte range of source code that this node represents.
    #[must_use]
    pub fn byte_range(&self) -> std::ops::Range<usize> {
        self.start_byte()..self.end_byte()
    }

    /// Get the range of source code that this node represents, both in terms of raw bytes
    /// and of row/column coordinates.
    #[must_use]
    pub fn range(&self) -> Range {
        Range {
            start_byte: self.start_byte(),
            end_byte: self.end_byte(),
            start_point: self.start_position(),
            end_point: self.end_position(),
        }
    }

    /// Get this node's start position in terms of rows and columns.
    #[doc(alias = "ts_node_start_point")]
    #[must_use]
    pub fn start_position(&self) -> Point {
        let result = unsafe { ffi::ts_node_start_point(self.0) };
        result.into()
    }

    /// Get this node's end position in terms of rows and columns.
    #[doc(alias = "ts_node_end_point")]
    #[must_use]
    pub fn end_position(&self) -> Point {
        let result = unsafe { ffi::ts_node_end_point(self.0) };
        result.into()
    }

    /// Get the node's child at the given index, where zero represents the first
    /// child.
    ///
    /// This method is fairly fast, but its cost is technically log(i), so if
    /// you might be iterating over a long list of children, you should use
    /// [`Node::children`] instead.
    #[doc(alias = "ts_node_child")]
    #[must_use]
    pub fn child(&self, i: usize) -> Option<Self> {
        Self::new(unsafe { ffi::ts_node_child(self.0, i as u32) })
    }

    /// Get this node's number of children.
    #[doc(alias = "ts_node_child_count")]
    #[must_use]
    pub fn child_count(&self) -> usize {
        unsafe { ffi::ts_node_child_count(self.0) as usize }
    }

    /// Get this node's *named* child at the given index.
    ///
    /// See also [`Node::is_named`].
    /// This method is fairly fast, but its cost is technically log(i), so if
    /// you might be iterating over a long list of children, you should use
    /// [`Node::named_children`] instead.
    #[doc(alias = "ts_node_named_child")]
    #[must_use]
    pub fn named_child(&self, i: usize) -> Option<Self> {
        Self::new(unsafe { ffi::ts_node_named_child(self.0, i as u32) })
    }

    /// Get this node's number of *named* children.
    ///
    /// See also [`Node::is_named`].
    #[doc(alias = "ts_node_named_child_count")]
    #[must_use]
    pub fn named_child_count(&self) -> usize {
        unsafe { ffi::ts_node_named_child_count(self.0) as usize }
    }

    /// Get the first child with the given field name.
    ///
    /// If multiple children may have the same field name, access them using
    /// [`children_by_field_name`](Node::children_by_field_name)
    #[doc(alias = "ts_node_child_by_field_name")]
    #[must_use]
    pub fn child_by_field_name(&self, field_name: impl AsRef<[u8]>) -> Option<Self> {
        let field_name = field_name.as_ref();
        Self::new(unsafe {
            ffi::ts_node_child_by_field_name(
                self.0,
                field_name.as_ptr().cast::<c_char>(),
                field_name.len() as u32,
            )
        })
    }

    /// Get this node's child with the given numerical field id.
    ///
    /// See also [`child_by_field_name`](Node::child_by_field_name). You can convert a field name to
    /// an id using [`Language::field_id_for_name`].
    #[doc(alias = "ts_node_child_by_field_id")]
    #[must_use]
    pub fn child_by_field_id(&self, field_id: u16) -> Option<Self> {
        Self::new(unsafe { ffi::ts_node_child_by_field_id(self.0, field_id) })
    }

    /// Get the field name of this node's child at the given index.
    #[doc(alias = "ts_node_field_name_for_child")]
    #[must_use]
    pub fn field_name_for_child(&self, child_index: u32) -> Option<&'static str> {
        unsafe {
            let ptr = ffi::ts_node_field_name_for_child(self.0, child_index);
            (!ptr.is_null()).then(|| CStr::from_ptr(ptr).to_str().unwrap())
        }
    }

    /// Iterate over this node's children.
    ///
    /// A [`TreeCursor`] is used to retrieve the children efficiently. Obtain
    /// a [`TreeCursor`] by calling [`Tree::walk`] or [`Node::walk`]. To avoid unnecessary
    /// allocations, you should reuse the same cursor for subsequent calls to
    /// this method.
    ///
    /// If you're walking the tree recursively, you may want to use the [`TreeCursor`]
    /// APIs directly instead.
    pub fn children<'cursor>(
        &self,
        cursor: &'cursor mut TreeCursor<'tree>,
    ) -> impl ExactSizeIterator<Item = Node<'tree>> + 'cursor {
        cursor.reset(*self);
        cursor.goto_first_child();
        (0..self.child_count()).map(move |_| {
            let result = cursor.node();
            cursor.goto_next_sibling();
            result
        })
    }

    /// Iterate over this node's named children.
    ///
    /// See also [`Node::children`].
    pub fn named_children<'cursor>(
        &self,
        cursor: &'cursor mut TreeCursor<'tree>,
    ) -> impl ExactSizeIterator<Item = Node<'tree>> + 'cursor {
        cursor.reset(*self);
        cursor.goto_first_child();
        (0..self.named_child_count()).map(move |_| {
            while !cursor.node().is_named() {
                if !cursor.goto_next_sibling() {
                    break;
                }
            }
            let result = cursor.node();
            cursor.goto_next_sibling();
            result
        })
    }

    /// Iterate over this node's children with a given field name.
    ///
    /// See also [`Node::children`].
    pub fn children_by_field_name<'cursor>(
        &self,
        field_name: &str,
        cursor: &'cursor mut TreeCursor<'tree>,
    ) -> impl Iterator<Item = Node<'tree>> + 'cursor {
        let field_id = self.language().field_id_for_name(field_name);
        let mut done = field_id.is_none();
        if !done {
            cursor.reset(*self);
            cursor.goto_first_child();
        }
        iter::from_fn(move || {
            if !done {
                while cursor.field_id() != field_id {
                    if !cursor.goto_next_sibling() {
                        return None;
                    }
                }
                let result = cursor.node();
                if !cursor.goto_next_sibling() {
                    done = true;
                }
                return Some(result);
            }
            None
        })
    }

    /// Iterate over this node's children with a given field id.
    ///
    /// See also [`Node::children_by_field_name`].
    pub fn children_by_field_id<'cursor>(
        &self,
        field_id: FieldId,
        cursor: &'cursor mut TreeCursor<'tree>,
    ) -> impl Iterator<Item = Node<'tree>> + 'cursor {
        cursor.reset(*self);
        cursor.goto_first_child();
        let mut done = false;
        iter::from_fn(move || {
            if !done {
                while cursor.field_id() != Some(field_id) {
                    if !cursor.goto_next_sibling() {
                        return None;
                    }
                }
                let result = cursor.node();
                if !cursor.goto_next_sibling() {
                    done = true;
                }
                return Some(result);
            }
            None
        })
    }

    /// Get this node's immediate parent.
    #[doc(alias = "ts_node_parent")]
    #[must_use]
    pub fn parent(&self) -> Option<Self> {
        Self::new(unsafe { ffi::ts_node_parent(self.0) })
    }

    /// Get this node's next sibling.
    #[doc(alias = "ts_node_next_sibling")]
    #[must_use]
    pub fn next_sibling(&self) -> Option<Self> {
        Self::new(unsafe { ffi::ts_node_next_sibling(self.0) })
    }

    /// Get this node's previous sibling.
    #[doc(alias = "ts_node_prev_sibling")]
    #[must_use]
    pub fn prev_sibling(&self) -> Option<Self> {
        Self::new(unsafe { ffi::ts_node_prev_sibling(self.0) })
    }

    /// Get this node's next named sibling.
    #[doc(alias = "ts_node_next_named_sibling")]
    #[must_use]
    pub fn next_named_sibling(&self) -> Option<Self> {
        Self::new(unsafe { ffi::ts_node_next_named_sibling(self.0) })
    }

    /// Get this node's previous named sibling.
    #[doc(alias = "ts_node_prev_named_sibling")]
    #[must_use]
    pub fn prev_named_sibling(&self) -> Option<Self> {
        Self::new(unsafe { ffi::ts_node_prev_named_sibling(self.0) })
    }

    /// Get the node's number of descendants, including one for the node itself.
    #[doc(alias = "ts_node_descendant_count")]
    #[must_use]
    pub fn descendant_count(&self) -> usize {
        unsafe { ffi::ts_node_descendant_count(self.0) as usize }
    }

    /// Get the smallest node within this node that spans the given range.
    #[doc(alias = "ts_node_descendant_for_byte_range")]
    #[must_use]
    pub fn descendant_for_byte_range(&self, start: usize, end: usize) -> Option<Self> {
        Self::new(unsafe {
            ffi::ts_node_descendant_for_byte_range(self.0, start as u32, end as u32)
        })
    }

    /// Get the smallest named node within this node that spans the given range.
    #[doc(alias = "ts_node_named_descendant_for_byte_range")]
    #[must_use]
    pub fn named_descendant_for_byte_range(&self, start: usize, end: usize) -> Option<Self> {
        Self::new(unsafe {
            ffi::ts_node_named_descendant_for_byte_range(self.0, start as u32, end as u32)
        })
    }

    /// Get the smallest node within this node that spans the given range.
    #[doc(alias = "ts_node_descendant_for_point_range")]
    #[must_use]
    pub fn descendant_for_point_range(&self, start: Point, end: Point) -> Option<Self> {
        Self::new(unsafe {
            ffi::ts_node_descendant_for_point_range(self.0, start.into(), end.into())
        })
    }

    /// Get the smallest named node within this node that spans the given range.
    #[doc(alias = "ts_node_named_descendant_for_point_range")]
    #[must_use]
    pub fn named_descendant_for_point_range(&self, start: Point, end: Point) -> Option<Self> {
        Self::new(unsafe {
            ffi::ts_node_named_descendant_for_point_range(self.0, start.into(), end.into())
        })
    }

    #[doc(alias = "ts_node_string")]
    #[must_use]
    pub fn to_sexp(&self) -> String {
        let c_string = unsafe { ffi::ts_node_string(self.0) };
        let result = unsafe { CStr::from_ptr(c_string) }
            .to_str()
            .unwrap()
            .to_string();
        unsafe { (FREE_FN)(c_string.cast::<c_void>()) };
        result
    }

    pub fn utf8_text<'a>(&self, source: &'a [u8]) -> Result<&'a str, str::Utf8Error> {
        str::from_utf8(&source[self.start_byte()..self.end_byte()])
    }

    #[must_use]
    pub fn utf16_text<'a>(&self, source: &'a [u16]) -> &'a [u16] {
        &source[self.start_byte()..self.end_byte()]
    }

    /// Create a new [`TreeCursor`] starting from this node.
    #[doc(alias = "ts_tree_cursor_new")]
    #[must_use]
    pub fn walk(&self) -> TreeCursor<'tree> {
        TreeCursor(unsafe { ffi::ts_tree_cursor_new(self.0) }, PhantomData)
    }

    /// Edit this node to keep it in-sync with source code that has been edited.
    ///
    /// This function is only rarely needed. When you edit a syntax tree with the
    /// [`Tree::edit`] method, all of the nodes that you retrieve from the tree
    /// afterward will already reflect the edit. You only need to use [`Node::edit`]
    /// when you have a specific [`Node`] instance that you want to keep and continue
    /// to use after an edit.
    #[doc(alias = "ts_node_edit")]
    pub fn edit(&mut self, edit: &InputEdit) {
        let edit = edit.into();
        unsafe { ffi::ts_node_edit(std::ptr::addr_of_mut!(self.0), &edit) }
    }
}

impl PartialEq for Node<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.0.id == other.0.id
    }
}

impl Eq for Node<'_> {}

impl hash::Hash for Node<'_> {
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        self.0.id.hash(state);
        self.0.context[0].hash(state);
        self.0.context[1].hash(state);
        self.0.context[2].hash(state);
        self.0.context[3].hash(state);
    }
}

impl fmt::Debug for Node<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{{Node {} {} - {}}}",
            self.kind(),
            self.start_position(),
            self.end_position()
        )
    }
}

impl fmt::Display for Node<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let sexp = self.to_sexp();
        if sexp.is_empty() {
            write!(f, "")
        } else if !f.alternate() {
            write!(f, "{}", sexp)
        } else {
            write!(f, "{}", format_sexp(&sexp, f.width().unwrap_or(0)))
        }
    }
}

impl<'cursor> TreeCursor<'cursor> {
    /// Get the tree cursor's current [`Node`].
    #[doc(alias = "ts_tree_cursor_current_node")]
    #[must_use]
    pub fn node(&self) -> Node<'cursor> {
        Node(
            unsafe { ffi::ts_tree_cursor_current_node(&self.0) },
            PhantomData,
        )
    }

    /// Get the numerical field id of this tree cursor's current node.
    ///
    /// See also [`field_name`](TreeCursor::field_name).
    #[doc(alias = "ts_tree_cursor_current_field_id")]
    #[must_use]
    pub fn field_id(&self) -> Option<FieldId> {
        let id = unsafe { ffi::ts_tree_cursor_current_field_id(&self.0) };
        FieldId::new(id)
    }

    /// Get the field name of this tree cursor's current node.
    #[doc(alias = "ts_tree_cursor_current_field_name")]
    #[must_use]
    pub fn field_name(&self) -> Option<&'static str> {
        unsafe {
            let ptr = ffi::ts_tree_cursor_current_field_name(&self.0);
            (!ptr.is_null()).then(|| CStr::from_ptr(ptr).to_str().unwrap())
        }
    }

    /// Get the numerical field id of this tree cursor's current node.
    ///
    /// See also [`field_name`](TreeCursor::field_name).
    #[doc(alias = "ts_tree_cursor_current_depth")]
    #[must_use]
    pub fn depth(&self) -> u32 {
        unsafe { ffi::ts_tree_cursor_current_depth(&self.0) }
    }

    /// Get the index of the cursor's current node out of all of the
    /// descendants of the original node that the cursor was constructed with
    #[doc(alias = "ts_tree_cursor_current_descendant_index")]
    #[must_use]
    pub fn descendant_index(&self) -> usize {
        unsafe { ffi::ts_tree_cursor_current_descendant_index(&self.0) as usize }
    }

    /// Move this cursor to the first child of its current node.
    ///
    /// This returns `true` if the cursor successfully moved, and returns `false`
    /// if there were no children.
    #[doc(alias = "ts_tree_cursor_goto_first_child")]
    pub fn goto_first_child(&mut self) -> bool {
        unsafe { ffi::ts_tree_cursor_goto_first_child(&mut self.0) }
    }

    /// Move this cursor to the last child of its current node.
    ///
    /// This returns `true` if the cursor successfully moved, and returns
    /// `false` if there were no children.
    ///
    /// Note that this function may be slower than
    /// [`goto_first_child`](TreeCursor::goto_first_child) because it needs to
    /// iterate through all the children to compute the child's position.
    #[doc(alias = "ts_tree_cursor_goto_last_child")]
    pub fn goto_last_child(&mut self) -> bool {
        unsafe { ffi::ts_tree_cursor_goto_last_child(&mut self.0) }
    }

    /// Move this cursor to the parent of its current node.
    ///
    /// This returns `true` if the cursor successfully moved, and returns `false`
    /// if there was no parent node (the cursor was already on the root node).
    #[doc(alias = "ts_tree_cursor_goto_parent")]
    pub fn goto_parent(&mut self) -> bool {
        unsafe { ffi::ts_tree_cursor_goto_parent(&mut self.0) }
    }

    /// Move this cursor to the next sibling of its current node.
    ///
    /// This returns `true` if the cursor successfully moved, and returns `false`
    /// if there was no next sibling node.
    #[doc(alias = "ts_tree_cursor_goto_next_sibling")]
    pub fn goto_next_sibling(&mut self) -> bool {
        unsafe { ffi::ts_tree_cursor_goto_next_sibling(&mut self.0) }
    }

    /// Move the cursor to the node that is the nth descendant of
    /// the original node that the cursor was constructed with, where
    /// zero represents the original node itself.
    #[doc(alias = "ts_tree_cursor_goto_descendant")]
    pub fn goto_descendant(&mut self, descendant_index: usize) {
        unsafe { ffi::ts_tree_cursor_goto_descendant(&mut self.0, descendant_index as u32) }
    }

    /// Move this cursor to the previous sibling of its current node.
    ///
    /// This returns `true` if the cursor successfully moved, and returns
    /// `false` if there was no previous sibling node.
    ///
    /// Note, that this function may be slower than
    /// [`goto_next_sibling`](TreeCursor::goto_next_sibling) due to how node
    /// positions are stored. In the worst case, this will need to iterate
    /// through all the children upto the previous sibling node to recalculate
    /// its position.
    #[doc(alias = "ts_tree_cursor_goto_previous_sibling")]
    pub fn goto_previous_sibling(&mut self) -> bool {
        unsafe { ffi::ts_tree_cursor_goto_previous_sibling(&mut self.0) }
    }

    /// Move this cursor to the first child of its current node that extends beyond
    /// the given byte offset.
    ///
    /// This returns the index of the child node if one was found, and returns `None`
    /// if no such child was found.
    #[doc(alias = "ts_tree_cursor_goto_first_child_for_byte")]
    pub fn goto_first_child_for_byte(&mut self, index: usize) -> Option<usize> {
        let result =
            unsafe { ffi::ts_tree_cursor_goto_first_child_for_byte(&mut self.0, index as u32) };
        (result >= 0).then_some(result as usize)
    }

    /// Move this cursor to the first child of its current node that extends beyond
    /// the given byte offset.
    ///
    /// This returns the index of the child node if one was found, and returns `None`
    /// if no such child was found.
    #[doc(alias = "ts_tree_cursor_goto_first_child_for_point")]
    pub fn goto_first_child_for_point(&mut self, point: Point) -> Option<usize> {
        let result =
            unsafe { ffi::ts_tree_cursor_goto_first_child_for_point(&mut self.0, point.into()) };
        (result >= 0).then_some(result as usize)
    }

    /// Re-initialize this tree cursor to start at a different node.
    #[doc(alias = "ts_tree_cursor_reset")]
    pub fn reset(&mut self, node: Node<'cursor>) {
        unsafe { ffi::ts_tree_cursor_reset(&mut self.0, node.0) };
    }

    /// Re-initialize a tree cursor to the same position as another cursor.
    ///
    /// Unlike [`reset`](TreeCursor::reset), this will not lose parent information and
    /// allows reusing already created cursors.
    #[doc(alias = "ts_tree_cursor_reset_to")]
    pub fn reset_to(&mut self, cursor: &TreeCursor<'cursor>) {
        unsafe { ffi::ts_tree_cursor_reset_to(&mut self.0, &cursor.0) };
    }
}

impl Clone for TreeCursor<'_> {
    fn clone(&self) -> Self {
        TreeCursor(unsafe { ffi::ts_tree_cursor_copy(&self.0) }, PhantomData)
    }
}

impl Drop for TreeCursor<'_> {
    fn drop(&mut self) {
        unsafe { ffi::ts_tree_cursor_delete(&mut self.0) }
    }
}

impl LookaheadIterator {
    /// Get the current language of the lookahead iterator.
    #[doc(alias = "ts_lookahead_iterator_language")]
    #[must_use]
    pub fn language(&self) -> LanguageRef<'_> {
        LanguageRef(
            unsafe { ffi::ts_lookahead_iterator_language(self.0.as_ptr()) },
            PhantomData,
        )
    }

    /// Get the current symbol of the lookahead iterator.
    #[doc(alias = "ts_lookahead_iterator_current_symbol")]
    #[must_use]
    pub fn current_symbol(&self) -> u16 {
        unsafe { ffi::ts_lookahead_iterator_current_symbol(self.0.as_ptr()) }
    }

    /// Get the current symbol name of the lookahead iterator.
    #[doc(alias = "ts_lookahead_iterator_current_symbol_name")]
    #[must_use]
    pub fn current_symbol_name(&self) -> &'static str {
        unsafe {
            CStr::from_ptr(ffi::ts_lookahead_iterator_current_symbol_name(
                self.0.as_ptr(),
            ))
            .to_str()
            .unwrap()
        }
    }

    /// Reset the lookahead iterator.
    ///
    /// This returns `true` if the language was set successfully and `false`
    /// otherwise.
    #[doc(alias = "ts_lookahead_iterator_reset")]
    pub fn reset(&mut self, language: &Language, state: u16) -> bool {
        unsafe { ffi::ts_lookahead_iterator_reset(self.0.as_ptr(), language.0, state) }
    }

    /// Reset the lookahead iterator to another state.
    ///
    /// This returns `true` if the iterator was reset to the given state and `false`
    /// otherwise.
    #[doc(alias = "ts_lookahead_iterator_reset_state")]
    pub fn reset_state(&mut self, state: u16) -> bool {
        unsafe { ffi::ts_lookahead_iterator_reset_state(self.0.as_ptr(), state) }
    }

    /// Iterate symbol names.
    pub fn iter_names(&mut self) -> impl Iterator<Item = &'static str> + '_ {
        LookaheadNamesIterator(self)
    }
}

impl Iterator for LookaheadNamesIterator<'_> {
    type Item = &'static str;

    #[doc(alias = "ts_lookahead_iterator_next")]
    fn next(&mut self) -> Option<Self::Item> {
        unsafe { ffi::ts_lookahead_iterator_next(self.0 .0.as_ptr()) }
            .then(|| self.0.current_symbol_name())
    }
}

impl Iterator for LookaheadIterator {
    type Item = u16;

    #[doc(alias = "ts_lookahead_iterator_next")]
    fn next(&mut self) -> Option<Self::Item> {
        // the first symbol is always `0` so we can safely skip it
        unsafe { ffi::ts_lookahead_iterator_next(self.0.as_ptr()) }.then(|| self.current_symbol())
    }
}

impl Drop for LookaheadIterator {
    #[doc(alias = "ts_lookahead_iterator_delete")]
    fn drop(&mut self) {
        unsafe { ffi::ts_lookahead_iterator_delete(self.0.as_ptr()) }
    }
}

impl Query {
    /// Create a new query from a string containing one or more S-expression
    /// patterns.
    ///
    /// The query is associated with a particular language, and can only be run
    /// on syntax nodes parsed with that language. References to Queries can be
    /// shared between multiple threads.
    pub fn new(language: &Language, source: &str) -> Result<Self, QueryError> {
        let mut error_offset = 0u32;
        let mut error_type: ffi::TSQueryError = 0;
        let bytes = source.as_bytes();

        // Compile the query.
        let ptr = unsafe {
            ffi::ts_query_new(
                language.0,
                bytes.as_ptr().cast::<c_char>(),
                bytes.len() as u32,
                std::ptr::addr_of_mut!(error_offset),
                std::ptr::addr_of_mut!(error_type),
            )
        };

        // On failure, build an error based on the error code and offset.
        if ptr.is_null() {
            if error_type == ffi::TSQueryErrorLanguage {
                return Err(QueryError {
                    row: 0,
                    column: 0,
                    offset: 0,
                    message: LanguageError {
                        version: language.version(),
                    }
                    .to_string(),
                    kind: QueryErrorKind::Language,
                });
            }

            let offset = error_offset as usize;
            let mut line_start = 0;
            let mut row = 0;
            let mut line_containing_error = None;
            for line in source.split('\n') {
                let line_end = line_start + line.len() + 1;
                if line_end > offset {
                    line_containing_error = Some(line);
                    break;
                }
                line_start = line_end;
                row += 1;
            }
            let column = offset - line_start;

            let kind;
            let message;
            match error_type {
                // Error types that report names
                ffi::TSQueryErrorNodeType | ffi::TSQueryErrorField | ffi::TSQueryErrorCapture => {
                    let suffix = source.split_at(offset).1;
                    let end_offset = suffix
                        .find(|c| !char::is_alphanumeric(c) && c != '_' && c != '-')
                        .unwrap_or(suffix.len());
                    message = suffix.split_at(end_offset).0.to_string();
                    kind = match error_type {
                        ffi::TSQueryErrorNodeType => QueryErrorKind::NodeType,
                        ffi::TSQueryErrorField => QueryErrorKind::Field,
                        ffi::TSQueryErrorCapture => QueryErrorKind::Capture,
                        _ => unreachable!(),
                    };
                }

                // Error types that report positions
                _ => {
                    message = line_containing_error.map_or_else(
                        || "Unexpected EOF".to_string(),
                        |line| line.to_string() + "\n" + &" ".repeat(offset - line_start) + "^",
                    );
                    kind = match error_type {
                        ffi::TSQueryErrorStructure => QueryErrorKind::Structure,
                        _ => QueryErrorKind::Syntax,
                    };
                }
            };

            return Err(QueryError {
                row,
                column,
                offset,
                message,
                kind,
            });
        }

        unsafe { Self::from_raw_parts(ptr, source) }
    }

    #[doc(hidden)]
    unsafe fn from_raw_parts(ptr: *mut ffi::TSQuery, source: &str) -> Result<Self, QueryError> {
        let ptr = {
            struct TSQueryDrop(*mut ffi::TSQuery);
            impl Drop for TSQueryDrop {
                fn drop(&mut self) {
                    unsafe { ffi::ts_query_delete(self.0) }
                }
            }
            TSQueryDrop(ptr)
        };

        let string_count = unsafe { ffi::ts_query_string_count(ptr.0) };
        let capture_count = unsafe { ffi::ts_query_capture_count(ptr.0) };
        let pattern_count = unsafe { ffi::ts_query_pattern_count(ptr.0) as usize };

        let mut capture_names = Vec::with_capacity(capture_count as usize);
        let mut capture_quantifiers_vec = Vec::with_capacity(pattern_count as usize);
        let mut text_predicates_vec = Vec::with_capacity(pattern_count);
        let mut property_predicates_vec = Vec::with_capacity(pattern_count);
        let mut property_settings_vec = Vec::with_capacity(pattern_count);
        let mut general_predicates_vec = Vec::with_capacity(pattern_count);

        // Build a vector of strings to store the capture names.
        for i in 0..capture_count {
            unsafe {
                let mut length = 0u32;
                let name =
                    ffi::ts_query_capture_name_for_id(ptr.0, i, std::ptr::addr_of_mut!(length))
                        .cast::<u8>();
                let name = slice::from_raw_parts(name, length as usize);
                let name = str::from_utf8_unchecked(name);
                capture_names.push(name);
            }
        }

        // Build a vector to store capture qunatifiers.
        for i in 0..pattern_count {
            let mut capture_quantifiers = Vec::with_capacity(capture_count as usize);
            for j in 0..capture_count {
                unsafe {
                    let quantifier = ffi::ts_query_capture_quantifier_for_id(ptr.0, i as u32, j);
                    capture_quantifiers.push(quantifier.into());
                }
            }
            capture_quantifiers_vec.push(capture_quantifiers.into());
        }

        // Build a vector of strings to represent literal values used in predicates.
        let string_values = (0..string_count)
            .map(|i| unsafe {
                let mut length = 0u32;
                let value =
                    ffi::ts_query_string_value_for_id(ptr.0, i, std::ptr::addr_of_mut!(length))
                        .cast::<u8>();
                let value = slice::from_raw_parts(value, length as usize);
                let value = str::from_utf8_unchecked(value);
                value
            })
            .collect::<Vec<_>>();

        // Build a vector of predicates for each pattern.
        for i in 0..pattern_count {
            let predicate_steps = unsafe {
                let mut length = 0u32;
                let raw_predicates = ffi::ts_query_predicates_for_pattern(
                    ptr.0,
                    i as u32,
                    std::ptr::addr_of_mut!(length),
                );
                (length > 0)
                    .then(|| slice::from_raw_parts(raw_predicates, length as usize))
                    .unwrap_or_default()
            };

            let byte_offset = unsafe { ffi::ts_query_start_byte_for_pattern(ptr.0, i as u32) };
            let row = source
                .char_indices()
                .take_while(|(i, _)| *i < byte_offset as usize)
                .filter(|(_, c)| *c == '\n')
                .count();

            use ffi::TSQueryPredicateStepType as T;
            const TYPE_DONE: T = ffi::TSQueryPredicateStepTypeDone;
            const TYPE_CAPTURE: T = ffi::TSQueryPredicateStepTypeCapture;
            const TYPE_STRING: T = ffi::TSQueryPredicateStepTypeString;

            let mut text_predicates = Vec::new();
            let mut property_predicates = Vec::new();
            let mut property_settings = Vec::new();
            let mut general_predicates = Vec::new();
            for p in predicate_steps.split(|s| s.type_ == TYPE_DONE) {
                if p.is_empty() {
                    continue;
                }

                if p[0].type_ != TYPE_STRING {
                    return Err(predicate_error(
                        row,
                        format!(
                            "Expected predicate to start with a function name. Got @{}.",
                            capture_names[p[0].value_id as usize],
                        ),
                    ));
                }

                // Build a predicate for each of the known predicate function names.
                let operator_name = string_values[p[0].value_id as usize];
                match operator_name {
                    "eq?" | "not-eq?" | "any-eq?" | "any-not-eq?" => {
                        if p.len() != 3 {
                            return Err(predicate_error(
                                row,
                                format!(
                                "Wrong number of arguments to #eq? predicate. Expected 2, got {}.",
                                p.len() - 1
                            ),
                            ));
                        }
                        if p[1].type_ != TYPE_CAPTURE {
                            return Err(predicate_error(row, format!(
                                "First argument to #eq? predicate must be a capture name. Got literal \"{}\".",
                                string_values[p[1].value_id as usize],
                            )));
                        }

                        let is_positive = operator_name == "eq?" || operator_name == "any-eq?";
                        let match_all = match operator_name {
                            "eq?" | "not-eq?" => true,
                            "any-eq?" | "any-not-eq?" => false,
                            _ => unreachable!(),
                        };
                        text_predicates.push(if p[2].type_ == TYPE_CAPTURE {
                            TextPredicateCapture::EqCapture(
                                p[1].value_id,
                                p[2].value_id,
                                is_positive,
                                match_all,
                            )
                        } else {
                            TextPredicateCapture::EqString(
                                p[1].value_id,
                                string_values[p[2].value_id as usize].to_string().into(),
                                is_positive,
                                match_all,
                            )
                        });
                    }

                    "match?" | "not-match?" | "any-match?" | "any-not-match?" => {
                        if p.len() != 3 {
                            return Err(predicate_error(row, format!(
                                "Wrong number of arguments to #match? predicate. Expected 2, got {}.",
                                p.len() - 1
                            )));
                        }
                        if p[1].type_ != TYPE_CAPTURE {
                            return Err(predicate_error(row, format!(
                                "First argument to #match? predicate must be a capture name. Got literal \"{}\".",
                                string_values[p[1].value_id as usize],
                            )));
                        }
                        if p[2].type_ == TYPE_CAPTURE {
                            return Err(predicate_error(row, format!(
                                "Second argument to #match? predicate must be a literal. Got capture @{}.",
                                capture_names[p[2].value_id as usize],
                            )));
                        }

                        let is_positive =
                            operator_name == "match?" || operator_name == "any-match?";
                        let match_all = match operator_name {
                            "match?" | "not-match?" => true,
                            "any-match?" | "any-not-match?" => false,
                            _ => unreachable!(),
                        };
                        let regex = &string_values[p[2].value_id as usize];
                        text_predicates.push(TextPredicateCapture::MatchString(
                            p[1].value_id,
                            regex::bytes::Regex::new(regex).map_err(|_| {
                                predicate_error(row, format!("Invalid regex '{regex}'"))
                            })?,
                            is_positive,
                            match_all,
                        ));
                    }

                    "set!" => property_settings.push(Self::parse_property(
                        row,
                        operator_name,
                        &capture_names,
                        &string_values,
                        &p[1..],
                    )?),

                    "is?" | "is-not?" => property_predicates.push((
                        Self::parse_property(
                            row,
                            operator_name,
                            &capture_names,
                            &string_values,
                            &p[1..],
                        )?,
                        operator_name == "is?",
                    )),

                    "any-of?" | "not-any-of?" => {
                        if p.len() < 2 {
                            return Err(predicate_error(row, format!(
                                "Wrong number of arguments to #any-of? predicate. Expected at least 1, got {}.",
                                p.len() - 1
                            )));
                        }
                        if p[1].type_ != TYPE_CAPTURE {
                            return Err(predicate_error(row, format!(
                                "First argument to #any-of? predicate must be a capture name. Got literal \"{}\".",
                                string_values[p[1].value_id as usize],
                            )));
                        }

                        let is_positive = operator_name == "any-of?";
                        let mut values = Vec::new();
                        for arg in &p[2..] {
                            if arg.type_ == TYPE_CAPTURE {
                                return Err(predicate_error(row, format!(
                                    "Arguments to #any-of? predicate must be literals. Got capture @{}.",
                                    capture_names[arg.value_id as usize],
                                )));
                            }
                            values.push(string_values[arg.value_id as usize]);
                        }
                        text_predicates.push(TextPredicateCapture::AnyString(
                            p[1].value_id,
                            values
                                .iter()
                                .map(|x| (*x).to_string().into())
                                .collect::<Vec<_>>()
                                .into(),
                            is_positive,
                        ));
                    }

                    _ => general_predicates.push(QueryPredicate {
                        operator: operator_name.to_string().into(),
                        args: p[1..]
                            .iter()
                            .map(|a| {
                                if a.type_ == TYPE_CAPTURE {
                                    QueryPredicateArg::Capture(a.value_id)
                                } else {
                                    QueryPredicateArg::String(
                                        string_values[a.value_id as usize].to_string().into(),
                                    )
                                }
                            })
                            .collect(),
                    }),
                }
            }

            text_predicates_vec.push(text_predicates.into());
            property_predicates_vec.push(property_predicates.into());
            property_settings_vec.push(property_settings.into());
            general_predicates_vec.push(general_predicates.into());
        }

        let result = Self {
            ptr: unsafe { NonNull::new_unchecked(ptr.0) },
            capture_names: capture_names.into(),
            capture_quantifiers: capture_quantifiers_vec.into(),
            text_predicates: text_predicates_vec.into(),
            property_predicates: property_predicates_vec.into(),
            property_settings: property_settings_vec.into(),
            general_predicates: general_predicates_vec.into(),
        };

        std::mem::forget(ptr);

        Ok(result)
    }

    /// Get the byte offset where the given pattern starts in the query's source.
    #[doc(alias = "ts_query_start_byte_for_pattern")]
    #[must_use]
    pub fn start_byte_for_pattern(&self, pattern_index: usize) -> usize {
        assert!(
            pattern_index < self.text_predicates.len(),
            "Pattern index is {pattern_index} but the pattern count is {}",
            self.text_predicates.len(),
        );
        unsafe {
            ffi::ts_query_start_byte_for_pattern(self.ptr.as_ptr(), pattern_index as u32) as usize
        }
    }

    /// Get the number of patterns in the query.
    #[doc(alias = "ts_query_pattern_count")]
    #[must_use]
    pub fn pattern_count(&self) -> usize {
        unsafe { ffi::ts_query_pattern_count(self.ptr.as_ptr()) as usize }
    }

    /// Get the names of the captures used in the query.
    #[must_use]
    pub const fn capture_names(&self) -> &[&str] {
        &self.capture_names
    }

    /// Get the quantifiers of the captures used in the query.
    #[must_use]
    pub const fn capture_quantifiers(&self, index: usize) -> &[CaptureQuantifier] {
        &self.capture_quantifiers[index]
    }

    /// Get the index for a given capture name.
    #[must_use]
    pub fn capture_index_for_name(&self, name: &str) -> Option<u32> {
        self.capture_names
            .iter()
            .position(|n| *n == name)
            .map(|ix| ix as u32)
    }

    /// Get the properties that are checked for the given pattern index.
    ///
    /// This includes predicates with the operators `is?` and `is-not?`.
    #[must_use]
    pub const fn property_predicates(&self, index: usize) -> &[(QueryProperty, bool)] {
        &self.property_predicates[index]
    }

    /// Get the properties that are set for the given pattern index.
    ///
    /// This includes predicates with the operator `set!`.
    #[must_use]
    pub const fn property_settings(&self, index: usize) -> &[QueryProperty] {
        &self.property_settings[index]
    }

    /// Get the other user-defined predicates associated with the given index.
    ///
    /// This includes predicate with operators other than:
    /// * `match?`
    /// * `eq?` and `not-eq?`
    /// * `is?` and `is-not?`
    /// * `set!`
    #[must_use]
    pub const fn general_predicates(&self, index: usize) -> &[QueryPredicate] {
        &self.general_predicates[index]
    }

    /// Disable a certain capture within a query.
    ///
    /// This prevents the capture from being returned in matches, and also avoids any
    /// resource usage associated with recording the capture.
    #[doc(alias = "ts_query_disable_capture")]
    pub fn disable_capture(&mut self, name: &str) {
        unsafe {
            ffi::ts_query_disable_capture(
                self.ptr.as_ptr(),
                name.as_bytes().as_ptr().cast::<c_char>(),
                name.len() as u32,
            );
        }
    }

    /// Disable a certain pattern within a query.
    ///
    /// This prevents the pattern from matching, and also avoids any resource usage
    /// associated with the pattern.
    #[doc(alias = "ts_query_disable_pattern")]
    pub fn disable_pattern(&mut self, index: usize) {
        unsafe { ffi::ts_query_disable_pattern(self.ptr.as_ptr(), index as u32) }
    }

    /// Check if a given pattern within a query has a single root node.
    #[doc(alias = "ts_query_is_pattern_rooted")]
    #[must_use]
    pub fn is_pattern_rooted(&self, index: usize) -> bool {
        unsafe { ffi::ts_query_is_pattern_rooted(self.ptr.as_ptr(), index as u32) }
    }

    /// Check if a given pattern within a query has a single root node.
    #[doc(alias = "ts_query_is_pattern_non_local")]
    #[must_use]
    pub fn is_pattern_non_local(&self, index: usize) -> bool {
        unsafe { ffi::ts_query_is_pattern_non_local(self.ptr.as_ptr(), index as u32) }
    }

    /// Check if a given step in a query is 'definite'.
    ///
    /// A query step is 'definite' if its parent pattern will be guaranteed to match
    /// successfully once it reaches the step.
    #[doc(alias = "ts_query_is_pattern_guaranteed_at_step")]
    #[must_use]
    pub fn is_pattern_guaranteed_at_step(&self, byte_offset: usize) -> bool {
        unsafe {
            ffi::ts_query_is_pattern_guaranteed_at_step(self.ptr.as_ptr(), byte_offset as u32)
        }
    }

    fn parse_property(
        row: usize,
        function_name: &str,
        capture_names: &[&str],
        string_values: &[&str],
        args: &[ffi::TSQueryPredicateStep],
    ) -> Result<QueryProperty, QueryError> {
        if args.is_empty() || args.len() > 3 {
            return Err(predicate_error(
                row,
                format!(
                    "Wrong number of arguments to {function_name} predicate. Expected 1 to 3, got {}.",
                    args.len(),
                ),
            ));
        }

        let mut capture_id = None;
        let mut key = None;
        let mut value = None;

        for arg in args {
            if arg.type_ == ffi::TSQueryPredicateStepTypeCapture {
                if capture_id.is_some() {
                    return Err(predicate_error(
                        row,
                        format!(
                            "Invalid arguments to {function_name} predicate. Unexpected second capture name @{}",
                            capture_names[arg.value_id as usize]
                        ),
                    ));
                }
                capture_id = Some(arg.value_id as usize);
            } else if key.is_none() {
                key = Some(&string_values[arg.value_id as usize]);
            } else if value.is_none() {
                value = Some(string_values[arg.value_id as usize]);
            } else {
                return Err(predicate_error(
                    row,
                    format!(
                        "Invalid arguments to {function_name} predicate. Unexpected third argument @{}",
                        string_values[arg.value_id as usize]
                    ),
                ));
            }
        }

        if let Some(key) = key {
            Ok(QueryProperty::new(key, value, capture_id))
        } else {
            Err(predicate_error(
                row,
                format!("Invalid arguments to {function_name} predicate. Missing key argument",),
            ))
        }
    }
}

impl Default for QueryCursor {
    fn default() -> Self {
        Self::new()
    }
}

impl QueryCursor {
    /// Create a new cursor for executing a given query.
    ///
    /// The cursor stores the state that is needed to iteratively search for matches.
    #[doc(alias = "ts_query_cursor_new")]
    #[must_use]
    pub fn new() -> Self {
        Self {
            ptr: unsafe { NonNull::new_unchecked(ffi::ts_query_cursor_new()) },
        }
    }

    /// Return the maximum number of in-progress matches for this cursor.
    #[doc(alias = "ts_query_cursor_match_limit")]
    #[must_use]
    pub fn match_limit(&self) -> u32 {
        unsafe { ffi::ts_query_cursor_match_limit(self.ptr.as_ptr()) }
    }

    /// Set the maximum number of in-progress matches for this cursor.  The limit must be > 0 and
    /// <= 65536.
    #[doc(alias = "ts_query_cursor_set_match_limit")]
    pub fn set_match_limit(&mut self, limit: u32) {
        unsafe {
            ffi::ts_query_cursor_set_match_limit(self.ptr.as_ptr(), limit);
        }
    }

    /// Check if, on its last execution, this cursor exceeded its maximum number of
    /// in-progress matches.
    #[doc(alias = "ts_query_cursor_did_exceed_match_limit")]
    #[must_use]
    pub fn did_exceed_match_limit(&self) -> bool {
        unsafe { ffi::ts_query_cursor_did_exceed_match_limit(self.ptr.as_ptr()) }
    }

    /// Iterate over all of the matches in the order that they were found.
    ///
    /// Each match contains the index of the pattern that matched, and a list of captures.
    /// Because multiple patterns can match the same set of nodes, one match may contain
    /// captures that appear *before* some of the captures from a previous match.
    #[doc(alias = "ts_query_cursor_exec")]
    pub fn matches<'query, 'tree, T: TextProvider<I>, I: AsRef<[u8]>>(
        &mut self,
        query: &'query Query,
        node: Node<'tree>,
        text_provider: T,
    ) -> QueryMatches<'query, 'tree, T, I> {
        let ptr = self.ptr.as_ptr();
        unsafe { ffi::ts_query_cursor_exec(ptr, query.ptr.as_ptr(), node.0) };
        QueryMatches {
            ptr,
            query,
            text_provider,
            buffer1: Vec::default(),
            buffer2: Vec::default(),
            _phantom: PhantomData,
        }
    }

    /// Iterate over all of the individual captures in the order that they appear.
    ///
    /// This is useful if you don't care about which pattern matched, and just want a single,
    /// ordered sequence of captures.
    #[doc(alias = "ts_query_cursor_exec")]
    pub fn captures<'query, 'tree, T: TextProvider<I>, I: AsRef<[u8]>>(
        &mut self,
        query: &'query Query,
        node: Node<'tree>,
        text_provider: T,
    ) -> QueryCaptures<'query, 'tree, T, I> {
        let ptr = self.ptr.as_ptr();
        unsafe { ffi::ts_query_cursor_exec(ptr, query.ptr.as_ptr(), node.0) };
        QueryCaptures {
            ptr,
            query,
            text_provider,
            buffer1: Vec::default(),
            buffer2: Vec::default(),
            _phantom: PhantomData,
        }
    }

    /// Set the range in which the query will be executed, in terms of byte offsets.
    #[doc(alias = "ts_query_cursor_set_byte_range")]
    pub fn set_byte_range(&mut self, range: ops::Range<usize>) -> &mut Self {
        unsafe {
            ffi::ts_query_cursor_set_byte_range(
                self.ptr.as_ptr(),
                range.start as u32,
                range.end as u32,
            );
        }
        self
    }

    /// Set the range in which the query will be executed, in terms of rows and columns.
    #[doc(alias = "ts_query_cursor_set_point_range")]
    pub fn set_point_range(&mut self, range: ops::Range<Point>) -> &mut Self {
        unsafe {
            ffi::ts_query_cursor_set_point_range(
                self.ptr.as_ptr(),
                range.start.into(),
                range.end.into(),
            );
        }
        self
    }

    /// Set the maximum start depth for a query cursor.
    ///
    /// This prevents cursors from exploring children nodes at a certain depth.
    /// Note if a pattern includes many children, then they will still be checked.
    ///
    /// The zero max start depth value can be used as a special behavior and
    /// it helps to destructure a subtree by staying on a node and using captures
    /// for interested parts. Note that the zero max start depth only limit a search
    /// depth for a pattern's root node but other nodes that are parts of the pattern
    /// may be searched at any depth what defined by the pattern structure.
    ///
    /// Set to `None` to remove the maximum start depth.
    #[doc(alias = "ts_query_cursor_set_max_start_depth")]
    pub fn set_max_start_depth(&mut self, max_start_depth: Option<u32>) -> &mut Self {
        unsafe {
            ffi::ts_query_cursor_set_max_start_depth(
                self.ptr.as_ptr(),
                max_start_depth.unwrap_or(u32::MAX),
            );
        }
        self
    }
}

impl<'tree> QueryMatch<'_, 'tree> {
    #[must_use]
    pub const fn id(&self) -> u32 {
        self.id
    }

    #[doc(alias = "ts_query_cursor_remove_match")]
    pub fn remove(self) {
        unsafe { ffi::ts_query_cursor_remove_match(self.cursor, self.id) }
    }

    pub fn nodes_for_capture_index(
        &self,
        capture_ix: u32,
    ) -> impl Iterator<Item = Node<'tree>> + '_ {
        self.captures
            .iter()
            .filter_map(move |capture| (capture.index == capture_ix).then_some(capture.node))
    }

    fn new(m: &ffi::TSQueryMatch, cursor: *mut ffi::TSQueryCursor) -> Self {
        QueryMatch {
            cursor,
            id: m.id,
            pattern_index: m.pattern_index as usize,
            captures: (m.capture_count > 0)
                .then(|| unsafe {
                    slice::from_raw_parts(
                        m.captures.cast::<QueryCapture<'tree>>(),
                        m.capture_count as usize,
                    )
                })
                .unwrap_or_default(),
        }
    }

    fn satisfies_text_predicates<I: AsRef<[u8]>>(
        &self,
        query: &Query,
        buffer1: &mut Vec<u8>,
        buffer2: &mut Vec<u8>,
        text_provider: &mut impl TextProvider<I>,
    ) -> bool {
        struct NodeText<'a, T> {
            buffer: &'a mut Vec<u8>,
            first_chunk: Option<T>,
        }
        impl<'a, T: AsRef<[u8]>> NodeText<'a, T> {
            fn new(buffer: &'a mut Vec<u8>) -> Self {
                Self {
                    buffer,
                    first_chunk: None,
                }
            }

            fn get_text(&mut self, chunks: &mut impl Iterator<Item = T>) -> &[u8] {
                self.first_chunk = chunks.next();
                if let Some(next_chunk) = chunks.next() {
                    self.buffer.clear();
                    self.buffer
                        .extend_from_slice(self.first_chunk.as_ref().unwrap().as_ref());
                    self.buffer.extend_from_slice(next_chunk.as_ref());
                    for chunk in chunks {
                        self.buffer.extend_from_slice(chunk.as_ref());
                    }
                    self.buffer.as_slice()
                } else if let Some(ref first_chunk) = self.first_chunk {
                    first_chunk.as_ref()
                } else {
                    Default::default()
                }
            }
        }

        let mut node_text1 = NodeText::new(buffer1);
        let mut node_text2 = NodeText::new(buffer2);

        query.text_predicates[self.pattern_index]
            .iter()
            .all(|predicate| match predicate {
                TextPredicateCapture::EqCapture(i, j, is_positive, match_all_nodes) => {
                    let mut nodes_1 = self.nodes_for_capture_index(*i);
                    let mut nodes_2 = self.nodes_for_capture_index(*j);
                    while let (Some(node1), Some(node2)) = (nodes_1.next(), nodes_2.next()) {
                        let mut text1 = text_provider.text(node1);
                        let mut text2 = text_provider.text(node2);
                        let text1 = node_text1.get_text(&mut text1);
                        let text2 = node_text2.get_text(&mut text2);
                        if (text1 == text2) != *is_positive && *match_all_nodes {
                            return false;
                        }
                        if (text1 == text2) == *is_positive && !*match_all_nodes {
                            return true;
                        }
                    }
                    nodes_1.next().is_none() && nodes_2.next().is_none()
                }
                TextPredicateCapture::EqString(i, s, is_positive, match_all_nodes) => {
                    let nodes = self.nodes_for_capture_index(*i);
                    for node in nodes {
                        let mut text = text_provider.text(node);
                        let text = node_text1.get_text(&mut text);
                        if (text == s.as_bytes()) != *is_positive && *match_all_nodes {
                            return false;
                        }
                        if (text == s.as_bytes()) == *is_positive && !*match_all_nodes {
                            return true;
                        }
                    }
                    true
                }
                TextPredicateCapture::MatchString(i, r, is_positive, match_all_nodes) => {
                    let nodes = self.nodes_for_capture_index(*i);
                    for node in nodes {
                        let mut text = text_provider.text(node);
                        let text = node_text1.get_text(&mut text);
                        if (r.is_match(text)) != *is_positive && *match_all_nodes {
                            return false;
                        }
                        if (r.is_match(text)) == *is_positive && !*match_all_nodes {
                            return true;
                        }
                    }
                    true
                }
                TextPredicateCapture::AnyString(i, v, is_positive) => {
                    let nodes = self.nodes_for_capture_index(*i);
                    for node in nodes {
                        let mut text = text_provider.text(node);
                        let text = node_text1.get_text(&mut text);
                        if (v.iter().any(|s| text == s.as_bytes())) != *is_positive {
                            return false;
                        }
                    }
                    true
                }
            })
    }
}

impl QueryProperty {
    #[must_use]
    pub fn new(key: &str, value: Option<&str>, capture_id: Option<usize>) -> Self {
        Self {
            capture_id,
            key: key.to_string().into(),
            value: value.map(|s| s.to_string().into()),
        }
    }
}

impl<'query, 'tree: 'query, T: TextProvider<I>, I: AsRef<[u8]>> Iterator
    for QueryMatches<'query, 'tree, T, I>
{
    type Item = QueryMatch<'query, 'tree>;

    fn next(&mut self) -> Option<Self::Item> {
        unsafe {
            loop {
                let mut m = MaybeUninit::<ffi::TSQueryMatch>::uninit();
                if ffi::ts_query_cursor_next_match(self.ptr, m.as_mut_ptr()) {
                    let result = QueryMatch::new(&m.assume_init(), self.ptr);
                    if result.satisfies_text_predicates(
                        self.query,
                        &mut self.buffer1,
                        &mut self.buffer2,
                        &mut self.text_provider,
                    ) {
                        return Some(result);
                    }
                } else {
                    return None;
                }
            }
        }
    }
}

impl<'query, 'tree: 'query, T: TextProvider<I>, I: AsRef<[u8]>> Iterator
    for QueryCaptures<'query, 'tree, T, I>
{
    type Item = (QueryMatch<'query, 'tree>, usize);

    fn next(&mut self) -> Option<Self::Item> {
        unsafe {
            loop {
                let mut capture_index = 0u32;
                let mut m = MaybeUninit::<ffi::TSQueryMatch>::uninit();
                if ffi::ts_query_cursor_next_capture(
                    self.ptr,
                    m.as_mut_ptr(),
                    std::ptr::addr_of_mut!(capture_index),
                ) {
                    let result = QueryMatch::new(&m.assume_init(), self.ptr);
                    if result.satisfies_text_predicates(
                        self.query,
                        &mut self.buffer1,
                        &mut self.buffer2,
                        &mut self.text_provider,
                    ) {
                        return Some((result, capture_index as usize));
                    }
                    result.remove();
                } else {
                    return None;
                }
            }
        }
    }
}

impl<T: TextProvider<I>, I: AsRef<[u8]>> QueryMatches<'_, '_, T, I> {
    #[doc(alias = "ts_query_cursor_set_byte_range")]
    pub fn set_byte_range(&mut self, range: ops::Range<usize>) {
        unsafe {
            ffi::ts_query_cursor_set_byte_range(self.ptr, range.start as u32, range.end as u32);
        }
    }

    #[doc(alias = "ts_query_cursor_set_point_range")]
    pub fn set_point_range(&mut self, range: ops::Range<Point>) {
        unsafe {
            ffi::ts_query_cursor_set_point_range(self.ptr, range.start.into(), range.end.into());
        }
    }
}

impl<T: TextProvider<I>, I: AsRef<[u8]>> QueryCaptures<'_, '_, T, I> {
    #[doc(alias = "ts_query_cursor_set_byte_range")]
    pub fn set_byte_range(&mut self, range: ops::Range<usize>) {
        unsafe {
            ffi::ts_query_cursor_set_byte_range(self.ptr, range.start as u32, range.end as u32);
        }
    }

    #[doc(alias = "ts_query_cursor_set_point_range")]
    pub fn set_point_range(&mut self, range: ops::Range<Point>) {
        unsafe {
            ffi::ts_query_cursor_set_point_range(self.ptr, range.start.into(), range.end.into());
        }
    }
}

impl fmt::Debug for QueryMatch<'_, '_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "QueryMatch {{ id: {}, pattern_index: {}, captures: {:?} }}",
            self.id, self.pattern_index, self.captures
        )
    }
}

impl<F, R, I> TextProvider<I> for F
where
    F: FnMut(Node) -> R,
    R: Iterator<Item = I>,
    I: AsRef<[u8]>,
{
    type I = R;

    fn text(&mut self, node: Node) -> Self::I {
        (self)(node)
    }
}

impl<'a> TextProvider<&'a [u8]> for &'a [u8] {
    type I = iter::Once<&'a [u8]>;

    fn text(&mut self, node: Node) -> Self::I {
        iter::once(&self[node.byte_range()])
    }
}

impl PartialEq for Query {
    fn eq(&self, other: &Self) -> bool {
        self.ptr == other.ptr
    }
}

impl Drop for Query {
    fn drop(&mut self) {
        unsafe { ffi::ts_query_delete(self.ptr.as_ptr()) }
    }
}

impl Drop for QueryCursor {
    fn drop(&mut self) {
        unsafe { ffi::ts_query_cursor_delete(self.ptr.as_ptr()) }
    }
}

impl Point {
    #[must_use]
    pub const fn new(row: usize, column: usize) -> Self {
        Self { row, column }
    }
}

impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({}, {})", self.row, self.column)
    }
}

impl From<Point> for ffi::TSPoint {
    fn from(val: Point) -> Self {
        Self {
            row: val.row as u32,
            column: val.column as u32,
        }
    }
}

impl From<ffi::TSPoint> for Point {
    fn from(point: ffi::TSPoint) -> Self {
        Self {
            row: point.row as usize,
            column: point.column as usize,
        }
    }
}

impl From<Range> for ffi::TSRange {
    fn from(val: Range) -> Self {
        Self {
            start_byte: val.start_byte as u32,
            end_byte: val.end_byte as u32,
            start_point: val.start_point.into(),
            end_point: val.end_point.into(),
        }
    }
}

impl From<ffi::TSRange> for Range {
    fn from(range: ffi::TSRange) -> Self {
        Self {
            start_byte: range.start_byte as usize,
            end_byte: range.end_byte as usize,
            start_point: range.start_point.into(),
            end_point: range.end_point.into(),
        }
    }
}

impl From<&'_ InputEdit> for ffi::TSInputEdit {
    fn from(val: &'_ InputEdit) -> Self {
        Self {
            start_byte: val.start_byte as u32,
            old_end_byte: val.old_end_byte as u32,
            new_end_byte: val.new_end_byte as u32,
            start_point: val.start_position.into(),
            old_end_point: val.old_end_position.into(),
            new_end_point: val.new_end_position.into(),
        }
    }
}

impl<'a> LossyUtf8<'a> {
    #[must_use]
    pub const fn new(bytes: &'a [u8]) -> Self {
        LossyUtf8 {
            bytes,
            in_replacement: false,
        }
    }
}

impl<'a> Iterator for LossyUtf8<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<&'a str> {
        if self.bytes.is_empty() {
            return None;
        }
        if self.in_replacement {
            self.in_replacement = false;
            return Some("\u{fffd}");
        }
        match std::str::from_utf8(self.bytes) {
            Ok(valid) => {
                self.bytes = Default::default();
                Some(valid)
            }
            Err(error) => {
                if let Some(error_len) = error.error_len() {
                    let error_start = error.valid_up_to();
                    if error_start > 0 {
                        let result =
                            unsafe { std::str::from_utf8_unchecked(&self.bytes[..error_start]) };
                        self.bytes = &self.bytes[(error_start + error_len)..];
                        self.in_replacement = true;
                        Some(result)
                    } else {
                        self.bytes = &self.bytes[error_len..];
                        Some("\u{fffd}")
                    }
                } else {
                    None
                }
            }
        }
    }
}

#[must_use]
const fn predicate_error(row: usize, message: String) -> QueryError {
    QueryError {
        kind: QueryErrorKind::Predicate,
        row,
        column: 0,
        offset: 0,
        message,
    }
}

impl fmt::Display for IncludedRangesError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Incorrect range by index: {}", self.0)
    }
}

impl fmt::Display for LanguageError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "Incompatible language version {}. Expected minimum {}, maximum {}",
            self.version, MIN_COMPATIBLE_LANGUAGE_VERSION, LANGUAGE_VERSION,
        )
    }
}

impl fmt::Display for QueryError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let msg = match self.kind {
            QueryErrorKind::Field => "Invalid field name ",
            QueryErrorKind::NodeType => "Invalid node type ",
            QueryErrorKind::Capture => "Invalid capture name ",
            QueryErrorKind::Predicate => "Invalid predicate: ",
            QueryErrorKind::Structure => "Impossible pattern:\n",
            QueryErrorKind::Syntax => "Invalid syntax:\n",
            QueryErrorKind::Language => "",
        };
        if msg.is_empty() {
            write!(f, "{}", self.message)
        } else {
            write!(
                f,
                "Query error at {}:{}. {}{}",
                self.row + 1,
                self.column + 1,
                msg,
                self.message
            )
        }
    }
}

#[doc(hidden)]
pub fn format_sexp(sexp: &str, initial_indent_level: usize) -> String {
    let mut indent_level = initial_indent_level;
    let mut formatted = String::new();
    let mut has_field = false;

    let mut c_iter = sexp.chars().peekable();
    let mut s = String::with_capacity(sexp.len());
    let mut quote = '\0';
    let mut saw_paren = false;
    let mut did_last = false;

    let mut fetch_next_str = |next: &mut String| {
        next.clear();
        while let Some(c) = c_iter.next() {
            if c == '\'' || c == '"' {
                quote = c;
            } else if c == ' ' || (c == ')' && quote != '\0') {
                if let Some(next_c) = c_iter.peek() {
                    if *next_c == quote {
                        next.push(c);
                        next.push(*next_c);
                        c_iter.next();
                        quote = '\0';
                        continue;
                    }
                }
                break;
            }
            if c == ')' {
                saw_paren = true;
                break;
            }
            next.push(c);
        }

        // at the end
        if c_iter.peek().is_none() && next.is_empty() {
            if saw_paren {
                // but did we see a ) before ending?
                saw_paren = false;
                return Some(());
            }
            if !did_last {
                // but did we account for the end empty string as if we're splitting?
                did_last = true;
                return Some(());
            }
            return None;
        }
        Some(())
    };

    while fetch_next_str(&mut s).is_some() {
        if s.is_empty() && indent_level > 0 {
            // ")"
            indent_level -= 1;
            write!(formatted, ")").unwrap();
        } else if s.starts_with('(') {
            if has_field {
                has_field = false;
            } else {
                if indent_level > 0 {
                    writeln!(formatted).unwrap();
                    for _ in 0..indent_level {
                        write!(formatted, "  ").unwrap();
                    }
                }
                indent_level += 1;
            }

            // "(node_name"
            write!(formatted, "{s}").unwrap();

            // "(MISSING node_name" or "(UNEXPECTED 'x'"
            if s.starts_with("(MISSING") || s.starts_with("(UNEXPECTED") {
                fetch_next_str(&mut s).unwrap();
                if s.is_empty() {
                    while indent_level > 0 {
                        indent_level -= 1;
                        write!(formatted, ")").unwrap();
                    }
                } else {
                    write!(formatted, " {s}").unwrap();
                }
            }
        } else if s.ends_with(':') {
            // "field:"
            writeln!(formatted).unwrap();
            for _ in 0..indent_level {
                write!(formatted, "  ").unwrap();
            }
            write!(formatted, "{s} ").unwrap();
            has_field = true;
            indent_level += 1;
        }
    }

    formatted
}

pub fn wasm_stdlib_symbols() -> impl Iterator<Item = &'static str> {
    const WASM_STDLIB_SYMBOLS: &str = include_str!(concat!(env!("OUT_DIR"), "/stdlib-symbols.txt"));

    WASM_STDLIB_SYMBOLS
        .lines()
        .map(|s| s.trim_matches(|c| c == '"' || c == ','))
}

extern "C" {
    fn free(ptr: *mut c_void);
}

static mut FREE_FN: unsafe extern "C" fn(ptr: *mut c_void) = free;

/// Sets the memory allocation functions that the core library should use.
///
/// # Safety
///
/// This function uses FFI and mutates a static global.
#[doc(alias = "ts_set_allocator")]
pub unsafe fn set_allocator(
    new_malloc: Option<unsafe extern "C" fn(usize) -> *mut c_void>,
    new_calloc: Option<unsafe extern "C" fn(usize, usize) -> *mut c_void>,
    new_realloc: Option<unsafe extern "C" fn(*mut c_void, usize) -> *mut c_void>,
    new_free: Option<unsafe extern "C" fn(*mut c_void)>,
) {
    FREE_FN = new_free.unwrap_or(free);
    ffi::ts_set_allocator(new_malloc, new_calloc, new_realloc, new_free);
}

impl error::Error for IncludedRangesError {}
impl error::Error for LanguageError {}
impl error::Error for QueryError {}

unsafe impl Send for Language {}
unsafe impl Sync for Language {}

unsafe impl Send for Node<'_> {}
unsafe impl Sync for Node<'_> {}

unsafe impl Send for LookaheadIterator {}
unsafe impl Sync for LookaheadIterator {}

unsafe impl Send for LookaheadNamesIterator<'_> {}
unsafe impl Sync for LookaheadNamesIterator<'_> {}

unsafe impl Send for Parser {}
unsafe impl Sync for Parser {}

unsafe impl Send for Query {}
unsafe impl Sync for Query {}

unsafe impl Send for QueryCursor {}
unsafe impl Sync for QueryCursor {}

unsafe impl Send for Tree {}
unsafe impl Sync for Tree {}

unsafe impl Send for TreeCursor<'_> {}
unsafe impl Sync for TreeCursor<'_> {}