all messages for Emacs-related lists mirrored at yhetil.org
 help / color / mirror / code / Atom feed
blob fd5fda78133afd27a4adfb66211c63b62a263889 126645 bytes (raw)
name: src/treesit.c 	 # note: path name is non-authoritative(*)

   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
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
 
/* Tree-sitter integration for GNU Emacs.

Copyright (C) 2021-2023 Free Software Foundation, Inc.

Maintainer: Yuan Fu <casouri@gmail.com>

This file is part of GNU Emacs.

GNU Emacs is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.

GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */

#include <config.h>
#include "lisp.h"
#include "buffer.h"

#include "treesit.h"

#if HAVE_TREE_SITTER

\f
/* Dynamic loading of libtree-sitter.  */

#ifdef WINDOWSNT
# include "w32common.h"

/* In alphabetical order.  */
#undef ts_language_version
#undef ts_node_child
#undef ts_node_child_by_field_name
#undef ts_node_child_count
#undef ts_node_descendant_for_byte_range
#undef ts_node_end_byte
#undef ts_node_eq
#undef ts_node_field_name_for_child
#undef ts_node_has_error
#undef ts_node_is_extra
#undef ts_node_is_missing
#undef ts_node_is_named
#undef ts_node_is_null
#undef ts_node_named_child
#undef ts_node_named_child_count
#undef ts_node_named_descendant_for_byte_range
#undef ts_node_next_named_sibling
#undef ts_node_next_sibling
#undef ts_node_prev_named_sibling
#undef ts_node_prev_sibling
#undef ts_node_start_byte
#undef ts_node_string
#undef ts_node_type
#undef ts_parser_delete
#undef ts_parser_included_ranges
#undef ts_parser_language
#undef ts_parser_new
#undef ts_parser_parse
#undef ts_parser_set_included_ranges
#undef ts_parser_set_language
#undef ts_query_capture_name_for_id
#undef ts_query_cursor_delete
#undef ts_query_cursor_exec
#undef ts_query_cursor_new
#undef ts_query_cursor_next_match
#undef ts_query_cursor_set_byte_range
#undef ts_query_delete
#undef ts_query_new
#undef ts_query_pattern_count
#undef ts_query_predicates_for_pattern
#undef ts_query_string_value_for_id
#undef ts_set_allocator
#undef ts_tree_cursor_copy
#undef ts_tree_cursor_current_node
#undef ts_tree_cursor_delete
#undef ts_tree_cursor_goto_first_child
#undef ts_tree_cursor_goto_next_sibling
#undef ts_tree_cursor_goto_parent
#undef ts_tree_cursor_new
#undef ts_tree_delete
#undef ts_tree_edit
#undef ts_tree_get_changed_ranges
#undef ts_tree_root_node

DEF_DLL_FN (uint32_t, ts_language_version, (const TSLanguage *));
DEF_DLL_FN (TSNode, ts_node_child, (TSNode, uint32_t));
DEF_DLL_FN (TSNode, ts_node_child_by_field_name,
	    (TSNode, const char *, uint32_t));
DEF_DLL_FN (uint32_t, ts_node_child_count, (TSNode));
DEF_DLL_FN (TSNode, ts_node_descendant_for_byte_range,
	    (TSNode, uint32_t, uint32_t));
DEF_DLL_FN (uint32_t, ts_node_end_byte, (TSNode));
DEF_DLL_FN (bool, ts_node_eq, (TSNode, TSNode));
DEF_DLL_FN (const char *, ts_node_field_name_for_child, (TSNode, uint32_t));
DEF_DLL_FN (bool, ts_node_has_error, (TSNode));
DEF_DLL_FN (bool, ts_node_is_extra, (TSNode));
DEF_DLL_FN (bool, ts_node_is_missing, (TSNode));
DEF_DLL_FN (bool, ts_node_is_named, (TSNode));
DEF_DLL_FN (bool, ts_node_is_null, (TSNode));
DEF_DLL_FN (TSNode, ts_node_named_child, (TSNode, uint32_t));
DEF_DLL_FN (uint32_t, ts_node_named_child_count, (TSNode));
DEF_DLL_FN (TSNode, ts_node_named_descendant_for_byte_range,
	    (TSNode, uint32_t, uint32_t));
DEF_DLL_FN (TSNode, ts_node_next_named_sibling, (TSNode));
DEF_DLL_FN (TSNode, ts_node_next_sibling, (TSNode));
DEF_DLL_FN (TSNode, ts_node_prev_named_sibling, (TSNode));
DEF_DLL_FN (TSNode, ts_node_prev_sibling, (TSNode));
DEF_DLL_FN (uint32_t, ts_node_start_byte, (TSNode));
DEF_DLL_FN (char *, ts_node_string, (TSNode));
DEF_DLL_FN (const char *, ts_node_type, (TSNode));
DEF_DLL_FN (void, ts_parser_delete, (TSParser *));
DEF_DLL_FN (const TSRange *, ts_parser_included_ranges,
	    (const TSParser *, uint32_t *));
DEF_DLL_FN (const TSLanguage *, ts_parser_language, (const TSParser *));
DEF_DLL_FN (TSParser *, ts_parser_new, (void));
DEF_DLL_FN (TSTree *, ts_parser_parse, (TSParser *, const TSTree *, TSInput));
DEF_DLL_FN (bool, ts_parser_set_included_ranges,
	    (TSParser *, const TSRange *, uint32_t));
DEF_DLL_FN (bool, ts_parser_set_language, (TSParser *, const TSLanguage *));
DEF_DLL_FN (const char *, ts_query_capture_name_for_id,
	    (const TSQuery *, uint32_t, uint32_t *));
DEF_DLL_FN (void, ts_query_cursor_delete, (TSQueryCursor *));
DEF_DLL_FN (void, ts_query_cursor_exec,
	    (TSQueryCursor *, const TSQuery *, TSNode));
DEF_DLL_FN (TSQueryCursor *, ts_query_cursor_new, (void));
DEF_DLL_FN (bool, ts_query_cursor_next_match,
	    (TSQueryCursor *, TSQueryMatch *));
DEF_DLL_FN (void, ts_query_cursor_set_byte_range,
	    (TSQueryCursor *, uint32_t, uint32_t));
DEF_DLL_FN (void, ts_query_delete, (TSQuery *));
DEF_DLL_FN (TSQuery *, ts_query_new,
	    (const TSLanguage *, const char *, uint32_t, uint32_t *, TSQueryError *));
DEF_DLL_FN (uint32_t, ts_query_pattern_count, (const TSQuery *));
DEF_DLL_FN (const TSQueryPredicateStep *, ts_query_predicates_for_pattern,
	    ( const TSQuery *, uint32_t, uint32_t *));
DEF_DLL_FN (const char *, ts_query_string_value_for_id,
	    (const TSQuery *, uint32_t, uint32_t *));
DEF_DLL_FN (void, ts_set_allocator,
	    (void *(*)(size_t), void *(*)(size_t, size_t), void *(*)(void *, size_t), void (*)(void *)));
DEF_DLL_FN (TSTreeCursor, ts_tree_cursor_copy, (const TSTreeCursor *));
DEF_DLL_FN (TSNode, ts_tree_cursor_current_node, (const TSTreeCursor *));
DEF_DLL_FN (void, ts_tree_cursor_delete, (const TSTreeCursor *));
DEF_DLL_FN (bool, ts_tree_cursor_goto_first_child, (TSTreeCursor *));
DEF_DLL_FN (bool, ts_tree_cursor_goto_next_sibling, (TSTreeCursor *));
DEF_DLL_FN (bool, ts_tree_cursor_goto_parent, (TSTreeCursor *));
DEF_DLL_FN (TSTreeCursor, ts_tree_cursor_new, (TSNode));
DEF_DLL_FN (void, ts_tree_delete, (TSTree *));
DEF_DLL_FN (void, ts_tree_edit, (TSTree *, const TSInputEdit *));
DEF_DLL_FN (TSRange *, ts_tree_get_changed_ranges,
	    (const TSTree *, const TSTree *, uint32_t *));
DEF_DLL_FN (TSNode, ts_tree_root_node, (const TSTree *));

static bool
init_treesit_functions (void)
{
  HMODULE library = w32_delayed_load (Qtree_sitter);

  if (!library)
    return false;

  LOAD_DLL_FN (library, ts_language_version);
  LOAD_DLL_FN (library, ts_node_child);
  LOAD_DLL_FN (library, ts_node_child_by_field_name);
  LOAD_DLL_FN (library, ts_node_child_count);
  LOAD_DLL_FN (library, ts_node_descendant_for_byte_range);
  LOAD_DLL_FN (library, ts_node_end_byte);
  LOAD_DLL_FN (library, ts_node_eq);
  LOAD_DLL_FN (library, ts_node_field_name_for_child);
  LOAD_DLL_FN (library, ts_node_has_error);
  LOAD_DLL_FN (library, ts_node_is_extra);
  LOAD_DLL_FN (library, ts_node_is_missing);
  LOAD_DLL_FN (library, ts_node_is_named);
  LOAD_DLL_FN (library, ts_node_is_null);
  LOAD_DLL_FN (library, ts_node_named_child);
  LOAD_DLL_FN (library, ts_node_named_child_count);
  LOAD_DLL_FN (library, ts_node_named_descendant_for_byte_range);
  LOAD_DLL_FN (library, ts_node_next_named_sibling);
  LOAD_DLL_FN (library, ts_node_next_sibling);
  LOAD_DLL_FN (library, ts_node_prev_named_sibling);
  LOAD_DLL_FN (library, ts_node_prev_sibling);
  LOAD_DLL_FN (library, ts_node_start_byte);
  LOAD_DLL_FN (library, ts_node_string);
  LOAD_DLL_FN (library, ts_node_type);
  LOAD_DLL_FN (library, ts_parser_delete);
  LOAD_DLL_FN (library, ts_parser_included_ranges);
  LOAD_DLL_FN (library, ts_parser_language);
  LOAD_DLL_FN (library, ts_parser_new);
  LOAD_DLL_FN (library, ts_parser_parse);
  LOAD_DLL_FN (library, ts_parser_set_included_ranges);
  LOAD_DLL_FN (library, ts_parser_set_language);
  LOAD_DLL_FN (library, ts_query_capture_name_for_id);
  LOAD_DLL_FN (library, ts_query_cursor_delete);
  LOAD_DLL_FN (library, ts_query_cursor_exec);
  LOAD_DLL_FN (library, ts_query_cursor_new);
  LOAD_DLL_FN (library, ts_query_cursor_next_match);
  LOAD_DLL_FN (library, ts_query_cursor_set_byte_range);
  LOAD_DLL_FN (library, ts_query_delete);
  LOAD_DLL_FN (library, ts_query_new);
  LOAD_DLL_FN (library, ts_query_pattern_count);
  LOAD_DLL_FN (library, ts_query_predicates_for_pattern);
  LOAD_DLL_FN (library, ts_query_string_value_for_id);
  LOAD_DLL_FN (library, ts_set_allocator);
  LOAD_DLL_FN (library, ts_tree_cursor_copy);
  LOAD_DLL_FN (library, ts_tree_cursor_current_node);
  LOAD_DLL_FN (library, ts_tree_cursor_delete);
  LOAD_DLL_FN (library, ts_tree_cursor_goto_first_child);
  LOAD_DLL_FN (library, ts_tree_cursor_goto_next_sibling);
  LOAD_DLL_FN (library, ts_tree_cursor_goto_parent);
  LOAD_DLL_FN (library, ts_tree_cursor_new);
  LOAD_DLL_FN (library, ts_tree_delete);
  LOAD_DLL_FN (library, ts_tree_edit);
  LOAD_DLL_FN (library, ts_tree_get_changed_ranges);
  LOAD_DLL_FN (library, ts_tree_root_node);

  return true;
}

#define ts_language_version fn_ts_language_version
#define ts_node_child fn_ts_node_child
#define ts_node_child_by_field_name fn_ts_node_child_by_field_name
#define ts_node_child_count fn_ts_node_child_count
#define ts_node_descendant_for_byte_range fn_ts_node_descendant_for_byte_range
#define ts_node_end_byte fn_ts_node_end_byte
#define ts_node_eq fn_ts_node_eq
#define ts_node_field_name_for_child fn_ts_node_field_name_for_child
#define ts_node_has_error fn_ts_node_has_error
#define ts_node_is_extra fn_ts_node_is_extra
#define ts_node_is_missing fn_ts_node_is_missing
#define ts_node_is_named fn_ts_node_is_named
#define ts_node_is_null fn_ts_node_is_null
#define ts_node_named_child fn_ts_node_named_child
#define ts_node_named_child_count fn_ts_node_named_child_count
#define ts_node_named_descendant_for_byte_range fn_ts_node_named_descendant_for_byte_range
#define ts_node_next_named_sibling fn_ts_node_next_named_sibling
#define ts_node_next_sibling fn_ts_node_next_sibling
#define ts_node_prev_named_sibling fn_ts_node_prev_named_sibling
#define ts_node_prev_sibling fn_ts_node_prev_sibling
#define ts_node_start_byte fn_ts_node_start_byte
#define ts_node_string fn_ts_node_string
#define ts_node_type fn_ts_node_type
#define ts_parser_delete fn_ts_parser_delete
#define ts_parser_included_ranges fn_ts_parser_included_ranges
#define ts_parser_language fn_ts_parser_language
#define ts_parser_new fn_ts_parser_new
#define ts_parser_parse fn_ts_parser_parse
#define ts_parser_set_included_ranges fn_ts_parser_set_included_ranges
#define ts_parser_set_language fn_ts_parser_set_language
#define ts_query_capture_name_for_id fn_ts_query_capture_name_for_id
#define ts_query_cursor_delete fn_ts_query_cursor_delete
#define ts_query_cursor_exec fn_ts_query_cursor_exec
#define ts_query_cursor_new fn_ts_query_cursor_new
#define ts_query_cursor_next_match fn_ts_query_cursor_next_match
#define ts_query_cursor_set_byte_range fn_ts_query_cursor_set_byte_range
#define ts_query_delete fn_ts_query_delete
#define ts_query_new fn_ts_query_new
#define ts_query_pattern_count fn_ts_query_pattern_count
#define ts_query_predicates_for_pattern fn_ts_query_predicates_for_pattern
#define ts_query_string_value_for_id fn_ts_query_string_value_for_id
#define ts_set_allocator fn_ts_set_allocator
#define ts_tree_cursor_copy fn_ts_tree_cursor_copy
#define ts_tree_cursor_current_node fn_ts_tree_cursor_current_node
#define ts_tree_cursor_delete fn_ts_tree_cursor_delete
#define ts_tree_cursor_goto_first_child fn_ts_tree_cursor_goto_first_child
#define ts_tree_cursor_goto_next_sibling fn_ts_tree_cursor_goto_next_sibling
#define ts_tree_cursor_goto_parent fn_ts_tree_cursor_goto_parent
#define ts_tree_cursor_new fn_ts_tree_cursor_new
#define ts_tree_delete fn_ts_tree_delete
#define ts_tree_edit fn_ts_tree_edit
#define ts_tree_get_changed_ranges fn_ts_tree_get_changed_ranges
#define ts_tree_root_node fn_ts_tree_root_node

#endif	/* WINDOWSNT */

\f
/* Commentary

   The Emacs wrapper of tree-sitter does not expose everything the C
   API provides, most notably:

   - It doesn't expose a syntax tree.  The syntax tree is part of the
     parser object, and updating the tree is handled on the C level.

   - It doesn't expose the tree cursor, either.  Presumably, Lisp is
     slow enough to make insignificant any performance advantages from
     using the cursor.  Not exposing the cursor also minimizes the
     number of new types this adds to Emacs Lisp; currently, this adds
     only the parser, node, and compiled query types.

   - Because updating the change is handled on the C level as each
     change is made in the buffer, there is no way for Lisp to update
     a node.  But since we can just retrieve a new node, it shouldn't
     be a limitation.

   - I didn't expose setting timeout and cancellation flag for a
     parser, mainly because I don't think they are really necessary
     in Emacs's use cases.

   - Many tree-sitter functions take a TSPoint, which is basically a
     row and column.  Emacs uses a gap buffer and does not keep
     information about the row and column position of a buffer.
     According to the author of tree-sitter, those functions only take
     a TSPoint so that it can be moved alongside the byte position and
     returned to the caller afterwards, and the position actually used
     is the specified byte position.  He also said that he _thinks_
     that just passing a byte position will also work.  As a result, a
     dummy value is used in place of each TSPoint.  Judging by the
     nature of parsing algorithms, I think it is safe to use only the
     byte position, and I don't think this will change in the future.

     See: https://github.com/tree-sitter/tree-sitter/issues/445

   treesit.h has some commentary on the two main data structure for
   the parser and node.  treesit_sync_visible_region has some
   commentary on how we make tree-sitter play well with narrowing (the
   tree-sitter parser only sees the visible region, so we need to
   translate positions back and forth).  Most action happens in
   treesit_ensure_parsed, treesit_read_buffer and
   treesit_record_change.

   A complete correspondence list between tree-sitter functions and
   exposed Lisp functions can be found in the manual node (elisp)API
   Correspondence.

   Placement of CHECK_xxx functions: call CHECK_xxx before using any
   unchecked Lisp values; these include arguments of Lisp functions,
   the return value of Fsymbol_value, and that of Fcar or Fcdr on
   user-specified conses.

   Initializing tree-sitter: there are two entry points to tree-sitter
   functions: 'treesit-parser-create' and
   'treesit-language-available-p'.  Technically we only need to call
   initialization function in those two functions, but in reality we
   check at the beginning of every Lisp function.  That should be more
   fool-proof.

   Tree-sitter offset (0-based) and buffer position (1-based):
     tree-sitter offset + buffer position = buffer position
     buffer position - buffer position = tree-sitter offset

   Tree-sitter-related code in other files:
   - src/alloc.c for gc for parser and node
   - src/casefiddle.c & src/insdel.c for notifying tree-sitter
     parser of buffer changes.
   - lisp/emacs-lisp/cl-preloaded.el & data.c & lisp.h for parser and
     node type.
   - print.c for printing tree-sitter objects (node, parser, query).

   Regarding signals: only raise signals in Lisp functions.

   Casts from EMACS_INT and ptrdiff_t to uint32_t: We install checks
   for buffer size and range and thus able to assume these casts never
   overflow.

   We don't parse at every keystroke.  Instead we only record the
   changes at each keystroke, and only parse when requested.  It is
   possible that lazy parsing is worse: instead of dispersed little
   pauses, now you have less frequent but larger pauses.  I doubt
   there will be any perceived difference, as the lazy parsing is
   going to be pretty frequent anyway.  Also this (lazy parsing) is
   what the mailing list guys wanted.

   Because it is pretty slow (comparing to other tree-sitter
   operations) for tree-sitter to parse the query and produce a query
   object, it is very wasteful to reparse the query every time
   treesit-query-capture is called, and it completely kills the
   performance of querying in a loop for a moderate amount of times
   (hundreds of queries takes seconds rather than milliseconds to
   complete).  Therefore we want some caching.  We can either use a
   search.c style transparent caching, or simply expose a new type,
   compiled-ts-query and let the user to manually compile AOT.  I
   believe AOT compiling gives users more control, makes the
   performance stable and easy to understand (compiled -> fast,
   uncompiled -> slow), and avoids some edge cases transparent cache
   could have (see below).  So I implemented the AOT compilation.

   Problems a transparent cache could have: Suppose we store cache
   entries in a fixed-length linked-list, and compare with EQ.  1)
   One-off query could kick out useful cache.  2) if the user messed
   up and the query doesn't EQ to the cache anymore, the performance
   mysteriously drops.  3) what if a user uses so many stuff that the
   default cache size (20) is not enough and we end up thrashing?
   These are all imaginary scenarios but they are not impossible
   :-)

   Parsers in indirect buffers: We make indirect buffers to share the
   parser of its base buffer.  Indirect buffers and their base buffer
   share the same buffer content but not other buffer attributes.  If
   they have separate parser lists, changes made in an indirect buffer
   will only update parsers of that indirect buffer, and not parsers
   in the base buffer or other indirect buffers, and vice versa.  We
   could keep track of all the base and indirect buffers, and update
   all of their parsers, but ultimately decide to take a simpler
   approach, which is to make indirect buffers share their base
   buffer's parser list.  The discussion can be found in bug#59693.  */

\f
/*** Initialization */

static Lisp_Object Vtreesit_str_libtree_sitter;
static Lisp_Object Vtreesit_str_tree_sitter;
static Lisp_Object Vtreesit_str_dot;
static Lisp_Object Vtreesit_str_question_mark;
static Lisp_Object Vtreesit_str_star;
static Lisp_Object Vtreesit_str_plus;
static Lisp_Object Vtreesit_str_pound_equal;
static Lisp_Object Vtreesit_str_pound_match;
static Lisp_Object Vtreesit_str_pound_pred;
static Lisp_Object Vtreesit_str_open_bracket;
static Lisp_Object Vtreesit_str_close_bracket;
static Lisp_Object Vtreesit_str_open_paren;
static Lisp_Object Vtreesit_str_close_paren;
static Lisp_Object Vtreesit_str_space;
static Lisp_Object Vtreesit_str_equal;
static Lisp_Object Vtreesit_str_match;
static Lisp_Object Vtreesit_str_pred;

/* This is the limit on recursion levels for some tree-sitter
   functions.  Remember to update docstrings when changing this
   value. */
const ptrdiff_t treesit_recursion_limit = 1000;
bool treesit_initialized = false;

static bool
load_tree_sitter_if_necessary (bool required)
{
#ifdef WINDOWSNT
  static bool tried_to_initialize_once;
  static bool tree_sitter_initialized;

  if (!tried_to_initialize_once)
    {
      Lisp_Object status;

      tried_to_initialize_once = true;
      tree_sitter_initialized = init_treesit_functions ();
      status = tree_sitter_initialized ? Qt : Qnil;
      Vlibrary_cache = Fcons (Fcons (Qtree_sitter, status), Vlibrary_cache);
    }

  if (required && !tree_sitter_initialized)
    xsignal1 (Qtreesit_error,
	      build_string ("tree-sitter library not found or failed to load"));

  return tree_sitter_initialized;
#else
  return true;
#endif
}

static void *
treesit_calloc_wrapper (size_t n, size_t size)
{
  return xzalloc (n * size);
}

static void
treesit_initialize (void)
{
  if (!treesit_initialized)
    {
      load_tree_sitter_if_necessary (true);
      ts_set_allocator (xmalloc, treesit_calloc_wrapper, xrealloc, xfree);
      treesit_initialized = true;
    }
}

\f
/*** Loading language library */

/* Translates a symbol treesit-<lang> to a C name
   treesit_<lang>.  */
static void
treesit_symbol_to_c_name (char *symbol_name)
{
  for (int idx = 0; idx < strlen (symbol_name); idx++)
    {
      if (symbol_name[idx] == '-')
	symbol_name[idx] = '_';
    }
}

static bool
treesit_find_override_name (Lisp_Object language_symbol, Lisp_Object *name,
			    Lisp_Object *c_symbol)
{
  Lisp_Object tem;

  CHECK_LIST (Vtreesit_load_name_override_list);

  tem = Vtreesit_load_name_override_list;

  FOR_EACH_TAIL (tem)
    {
      Lisp_Object lang = XCAR (XCAR (tem));
      CHECK_SYMBOL (lang);

      if (EQ (lang, language_symbol))
	{
	  *name = Fnth (make_fixnum (1), XCAR (tem));
	  CHECK_STRING (*name);
	  *c_symbol = Fnth (make_fixnum (2), XCAR (tem));
	  CHECK_STRING (*c_symbol);

	  return true;
	}
    }

  CHECK_LIST_END (tem, Vtreesit_load_name_override_list);

  return false;
}

/* For example, if Vdynamic_library_suffixes is (".so", ".dylib"),
   this function pushes "lib_base_name.so" and "lib_base_name.dylib"
   into *path_candidates.  Obviously path_candidates should be a Lisp
   list of Lisp strings.  */
static void
treesit_load_language_push_for_each_suffix (Lisp_Object lib_base_name,
					    Lisp_Object *path_candidates)
{
  Lisp_Object suffixes;

  suffixes = Vdynamic_library_suffixes;

  FOR_EACH_TAIL (suffixes)
    *path_candidates = Fcons (concat2 (lib_base_name, XCAR (suffixes)),
			      *path_candidates);
}

/* Load the dynamic library of LANGUAGE_SYMBOL and return the pointer
   to the language definition.

   If error occurs, return NULL and fill SIGNAL_SYMBOL and SIGNAL_DATA
   with values suitable for xsignal.  */
static TSLanguage *
treesit_load_language (Lisp_Object language_symbol,
		       Lisp_Object *signal_symbol, Lisp_Object *signal_data)
{
  Lisp_Object symbol_name = Fsymbol_name (language_symbol);

  CHECK_LIST (Vtreesit_extra_load_path);

  /* Figure out the library name and C name.  */
  Lisp_Object lib_base_name
    = concat2 (Vtreesit_str_libtree_sitter, symbol_name);
  Lisp_Object base_name
    = concat2 (Vtreesit_str_tree_sitter, symbol_name);

  /* Override the library name and C name, if appropriate.  */
  Lisp_Object override_name;
  Lisp_Object override_c_name;
  bool found_override = treesit_find_override_name (language_symbol,
						    &override_name,
						    &override_c_name);
  if (found_override)
    lib_base_name = override_name;

  /* Now we generate a list of possible library paths.  */
  Lisp_Object path_candidates = Qnil;
  /* First push just the filenames to the candidate list, which will
     make dynlib_open look under standard system load paths.  */
  treesit_load_language_push_for_each_suffix (lib_base_name, &path_candidates);
  /* This is used for reporting errors (i.e., just filenames).  */
  Lisp_Object base_candidates = path_candidates;
  /* Then push ~/.emacs.d/tree-sitter paths.  */
  Lisp_Object lib_name
    = Fexpand_file_name (concat2 (build_string ("tree-sitter/"), lib_base_name),
			 Fsymbol_value (Quser_emacs_directory));
  treesit_load_language_push_for_each_suffix (lib_name, &path_candidates);
  /* Then push paths from treesit-extra-load-path.  */
  Lisp_Object tail;

  tail = Freverse (Vtreesit_extra_load_path);

  FOR_EACH_TAIL (tail)
    {
      Lisp_Object expanded_lib = Fexpand_file_name (lib_base_name, XCAR (tail));
      treesit_load_language_push_for_each_suffix (expanded_lib,
						  &path_candidates);
    }

  /* Try loading the dynamic library by each path candidate.  Stop
     when succeed, record the error message and try the next one when
     fail.  */
  dynlib_handle_ptr handle;
  const char *error;

  tail = path_candidates;
  error = NULL;
  handle = NULL;

  FOR_EACH_TAIL (tail)
    {
      char *library_name = SSDATA (XCAR (tail));
      dynlib_error ();
      handle = dynlib_open (library_name);
      error = dynlib_error ();
      if (error == NULL)
	break;
    }

  if (error != NULL)
    {
      *signal_symbol = Qtreesit_load_language_error;
      *signal_data = list3 (Qnot_found, base_candidates,
			    build_string ("No such file or directory"));
      return NULL;
    }

  /* Load TSLanguage.  */
  eassume (handle != NULL);
  dynlib_error ();
  TSLanguage *(*langfn) (void);
  char *c_name;
  if (found_override)
    c_name = xstrdup (SSDATA (override_c_name));
  else
    {
      c_name = xstrdup (SSDATA (base_name));
      treesit_symbol_to_c_name (c_name);
    }
  langfn = dynlib_sym (handle, c_name);
  xfree (c_name);
  error = dynlib_error ();
  if (error != NULL)
    {
      *signal_symbol = Qtreesit_load_language_error;
      *signal_data = list2 (Qsymbol_error, build_string (error));
      return NULL;
    }
  TSLanguage *lang = (*langfn) ();

  /* Check if language version matches tree-sitter version.  */
  TSParser *parser = ts_parser_new ();
  bool success = ts_parser_set_language (parser, lang);
  ts_parser_delete (parser);
  if (!success)
    {
      *signal_symbol = Qtreesit_load_language_error;
      *signal_data = list2 (Qversion_mismatch,
			    make_fixnum (ts_language_version (lang)));
      return NULL;
    }
  return lang;
}

DEFUN ("treesit-language-available-p", Ftreesit_language_available_p,
       Streesit_language_available_p,
       1, 2, 0,
       doc: /* Return non-nil if LANGUAGE exists and is loadable.

If DETAIL is non-nil, return (t . nil) when LANGUAGE is available,
(nil . DATA) when unavailable.  DATA is the signal data of
`treesit-load-language-error'.  */)
  (Lisp_Object language, Lisp_Object detail)
{
  CHECK_SYMBOL (language);
  treesit_initialize ();
  Lisp_Object signal_symbol = Qnil;
  Lisp_Object signal_data = Qnil;
  if (treesit_load_language (language, &signal_symbol, &signal_data) == NULL)
    {
      if (NILP (detail))
	return Qnil;
      else
	return Fcons (Qnil, signal_data);
    }
  else
    {
      if (NILP (detail))
	return Qt;
      else
	return Fcons (Qt, Qnil);
    }
}

DEFUN ("treesit-library-abi-version", Ftreesit_library_abi_version,
       Streesit_library_abi_version,
       0, 1, 0,
       doc: /* Return the language ABI version of the tree-sitter library.

By default, report the latest ABI version supported by the library for
loading language support modules.  The library is backward-compatible
with language modules which use older ABI versions; if MIN-COMPATIBLE
is non-nil, return the oldest compatible ABI version.  */)
  (Lisp_Object min_compatible)
{
  if (NILP (min_compatible))
    return make_fixnum (TREE_SITTER_LANGUAGE_VERSION);
  else
    return make_fixnum (TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION);
}

DEFUN ("treesit-language-abi-version", Ftreesit_language_abi_version,
       Streesit_language_abi_version,
       0, 1, 0,
       doc: /* Return the ABI version of the tree-sitter grammar for LANGUAGE.
Return nil if a grammar library for LANGUAGE is not available.  */)
  (Lisp_Object language)
{
  if (NILP (Ftreesit_language_available_p (language, Qnil)))
    return Qnil;
  else
    {
      Lisp_Object signal_symbol = Qnil;
      Lisp_Object signal_data = Qnil;
      TSLanguage *ts_language = treesit_load_language (language,
						       &signal_symbol,
						       &signal_data);
      if (ts_language == NULL)
	return Qnil;
      uint32_t version =  ts_language_version (ts_language);
      return make_fixnum((ptrdiff_t) version);
    }
}

\f
/*** Parsing functions */

static void
treesit_check_parser (Lisp_Object obj)
{
  CHECK_TS_PARSER (obj);
  if (XTS_PARSER (obj)->deleted)
    xsignal1 (Qtreesit_parser_deleted, obj);
}

/* An auxiliary function that saves a few lines of code.  Assumes TREE
   is not NULL.  START_BYTE, OLD_END_BYTE, NEW_END_BYTE must not be
   larger than UINT32_MAX.  */
static inline void
treesit_tree_edit_1 (TSTree *tree, ptrdiff_t start_byte,
		     ptrdiff_t old_end_byte, ptrdiff_t new_end_byte)
{
  eassert (start_byte >= 0);
  eassert (start_byte <= old_end_byte);
  eassert (start_byte <= new_end_byte);
  TSPoint dummy_point = {0, 0};
  eassert (start_byte <= UINT32_MAX);
  eassert (old_end_byte <= UINT32_MAX);
  eassert (new_end_byte <= UINT32_MAX);
  TSInputEdit edit = {(uint32_t) start_byte,
		      (uint32_t) old_end_byte,
		      (uint32_t) new_end_byte,
		      dummy_point, dummy_point, dummy_point};
  ts_tree_edit (tree, &edit);
}

/* Update each parser's tree after the user made an edit.  This
   function does not parse the buffer and only updates the tree, so it
   should be very fast.  */
void
treesit_record_change (ptrdiff_t start_byte, ptrdiff_t old_end_byte,
		       ptrdiff_t new_end_byte)
{
  struct buffer *base_buffer = current_buffer;
  if (current_buffer->base_buffer)
    base_buffer = current_buffer->base_buffer;
  Lisp_Object parser_list = BVAR (base_buffer, ts_parser_list);

  FOR_EACH_TAIL_SAFE (parser_list)
    {
      CHECK_CONS (parser_list);
      Lisp_Object lisp_parser = XCAR (parser_list);
      treesit_check_parser (lisp_parser);
      TSTree *tree = XTS_PARSER (lisp_parser)->tree;
      /* See comment (ref:visible-beg-null) if you wonder why we don't
	 update visible_beg/end when tree is NULL.  */

      if (tree != NULL)
	{
	  eassert (start_byte <= old_end_byte);
	  eassert (start_byte <= new_end_byte);
	  /* Think the recorded change as a delete followed by an
	     insert, and think of them as moving unchanged text back
	     and forth.  After all, the whole point of updating the
	     tree is to update the position of unchanged text.  */
	  ptrdiff_t visible_beg = XTS_PARSER (lisp_parser)->visible_beg;
	  ptrdiff_t visible_end = XTS_PARSER (lisp_parser)->visible_end;
	  eassert (visible_beg >= 0);
	  eassert (visible_beg <= visible_end);

	  /* AFFECTED_START/OLD_END/NEW_END are (0-based) offsets from
	     VISIBLE_BEG.  min(visi_end, max(visi_beg, value)) clips
	     value into [visi_beg, visi_end], and subtracting visi_beg
	     gives the offset from visi_beg.  */
	  ptrdiff_t start_offset = (min (visible_end,
					 max (visible_beg, start_byte))
				    - visible_beg);
	  ptrdiff_t old_end_offset = (min (visible_end,
					   max (visible_beg, old_end_byte))
				      - visible_beg);
	  /* We don't clip new_end_offset under visible_end, because
	     otherwise we would miss updating the clipped part.  Plus,
	     when inserting in narrowed region, the narrowed region
	     will grow to accommodate the new text, so this is the
	     correct behavior.  (Bug#61369).  */
	  ptrdiff_t new_end_offset = (max (visible_beg, new_end_byte)
				      - visible_beg);
	  eassert (start_offset <= old_end_offset);
	  eassert (start_offset <= new_end_offset);

	  treesit_tree_edit_1 (tree, start_offset, old_end_offset,
			       new_end_offset);
	  XTS_PARSER (lisp_parser)->need_reparse = true;
	  XTS_PARSER (lisp_parser)->timestamp++;

	  /* VISIBLE_BEG/END records tree-sitter's range of view in
	     the buffer.  We need to adjust them when tree-sitter's
	     view changes.  */
	  ptrdiff_t visi_beg_delta;
	  if (old_end_byte > new_end_byte)
	    /* Move backward.  */
	    visi_beg_delta = (min (visible_beg, new_end_byte)
			      - min (visible_beg, old_end_byte));
	  else
	    /* Move forward.  */
	    visi_beg_delta = (old_end_byte < visible_beg
			      ? new_end_byte - old_end_byte : 0);

	  XTS_PARSER (lisp_parser)->visible_beg = visible_beg + visi_beg_delta;
	  XTS_PARSER (lisp_parser)->visible_end = (visible_end
						   + visi_beg_delta
						   + (new_end_offset
						      - old_end_offset));

	  eassert (XTS_PARSER (lisp_parser)->visible_beg >= 0);
	  eassert (XTS_PARSER (lisp_parser)->visible_beg
		   <= XTS_PARSER (lisp_parser)->visible_end);
	}
    }
}

/* Comment (ref:visible-beg-null) The purpose of visible_beg/end is to
   keep track of "which part of the buffer does the tree-sitter tree
   see", in order to update the tree correctly.  Visible_beg/end have
   two purposes: they "clip" buffer changes within them, and they
   translate positions in the buffer to positions in the tree
   (buffer position - visible_beg = tree position).

   Conceptually, visible_beg/end hold the visible region of the buffer
   when we last reparsed.  In-between two reparses, we don't really
   care if the visible region of the buffer changes.

   Right before we reparse, we make tree-sitter's visible region
   match that of the buffer, and update visible_beg/end.

   That is, the whole purpose of visible_beg/end (and also of
   treesit_record_change and treesit_sync_visible_region) is to update
   the tree (by ts_tree_edit).  So if the tree is NULL,
   visible_beg/end are considered uninitialized.  Only when we already
   have a tree, do we need to keep track of position changes and
   update it correctly, so it can be fed into ts_parser_parse as the
   old tree, so that tree-sitter will only parse the changed part,
   incrementally.

   In a nutshell, tree-sitter incremental parsing in Emacs looks like:

   treesit_record_change (tree)  \
   treesit_record_change (tree)  | user edits buffer
   ...                           /

   treesit_sync_visible_region (tree) \ treesit_ensure_parsed
   ts_parser_parse(tree) -> tree      /

   treesit_record_change (tree)  \
   treesit_record_change (tree)  | user edits buffer
   ...                           /

   and so on.  */

/* Make sure the tree's visible range is in sync with the buffer's
   visible range, and PARSER's visible_beg and visible_end are in sync
   with BUF_BEGV_BYTE and BUG_ZV_BYTE.  When calling this function you
   must make sure the current buffer's size in bytes is not larger than
   UINT32_MAX.  Basically, always call treesit_check_buffer_size before
   this function.

   If buffer range changed since last parse (visible_beg/end doesn't
   match buffer visible beginning/end), set need_reparse to true.  */
static void
treesit_sync_visible_region (Lisp_Object parser)
{
  TSTree *tree = XTS_PARSER (parser)->tree;
  struct buffer *buffer = XBUFFER (XTS_PARSER (parser)->buffer);

  /* If we are setting visible_beg/end for the first time, we can skip
  the offset acrobatics and updating the tree below.  */
  if (tree == NULL)
    {
      XTS_PARSER (parser)->visible_beg = BUF_BEGV_BYTE (buffer);
      XTS_PARSER (parser)->visible_end = BUF_ZV_BYTE (buffer);
      return;
    }

  ptrdiff_t visible_beg = XTS_PARSER (parser)->visible_beg;
  ptrdiff_t visible_end = XTS_PARSER (parser)->visible_end;
  eassert (0 <= visible_beg);
  eassert (visible_beg <= visible_end);

  eassert (BUF_BEGV_BYTE (buffer) <= UINT32_MAX);
  eassert (BUF_ZV_BYTE (buffer) <= UINT32_MAX);

  /* If buffer restriction changed and user requests for a node (hence
     this function is called), we need to reparse.  */
  if (visible_beg != BUF_BEGV_BYTE (buffer)
      || visible_end != BUF_ZV_BYTE (buffer))
    XTS_PARSER (parser)->need_reparse = true;

  /* Before we parse or set ranges, catch up with the narrowing
     situation.  We change visible_beg and visible_end to match
     BUF_BEGV_BYTE and BUF_ZV_BYTE, and inform tree-sitter of the
     change.  We want to move the visible range of tree-sitter to
     match the narrowed range.  For example,
     from ________|xxxx|__
     to   |xxxx|__________ */

  /* 1. Make sure visible_beg <= BUF_BEGV_BYTE.  */
  if (visible_beg > BUF_BEGV_BYTE (buffer))
    {
      /* Tree-sitter sees: insert at the beginning.  */
      treesit_tree_edit_1 (tree, 0, 0, visible_beg - BUF_BEGV_BYTE (buffer));
      visible_beg = BUF_BEGV_BYTE (buffer);
      eassert (visible_beg <= visible_end);
    }
  /* 2. Make sure visible_end = BUF_ZV_BYTE.  */
  if (visible_end < BUF_ZV_BYTE (buffer))
    {
      /* Tree-sitter sees: insert at the end.  */
      treesit_tree_edit_1 (tree, visible_end - visible_beg,
			   visible_end - visible_beg,
			   BUF_ZV_BYTE (buffer) - visible_beg);
      visible_end = BUF_ZV_BYTE (buffer);
      eassert (visible_beg <= visible_end);
    }
  else if (visible_end > BUF_ZV_BYTE (buffer))
    {
      /* Tree-sitter sees: delete at the end.  */
      treesit_tree_edit_1 (tree, BUF_ZV_BYTE (buffer) - visible_beg,
			   visible_end - visible_beg,
			   BUF_ZV_BYTE (buffer) - visible_beg);
      visible_end = BUF_ZV_BYTE (buffer);
      eassert (visible_beg <= visible_end);
    }
  /* 3. Make sure visible_beg = BUF_BEGV_BYTE.  */
  if (visible_beg < BUF_BEGV_BYTE (buffer))
    {
      /* Tree-sitter sees: delete at the beginning.  */
      treesit_tree_edit_1 (tree, 0, BUF_BEGV_BYTE (buffer) - visible_beg, 0);
      visible_beg = BUF_BEGV_BYTE (buffer);
      eassert (visible_beg <= visible_end);
    }
  eassert (0 <= visible_beg);
  eassert (visible_beg <= visible_end);
  eassert (visible_beg == BUF_BEGV_BYTE (buffer));
  eassert (visible_end == BUF_ZV_BYTE (buffer));

  XTS_PARSER (parser)->visible_beg = visible_beg;
  XTS_PARSER (parser)->visible_end = visible_end;
}

static void
treesit_check_buffer_size (struct buffer *buffer)
{
  ptrdiff_t buffer_size_bytes = (BUF_Z_BYTE (buffer) - BUF_BEG_BYTE (buffer));
  if (buffer_size_bytes > UINT32_MAX)
    xsignal2 (Qtreesit_buffer_too_large,
	      build_string ("Buffer size cannot be larger than 4GB"),
	      make_fixnum (buffer_size_bytes));
}

static Lisp_Object treesit_make_ranges (const TSRange *, uint32_t, struct buffer *);

static void
treesit_call_after_change_functions (TSTree *old_tree, TSTree *new_tree,
				     Lisp_Object parser)
{
  /* If the old_tree is NULL, meaning this is the first parse, the
     changed range is the whole buffer.  */
  Lisp_Object lisp_ranges;
  struct buffer *buf = XBUFFER (XTS_PARSER (parser)->buffer);
  if (old_tree)
    {
      uint32_t len;
      TSRange *ranges = ts_tree_get_changed_ranges (old_tree, new_tree, &len);
      lisp_ranges = treesit_make_ranges (ranges, len, buf);
      xfree (ranges);
    }
  else
    {
      struct buffer *oldbuf = current_buffer;
      set_buffer_internal (buf);
      lisp_ranges = Fcons (Fcons (Fpoint_min (), Fpoint_max ()), Qnil);
      set_buffer_internal (oldbuf);
    }

  specpdl_ref count = SPECPDL_INDEX ();

  /* let's trust the after change functions and not clone a new ranges
     for each of them.  */
  Lisp_Object functions = XTS_PARSER (parser)->after_change_functions;
  FOR_EACH_TAIL (functions)
    safe_call2 (XCAR (functions), lisp_ranges, parser);

  unbind_to (count, Qnil);
}

/* Parse the buffer.  We don't parse until we have to.  When we have
   to, we call this function to parse and update the tree.  */
static void
treesit_ensure_parsed (Lisp_Object parser)
{
  struct buffer *buffer = XBUFFER (XTS_PARSER (parser)->buffer);

  /* Before we parse, catch up with the narrowing situation.  */
  treesit_check_buffer_size (buffer);
  /* This function has to run before we check for need_reparse flag,
     because it might set the flag to true.  */
  treesit_sync_visible_region (parser);

  /* Make sure this comes before everything else, see comment
     (ref:notifier-inside-ensure-parsed) for more detail.  */
  if (!XTS_PARSER (parser)->need_reparse)
    return;

  TSParser *treesit_parser = XTS_PARSER (parser)->parser;
  TSTree *tree = XTS_PARSER (parser)->tree;
  TSInput input = XTS_PARSER (parser)->input;

  TSTree *new_tree = ts_parser_parse (treesit_parser, tree, input);
  /* This should be very rare (impossible, really): it only happens
     when 1) language is not set (impossible in Emacs because the user
     has to supply a language to create a parser), 2) parse canceled
     due to timeout (impossible because we don't set a timeout), 3)
     parse canceled due to cancellation flag (impossible because we
     don't set the flag).  (See comments for ts_parser_parse in
     tree_sitter/api.h.)  */
  if (new_tree == NULL)
    {
      Lisp_Object buf;
      XSETBUFFER (buf, buffer);
      xsignal1 (Qtreesit_parse_error, buf);
    }

  XTS_PARSER (parser)->tree = new_tree;
  XTS_PARSER (parser)->need_reparse = false;

  /* After-change functions should run at the very end, most crucially
     after need_reparse is set to false, this way if the function
     calls some tree-sitter function which invokes
     treesit_ensure_parsed again, it returns early and do not
     recursively call the after change functions again.
     (ref:notifier-inside-ensure-parsed)  */
  treesit_call_after_change_functions (tree, new_tree, parser);
  ts_tree_delete (tree);
}

/* This is the read function provided to tree-sitter to read from a
   buffer.  It reads one character at a time and automatically skips
   the gap.  */
static const char*
treesit_read_buffer (void *parser, uint32_t byte_index,
		     TSPoint position, uint32_t *bytes_read)
{
  struct buffer *buffer = XBUFFER (((struct Lisp_TS_Parser *) parser)->buffer);
  ptrdiff_t visible_beg = ((struct Lisp_TS_Parser *) parser)->visible_beg;
  ptrdiff_t visible_end = ((struct Lisp_TS_Parser *) parser)->visible_end;
  ptrdiff_t byte_pos = byte_index + visible_beg;
  /* We will make sure visible_beg = BUF_BEGV_BYTE before re-parse (in
     treesit_ensure_parsed), so byte_pos will never be smaller than
     BUF_BEG_BYTE.  */
  eassert (visible_beg = BUF_BEGV_BYTE (buffer));
  eassert (visible_end = BUF_ZV_BYTE (buffer));

  /* Read one character.  Tree-sitter wants us to set bytes_read to 0
     if it reads to the end of buffer.  It doesn't say what it wants
     for the return value in that case, so we just give it an empty
     string.  */
  char *beg;
  int len;
  /* This function could run from a user command, so it is better to
     do nothing instead of raising an error.  (It was a pain in the a**
     to decrypt mega-if-conditions in Emacs source, so I wrote the two
     branches separately, you are welcome.)  */
  if (!BUFFER_LIVE_P (buffer))
    {
      beg = NULL;
      len = 0;
    }
  /* Reached visible end-of-buffer, tell tree-sitter to read no more.  */
  else if (byte_pos >= visible_end)
    {
      beg = NULL;
      len = 0;
    }
  /* Normal case, read a character.  */
  else
    {
      beg = (char *) BUF_BYTE_ADDRESS (buffer, byte_pos);
      len = BYTES_BY_CHAR_HEAD ((int) *beg);
    }
  /* We never let tree-sitter to parse buffers that large so this
     assertion should never hit.  */
  eassert (len < UINT32_MAX);
  *bytes_read = (uint32_t) len;
  return beg;
}

\f
/*** Functions for parser and node object */

/* Wrap the parser in a Lisp_Object to be used in the Lisp
   machine.  */
Lisp_Object
make_treesit_parser (Lisp_Object buffer, TSParser *parser,
		     TSTree *tree, Lisp_Object language_symbol)
{
  struct Lisp_TS_Parser *lisp_parser;

  lisp_parser = ALLOCATE_PSEUDOVECTOR (struct Lisp_TS_Parser,
				       buffer, PVEC_TS_PARSER);

  lisp_parser->language_symbol = language_symbol;
  lisp_parser->after_change_functions = Qnil;
  lisp_parser->buffer = buffer;
  lisp_parser->parser = parser;
  lisp_parser->tree = tree;
  TSInput input = {lisp_parser, treesit_read_buffer, TSInputEncodingUTF8};
  lisp_parser->input = input;
  lisp_parser->need_reparse = true;
  lisp_parser->visible_beg = BUF_BEGV_BYTE (XBUFFER (buffer));
  lisp_parser->visible_end = BUF_ZV_BYTE (XBUFFER (buffer));
  lisp_parser->timestamp = 0;
  lisp_parser->deleted = false;
  lisp_parser->has_range = false;
  eassert (lisp_parser->visible_beg <= lisp_parser->visible_end);
  return make_lisp_ptr (lisp_parser, Lisp_Vectorlike);
}

/* Wrap the node in a Lisp_Object to be used in the Lisp machine.  */
Lisp_Object
make_treesit_node (Lisp_Object parser, TSNode node)
{
  struct Lisp_TS_Node *lisp_node;

  lisp_node = ALLOCATE_PSEUDOVECTOR (struct Lisp_TS_Node,
				     parser, PVEC_TS_NODE);
  lisp_node->parser = parser;
  lisp_node->node = node;
  lisp_node->timestamp = XTS_PARSER (parser)->timestamp;
  return make_lisp_ptr (lisp_node, Lisp_Vectorlike);
}

/* Make a compiled query.  QUERY has to be either a cons or a
   string.  */
static Lisp_Object
make_treesit_query (Lisp_Object query, Lisp_Object language)
{
  TSQueryCursor *treesit_cursor = ts_query_cursor_new ();
  struct Lisp_TS_Query *lisp_query;

  lisp_query = ALLOCATE_PSEUDOVECTOR (struct Lisp_TS_Query,
				      source, PVEC_TS_COMPILED_QUERY);

  lisp_query->language = language;
  lisp_query->source = query;
  lisp_query->query = NULL;
  lisp_query->cursor = treesit_cursor;
  return make_lisp_ptr (lisp_query, Lisp_Vectorlike);
}

/* The following two functions are called from alloc.c:cleanup_vector.  */
void
treesit_delete_parser (struct Lisp_TS_Parser *lisp_parser)
{
  ts_tree_delete (lisp_parser->tree);
  ts_parser_delete (lisp_parser->parser);
}

void
treesit_delete_query (struct Lisp_TS_Query *lisp_query)
{
  ts_query_delete (lisp_query->query);
  ts_query_cursor_delete (lisp_query->cursor);
}

/* The following function is called from print.c:print_vectorlike.  */
bool
treesit_named_node_p (TSNode node)
{
  return ts_node_is_named (node);
}

static const char*
treesit_query_error_to_string (TSQueryError error)
{
  switch (error)
    {
    case TSQueryErrorNone:
      return "None";
    case TSQueryErrorSyntax:
      return "Syntax error at";
    case TSQueryErrorNodeType:
      return "Node type error at";
    case TSQueryErrorField:
      return "Field error at";
    case TSQueryErrorCapture:
      return "Capture error at";
    case TSQueryErrorStructure:
      return "Structure error at";
    default:
      return "Unknown error";
    }
}

static Lisp_Object
treesit_compose_query_signal_data (uint32_t error_offset,
				   TSQueryError error_type,
				   Lisp_Object query_source)
{
  return list4 (build_string (treesit_query_error_to_string (error_type)),
		make_fixnum (error_offset + 1),
		query_source,
		build_string ("Debug the query with `treesit-query-validate'"));
}

/* Ensure the QUERY is compiled.  Return the TSQuery.  It could be
   NULL if error occurs, in which case ERROR_OFFSET and ERROR_TYPE are
   bound.  If error occurs, return NULL, and assign SIGNAL_SYMBOL and
   SIGNAL_DATA accordingly.  */
static TSQuery *
treesit_ensure_query_compiled (Lisp_Object query, Lisp_Object *signal_symbol,
			       Lisp_Object *signal_data)
{
  /* If query is already compiled (not null), return that, otherwise
     compile and return it.  */
  TSQuery *treesit_query = XTS_COMPILED_QUERY (query)->query;
  if (treesit_query != NULL)
    return treesit_query;

  /* Get query source and TSLanguage ready.  */
  Lisp_Object source = XTS_COMPILED_QUERY (query)->source;
  Lisp_Object language = XTS_COMPILED_QUERY (query)->language;
  /* This is the main reason why we compile query lazily: to avoid
     loading languages early.  */
  TSLanguage *treesit_lang = treesit_load_language (language, signal_symbol,
						    signal_data);
  if (treesit_lang == NULL)
    return NULL;

  if (CONSP (source))
    source = Ftreesit_query_expand (source);

  /* Create TSQuery.  */
  uint32_t error_offset;
  TSQueryError error_type;
  char *treesit_source = SSDATA (source);
  treesit_query = ts_query_new (treesit_lang, treesit_source,
				strlen (treesit_source),
				&error_offset, &error_type);
  if (treesit_query == NULL)
    {
      *signal_symbol = Qtreesit_query_error;
      *signal_data = treesit_compose_query_signal_data (error_offset,
							error_type,
							source);
    }
  XTS_COMPILED_QUERY (query)->query = treesit_query;
  return treesit_query;
}

\f
/* Lisp definitions.  */

DEFUN ("treesit-parser-p",
       Ftreesit_parser_p, Streesit_parser_p, 1, 1, 0,
       doc: /* Return t if OBJECT is a tree-sitter parser.  */)
  (Lisp_Object object)
{
  if (TS_PARSERP (object))
    return Qt;
  else
    return Qnil;
}

DEFUN ("treesit-node-p",
       Ftreesit_node_p, Streesit_node_p, 1, 1, 0,
       doc: /* Return t if OBJECT is a tree-sitter node.  */)
  (Lisp_Object object)
{
  if (TS_NODEP (object))
    return Qt;
  else
    return Qnil;
}

DEFUN ("treesit-compiled-query-p",
       Ftreesit_compiled_query_p, Streesit_compiled_query_p, 1, 1, 0,
       doc: /* Return t if OBJECT is a compiled tree-sitter query.  */)
  (Lisp_Object object)
{
  if (TS_COMPILED_QUERY_P (object))
    return Qt;
  else
    return Qnil;
}

DEFUN ("treesit-query-p",
       Ftreesit_query_p, Streesit_query_p, 1, 1, 0,
       doc: /* Return t if OBJECT is a generic tree-sitter query.  */)
  (Lisp_Object object)
{
  if (TS_COMPILED_QUERY_P (object)
      || CONSP (object) || STRINGP (object))
    return Qt;
  else
    return Qnil;
}

DEFUN ("treesit-query-language",
       Ftreesit_query_language, Streesit_query_language, 1, 1, 0,
       doc: /* Return the language of QUERY.
QUERY has to be a compiled query.  */)
  (Lisp_Object query)
{
  CHECK_TS_COMPILED_QUERY (query);
  return XTS_COMPILED_QUERY (query)->language;
}

DEFUN ("treesit-node-parser",
       Ftreesit_node_parser, Streesit_node_parser,
       1, 1, 0,
       doc: /* Return the parser to which NODE belongs.  */)
  (Lisp_Object node)
{
  CHECK_TS_NODE (node);
  return XTS_NODE (node)->parser;
}

DEFUN ("treesit-parser-create",
       Ftreesit_parser_create, Streesit_parser_create,
       1, 3, 0,
       doc: /* Create and return a parser in BUFFER for LANGUAGE.

The parser is automatically added to BUFFER's parser list, as returned
by `treesit-parser-list'.  LANGUAGE is a language symbol.  If BUFFER
is nil or omitted, it defaults to the current buffer.  If BUFFER
already has a parser for LANGUAGE, return that parser, but if NO-REUSE
is non-nil, always create a new parser.

If that buffer is an indirect buffer, its base buffer is used instead.
That is, indirect buffers use their base buffer's parsers.  Lisp
programs should widen as necessary should they want to use a parser in
an indirect buffer.  */)
  (Lisp_Object language, Lisp_Object buffer, Lisp_Object no_reuse)
{
  treesit_initialize ();

  CHECK_SYMBOL (language);
  struct buffer *buf;
  if (NILP (buffer))
    buf = current_buffer;
  else
    {
      CHECK_BUFFER (buffer);
      buf = XBUFFER (buffer);
    }
  if (buf->base_buffer)
    buf = buf->base_buffer;

  treesit_check_buffer_size (buf);

  /* See if we can reuse a parser.  */
  if (NILP (no_reuse))
    {
      Lisp_Object tail = BVAR (buf, ts_parser_list);
      FOR_EACH_TAIL (tail)
      {
	struct Lisp_TS_Parser *parser = XTS_PARSER (XCAR (tail));
	if (EQ (parser->language_symbol, language))
	  return XCAR (tail);
      }
    }

  /* Load language.  */
  Lisp_Object signal_symbol = Qnil;
  Lisp_Object signal_data = Qnil;
  TSParser *parser = ts_parser_new ();
  TSLanguage *lang = treesit_load_language (language, &signal_symbol,
					    &signal_data);
  if (lang == NULL)
    xsignal (signal_symbol, signal_data);
  /* We check language version when loading a language, so this should
     always succeed.  */
  ts_parser_set_language (parser, lang);

  /* Create parser.  */
  Lisp_Object lisp_parser = make_treesit_parser (Fcurrent_buffer (),
						 parser, NULL,
						 language);

  /* Update parser-list.  */
  BVAR (buf, ts_parser_list) = Fcons (lisp_parser, BVAR (buf, ts_parser_list));

  return lisp_parser;
}

DEFUN ("treesit-parser-delete",
       Ftreesit_parser_delete, Streesit_parser_delete,
       1, 1, 0,
       doc: /* Delete PARSER from its buffer's parser list.
See `treesit-parser-list' for the buffer's parser list.  */)
  (Lisp_Object parser)
{
  treesit_check_parser (parser);

  Lisp_Object buffer = XTS_PARSER (parser)->buffer;
  struct buffer *buf = XBUFFER (buffer);

  BVAR (buf, ts_parser_list)
    = Fdelete (parser, BVAR (buf, ts_parser_list));

  XTS_PARSER (parser)->deleted = true;
  return Qnil;
}

DEFUN ("treesit-parser-list",
       Ftreesit_parser_list, Streesit_parser_list,
       0, 1, 0,
       doc: /* Return BUFFER's parser list.

BUFFER defaults to the current buffer.  If that buffer is an indirect
buffer, its base buffer is used instead.  That is, indirect buffers
use their base buffer's parsers.  */)
  (Lisp_Object buffer)
{
  struct buffer *buf;
  if (NILP (buffer))
    buf = current_buffer;
  else
    {
      CHECK_BUFFER (buffer);
      buf = XBUFFER (buffer);
    }
  if (buf->base_buffer)
    buf = buf->base_buffer;

  /* Return a fresh list so messing with that list doesn't affect our
     internal data.  */
  Lisp_Object return_list = Qnil;
  Lisp_Object tail;

  tail = BVAR (buf, ts_parser_list);

  FOR_EACH_TAIL (tail)
    return_list = Fcons (XCAR (tail), return_list);

  return Freverse (return_list);
}

DEFUN ("treesit-parser-buffer",
       Ftreesit_parser_buffer, Streesit_parser_buffer,
       1, 1, 0,
       doc: /* Return the buffer of PARSER.  */)
  (Lisp_Object parser)
{
  treesit_check_parser (parser);
  Lisp_Object buf;
  XSETBUFFER (buf, XBUFFER (XTS_PARSER (parser)->buffer));
  return buf;
}

DEFUN ("treesit-parser-language",
       Ftreesit_parser_language, Streesit_parser_language,
       1, 1, 0,
       doc: /* Return PARSER's language symbol.
This symbol is the one used to create the parser.  */)
  (Lisp_Object parser)
{
  treesit_check_parser (parser);
  return XTS_PARSER (parser)->language_symbol;
}

/* Return true if PARSER is not deleted and its buffer is live.  */
static bool
treesit_parser_live_p (Lisp_Object parser)
{
  CHECK_TS_PARSER (parser);
  return ((!XTS_PARSER (parser)->deleted) &&
	  (!NILP (Fbuffer_live_p (XTS_PARSER (parser)->buffer))));
}

\f
/*** Parser API */

DEFUN ("treesit-parser-root-node",
       Ftreesit_parser_root_node, Streesit_parser_root_node,
       1, 1, 0,
       doc: /* Return the root node of PARSER.  */)
  (Lisp_Object parser)
{
  treesit_check_parser (parser);
  treesit_initialize ();
  treesit_ensure_parsed (parser);
  TSNode root_node = ts_tree_root_node (XTS_PARSER (parser)->tree);
  return make_treesit_node (parser, root_node);
}

/* Checks that the RANGES argument of
   treesit-parser-set-included-ranges is valid.  */
static void
treesit_check_range_argument (Lisp_Object ranges)
{
  struct buffer *buffer = current_buffer;
  ptrdiff_t point_min = BUF_BEGV (buffer);
  ptrdiff_t point_max = BUF_ZV (buffer);
  EMACS_INT last_point = point_min;
  Lisp_Object tail;

  tail = ranges;

  CHECK_LIST (tail);

  FOR_EACH_TAIL (tail)
    {
      CHECK_CONS (tail);
      Lisp_Object range = XCAR (tail);
      CHECK_CONS (range);
      CHECK_FIXNUM (XCAR (range));
      CHECK_FIXNUM (XCDR (range));
      EMACS_INT beg = XFIXNUM (XCAR (range));
      EMACS_INT end = XFIXNUM (XCDR (range));
      if (!(last_point <= beg && beg <= end && end <= point_max))
	xsignal2 (Qtreesit_range_invalid,
		  build_string ("RANGE is either overlapping,"
		                " out-of-order or out-of-range"),
		  ranges);
      last_point = end;
    }

  CHECK_LIST_END (tail, ranges);
}

/* Generate a list of ranges in Lisp from RANGES.  Assumes tree-sitter
   tree and the buffer has the same visible region (wrt narrowing).
   This function doesn't take ownership of RANGES.  BUFFER is used to
   convert between tree-sitter buffer offset and buffer position.  */
static Lisp_Object
treesit_make_ranges (const TSRange *ranges, uint32_t len,
		     struct buffer *buffer)
{
  Lisp_Object list = Qnil;
  for (int idx = 0; idx < len; idx++)
    {
      TSRange range = ranges[idx];
      uint32_t beg_byte = range.start_byte + BUF_BEGV_BYTE (buffer);
      uint32_t end_byte = range.end_byte + BUF_BEGV_BYTE (buffer);
      eassert (BUF_BEGV_BYTE (buffer) <= beg_byte);
      eassert (beg_byte <= end_byte);
      eassert (end_byte <= BUF_ZV_BYTE (buffer));

      Lisp_Object lisp_range
	= Fcons (make_fixnum (buf_bytepos_to_charpos (buffer, beg_byte)),
		 make_fixnum (buf_bytepos_to_charpos (buffer, end_byte)));
      list = Fcons (lisp_range, list);
    }
  return Fnreverse (list);
}

DEFUN ("treesit-parser-set-included-ranges",
       Ftreesit_parser_set_included_ranges,
       Streesit_parser_set_included_ranges,
       2, 2, 0,
       doc: /* Limit PARSER to RANGES.

RANGES is a list of (BEG . END), each (BEG . END) defines a region in
which the parser should operate.  Regions must not overlap, and the
regions should come in order in the list.  Signal
`treesit-set-range-error' if the argument is invalid, or something
else went wrong.  If RANGES is nil, the PARSER is to parse the whole
buffer.  */)
  (Lisp_Object parser, Lisp_Object ranges)
{
  treesit_check_parser (parser);
  if (!NILP (ranges))
    CHECK_CONS (ranges);
  treesit_check_range_argument (ranges);

  treesit_initialize ();
  /* Before we parse, catch up with narrowing/widening.  */
  treesit_check_buffer_size (XBUFFER (XTS_PARSER (parser)->buffer));
  treesit_sync_visible_region (parser);

  bool success;
  if (NILP (ranges))
    {
      XTS_PARSER (parser)->has_range = false;
      /* If RANGES is nil, make parser to parse the whole document.
	 To do that we give tree-sitter a 0 length, the range is a
	 dummy.  */
      TSRange treesit_range = {{0, 0}, {0, 0}, 0, 0};
      success = ts_parser_set_included_ranges (XTS_PARSER (parser)->parser,
					       &treesit_range , 0);
    }
  else
    {
      /* Set ranges for PARSER.  */
      XTS_PARSER (parser)->has_range = true;

      if (list_length (ranges) > UINT32_MAX)
	xsignal (Qargs_out_of_range, list2 (ranges, Flength (ranges)));
      uint32_t len = (uint32_t) list_length (ranges);
      TSRange *treesit_ranges = xmalloc (sizeof (TSRange) * len);
      struct buffer *buffer = XBUFFER (XTS_PARSER (parser)->buffer);

      for (int idx = 0; !NILP (ranges); idx++, ranges = XCDR (ranges))
	{
	  Lisp_Object range = XCAR (ranges);
	  ptrdiff_t beg_byte = buf_charpos_to_bytepos (buffer,
						       XFIXNUM (XCAR (range)));
	  ptrdiff_t end_byte = buf_charpos_to_bytepos (buffer,
						       XFIXNUM (XCDR (range)));
	  /* Shouldn't violate assertion since we just checked for
	     buffer size at the beginning of this function.  */
	  eassert (beg_byte - BUF_BEGV_BYTE (buffer) <= UINT32_MAX);
	  eassert (end_byte - BUF_BEGV_BYTE (buffer) <= UINT32_MAX);
	  /* We don't care about start and end points, put in dummy
	     values.  */
	  TSRange rg = {{0, 0}, {0, 0},
			(uint32_t) beg_byte - BUF_BEGV_BYTE (buffer),
			(uint32_t) end_byte - BUF_BEGV_BYTE (buffer)};
	  treesit_ranges[idx] = rg;
	}
      success = ts_parser_set_included_ranges (XTS_PARSER (parser)->parser,
					       treesit_ranges, len);
      /* Although XFIXNUM could signal, it should be impossible
	 because we have checked the input by treesit_check_range_argument.
	 So there is no need for unwind-protect.  */
      xfree (treesit_ranges);
    }

  if (!success)
    xsignal2 (Qtreesit_range_invalid,
	      build_string ("Something went wrong when setting ranges"),
	      ranges);

  XTS_PARSER (parser)->need_reparse = true;
  return Qnil;
}

DEFUN ("treesit-parser-included-ranges",
       Ftreesit_parser_included_ranges,
       Streesit_parser_included_ranges,
       1, 1, 0,
       doc: /* Return the ranges set for PARSER.
If no ranges are set for PARSER, return nil.
See also `treesit-parser-set-included-ranges'.  */)
  (Lisp_Object parser)
{
  treesit_check_parser (parser);
  treesit_initialize ();

  /* When the parser doesn't have a range set and we call
     ts_parser_included_ranges on it, it doesn't return an empty list,
     but rather return some garbled data. (A single range where
     start_byte = 0, end_byte = UINT32_MAX).  So we need to track
     whether the parser is ranged ourselves.  */
  if (!XTS_PARSER (parser)->has_range)
    return Qnil;

  uint32_t len;
  const TSRange *ranges
    = ts_parser_included_ranges (XTS_PARSER (parser)->parser, &len);

  /* Our return value depends on the buffer state (BUF_BEGV_BYTE,
     etc), so we need to sync up.  */
  treesit_check_buffer_size (XBUFFER (XTS_PARSER (parser)->buffer));
  treesit_sync_visible_region (parser);

  struct buffer *buffer = XBUFFER (XTS_PARSER (parser)->buffer);
  return treesit_make_ranges (ranges, len, buffer);
}

DEFUN ("treesit-parser-notifiers", Ftreesit_parser_notifiers,
       Streesit_parser_notifiers,
       1, 1, 0,
       doc: /* Return the list of after-change notifier functions for PARSER.  */)
  (Lisp_Object parser)
{
  treesit_check_parser (parser);

  Lisp_Object return_list = Qnil;
  Lisp_Object tail = XTS_PARSER (parser)->after_change_functions;
  FOR_EACH_TAIL (tail)
    return_list = Fcons (XCAR (tail), return_list);

  return return_list;
}

DEFUN ("treesit-parser-add-notifier", Ftreesit_parser_add_notifier,
       Streesit_parser_add_notifier,
       2, 2, 0,
       doc: /* Add FUNCTION to the list of PARSER's after-change notifiers.
FUNCTION must be a function symbol, rather than a lambda form.
FUNCTION should take 2 arguments, RANGES and PARSER.  RANGES is a list
of cons cells of the form (START . END), where START and END are buffer
positions.  PARSER is the parser issuing the notification.  */)
  (Lisp_Object parser, Lisp_Object function)
{
  treesit_check_parser (parser);
  /* For simplicity we don't accept lambda functions.  */
  CHECK_SYMBOL (function);

  Lisp_Object functions = XTS_PARSER (parser)->after_change_functions;
  if (NILP (Fmemq (function, functions)))
    XTS_PARSER (parser)->after_change_functions = Fcons (function, functions);
  return Qnil;
}

DEFUN ("treesit-parser-remove-notifier", Ftreesit_parser_remove_notifier,
       Streesit_parser_remove_notifier,
       2, 2, 0,
       doc: /* Remove FUNCTION from the list of PARSER's after-change notifiers.
  FUNCTION must be a function symbol, rather than a lambda form.
FUNCTION should take 2 arguments, RANGES and PARSER.  RANGES is a list
of cons of the form (START . END), where START and END are buffer
positions.  PARSER is the parser issuing the notification.   */)
  (Lisp_Object parser, Lisp_Object function)
{
  treesit_check_parser (parser);
  /* For simplicity we don't accept lambda functions.  */
  CHECK_SYMBOL (function);

  Lisp_Object functions = XTS_PARSER (parser)->after_change_functions;
  if (!NILP (Fmemq (function, functions)))
    XTS_PARSER (parser)->after_change_functions = Fdelq (function, functions);
  return Qnil;
}

\f
/*** Node API  */

/* Check that OBJ is a positive integer and signal an error if
   otherwise.  */
static void
treesit_check_positive_integer (Lisp_Object obj)
{
  CHECK_INTEGER (obj);
  if (XFIXNUM (obj) < 0)
    xsignal1 (Qargs_out_of_range, obj);
}

static void
treesit_check_node (Lisp_Object obj)
{
  CHECK_TS_NODE (obj);
  if (!treesit_node_uptodate_p (obj))
    xsignal1 (Qtreesit_node_outdated, obj);
}

/* Checks that OBJ is a positive integer and it is within the visible
   portion of BUF. */
static void
treesit_check_position (Lisp_Object obj, struct buffer *buf)
{
  treesit_check_positive_integer (obj);
  ptrdiff_t pos = XFIXNUM (obj);
  if (pos < BUF_BEGV (buf) || pos > BUF_ZV (buf))
    xsignal1 (Qargs_out_of_range, obj);
}

bool
treesit_node_uptodate_p (Lisp_Object obj)
{
  Lisp_Object lisp_parser = XTS_NODE (obj)->parser;
  return XTS_NODE (obj)->timestamp == XTS_PARSER (lisp_parser)->timestamp;
}

DEFUN ("treesit-node-type",
       Ftreesit_node_type, Streesit_node_type, 1, 1, 0,
       doc: /* Return the NODE's type as a string.
If NODE is nil, return nil.  */)
  (Lisp_Object node)
{
  if (NILP (node)) return Qnil;
  treesit_check_node (node);
  treesit_initialize ();

  TSNode treesit_node = XTS_NODE (node)->node;
  const char *type = ts_node_type (treesit_node);
  return build_string (type);
}

DEFUN ("treesit-node-start",
       Ftreesit_node_start, Streesit_node_start, 1, 1, 0,
       doc: /* Return the NODE's start position in its buffer.
If NODE is nil, return nil.  */)
  (Lisp_Object node)
{
  if (NILP (node)) return Qnil;
  treesit_check_node (node);
  treesit_initialize ();

  TSNode treesit_node = XTS_NODE (node)->node;
  ptrdiff_t visible_beg = XTS_PARSER (XTS_NODE (node)->parser)->visible_beg;
  uint32_t start_byte_offset = ts_node_start_byte (treesit_node);
  struct buffer *buffer
    = XBUFFER (XTS_PARSER (XTS_NODE (node)->parser)->buffer);
  ptrdiff_t start_pos
    = buf_bytepos_to_charpos (buffer,
			      start_byte_offset + visible_beg);
  return make_fixnum (start_pos);
}

DEFUN ("treesit-node-end",
       Ftreesit_node_end, Streesit_node_end, 1, 1, 0,
       doc: /* Return the NODE's end position in its buffer.
If NODE is nil, return nil.  */)
  (Lisp_Object node)
{
  if (NILP (node)) return Qnil;
  treesit_check_node (node);
  treesit_initialize ();

  TSNode treesit_node = XTS_NODE (node)->node;
  ptrdiff_t visible_beg = XTS_PARSER (XTS_NODE (node)->parser)->visible_beg;
  uint32_t end_byte_offset = ts_node_end_byte (treesit_node);
  struct buffer *buffer
    = XBUFFER (XTS_PARSER (XTS_NODE (node)->parser)->buffer);
  ptrdiff_t end_pos
    = buf_bytepos_to_charpos (buffer, end_byte_offset + visible_beg);
  return make_fixnum (end_pos);
}

DEFUN ("treesit-node-string",
       Ftreesit_node_string, Streesit_node_string, 1, 1, 0,
       doc: /* Return the string representation of NODE.
If NODE is nil, return nil.  */)
  (Lisp_Object node)
{
  if (NILP (node)) return Qnil;
  treesit_check_node (node);
  treesit_initialize ();

  TSNode treesit_node = XTS_NODE (node)->node;
  char *string = ts_node_string (treesit_node);
  return build_string (string);
}

static bool treesit_cursor_helper (TSTreeCursor *, TSNode, Lisp_Object);

DEFUN ("treesit-node-parent",
       Ftreesit_node_parent, Streesit_node_parent, 1, 1, 0,
       doc: /* Return the immediate parent of NODE.
Return nil if NODE has no parent.  If NODE is nil, return nil.  */)
  (Lisp_Object node)
{
  if (NILP (node)) return Qnil;
  treesit_check_node (node);
  treesit_initialize ();

  Lisp_Object return_value = Qnil;

  TSNode treesit_node = XTS_NODE (node)->node;
  Lisp_Object parser = XTS_NODE (node)->parser;
  TSTreeCursor cursor;
  if (!treesit_cursor_helper (&cursor, treesit_node, parser))
    return return_value;

  if (ts_tree_cursor_goto_parent (&cursor))
  {
    TSNode parent = ts_tree_cursor_current_node (&cursor);
    return_value = make_treesit_node (parser, parent);
  }
  ts_tree_cursor_delete (&cursor);
  return return_value;
}

DEFUN ("treesit-node-child",
       Ftreesit_node_child, Streesit_node_child, 2, 3, 0,
       doc: /* Return the Nth child of NODE.

Return nil if there is no Nth child.  If NAMED is non-nil, look for
named child only.  NAMED defaults to nil.  If NODE is nil, return
nil.

N could be negative, e.g., -1 represents the last child.  */)
  (Lisp_Object node, Lisp_Object n, Lisp_Object named)
{
  if (NILP (node)) return Qnil;
  treesit_check_node (node);
  CHECK_INTEGER (n);
  EMACS_INT idx = XFIXNUM (n);

  treesit_initialize ();

  TSNode treesit_node = XTS_NODE (node)->node;
  TSNode child;

  /* Process negative index.  */
  if (idx < 0)
    {
      if (NILP (named))
	idx = ts_node_child_count (treesit_node) + idx;
      else
	idx = ts_node_named_child_count (treesit_node) + idx;
    }
  if (idx < 0)
    return Qnil;
  if (idx > UINT32_MAX)
    xsignal1 (Qargs_out_of_range, n);

  if (NILP (named))
    child = ts_node_child (treesit_node, (uint32_t) idx);
  else
    child = ts_node_named_child (treesit_node, (uint32_t) idx);

  if (ts_node_is_null (child))
    return Qnil;

  return make_treesit_node (XTS_NODE (node)->parser, child);
}

DEFUN ("treesit-node-check",
       Ftreesit_node_check, Streesit_node_check, 2, 2, 0,
       doc: /* Return non-nil if NODE has PROPERTY, nil otherwise.

PROPERTY could be `named', `missing', `extra', `outdated',
`has-error', or `live'.

Named nodes correspond to named rules in the language definition,
whereas "anonymous" nodes correspond to string literals in the
language definition.

Missing nodes are inserted by the parser in order to recover from
certain kinds of syntax errors, i.e., should be there but not there.

Extra nodes represent things like comments, which are not required the
language definition, but can appear anywhere.

A node is "outdated" if the parser has reparsed at least once after
the node was created.

A node "has error" if itself is a syntax error or contains any syntax
errors.

A node is "live" if its parser is not deleted and its buffer is
live.  */)
  (Lisp_Object node, Lisp_Object property)
{
  if (NILP (node)) return Qnil;
  CHECK_TS_NODE (node);
  CHECK_SYMBOL (property);
  treesit_initialize ();

  TSNode treesit_node = XTS_NODE (node)->node;
  bool result;

  if (EQ (property, Qoutdated))
    return treesit_node_uptodate_p (node) ? Qnil : Qt;

  treesit_check_node (node);
  if (EQ (property, Qnamed))
    result = ts_node_is_named (treesit_node);
  else if (EQ (property, Qmissing))
    result = ts_node_is_missing (treesit_node);
  else if (EQ (property, Qextra))
    result = ts_node_is_extra (treesit_node);
  else if (EQ (property, Qhas_error))
    result = ts_node_has_error (treesit_node);
  else if (EQ (property, Qlive))
    result = treesit_parser_live_p (XTS_NODE (node)->parser);
  else
    signal_error ("Expecting `named', `missing', `extra', "
                  "`outdated', `has-error', or `live', but got",
		  property);
  return result ? Qt : Qnil;
}

DEFUN ("treesit-node-field-name-for-child",
       Ftreesit_node_field_name_for_child,
       Streesit_node_field_name_for_child, 2, 2, 0,
       doc: /* Return the field name of the Nth child of NODE.

Return nil if there's no Nth child, or if it has no field.
If NODE is nil, return nil.

N counts all children, i.e., named ones and anonymous ones.

N could be negative, e.g., -1 represents the last child.  */)
  (Lisp_Object node, Lisp_Object n)
{
  if (NILP (node))
    return Qnil;
  treesit_check_node (node);
  CHECK_INTEGER (n);
  EMACS_INT idx = XFIXNUM (n);
  treesit_initialize ();

  TSNode treesit_node = XTS_NODE (node)->node;

  /* Process negative index.  */
  if (idx < 0)
    idx = ts_node_child_count (treesit_node) + idx;
  if (idx < 0)
    return Qnil;
  if (idx > UINT32_MAX)
    xsignal1 (Qargs_out_of_range, n);

  const char *name
    = ts_node_field_name_for_child (treesit_node, (uint32_t) idx);

  if (name == NULL)
    return Qnil;

  return build_string (name);
}

DEFUN ("treesit-node-child-count",
       Ftreesit_node_child_count,
       Streesit_node_child_count, 1, 2, 0,
       doc: /* Return the number of children of NODE.

If NAMED is non-nil, count named children only.  NAMED defaults to
nil.  If NODE is nil, return nil.  */)
  (Lisp_Object node, Lisp_Object named)
{
  if (NILP (node))
    return Qnil;
  treesit_check_node (node);
  treesit_initialize ();

  TSNode treesit_node = XTS_NODE (node)->node;
  uint32_t count;
  if (NILP (named))
    count = ts_node_child_count (treesit_node);
  else
    count = ts_node_named_child_count (treesit_node);
  return make_fixnum (count);
}

DEFUN ("treesit-node-child-by-field-name",
       Ftreesit_node_child_by_field_name,
       Streesit_node_child_by_field_name, 2, 2, 0,
       doc: /* Return the child of NODE with FIELD-NAME.
Return nil if there is no such child.  If NODE is nil, return nil.  */)
  (Lisp_Object node, Lisp_Object field_name)
{
  if (NILP (node))
    return Qnil;
  treesit_check_node (node);
  CHECK_STRING (field_name);
  treesit_initialize ();

  char *name_str = SSDATA (field_name);
  TSNode treesit_node = XTS_NODE (node)->node;
  TSNode child
    = ts_node_child_by_field_name (treesit_node, name_str,
				   strlen (name_str));

  if (ts_node_is_null (child))
    return Qnil;

  return make_treesit_node (XTS_NODE (node)->parser, child);
}

DEFUN ("treesit-node-next-sibling",
       Ftreesit_node_next_sibling,
       Streesit_node_next_sibling, 1, 2, 0,
       doc: /* Return the next sibling of NODE.

Return nil if there is no next sibling.  If NAMED is non-nil, look for named
siblings only.  NAMED defaults to nil.  If NODE is nil, return nil.  */)
  (Lisp_Object node, Lisp_Object named)
{
  if (NILP (node)) return Qnil;
  treesit_check_node (node);
  treesit_initialize ();

  TSNode treesit_node = XTS_NODE (node)->node;
  TSNode sibling;
  if (NILP (named))
    sibling = ts_node_next_sibling (treesit_node);
  else
    sibling = ts_node_next_named_sibling (treesit_node);

  if (ts_node_is_null (sibling))
    return Qnil;

  return make_treesit_node (XTS_NODE (node)->parser, sibling);
}

DEFUN ("treesit-node-prev-sibling",
       Ftreesit_node_prev_sibling,
       Streesit_node_prev_sibling, 1, 2, 0,
       doc: /* Return the previous sibling of NODE.

Return nil if there is no previous sibling.  If NAMED is non-nil, look
for named siblings only.  NAMED defaults to nil.  If NODE is nil,
return nil.  */)
  (Lisp_Object node, Lisp_Object named)
{
  if (NILP (node)) return Qnil;
  treesit_check_node (node);
  treesit_initialize ();

  TSNode treesit_node = XTS_NODE (node)->node;
  TSNode sibling;

  if (NILP (named))
    sibling = ts_node_prev_sibling (treesit_node);
  else
    sibling = ts_node_prev_named_sibling (treesit_node);

  if (ts_node_is_null (sibling))
    return Qnil;

  return make_treesit_node (XTS_NODE (node)->parser, sibling);
}

/* Our reimplementation of ts_node_first_child_for_byte.  The current
   implementation of that function has problems (see bug#60127), so
   before it's fixed upstream, we use our own reimplementation of it.
   Return true if there is a valid sibling, return false otherwise.
   If the return value is false, the position of the cursor is
   undefined.  (We use cursor because technically we can't make a null
   node for ourselves, also, using cursor is more convenient.)

   TODO: Remove this function once tree-sitter fixed the bug.  */
static bool treesit_cursor_first_child_for_byte
(TSTreeCursor *cursor, ptrdiff_t pos, bool named)
{
  if (!ts_tree_cursor_goto_first_child (cursor))
    return false;

  TSNode node = ts_tree_cursor_current_node (cursor);
  while (ts_node_end_byte (node) <= pos)
    {
      if (ts_tree_cursor_goto_next_sibling (cursor))
	node = ts_tree_cursor_current_node (cursor);
      else
	/* Reached the end and still can't find a valid sibling.  */
	return false;
    }
  while (named && (!ts_node_is_named (node)))
    {
      if (ts_tree_cursor_goto_next_sibling (cursor))
	node = ts_tree_cursor_current_node (cursor);
      else
	/* Reached the end and still can't find a named sibling.  */
	return false;
    }
  return true;
}

DEFUN ("treesit-node-first-child-for-pos",
       Ftreesit_node_first_child_for_pos,
       Streesit_node_first_child_for_pos, 2, 3, 0,
       doc: /* Return the first child of NODE for buffer position POS.

Specifically, return the first child that extends beyond POS.
Return nil if there is no such child.
If NAMED is non-nil, look for named children only.  NAMED defaults to nil.
Note that this function returns an immediate child, not the smallest
(grand)child.  If NODE is nil, return nil.  */)
  (Lisp_Object node, Lisp_Object pos, Lisp_Object named)
{
  if (NILP (node))
    return Qnil;
  treesit_check_node (node);

  struct buffer *buf = XBUFFER (XTS_PARSER (XTS_NODE (node)->parser)->buffer);
  ptrdiff_t visible_beg = XTS_PARSER (XTS_NODE (node)->parser)->visible_beg;

  treesit_check_position (pos, buf);
  treesit_initialize ();

  ptrdiff_t byte_pos = buf_charpos_to_bytepos (buf, XFIXNUM (pos));
  TSNode treesit_node = XTS_NODE (node)->node;

  TSTreeCursor cursor = ts_tree_cursor_new (treesit_node);
  ptrdiff_t treesit_pos = byte_pos - visible_beg;
  bool success;
  success = treesit_cursor_first_child_for_byte (&cursor, treesit_pos,
						 !NILP (named));
  TSNode child = ts_tree_cursor_current_node (&cursor);
  ts_tree_cursor_delete (&cursor);

  if (!success)
    return Qnil;
  return make_treesit_node (XTS_NODE (node)->parser, child);
}

DEFUN ("treesit-node-descendant-for-range",
       Ftreesit_node_descendant_for_range,
       Streesit_node_descendant_for_range, 3, 4, 0,
       doc: /* Return the smallest node that covers buffer positions BEG to END.

The returned node is a descendant of NODE.
Return nil if there is no such node.
If NAMED is non-nil, look for named child only.  NAMED defaults to nil.
If NODE is nil, return nil.  */)
  (Lisp_Object node, Lisp_Object beg, Lisp_Object end, Lisp_Object named)
{
  if (NILP (node)) return Qnil;
  treesit_check_node (node);

  struct buffer *buf = XBUFFER (XTS_PARSER (XTS_NODE (node)->parser)->buffer);
  ptrdiff_t visible_beg = XTS_PARSER (XTS_NODE (node)->parser)->visible_beg;

  treesit_check_position (beg, buf);
  treesit_check_position (end, buf);

  treesit_initialize ();

  ptrdiff_t byte_beg = buf_charpos_to_bytepos (buf, XFIXNUM (beg));
  ptrdiff_t byte_end = buf_charpos_to_bytepos (buf, XFIXNUM (end));
  TSNode treesit_node = XTS_NODE (node)->node;
  TSNode child;
  if (NILP (named))
    child = ts_node_descendant_for_byte_range (treesit_node, byte_beg - visible_beg,
					       byte_end - visible_beg);
  else
    child = ts_node_named_descendant_for_byte_range (treesit_node,
						     byte_beg - visible_beg,
						     byte_end - visible_beg);

  if (ts_node_is_null (child))
    return Qnil;

  return make_treesit_node (XTS_NODE (node)->parser, child);
}

/* Return true if NODE1 and NODE2 are the same node.  Assumes they are
   TS_NODE type.  */
bool treesit_node_eq (Lisp_Object node1, Lisp_Object node2)
{
  treesit_initialize ();
  TSNode treesit_node_1 = XTS_NODE (node1)->node;
  TSNode treesit_node_2 = XTS_NODE (node2)->node;
  return ts_node_eq (treesit_node_1, treesit_node_2);
}

DEFUN ("treesit-node-eq",
       Ftreesit_node_eq,
       Streesit_node_eq, 2, 2, 0,
       doc: /* Return non-nil if NODE1 and NODE2 refer to the same node.
If any one of NODE1 and NODE2 is nil, return nil.
This function uses the same equivalence metric as `equal', and returns
non-nil if NODE1 and NODE2 refer to the same node in a syntax tree
produced by tree-sitter.  */)
  (Lisp_Object node1, Lisp_Object node2)
{
  if (NILP (node1) || NILP (node2))
    return Qnil;
  CHECK_TS_NODE (node1);
  CHECK_TS_NODE (node2);

  bool same_node = treesit_node_eq (node1, node2);
  return same_node ? Qt : Qnil;
}

\f
/*** Query functions */

DEFUN ("treesit-pattern-expand",
       Ftreesit_pattern_expand,
       Streesit_pattern_expand, 1, 1, 0,
       doc: /* Expand PATTERN to its string form.

PATTERN can be

    :anchor
    :?
    :*
    :+
    :equal
    :match
    (TYPE PATTERN...)
    [PATTERN...]
    FIELD-NAME:
    @CAPTURE-NAME
    (_)
    _
    \"TYPE\"

See Info node `(elisp)Pattern Matching' for detailed explanation.  */)
  (Lisp_Object pattern)
{
  if (EQ (pattern, QCanchor))
    return Vtreesit_str_dot;
  if (EQ (pattern, intern_c_string (":?")))
    return Vtreesit_str_question_mark;
  if (EQ (pattern, intern_c_string (":*")))
    return Vtreesit_str_star;
  if (EQ (pattern, intern_c_string (":+")))
    return Vtreesit_str_plus;
  if (EQ (pattern, QCequal))
    return Vtreesit_str_pound_equal;
  if (EQ (pattern, QCmatch))
    return Vtreesit_str_pound_match;
  if (EQ (pattern, QCpred))
    return Vtreesit_str_pound_pred;
  Lisp_Object opening_delimeter
    = VECTORP (pattern)
      ? Vtreesit_str_open_bracket : Vtreesit_str_open_paren;
  Lisp_Object closing_delimiter
    = VECTORP (pattern)
      ? Vtreesit_str_close_bracket : Vtreesit_str_close_paren;
  if (VECTORP (pattern) || CONSP (pattern))
    return concat3 (opening_delimeter,
		    Fmapconcat (Qtreesit_pattern_expand,
				pattern,
				Vtreesit_str_space),
		    closing_delimiter);
  return Fprin1_to_string (pattern, Qnil, Qt);
}

DEFUN ("treesit-query-expand",
       Ftreesit_query_expand,
       Streesit_query_expand, 1, 1, 0,
       doc: /* Expand sexp QUERY to its string form.

A PATTERN in QUERY can be

    :anchor
    :?
    :*
    :+
    :equal
    :match
    (TYPE PATTERN...)
    [PATTERN...]
    FIELD-NAME:
    @CAPTURE-NAME
    (_)
    _
    \"TYPE\"

See Info node `(elisp)Pattern Matching' for detailed explanation.  */)
  (Lisp_Object query)
{
  return Fmapconcat (Qtreesit_pattern_expand, query, Vtreesit_str_space);
}

/* This struct is used for passing captures to be check against
   predicates.  Captures we check for are the ones in START before
   END.  For example, if START and END are

   START       END
    v              v
   (1 . (2 . (3 . (4 . (5 . (6 . nil))))))

   We only look at captures 1 2 3.  */
struct capture_range
{
  Lisp_Object start;
  Lisp_Object end;
};

/* Collect predicates for this match and return them in a list.  Each
   predicate is a list of strings and symbols.  */
static Lisp_Object
treesit_predicates_for_pattern (TSQuery *query, uint32_t pattern_index)
{
  uint32_t len;
  const TSQueryPredicateStep *predicate_list
    = ts_query_predicates_for_pattern (query, pattern_index, &len);
  Lisp_Object result = Qnil;
  Lisp_Object predicate = Qnil;
  for (int idx = 0; idx < len; idx++)
    {
      TSQueryPredicateStep step = predicate_list[idx];
      switch (step.type)
	{
	case TSQueryPredicateStepTypeCapture:
	  {
	    uint32_t str_len;
	    const char *str = ts_query_capture_name_for_id (query,
							    step.value_id,
							    &str_len);
	    predicate = Fcons (intern_c_string_1 (str, str_len),
			       predicate);
	    break;
	  }
	case TSQueryPredicateStepTypeString:
	  {
	    uint32_t str_len;
	    const char *str = ts_query_string_value_for_id (query,
							    step.value_id,
							    &str_len);
	    predicate = Fcons (make_string (str, str_len), predicate);
	    break;
	  }
	case TSQueryPredicateStepTypeDone:
	  result = Fcons (Fnreverse (predicate), result);
	  predicate = Qnil;
	  break;
	}
    }
  return Fnreverse (result);
}

/* Translate a capture NAME (symbol) to a node.  If everything goes
   fine, set NODE and return true; if error occurs (e.g., when there
   is no node for the capture name), set NODE to Qnil, SIGNAL_DATA to
   a suitable signal data, and return false.  */
static bool
treesit_predicate_capture_name_to_node (Lisp_Object name,
					struct capture_range captures,
					Lisp_Object *node,
					Lisp_Object *signal_data)
{
  *node = Qnil;
  for (Lisp_Object tail = captures.start; !EQ (tail, captures.end);
       tail = XCDR (tail))
    {
      if (EQ (XCAR (XCAR (tail)), name))
	{
	  *node = XCDR (XCAR (tail));
	  break;
	}
    }

  if (NILP (*node))
    {
      *signal_data = list3 (build_string ("Cannot find captured node"),
			    name, build_string ("A predicate can only refer"
						" to captured nodes in the "
						"same pattern"));
      return false;
    }
  return true;
}

/* Translate a capture NAME (symbol) to the text of the captured node.
   If everything goes fine, set TEXT to the text and return true;
   otherwise set TEXT to Qnil and set SIGNAL_DATA to a suitable signal
   data.  */
static bool
treesit_predicate_capture_name_to_text (Lisp_Object name,
					struct capture_range captures,
					Lisp_Object *text,
					Lisp_Object *signal_data)
{
  Lisp_Object node = Qnil;
  if (!treesit_predicate_capture_name_to_node (name, captures, &node, signal_data))
    return false;

  struct buffer *old_buffer = current_buffer;
  set_buffer_internal (XBUFFER (XTS_PARSER (XTS_NODE (node)->parser)->buffer));
  *text = Fbuffer_substring (Ftreesit_node_start (node),
			     Ftreesit_node_end (node));
  set_buffer_internal (old_buffer);
  return true;
}

/* Handles predicate (#equal A B).  Return true if A equals B; return
   false otherwise.  A and B can be either string, or a capture name.
   The capture name evaluates to the text its captured node spans in
   the buffer.  If everything goes fine, don't touch SIGNAL_DATA; if
   error occurs, set it to a suitable signal data.  */
static bool
treesit_predicate_equal (Lisp_Object args, struct capture_range captures,
			 Lisp_Object *signal_data)
{
  if (XFIXNUM (Flength (args)) != 2)
    {
      *signal_data = list2 (build_string ("Predicate `equal' requires "
					  "two arguments but only given"),
			    Flength (args));
      return false;
    }
  Lisp_Object arg1 = XCAR (args);
  Lisp_Object arg2 = XCAR (XCDR (args));
  Lisp_Object text1 = arg1;
  Lisp_Object text2 = arg2;
  if (SYMBOLP (arg1))
    {
      if (!treesit_predicate_capture_name_to_text (arg1, captures, &text1,
						   signal_data))
	return false;
    }
  if (SYMBOLP (arg2))
    {
      if (!treesit_predicate_capture_name_to_text (arg2, captures, &text2,
						   signal_data))
	return false;
    }

  return !NILP (Fstring_equal (text1, text2));
}

/* Handles predicate (#match "regexp" @node).  Return true if "regexp"
   matches the text spanned by @node; return false otherwise.
   Matching is case-sensitive.  If everything goes fine, don't touch
   SIGNAL_DATA; if error occurs, set it to a suitable signal data.  */
static bool
treesit_predicate_match (Lisp_Object args, struct capture_range captures,
			 Lisp_Object *signal_data)
{
  if (XFIXNUM (Flength (args)) != 2)
    {
      *signal_data = list2 (build_string ("Predicate `match' requires two "
					  "arguments but only given"),
			    Flength (args));
      return false;
    }
  Lisp_Object regexp = XCAR (args);
  Lisp_Object capture_name = XCAR (XCDR (args));

  /* It's probably common to get the argument order backwards.  Catch
     this mistake early and show helpful explanation, because Emacs
     loves you.  (We put the regexp first because that's what
     string-match does.)  */
  if (!STRINGP (regexp))
    xsignal1 (Qtreesit_query_error,
	      build_string ("The first argument to `match' should "
		            "be a regexp string, not a capture name"));
  if (!SYMBOLP (capture_name))
    xsignal1 (Qtreesit_query_error,
	      build_string ("The second argument to `match' should "
		            "be a capture name, not a string"));

  Lisp_Object node = Qnil;
  if (!treesit_predicate_capture_name_to_node (capture_name, captures, &node,
					       signal_data))
    return false;

  TSNode treesit_node = XTS_NODE (node)->node;
  ptrdiff_t visible_beg = XTS_PARSER (XTS_NODE (node)->parser)->visible_beg;
  uint32_t start_byte_offset = ts_node_start_byte (treesit_node);
  uint32_t end_byte_offset = ts_node_end_byte (treesit_node);
  ptrdiff_t start_byte = visible_beg + start_byte_offset;
  ptrdiff_t end_byte = visible_beg + end_byte_offset;
  ptrdiff_t start_pos = BYTE_TO_CHAR (start_byte);
  ptrdiff_t end_pos = BYTE_TO_CHAR (end_byte);
  ptrdiff_t old_begv = BEGV;
  ptrdiff_t old_begv_byte = BEGV_BYTE;
  ptrdiff_t old_zv = ZV;
  ptrdiff_t old_zv_byte = ZV_BYTE;

  BEGV = start_pos;
  BEGV_BYTE = start_byte;
  ZV = end_pos;
  ZV_BYTE = end_byte;

  ptrdiff_t val = search_buffer (regexp, start_pos, start_byte,
				 end_pos, end_byte, 1, 1, Qnil, Qnil, false);

  BEGV = old_begv;
  BEGV_BYTE = old_begv_byte;
  ZV = old_zv;
  ZV_BYTE = old_zv_byte;

  return (val > 0);
}

/* Handles predicate (#pred FN ARG...).  Return true if FN returns
   non-nil; return false otherwise.  The arity of FN must match the
   number of ARGs.  If everything goes fine, don't touch SIGNAL_DATA;
   if error occurs, set it to a suitable signal data.  */
static bool
treesit_predicate_pred (Lisp_Object args, struct capture_range captures,
			Lisp_Object *signal_data)
{
  if (XFIXNUM (Flength (args)) < 2)
    {
      *signal_data = list2 (build_string ("Predicate `pred' requires "
					  "at least two arguments, "
					  "but was only given"),
			    Flength (args));
      return false;
    }

  Lisp_Object fn = Fintern (XCAR (args), Qnil);
  Lisp_Object nodes = Qnil;
  Lisp_Object tail = XCDR (args);
  FOR_EACH_TAIL (tail)
  {
    Lisp_Object node = Qnil;
    if (!treesit_predicate_capture_name_to_node (XCAR (tail), captures, &node,
						 signal_data))
      return false;
    nodes = Fcons (node, nodes);
  }
  nodes = Fnreverse (nodes);

  return !NILP (CALLN (Fapply, fn, nodes));
}

/* If all predicates in PREDICATES passes, return true; otherwise
   return false.  If everything goes fine, don't touch SIGNAL_DATA; if
   error occurs, set it to a suitable signal data.  */
static bool
treesit_eval_predicates (struct capture_range captures, Lisp_Object predicates,
			 Lisp_Object *signal_data)
{
  bool pass = true;
  /* Evaluate each predicates.  */
  for (Lisp_Object tail = predicates;
       pass && !NILP (tail); tail = XCDR (tail))
    {
      Lisp_Object predicate = XCAR (tail);
      Lisp_Object fn = XCAR (predicate);
      Lisp_Object args = XCDR (predicate);
      if (!NILP (Fstring_equal (fn, Vtreesit_str_equal)))
	pass &= treesit_predicate_equal (args, captures, signal_data);
      else if (!NILP (Fstring_equal (fn, Vtreesit_str_match)))
	pass &= treesit_predicate_match (args, captures, signal_data);
      else if (!NILP (Fstring_equal (fn, Vtreesit_str_pred)))
	pass &= treesit_predicate_pred (args, captures, signal_data);
      else
	{
	  *signal_data = list3 (build_string ("Invalid predicate"),
				fn, build_string ("Currently Emacs only supports"
						  " equal, match, and pred"
						  " predicates"));
	  pass = false;
	}
    }
  /* If all predicates passed, add captures to result list.  */
  return pass;
}

DEFUN ("treesit-query-compile",
       Ftreesit_query_compile,
       Streesit_query_compile, 2, 3, 0,
       doc: /* Compile QUERY to a compiled query.

Querying with a compiled query is much faster than an uncompiled one.
LANGUAGE is the language this query is for.

If EAGER is non-nil, immediately load LANGUAGE and compile the query.
Otherwise defer the compilation until the query is first used.

Signal `treesit-query-error' if QUERY is malformed or something else
goes wrong.  (This only happens if EAGER is non-nil.)
You can use `treesit-query-validate' to validate and debug a query.  */)
  (Lisp_Object language, Lisp_Object query, Lisp_Object eager)
{
  if (NILP (Ftreesit_query_p (query)))
    wrong_type_argument (Qtreesit_query_p, query);
  CHECK_SYMBOL (language);
  if (TS_COMPILED_QUERY_P (query))
    return query;

  treesit_initialize ();

  Lisp_Object lisp_query = make_treesit_query (query, language);

  /* Maybe actually compile.  */
  if (NILP (eager))
    return lisp_query;
  else
    {
      Lisp_Object signal_symbol = Qnil;
      Lisp_Object signal_data = Qnil;
      TSQuery *treesit_query = treesit_ensure_query_compiled (lisp_query,
							      &signal_symbol,
							      &signal_data);

      if (treesit_query == NULL)
	xsignal (signal_symbol, signal_data);

      return lisp_query;
    }
}

/* Resolve OBJ into a tree-sitter node Lisp_Object.  OBJ can be a
   node, a parser, or a language symbol.  Note that this function can
   signal.  */
static Lisp_Object treesit_resolve_node (Lisp_Object obj)
{
  if (TS_NODEP (obj))
    {
      treesit_check_node (obj); /* Check if up-to-date.  */
      return obj;
    }
  else if (TS_PARSERP (obj))
    {
      treesit_check_parser (obj); /* Check if deleted.  */
      return Ftreesit_parser_root_node (obj);
    }
  else if (SYMBOLP (obj))
    {
      Lisp_Object parser
	= Ftreesit_parser_create (obj, Fcurrent_buffer (), Qnil);
      return Ftreesit_parser_root_node (parser);
    }
  else
    xsignal2 (Qwrong_type_argument,
	      list4 (Qor, Qtreesit_node_p, Qtreesit_parser_p, Qsymbolp),
	      obj);
}

/* Create and initialize QUERY.  When success, initialize TS_QUERY,
   CURSOR, and NEED_FREE, and return true; if failed, initialize
   SIGNAL_SYMBOL and SIGNAL_DATA, and return false.  If NEED_FREE is
   initialized to true, the TS_QUERY and CURSOR needs to be freed
   after use; otherwise they shouldn't be freed by hand.

   Basically this function looks at QUERY and check its type, if QUERY
   is a compiled query, this function takes out its query and cursor;
   if QUERY is a string or a cons, this function creates a new query
   and cursor (so they need to be manually freed).

   This function assumes QUERY is either a compiled query, a string or
   a cons, the caller should make sure QUERY is valid.

   LANG is the language to use if we need to create the query and
   cursor.  */
static bool
treesit_initialize_query (Lisp_Object query, const TSLanguage *lang,
			  TSQuery **ts_query, TSQueryCursor **cursor,
			  bool *need_free, Lisp_Object *signal_symbol,
			  Lisp_Object *signal_data)
{
  if (TS_COMPILED_QUERY_P (query))
    {
      *ts_query = treesit_ensure_query_compiled (query, signal_symbol,
						 signal_data);
      *cursor = XTS_COMPILED_QUERY (query)->cursor;
      /* We don't need to free ts_query and cursor because they
	 are stored in a lisp object, which is tracked by gc.  */
      *need_free = false;
      return (*ts_query != NULL);
    }
  else
    {
      /* Since query is not TS_COMPILED_QUERY, it can only be a string
	 or a cons.  */
      if (CONSP (query))
	query = Ftreesit_query_expand (query);
      char *query_string = SSDATA (query);
      uint32_t error_offset;
      TSQueryError error_type;
      *ts_query = ts_query_new (lang, query_string, strlen (query_string),
				&error_offset, &error_type);
      if (*ts_query == NULL)
	{
	  *signal_symbol = Qtreesit_query_error;
	  *signal_data = treesit_compose_query_signal_data (error_offset,
							    error_type, query);
	  return false;
	}
      else
	{
	  *cursor = ts_query_cursor_new ();
	  *need_free = true;
	  return true;
	}
    }
}

DEFUN ("treesit-query-capture",
       Ftreesit_query_capture,
       Streesit_query_capture, 2, 5, 0,
       doc: /* Query NODE with patterns in QUERY.

Return a list of (CAPTURE_NAME . NODE).  CAPTURE_NAME is the name
assigned to the node in PATTERN.  NODE is the captured node.

QUERY is either a string query, a sexp query, or a compiled query.
See Info node `(elisp)Pattern Matching' for how to write a query in
either string or sexp form.  When using repeatedly, a compiled query
is much faster than a string or sexp one, so it is recommend to
compile your query if it will be used repeatedly.

BEG and END, if both non-nil, specify the region of buffer positions
in which the query is executed.  Any matching node whose span overlaps
with the region between BEG and END are captured, it doesn't have to
be completely in the region.

If NODE-ONLY is non-nil, return a list of nodes.

Besides a node, NODE can also be a parser, in which case the root node
of that parser is used.
NODE can also be a language symbol, in which case the root node of a
parser for that language is used.  If such a parser doesn't exist, it
is created.

Signal `treesit-query-error' if QUERY is malformed or something else
goes wrong.  You can use `treesit-query-validate' to validate and debug
the query.  */)
  (Lisp_Object node, Lisp_Object query,
   Lisp_Object beg, Lisp_Object end, Lisp_Object node_only)
{
  if (!(TS_COMPILED_QUERY_P (query)
	|| CONSP (query) || STRINGP (query)))
    wrong_type_argument (Qtreesit_query_p, query);

  treesit_initialize ();

  /* Resolve NODE into an actual node.  */
  Lisp_Object lisp_node = treesit_resolve_node (node);

  /* Extract C values from Lisp objects.  */
  TSNode treesit_node = XTS_NODE (lisp_node)->node;
  Lisp_Object lisp_parser = XTS_NODE (lisp_node)->parser;

  const TSLanguage *lang
    = ts_parser_language (XTS_PARSER (lisp_parser)->parser);

  /* Check BEG and END.  */
  struct buffer *buf = XBUFFER (XTS_PARSER (lisp_parser)->buffer);
  if (!NILP (beg))
    treesit_check_position (beg, buf);
  if (!NILP (end))
    treesit_check_position (end, buf);

  /* Initialize query objects.  At the end of this block, we should
     have a working TSQuery and a TSQueryCursor.  */
  TSQuery *treesit_query;
  TSQueryCursor *cursor;
  bool needs_to_free_query_and_cursor;
  Lisp_Object signal_symbol;
  Lisp_Object signal_data;
  if (!treesit_initialize_query (query, lang, &treesit_query, &cursor,
				 &needs_to_free_query_and_cursor,
				 &signal_symbol, &signal_data))
    xsignal (signal_symbol, signal_data);

  /* WARN: After this point, free TREESIT_QUERY and CURSOR before every
     signal and return if NEEDS_TO_FREE_QUERY_AND_CURSOR is true.  */

  /* Set query range.  */
  if (!NILP (beg) && !NILP (end))
    {
      ptrdiff_t visible_beg
	= XTS_PARSER (XTS_NODE (lisp_node)->parser)->visible_beg;
      ptrdiff_t beg_byte = CHAR_TO_BYTE (XFIXNUM (beg));
      ptrdiff_t end_byte = CHAR_TO_BYTE (XFIXNUM (end));
      /* We never let tree-sitter run on buffers too large, so these
	 assertion should never hit.  */
      eassert (beg_byte - visible_beg <= UINT32_MAX);
      eassert (end_byte - visible_beg <= UINT32_MAX);
      ts_query_cursor_set_byte_range (cursor,
				      (uint32_t) (beg_byte - visible_beg),
				      (uint32_t) (end_byte - visible_beg));
    }

  /* Execute query.  */
  ts_query_cursor_exec (cursor, treesit_query, treesit_node);
  TSQueryMatch match;

  /* Go over each match, collect captures and predicates.  Include the
     captures in the RESULT list unconditionally as we get them, then
     test for predicates.  If predicates pass, then all good, if
     predicates don't pass, revert the result back to the result
     before this loop (PREV_RESULT).  (Predicates control the entire
     match.) This way we don't need to create a list of captures in
     every for loop and nconc it to RESULT every time.  That is indeed
     the initial implementation in which Yoav found nconc being the
     bottleneck (98.4% of the running time spent on nconc).  */
  uint32_t patterns_count = ts_query_pattern_count (treesit_query);
  Lisp_Object result = Qnil;
  Lisp_Object prev_result = result;
  Lisp_Object predicates_table = make_vector (patterns_count, Qt);
  Lisp_Object predicate_signal_data = Qnil;

  struct buffer *old_buf = current_buffer;
  set_buffer_internal (buf);

  while (ts_query_cursor_next_match (cursor, &match))
    {
      /* Record the checkpoint that we may roll back to.  */
      prev_result = result;
      /* 1. Get captured nodes.  */
      const TSQueryCapture *captures = match.captures;
      for (int idx = 0; idx < match.capture_count; idx++)
	{
	  uint32_t capture_name_len;
	  TSQueryCapture capture = captures[idx];
	  Lisp_Object captured_node = make_treesit_node (lisp_parser,
							 capture.node);

	  Lisp_Object cap;
	  if (NILP (node_only))
	    {
	      const char *capture_name
		= ts_query_capture_name_for_id (treesit_query, capture.index,
						&capture_name_len);
	      cap = Fcons (intern_c_string_1 (capture_name, capture_name_len),
			   captured_node);
	    }
	  else
	    cap = captured_node;

	  result = Fcons (cap, result);
	}
      /* 2. Get predicates and check whether this match can be
         included in the result list.  */
      Lisp_Object predicates = AREF (predicates_table, match.pattern_index);
      if (EQ (predicates, Qt))
	{
	  predicates = treesit_predicates_for_pattern (treesit_query,
						       match.pattern_index);
	  ASET (predicates_table, match.pattern_index, predicates);
	}

      /* captures_lisp = Fnreverse (captures_lisp); */
      struct capture_range captures_range = { result, prev_result };
      bool match = treesit_eval_predicates (captures_range, predicates,
					    &predicate_signal_data);
      if (!NILP (predicate_signal_data))
	break;

      /* Predicates didn't pass, roll back.  */
      if (!match)
	result = prev_result;
    }

  /* Final clean up.  */
  if (needs_to_free_query_and_cursor)
    {
      ts_query_delete (treesit_query);
      ts_query_cursor_delete (cursor);
    }
  set_buffer_internal (old_buf);

  /* Some capture predicate signaled an error.  */
  if (!NILP (predicate_signal_data))
    xsignal (Qtreesit_query_error, predicate_signal_data);

  return Fnreverse (result);
}

\f
/*** Navigation */

static inline void
treesit_assume_true (bool val)
{
  eassert (val == true);
}

/* Tries to move CURSOR to point to TARGET.  END_POS is the end of
   TARGET.  If success, return true, otherwise move CURSOR back to
   starting position and return false.  LIMIT is the recursion
   limit.  */
static bool
treesit_cursor_helper_1 (TSTreeCursor *cursor, TSNode *target,
			 uint32_t end_pos, ptrdiff_t limit)
{
  if (limit <= 0)
    return false;

  TSNode cursor_node = ts_tree_cursor_current_node (cursor);
  if (ts_node_eq (cursor_node, *target))
    return true;

  if (!ts_tree_cursor_goto_first_child (cursor))
    return false;

  /* Skip nodes that definitely don't contain TARGET.  */
  while (ts_node_end_byte (cursor_node) < end_pos)
    {
      if (!ts_tree_cursor_goto_next_sibling (cursor))
	break;
      cursor_node = ts_tree_cursor_current_node (cursor);
    }

  /* Go through each sibling that could contain TARGET.  Because of
     missing nodes (their width is 0), there could be multiple
     siblings that could contain TARGET.  */
  while (ts_node_start_byte (cursor_node) <= end_pos)
    {
      if (treesit_cursor_helper_1 (cursor, target, end_pos, limit - 1))
	return true;

      if (!ts_tree_cursor_goto_next_sibling (cursor))
	break;
      cursor_node = ts_tree_cursor_current_node (cursor);
    }

  /* Couldn't find TARGET, must be not in this subtree, move cursor
     back and pray that other brothers and sisters can succeed.  */
  treesit_assume_true (ts_tree_cursor_goto_parent (cursor));
  return false;
}

/* Create a TSTreeCursor pointing at NODE.  PARSER is the lisp parser
   that produced NODE.  If success, return true, otherwise return
   false.  This function should almost always succeed, but if the parse
   tree is strangely too deep and exceeds the recursion limit, this
   function will fail and return false.

   If this function returns true, caller needs to free CURSOR; if
   returns false, caller don't need to free CURSOR.

   The reason we need this instead of simply using ts_tree_cursor_new
   is that we have to create the cursor on the root node and traverse
   down to NODE, in order to record the correct stack of parent nodes.
   Otherwise going to sibling or parent of NODE wouldn't work.

   (Wow perfect filling.)  */
static bool
treesit_cursor_helper (TSTreeCursor *cursor, TSNode node, Lisp_Object parser)
{
  uint32_t end_pos = ts_node_end_byte (node);
  TSNode root = ts_tree_root_node (XTS_PARSER (parser)->tree);
  *cursor = ts_tree_cursor_new (root);
  bool success = treesit_cursor_helper_1 (cursor, &node, end_pos,
					  treesit_recursion_limit);
  if (!success)
    ts_tree_cursor_delete (cursor);
  return success;
}

/* Move CURSOR to the next/previous sibling.  FORWARD controls the
   direction.  NAMED controls the namedness.  If there is a valid
   sibling, move CURSOR to it and return true, otherwise return false.
   When false is returned, CURSOR points to a sibling node of the node
   we started at, but exactly which is undefined.  */
static bool
treesit_traverse_sibling_helper (TSTreeCursor *cursor,
				 bool forward, bool named)
{
  if (forward)
    {
      if (!named)
	return ts_tree_cursor_goto_next_sibling (cursor);
      /* Else named...  */
      while (ts_tree_cursor_goto_next_sibling (cursor))
	{
	  if (ts_node_is_named (ts_tree_cursor_current_node (cursor)))
	    return true;
	}
      return false;
    }
  else /* Backward.  */
    {
      /* Go to first child and go through each sibling, until we find
	 the one just before the starting node.  */
      TSNode start = ts_tree_cursor_current_node (cursor);
      if (!ts_tree_cursor_goto_parent (cursor))
	return false;
      treesit_assume_true (ts_tree_cursor_goto_first_child (cursor));

      /* Now CURSOR is at the first child.  If we started at the first
	 child, then there is no further siblings.  */
      TSNode first_child = ts_tree_cursor_current_node (cursor);
      if (ts_node_eq (first_child, start))
	return false;

      /* PROBE is always DELTA siblings ahead of CURSOR. */
      TSTreeCursor probe = ts_tree_cursor_copy (cursor);
      /* This is position of PROBE minus position of CURSOR.  */
      ptrdiff_t delta = 0;
      TSNode probe_node;
      TSNode cursor_node;
      while (ts_tree_cursor_goto_next_sibling (&probe))
	{
	  /* Move PROBE forward, if it equals to the starting node,
	     CURSOR points to the node we want (prev valid sibling of
	     the starting node).  */
	  delta++;
	  probe_node = ts_tree_cursor_current_node (&probe);

	  /* PROBE matched, depending on NAMED, return true/false.  */
	  if (ts_node_eq (probe_node, start))
	    {
	      ts_tree_cursor_delete (&probe);
	      cursor_node = ts_tree_cursor_current_node (cursor);
	      ts_tree_cursor_delete (&probe);
	      return (!named || (named && ts_node_is_named (cursor_node)));
	    }

	  /* PROBE didn't match, move CURSOR forward to PROBE's
	     position, but if we are looking for named nodes, only
	     move CURSOR to PROBE if PROBE is at a named node.  */
	  if (!named || (named && ts_node_is_named (probe_node)))
	    for (; delta > 0; delta--)
	      treesit_assume_true (ts_tree_cursor_goto_next_sibling (cursor));
	}
      ts_tree_cursor_delete (&probe);
      return false;
    }
}

/* Move CURSOR to the first/last child.  FORWARD controls the
   direction.  NAMED controls the namedness.  If there is a valid
   child, move CURSOR to it and return true, otherwise don't move
   CURSOR and return false.  */
static bool
treesit_traverse_child_helper (TSTreeCursor *cursor,
			       bool forward, bool named)
{
  if (forward)
    {
      if (!named)
	return ts_tree_cursor_goto_first_child (cursor);
      else
	{
	  if (!ts_tree_cursor_goto_first_child (cursor))
	    return false;
	  /* After this point, if you return false, make sure to go
	     back to parent.  */
	  TSNode first_child = ts_tree_cursor_current_node (cursor);
	  if (ts_node_is_named (first_child))
	    return true;

	  if (treesit_traverse_sibling_helper (cursor, true, true))
	    return true;
	  else
	    {
	      treesit_assume_true (ts_tree_cursor_goto_parent (cursor));
	      return false;
	    }
	}
    }
  else /* Backward.  */
    {
      if (!ts_tree_cursor_goto_first_child (cursor))
	return false;
      /* After this point, if you return false, make sure to go
	 back to parent.  */

      /* First go to the last child.  */
      while (ts_tree_cursor_goto_next_sibling (cursor));

      if (!named)
	return true;
      /* Else named... */
      if (treesit_traverse_sibling_helper(cursor, false, true))
	return true;
      else
	{
	  treesit_assume_true (ts_tree_cursor_goto_parent (cursor));
	  return false;
	}
    }
}

/* Return true if the node at CURSOR matches PRED.  PRED can be a
   string or a function.  This function assumes PRED is either a
   string or a function.  If NAMED is true, also check that the node
   is named.  */
static bool
treesit_traverse_match_predicate (TSTreeCursor *cursor, Lisp_Object pred,
				  Lisp_Object parser, bool named)
{
  TSNode node = ts_tree_cursor_current_node (cursor);
  if (named && !ts_node_is_named (node))
    return false;

  if (STRINGP (pred))
    {
      const char *type = ts_node_type (node);
      return fast_c_string_match (pred, type, strlen (type)) >= 0;
    }
  else
    {
      Lisp_Object lisp_node = make_treesit_node (parser, node);
      return !NILP (CALLN (Ffuncall, pred, lisp_node));
    }
}

/* Traverse the parse tree starting from CURSOR.  PRED can be a
   function (takes a node and returns nil/non-nil), or a string
   (treated as regexp matching the node's type, must be all single
   byte characters).  If the node satisfies PRED, leave CURSOR on that
   node and return true.  If no node satisfies PRED, move CURSOR back
   to starting position and return false.

   LIMIT is the number of levels we descend in the tree.  FORWARD
   controls the direction in which we traverse the tree, true means
   forward, false backward.  If SKIP_ROOT is true, don't match ROOT.
   */
static bool
treesit_search_dfs (TSTreeCursor *cursor,
		    Lisp_Object pred, Lisp_Object parser,
		    bool forward, bool named, ptrdiff_t limit,
		    bool skip_root)
{
  if (!skip_root
      && treesit_traverse_match_predicate (cursor, pred, parser, named))
    return true;

  if (limit == 0)
    return false;

  if (!treesit_traverse_child_helper (cursor, forward, named))
    return false;
  /* After this point, if you return false, make sure to go back to
     parent.  */

  do /* Iterate through each child.  */
    {
      if (treesit_search_dfs (cursor, pred, parser, forward,
			      named, limit - 1, false))
	return true;
    }
  while (treesit_traverse_sibling_helper (cursor, forward, false));

  /* No match in any child's subtree, go back to starting node.  */
  treesit_assume_true (ts_tree_cursor_goto_parent (cursor));
  return false;
}

/* Go through the whole tree linearly, leaf-first, starting from
   START.  PRED, PARSER, NAMED, FORWARD are the same as in
   ts_search_subtree.  If a match is found, leave CURSOR at that node,
   and return true, if no match is found, return false, and CURSOR's
   position is undefined.  */
static bool
treesit_search_forward (TSTreeCursor *cursor,
			Lisp_Object pred, Lisp_Object parser,
			bool forward, bool named)
{
  /* We don't search for subtree and always search from the leaf
     nodes.  This way repeated call of this function traverses each
     node in the tree once and only once:

     (while node (setq node (treesit-search-forward node)))
  */
  bool initial = true;
  while (true)
    {
      if (!initial /* We don't match the starting node.  */
	  && treesit_traverse_match_predicate (cursor, pred, parser, named))
	return true;
      initial = false;

      /* Try going to the next sibling, if there is no next sibling,
	 go to parent and try again.  */
      while (!treesit_traverse_sibling_helper (cursor, forward, named))
	{
	  /* There is no next sibling, go to parent.  */
	  if (!ts_tree_cursor_goto_parent (cursor))
	    return false;

	  if (treesit_traverse_match_predicate (cursor, pred, parser, named))
	      return true;
	}
      /* We are at the next sibling, deep dive into the first leaf
	 node.  */
      while (treesit_traverse_child_helper (cursor, forward, false));
      /* At this point CURSOR is at a leaf node.  */
    }
}

DEFUN ("treesit-search-subtree",
       Ftreesit_search_subtree,
       Streesit_search_subtree, 2, 5, 0,
       doc: /* Traverse the parse tree of NODE depth-first using PREDICATE.

Traverse the subtree of NODE, and match PREDICATE with each node along
the way.  PREDICATE is a regexp string that matches against each
node's type, or a function that takes a node and returns nil/non-nil.

By default, only traverse named nodes, but if ALL is non-nil, traverse
all nodes.  If BACKWARD is non-nil, traverse backwards.  If DEPTH is
non-nil, only traverse nodes up to that number of levels down in the
tree.  If DEPTH is nil, default to 1000.

Return the first matched node, or nil if none matches.  */)
  (Lisp_Object node, Lisp_Object predicate, Lisp_Object backward,
   Lisp_Object all, Lisp_Object depth)
{
  CHECK_TS_NODE (node);
  CHECK_TYPE (STRINGP (predicate) || FUNCTIONP (predicate),
	      list3 (Qor, Qstringp, Qfunctionp), predicate);
  CHECK_SYMBOL (all);
  CHECK_SYMBOL (backward);

  /* We use a default limit of 1000.  See bug#59426 for the
     discussion.  */
  ptrdiff_t the_limit = treesit_recursion_limit;
  if (!NILP (depth))
    {
      CHECK_FIXNUM (depth);
      the_limit = XFIXNUM (depth);
    }

  treesit_initialize ();

  Lisp_Object parser = XTS_NODE (node)->parser;
  Lisp_Object return_value = Qnil;
  TSTreeCursor cursor;
  if (!treesit_cursor_helper (&cursor, XTS_NODE (node)->node, parser))
    return return_value;

  if (treesit_search_dfs (&cursor, predicate, parser, NILP (backward),
			  NILP (all), the_limit, false))
    {
      TSNode node = ts_tree_cursor_current_node (&cursor);
      return_value = make_treesit_node (parser, node);
    }
  ts_tree_cursor_delete (&cursor);
  return return_value;
}

DEFUN ("treesit-search-forward",
       Ftreesit_search_forward,
       Streesit_search_forward, 2, 4, 0,
       doc: /* Search for node matching PREDICATE in the parse tree of START.

Start traversing the tree from node START, and match PREDICATE with
each node (except START itself) along the way.  PREDICATE is a regexp
string that matches against each node's type, or a function that takes
a node and returns non-nil if it matches.

By default, only search for named nodes, but if ALL is non-nil, search
for all nodes.  If BACKWARD is non-nil, search backwards.

Return the first matched node, or nil if none matches.

For a tree like below, where START is marked by S, traverse as
numbered from 1 to 12:

                12
                |
       S--------3----------11
       |        |          |
  o--o-+--o  1--+--2    6--+-----10
  |  |                  |        |
  o  o                +-+-+   +--+--+
                      |   |   |  |  |
                      4   5   7  8  9

Note that this function doesn't traverse the subtree of START, and it
always traverse leaf nodes first, then upwards.  */)
  (Lisp_Object start, Lisp_Object predicate, Lisp_Object backward,
   Lisp_Object all)
{
  CHECK_TS_NODE (start);
  CHECK_TYPE (STRINGP (predicate) || FUNCTIONP (predicate),
	      list3 (Qor, Qstringp, Qfunctionp), predicate);
  CHECK_SYMBOL (all);
  CHECK_SYMBOL (backward);

  treesit_initialize ();

  Lisp_Object parser = XTS_NODE (start)->parser;
  Lisp_Object return_value = Qnil;
  TSTreeCursor cursor;
  if (!treesit_cursor_helper (&cursor, XTS_NODE (start)->node, parser))
    return return_value;

  if (treesit_search_forward (&cursor, predicate, parser,
			      NILP (backward), NILP (all)))
    {
      TSNode node = ts_tree_cursor_current_node (&cursor);
      return_value = make_treesit_node (parser, node);
    }
  ts_tree_cursor_delete (&cursor);
  return return_value;
}

/* Recursively traverse the tree under CURSOR, and append the result
   subtree to PARENT's cdr.  See more in Ftreesit_induce_sparse_tree.
   Note that the top-level children list is reversed, because
   reasons.  */
static void
treesit_build_sparse_tree (TSTreeCursor *cursor, Lisp_Object parent,
			   Lisp_Object pred, Lisp_Object process_fn,
			   ptrdiff_t limit, Lisp_Object parser)
{
  bool match = treesit_traverse_match_predicate (cursor, pred, parser, false);
  if (match)
    {
      /* If this node matches pred, add a new node to the parent's
	 children list.  */
      TSNode node = ts_tree_cursor_current_node (cursor);
      Lisp_Object lisp_node = make_treesit_node (parser, node);
      if (!NILP (process_fn))
	lisp_node = CALLN (Ffuncall, process_fn, lisp_node);

      Lisp_Object this = Fcons (lisp_node, Qnil);
      Fsetcdr (parent, Fcons (this, Fcdr (parent)));
      /* Now for children nodes, this is the new parent.  */
      parent = this;
    }
  /* Go through each child.  */
  if (limit > 0 && ts_tree_cursor_goto_first_child (cursor))
    {
      do
	{
	  /* Make sure not to use node after the recursive funcall.
	     Then C compilers should be smart enough not to copy NODE
	     to stack.  */
	  treesit_build_sparse_tree (cursor, parent, pred, process_fn,
				     limit - 1, parser);
	}
      while (ts_tree_cursor_goto_next_sibling (cursor));
      /* Don't forget to come back to this node.  */
      ts_tree_cursor_goto_parent (cursor);
    }
  /* Before we go, reverse children in the sparse tree.  */
  if (match)
    /* When match == true, "parent" is actually the node we added in
       this layer (parent = this).  */
    Fsetcdr (parent, Fnreverse (Fcdr (parent)));
}

DEFUN ("treesit-induce-sparse-tree",
       Ftreesit_induce_sparse_tree,
       Streesit_induce_sparse_tree, 2, 4, 0,
       doc: /* Create a sparse tree of ROOT's subtree.

This takes the subtree under ROOT, and combs it so only the nodes
that match PREDICATE are left, like picking out grapes on the vine.
PREDICATE is a regexp string that matches against each node's type.

For a subtree on the left that consist of both numbers and letters, if
PREDICATE is "is letter", the returned tree is the one on the right.

	a                 a              a
	|                 |              |
    +---+---+         +---+---+      +---+---+
    |   |   |         |   |   |      |   |   |
    b   1   2         b   |   |      b   c   d
	|   |     =>      |   |  =>      |
	c   +--+          c   +          e
	|   |  |          |   |
     +--+   d  4       +--+   d
     |  |              |
     e  5              e

If PROCESS-FN is non-nil, it should be a function of one argument.  In
that case, instead of returning the matched nodes, pass each node to
PROCESS-FN, and use its return value instead.

If non-nil, DEPTH is the number of levels to go down the tree from
ROOT.  If DEPTH is nil or omitted, it defaults to 1000.

Each node in the returned tree looks like (NODE . (CHILD ...)).  The
root of this tree might be nil, if ROOT doesn't match PREDICATE.

If no node matches PREDICATE, return nil.

PREDICATE can also be a function that takes a node and returns
nil/non-nil, but it is slower and more memory consuming than using
a regexp.  */)
  (Lisp_Object root, Lisp_Object predicate, Lisp_Object process_fn,
   Lisp_Object depth)
{
  CHECK_TS_NODE (root);
  CHECK_TYPE (STRINGP (predicate) || FUNCTIONP (predicate),
	      list3 (Qor, Qstringp, Qfunctionp), predicate);

  if (!NILP (process_fn))
    CHECK_TYPE (FUNCTIONP (process_fn), Qfunctionp, process_fn);

  /* We use a default limit of 1000.  See bug#59426 for the
     discussion.  */
  ptrdiff_t the_limit = treesit_recursion_limit;
  if (!NILP (depth))
    {
      CHECK_FIXNUM (depth);
      the_limit = XFIXNUM (depth);
    }

  treesit_initialize ();

  Lisp_Object parser = XTS_NODE (root)->parser;
  Lisp_Object parent = Fcons (Qnil, Qnil);
  /* In this function we never traverse above NODE, so we don't need
     to use treesit_cursor_helper.  */
  TSTreeCursor cursor = ts_tree_cursor_new (XTS_NODE (root)->node);

  treesit_build_sparse_tree (&cursor, parent, predicate, process_fn,
			     the_limit, parser);
  ts_tree_cursor_delete (&cursor);
  Fsetcdr (parent, Fnreverse (Fcdr (parent)));
  if (NILP (Fcdr (parent)))
    return Qnil;
  else
    return parent;
}

DEFUN ("treesit-subtree-stat",
       Ftreesit_subtree_stat,
       Streesit_subtree_stat, 1, 1, 0,
       doc: /* Return information about the subtree of NODE.

Return a list (MAX-DEPTH MAX-WIDTH COUNT), where MAX-DEPTH is the
maximum depth of the subtree, MAX-WIDTH is the maximum number of
direct children of nodes in the subtree, and COUNT is the number of
nodes in the subtree, including NODE.  */)
  (Lisp_Object node)
{
  /* Having a limit on the depth to traverse doesn't have much impact
     on the time it takes, so I left that out.  */
  CHECK_TS_NODE (node);

  treesit_initialize ();

  TSTreeCursor cursor = ts_tree_cursor_new (XTS_NODE (node)->node);
  ptrdiff_t max_depth = 1;
  ptrdiff_t max_width = 0;
  ptrdiff_t count = 0;
  ptrdiff_t current_depth = 0;

  /* Traverse the subtree depth-first.  */
  while (true)
    {
      count++;

      /* Go down depth-first.  */
      while (ts_tree_cursor_goto_first_child (&cursor))
	{
	  current_depth++;
	  count++;
	  /* While we're at here, measure the number of siblings.  */
	  ptrdiff_t width_count = 1;
	  while (ts_tree_cursor_goto_next_sibling (&cursor))
	    width_count++;
	  max_width = max (max_width, width_count);
	  /* Go back to the first sibling.  */
	  treesit_assume_true (ts_tree_cursor_goto_parent (&cursor));
	  treesit_assume_true (ts_tree_cursor_goto_first_child (&cursor));
	}
      max_depth = max (max_depth, current_depth);

      /* Go to next sibling.  If there is no next sibling, go to
         parent's next sibling, and so on.  If there is no more
         parent, we've traversed the whole subtree, stop.  */
      while (!ts_tree_cursor_goto_next_sibling (&cursor))
	{
	  if (ts_tree_cursor_goto_parent (&cursor))
	    current_depth--;
	  else
	    {
	      ts_tree_cursor_delete (&cursor);
	      return list3 (make_fixnum (max_depth),
			    make_fixnum (max_width),
			    make_fixnum (count));
	    }
	}
    }
}

#endif	/* HAVE_TREE_SITTER */

DEFUN ("treesit-available-p", Ftreesit_available_p,
       Streesit_available_p, 0, 0, 0,
       doc: /* Return non-nil if tree-sitter support is built-in and available.  */)
  (void)
{
#if HAVE_TREE_SITTER
  return load_tree_sitter_if_necessary (false) ? Qt : Qnil;
#else
  return Qnil;
#endif
}

\f
/*** Initialization */

/* Initialize the tree-sitter routines.  */
void
syms_of_treesit (void)
{
#if HAVE_TREE_SITTER
  DEFSYM (Qtreesit_parser_p, "treesit-parser-p");
  DEFSYM (Qtreesit_node_p, "treesit-node-p");
  DEFSYM (Qtreesit_compiled_query_p, "treesit-compiled-query-p");
  DEFSYM (Qtreesit_query_p, "treesit-query-p");
  DEFSYM (Qnamed, "named");
  DEFSYM (Qmissing, "missing");
  DEFSYM (Qextra, "extra");
  DEFSYM (Qoutdated, "outdated");
  DEFSYM (Qhas_error, "has-error");
  DEFSYM (Qlive, "live");

  DEFSYM (QCanchor, ":anchor");
  DEFSYM (QCequal, ":equal");
  DEFSYM (QCmatch, ":match");
  DEFSYM (QCpred, ":pred");

  DEFSYM (Qnot_found, "not-found");
  DEFSYM (Qsymbol_error, "symbol-error");
  DEFSYM (Qversion_mismatch, "version-mismatch");

  DEFSYM (Qtreesit_error, "treesit-error");
  DEFSYM (Qtreesit_query_error, "treesit-query-error");
  DEFSYM (Qtreesit_parse_error, "treesit-parse-error");
  DEFSYM (Qtreesit_range_invalid, "treesit-range-invalid");
  DEFSYM (Qtreesit_buffer_too_large,
	  "treesit-buffer-too-large");
  DEFSYM (Qtreesit_load_language_error,
	  "treesit-load-language-error");
  DEFSYM (Qtreesit_node_outdated,
	  "treesit-node-outdated");
  DEFSYM (Quser_emacs_directory,
	  "user-emacs-directory");
  DEFSYM (Qtreesit_parser_deleted, "treesit-parser-deleted");
  DEFSYM (Qtreesit_pattern_expand, "treesit-pattern-expand");

  DEFSYM (Qor, "or");

#ifdef WINDOWSNT
  DEFSYM (Qtree_sitter, "tree-sitter");
#endif

  define_error (Qtreesit_error, "Generic tree-sitter error", Qerror);
  define_error (Qtreesit_query_error, "Query pattern is malformed",
		Qtreesit_error);
  /* Should be impossible, no need to document this error.  */
  define_error (Qtreesit_parse_error, "Parse failed",
		Qtreesit_error);
  define_error (Qtreesit_range_invalid,
		"RANGES are invalid, they have to be ordered and not overlapping",
		Qtreesit_error);
  define_error (Qtreesit_buffer_too_large, "Buffer too large (> 4GB)",
		Qtreesit_error);
  define_error (Qtreesit_load_language_error,
		"Cannot load language definition",
		Qtreesit_error);
  define_error (Qtreesit_node_outdated,
		"This node is outdated, please retrieve a new one",
		Qtreesit_error);
  define_error (Qtreesit_parser_deleted,
		"This parser is deleted and cannot be used",
		Qtreesit_error);

  DEFVAR_LISP ("treesit-load-name-override-list",
	       Vtreesit_load_name_override_list,
	       doc:
	       /* An override list for unconventional tree-sitter libraries.

By default, Emacs assumes the dynamic library for LANG is
libtree-sitter-LANG.EXT, where EXT is the OS specific extension for
dynamic libraries.  Emacs also assumes that the name of the C function
the library provides is tree_sitter_LANG.  If that is not the case,
you can add an entry

    (LANG LIBRARY-BASE-NAME FUNCTION-NAME)

to this list, where LIBRARY-BASE-NAME is the filename of the dynamic
library without the file-name extension, and FUNCTION-NAME is the
function provided by the library.  */);
  Vtreesit_load_name_override_list = Qnil;

  DEFVAR_LISP ("treesit-extra-load-path",
	       Vtreesit_extra_load_path,
	       doc:
	       /* Additional directories to look for tree-sitter language definitions.
The value should be a list of directories.
When trying to load a tree-sitter language definition,
Emacs first looks in the directories mentioned in this variable,
then in the `tree-sitter' subdirectory of `user-emacs-directory', and
then in the system default locations for dynamic libraries, in that order.  */);
  Vtreesit_extra_load_path = Qnil;

  staticpro (&Vtreesit_str_libtree_sitter);
  Vtreesit_str_libtree_sitter = build_pure_c_string ("libtree-sitter-");
  staticpro (&Vtreesit_str_tree_sitter);
  Vtreesit_str_tree_sitter = build_pure_c_string ("tree-sitter-");
  staticpro (&Vtreesit_str_dot);
  Vtreesit_str_dot = build_pure_c_string (".");
  staticpro (&Vtreesit_str_question_mark);
  Vtreesit_str_question_mark = build_pure_c_string ("?");
  staticpro (&Vtreesit_str_star);
  Vtreesit_str_star = build_pure_c_string ("*");
  staticpro (&Vtreesit_str_plus);
  Vtreesit_str_plus = build_pure_c_string ("+");
  staticpro (&Vtreesit_str_pound_equal);
  Vtreesit_str_pound_equal = build_pure_c_string ("#equal");
  staticpro (&Vtreesit_str_pound_match);
  Vtreesit_str_pound_match = build_pure_c_string ("#match");
  staticpro (&Vtreesit_str_pound_pred);
  Vtreesit_str_pound_pred = build_pure_c_string ("#pred");
  staticpro (&Vtreesit_str_open_bracket);
  Vtreesit_str_open_bracket = build_pure_c_string ("[");
  staticpro (&Vtreesit_str_close_bracket);
  Vtreesit_str_close_bracket = build_pure_c_string ("]");
  staticpro (&Vtreesit_str_open_paren);
  Vtreesit_str_open_paren = build_pure_c_string ("(");
  staticpro (&Vtreesit_str_close_paren);
  Vtreesit_str_close_paren = build_pure_c_string (")");
  staticpro (&Vtreesit_str_space);
  Vtreesit_str_space = build_pure_c_string (" ");
  staticpro (&Vtreesit_str_equal);
  Vtreesit_str_equal = build_pure_c_string ("equal");
  staticpro (&Vtreesit_str_match);
  Vtreesit_str_match = build_pure_c_string ("match");
  staticpro (&Vtreesit_str_pred);
  Vtreesit_str_pred = build_pure_c_string ("pred");

  defsubr (&Streesit_language_available_p);
  defsubr (&Streesit_library_abi_version);
  defsubr (&Streesit_language_abi_version);

  defsubr (&Streesit_parser_p);
  defsubr (&Streesit_node_p);
  defsubr (&Streesit_compiled_query_p);
  defsubr (&Streesit_query_p);
  defsubr (&Streesit_query_language);

  defsubr (&Streesit_node_parser);

  defsubr (&Streesit_parser_create);
  defsubr (&Streesit_parser_delete);
  defsubr (&Streesit_parser_list);
  defsubr (&Streesit_parser_buffer);
  defsubr (&Streesit_parser_language);

  defsubr (&Streesit_parser_root_node);
  /* defsubr (&Streesit_parse_string); */

  defsubr (&Streesit_parser_set_included_ranges);
  defsubr (&Streesit_parser_included_ranges);

  defsubr (&Streesit_parser_notifiers);
  defsubr (&Streesit_parser_add_notifier);
  defsubr (&Streesit_parser_remove_notifier);

  defsubr (&Streesit_node_type);
  defsubr (&Streesit_node_start);
  defsubr (&Streesit_node_end);
  defsubr (&Streesit_node_string);
  defsubr (&Streesit_node_parent);
  defsubr (&Streesit_node_child);
  defsubr (&Streesit_node_check);
  defsubr (&Streesit_node_field_name_for_child);
  defsubr (&Streesit_node_child_count);
  defsubr (&Streesit_node_child_by_field_name);
  defsubr (&Streesit_node_next_sibling);
  defsubr (&Streesit_node_prev_sibling);
  defsubr (&Streesit_node_first_child_for_pos);
  defsubr (&Streesit_node_descendant_for_range);
  defsubr (&Streesit_node_eq);

  defsubr (&Streesit_pattern_expand);
  defsubr (&Streesit_query_expand);
  defsubr (&Streesit_query_compile);
  defsubr (&Streesit_query_capture);

  defsubr (&Streesit_search_subtree);
  defsubr (&Streesit_search_forward);
  defsubr (&Streesit_induce_sparse_tree);
  defsubr (&Streesit_subtree_stat);
#endif /* HAVE_TREE_SITTER */
  defsubr (&Streesit_available_p);
}

debug log:

solving fd5fda78133 ...
found fd5fda78133 in https://git.savannah.gnu.org/cgit/emacs.git

(*) Git path names are given by the tree(s) the blob belongs to.
    Blobs themselves have no identifier aside from the hash of its contents.^

Code repositories for project(s) associated with this external index

	https://git.savannah.gnu.org/cgit/emacs.git
	https://git.savannah.gnu.org/cgit/emacs/org-mode.git

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.