llvm-native-core 0.1.12

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
//! clang_compiler_service — Compiler-as-a-service via Clang tooling.
//!
//! Covers:
//! - clangd language server: full LSP protocol implementation
//! - libclang C API full: CXIndex, CXTranslationUnit, CXCursor, CXType, etc.
//! - Compilation database watcher: file monitoring for compile_commands.json
//! - Background indexing: index TUs in background, update on source change
//! - AST-based code completion: type-aware completion at cursor position
//! - Cross-reference: find all references, call hierarchy, type hierarchy
//! - Inlay hints: parameter names, type annotations, auto deduction
//! - Document symbols: outline view with function/class/namespace hierarchy
//! - Workspace symbols: fuzzy search across all open files
//! - Semantic highlighting: token-based coloring with scope information
//!
//! Clean-room reconstruction from LSP spec and Clang tooling documentation.

use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::fmt;
use std::io;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant, SystemTime};

// ============================================================================
// LSP Protocol — Core Types
// ============================================================================

/// Document URI represented as string.
pub type DocumentUri = String;

/// LSP integer types.
pub type LspInt = i64;
pub type LspUint = u64;

/// A position in a text document (zero-based).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Position {
    pub line: LspUint,
    pub character: LspUint,
}

impl Position {
    pub fn new(line: LspUint, character: LspUint) -> Self {
        Self { line, character }
    }
}

impl fmt::Display for Position {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}", self.line, self.character)
    }
}

/// A range in a text document.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Range {
    pub start: Position,
    pub end: Position,
}

impl Range {
    pub fn new(start: Position, end: Position) -> Self {
        Self { start, end }
    }

    pub fn from_coords(start_line: LspUint, start_char: LspUint, end_line: LspUint, end_char: LspUint) -> Self {
        Self {
            start: Position::new(start_line, start_char),
            end: Position::new(end_line, end_char),
        }
    }

    pub fn covers(&self, pos: Position) -> bool {
        if pos.line < self.start.line || pos.line > self.end.line {
            return false;
        }
        if pos.line == self.start.line && pos.character < self.start.character {
            return false;
        }
        if pos.line == self.end.line && pos.character > self.end.character {
            return false;
        }
        true
    }
}

/// A location inside a text document.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Location {
    pub uri: DocumentUri,
    pub range: Range,
}

/// A link between a source location and a target location.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LocationLink {
    pub origin_selection_range: Option<Range>,
    pub target_uri: DocumentUri,
    pub target_range: Range,
    pub target_selection_range: Range,
}

/// Text document identifier.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextDocumentIdentifier {
    pub uri: DocumentUri,
}

/// Versioned text document identifier.
#[derive(Debug, Clone)]
pub struct VersionedTextDocumentIdentifier {
    pub uri: DocumentUri,
    pub version: LspInt,
}

/// Text document position parameters.
#[derive(Debug, Clone)]
pub struct TextDocumentPositionParams {
    pub text_document: TextDocumentIdentifier,
    pub position: Position,
}

// ============================================================================
// LSP — Initialize
// ============================================================================

/// Initialize parameters sent from client to server.
#[derive(Debug, Clone)]
pub struct InitializeParams {
    pub process_id: Option<LspInt>,
    pub client_info: Option<ClientInfo>,
    pub locale: Option<String>,
    pub root_path: Option<String>,
    pub root_uri: Option<DocumentUri>,
    pub initialization_options: Option<serde_json::Value>,
    pub capabilities: ClientCapabilities,
    pub trace: Option<TraceValue>,
    pub workspace_folders: Option<Vec<WorkspaceFolder>>,
}

/// Client info.
#[derive(Debug, Clone)]
pub struct ClientInfo {
    pub name: String,
    pub version: Option<String>,
}

/// Trace values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TraceValue {
    Off,
    Messages,
    Verbose,
}

impl fmt::Display for TraceValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Off => write!(f, "off"),
            Self::Messages => write!(f, "messages"),
            Self::Verbose => write!(f, "verbose"),
        }
    }
}

/// Workspace folder.
#[derive(Debug, Clone)]
pub struct WorkspaceFolder {
    pub uri: DocumentUri,
    pub name: String,
}

/// Client capabilities.
#[derive(Debug, Clone, Default)]
pub struct ClientCapabilities {
    pub workspace: Option<WorkspaceClientCapabilities>,
    pub text_document: Option<TextDocumentClientCapabilities>,
    pub window: Option<WindowClientCapabilities>,
    pub general: Option<GeneralClientCapabilities>,
    pub experimental: Option<serde_json::Value>,
}

/// Workspace client capabilities.
#[derive(Debug, Clone, Default)]
pub struct WorkspaceClientCapabilities {
    pub apply_edit: Option<bool>,
    pub workspace_edit: Option<WorkspaceEditCapabilities>,
    pub did_change_configuration: Option<DidChangeConfigurationCapabilities>,
    pub did_change_watched_files: Option<DidChangeWatchedFilesCapabilities>,
    pub symbol: Option<WorkspaceSymbolCapabilities>,
    pub execute_command: Option<ExecuteCommandCapabilities>,
    pub workspace_folders: Option<bool>,
    pub configuration: Option<bool>,
    pub semantic_tokens: Option<SemanticTokensWorkspaceCapabilities>,
    pub code_lens: Option<CodeLensWorkspaceCapabilities>,
    pub file_operations: Option<FileOperationCapabilities>,
    pub inline_value: Option<InlineValueWorkspaceCapabilities>,
    pub inlay_hint: Option<InlayHintWorkspaceCapabilities>,
    pub diagnostics: Option<DiagnosticWorkspaceCapabilities>,
}

/// Workspace edit capabilities.
#[derive(Debug, Clone, Default)]
pub struct WorkspaceEditCapabilities {
    pub document_changes: Option<bool>,
    pub resource_operations: Option<Vec<String>>,
    pub failure_handling: Option<String>,
    pub normalizes_line_endings: Option<bool>,
    pub change_annotation_support: Option<ChangeAnnotationSupport>,
}

/// Change annotation support.
#[derive(Debug, Clone, Default)]
pub struct ChangeAnnotationSupport {
    pub groups_on_label: Option<bool>,
}

/// Did change configuration capabilities.
#[derive(Debug, Clone, Default)]
pub struct DidChangeConfigurationCapabilities {
    pub dynamic_registration: Option<bool>,
}

/// Did change watched files capabilities.
#[derive(Debug, Clone, Default)]
pub struct DidChangeWatchedFilesCapabilities {
    pub dynamic_registration: Option<bool>,
    pub relative_pattern_support: Option<bool>,
}

/// Workspace symbol capabilities.
#[derive(Debug, Clone, Default)]
pub struct WorkspaceSymbolCapabilities {
    pub dynamic_registration: Option<bool>,
    pub symbol_kind: Option<Vec<SymbolKind>>,
    pub tag_support: Option<SymbolTagSupport>,
    pub resolve_support: Option<ResolveSupport>,
}

/// Symbol tag support.
#[derive(Debug, Clone, Default)]
pub struct SymbolTagSupport {
    pub value_set: Vec<SymbolTag>,
}

/// Resolve support.
#[derive(Debug, Clone, Default)]
pub struct ResolveSupport {
    pub properties: Vec<String>,
}

/// Execute command capabilities.
#[derive(Debug, Clone, Default)]
pub struct ExecuteCommandCapabilities {
    pub dynamic_registration: Option<bool>,
}

/// Semantic tokens workspace capabilities.
#[derive(Debug, Clone, Default)]
pub struct SemanticTokensWorkspaceCapabilities {
    pub refresh_support: Option<bool>,
}

/// Code lens workspace capabilities.
#[derive(Debug, Clone, Default)]
pub struct CodeLensWorkspaceCapabilities {
    pub refresh_support: Option<bool>,
}

/// File operation capabilities.
#[derive(Debug, Clone, Default)]
pub struct FileOperationCapabilities {
    pub dynamic_registration: Option<bool>,
    pub did_create: Option<bool>,
    pub will_create: Option<bool>,
    pub did_rename: Option<bool>,
    pub will_rename: Option<bool>,
    pub did_delete: Option<bool>,
    pub will_delete: Option<bool>,
}

/// Inline value workspace capabilities.
#[derive(Debug, Clone, Default)]
pub struct InlineValueWorkspaceCapabilities {
    pub refresh_support: Option<bool>,
}

/// Inlay hint workspace capabilities.
#[derive(Debug, Clone, Default)]
pub struct InlayHintWorkspaceCapabilities {
    pub refresh_support: Option<bool>,
}

/// Diagnostic workspace capabilities.
#[derive(Debug, Clone, Default)]
pub struct DiagnosticWorkspaceCapabilities {
    pub refresh_support: Option<bool>,
}

/// Text document client capabilities.
#[derive(Debug, Clone, Default)]
pub struct TextDocumentClientCapabilities {
    pub synchronization: Option<TextDocumentSyncCapabilities>,
    pub completion: Option<CompletionCapabilities>,
    pub hover: Option<HoverCapabilities>,
    pub signature_help: Option<SignatureHelpCapabilities>,
    pub declaration: Option<DeclarationCapabilities>,
    pub definition: Option<DefinitionCapabilities>,
    pub type_definition: Option<TypeDefinitionCapabilities>,
    pub implementation: Option<ImplementationCapabilities>,
    pub references: Option<ReferenceCapabilities>,
    pub document_highlight: Option<DocumentHighlightCapabilities>,
    pub document_symbol: Option<DocumentSymbolCapabilities>,
    pub code_action: Option<CodeActionCapabilities>,
    pub code_lens: Option<CodeLensCapabilities>,
    pub document_link: Option<DocumentLinkCapabilities>,
    pub color_provider: Option<ColorProviderCapabilities>,
    pub formatting: Option<FormattingCapabilities>,
    pub range_formatting: Option<RangeFormattingCapabilities>,
    pub on_type_formatting: Option<OnTypeFormattingCapabilities>,
    pub rename: Option<RenameCapabilities>,
    pub folding_range: Option<FoldingRangeCapabilities>,
    pub selection_range: Option<SelectionRangeCapabilities>,
    pub publish_diagnostics: Option<PublishDiagnosticsCapabilities>,
    pub call_hierarchy: Option<CallHierarchyCapabilities>,
    pub semantic_tokens: Option<SemanticTokensCapabilities>,
    pub linked_editing_range: Option<LinkedEditingRangeCapabilities>,
    pub moniker: Option<MonikerCapabilities>,
    pub type_hierarchy: Option<TypeHierarchyCapabilities>,
    pub inline_value: Option<InlineValueCapabilities>,
    pub inlay_hint: Option<InlayHintCapabilities>,
    pub diagnostic: Option<DiagnosticCapabilities>,
}

/// Text document sync capabilities.
#[derive(Debug, Clone, Default)]
pub struct TextDocumentSyncCapabilities {
    pub dynamic_registration: Option<bool>,
    pub will_save: Option<bool>,
    pub will_save_wait_until: Option<bool>,
    pub did_save: Option<bool>,
}

/// Completion capabilities.
#[derive(Debug, Clone, Default)]
pub struct CompletionCapabilities {
    pub dynamic_registration: Option<bool>,
    pub completion_item: Option<CompletionItemCapabilities>,
    pub completion_item_kind: Option<CompletionItemKindCapabilities>,
    pub insert_text_mode: Option<InsertTextMode>,
    pub context_support: Option<bool>,
    pub completion_list: Option<CompletionListCapabilities>,
}

/// Completion item capabilities.
#[derive(Debug, Clone, Default)]
pub struct CompletionItemCapabilities {
    pub snippet_support: Option<bool>,
    pub commit_characters_support: Option<bool>,
    pub documentation_format: Option<Vec<MarkupKind>>,
    pub deprecated_support: Option<bool>,
    pub preselect_support: Option<bool>,
    pub tag_support: Option<TagSupport<CompletionItemTag>>,
    pub insert_replace_support: Option<bool>,
    pub resolve_support: Option<ResolveSupport>,
    pub insert_text_mode_support: Option<InsertTextModeSupport>,
    pub label_details_support: Option<bool>,
}

/// Completion item kind capabilities.
#[derive(Debug, Clone, Default)]
pub struct CompletionItemKindCapabilities {
    pub value_set: Option<Vec<CompletionItemKind>>,
}

/// Tag support generic.
#[derive(Debug, Clone, Default)]
pub struct TagSupport<T> {
    pub value_set: Vec<T>,
}

/// Insert text mode support.
#[derive(Debug, Clone, Default)]
pub struct InsertTextModeSupport {
    pub value_set: Vec<InsertTextMode>,
}

/// Completion list capabilities.
#[derive(Debug, Clone, Default)]
pub struct CompletionListCapabilities {
    pub item_defaults: Option<Vec<String>>,
}

/// Hover capabilities.
#[derive(Debug, Clone, Default)]
pub struct HoverCapabilities {
    pub dynamic_registration: Option<bool>,
    pub content_format: Option<Vec<MarkupKind>>,
}

/// Markup kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MarkupKind {
    PlainText,
    Markdown,
}

impl fmt::Display for MarkupKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::PlainText => write!(f, "plaintext"),
            Self::Markdown => write!(f, "markdown"),
        }
    }
}

/// Signature help capabilities.
#[derive(Debug, Clone, Default)]
pub struct SignatureHelpCapabilities {
    pub dynamic_registration: Option<bool>,
    pub signature_information: Option<SignatureInformationCapabilities>,
    pub context_support: Option<bool>,
}

/// Signature information capabilities.
#[derive(Debug, Clone, Default)]
pub struct SignatureInformationCapabilities {
    pub documentation_format: Option<Vec<MarkupKind>>,
    pub parameter_information: Option<ParameterInformationCapabilities>,
    pub active_parameter_support: Option<bool>,
}

/// Parameter information capabilities.
#[derive(Debug, Clone, Default)]
pub struct ParameterInformationCapabilities {
    pub label_offset_support: Option<bool>,
}

/// Declaration capabilities.
#[derive(Debug, Clone, Default)]
pub struct DeclarationCapabilities {
    pub dynamic_registration: Option<bool>,
    pub link_support: Option<bool>,
}

/// Definition capabilities.
#[derive(Debug, Clone, Default)]
pub struct DefinitionCapabilities {
    pub dynamic_registration: Option<bool>,
    pub link_support: Option<bool>,
}

/// Type definition capabilities.
#[derive(Debug, Clone, Default)]
pub struct TypeDefinitionCapabilities {
    pub dynamic_registration: Option<bool>,
    pub link_support: Option<bool>,
}

/// Implementation capabilities.
#[derive(Debug, Clone, Default)]
pub struct ImplementationCapabilities {
    pub dynamic_registration: Option<bool>,
    pub link_support: Option<bool>,
}

/// Reference capabilities.
#[derive(Debug, Clone, Default)]
pub struct ReferenceCapabilities {
    pub dynamic_registration: Option<bool>,
}

/// Document highlight capabilities.
#[derive(Debug, Clone, Default)]
pub struct DocumentHighlightCapabilities {
    pub dynamic_registration: Option<bool>,
}

/// Document symbol capabilities.
#[derive(Debug, Clone, Default)]
pub struct DocumentSymbolCapabilities {
    pub dynamic_registration: Option<bool>,
    pub symbol_kind: Option<Vec<SymbolKind>>,
    pub hierarchical_document_symbol_support: Option<bool>,
    pub tag_support: Option<TagSupport<SymbolTag>>,
    pub label_support: Option<bool>,
}

/// Code action capabilities.
#[derive(Debug, Clone, Default)]
pub struct CodeActionCapabilities {
    pub dynamic_registration: Option<bool>,
    pub code_action_literal_support: Option<CodeActionLiteralSupport>,
    pub is_preferred_support: Option<bool>,
    pub disabled_support: Option<bool>,
    pub data_support: Option<bool>,
    pub resolve_support: Option<ResolveSupport>,
    pub honors_change_annotations: Option<bool>,
}

/// Code action literal support.
#[derive(Debug, Clone, Default)]
pub struct CodeActionLiteralSupport {
    pub code_action_kind: CodeActionKindCapability,
}

/// Code action kind capability.
#[derive(Debug, Clone, Default)]
pub struct CodeActionKindCapability {
    pub value_set: Vec<String>,
}

/// Code lens capabilities.
#[derive(Debug, Clone, Default)]
pub struct CodeLensCapabilities {
    pub dynamic_registration: Option<bool>,
}

/// Document link capabilities.
#[derive(Debug, Clone, Default)]
pub struct DocumentLinkCapabilities {
    pub dynamic_registration: Option<bool>,
    pub tooltip_support: Option<bool>,
}

/// Color provider capabilities.
#[derive(Debug, Clone, Default)]
pub struct ColorProviderCapabilities {
    pub dynamic_registration: Option<bool>,
}

/// Formatting capabilities.
#[derive(Debug, Clone, Default)]
pub struct FormattingCapabilities {
    pub dynamic_registration: Option<bool>,
}

/// Range formatting capabilities.
#[derive(Debug, Clone, Default)]
pub struct RangeFormattingCapabilities {
    pub dynamic_registration: Option<bool>,
}

/// On type formatting capabilities.
#[derive(Debug, Clone, Default)]
pub struct OnTypeFormattingCapabilities {
    pub dynamic_registration: Option<bool>,
}

/// Rename capabilities.
#[derive(Debug, Clone, Default)]
pub struct RenameCapabilities {
    pub dynamic_registration: Option<bool>,
    pub prepare_support: Option<bool>,
    pub prepare_support_default_behavior: Option<String>,
    pub honors_change_annotations: Option<bool>,
}

/// Folding range capabilities.
#[derive(Debug, Clone, Default)]
pub struct FoldingRangeCapabilities {
    pub dynamic_registration: Option<bool>,
    pub range_limit: Option<LspUint>,
    pub line_folding_only: Option<bool>,
    pub folding_range_kind: Option<FoldingRangeKindCapabilities>,
}

/// Folding range kind capabilities.
#[derive(Debug, Clone, Default)]
pub struct FoldingRangeKindCapabilities {
    pub value_set: Option<Vec<String>>,
}

/// Selection range capabilities.
#[derive(Debug, Clone, Default)]
pub struct SelectionRangeCapabilities {
    pub dynamic_registration: Option<bool>,
}

/// Publish diagnostics capabilities.
#[derive(Debug, Clone, Default)]
pub struct PublishDiagnosticsCapabilities {
    pub related_information: Option<bool>,
    pub tag_support: Option<TagSupport<DiagnosticTag>>,
    pub version_support: Option<bool>,
    pub code_description_support: Option<bool>,
    pub data_support: Option<bool>,
}

/// Call hierarchy capabilities.
#[derive(Debug, Clone, Default)]
pub struct CallHierarchyCapabilities {
    pub dynamic_registration: Option<bool>,
}

/// Semantic tokens capabilities.
#[derive(Debug, Clone, Default)]
pub struct SemanticTokensCapabilities {
    pub dynamic_registration: Option<bool>,
    pub requests: SemanticTokensRequestCapabilities,
    pub token_types: Vec<String>,
    pub token_modifiers: Vec<String>,
    pub formats: Vec<String>,
    pub overlapping_token_support: Option<bool>,
    pub multiline_token_support: Option<bool>,
    pub server_cancel_support: Option<bool>,
    pub augments_syntax_tokens: Option<bool>,
}

/// Semantic tokens request capabilities.
#[derive(Debug, Clone, Default)]
pub struct SemanticTokensRequestCapabilities {
    pub range: Option<bool>,
    pub full: Option<SemanticTokensFullCapabilities>,
}

/// Semantic tokens full capabilities.
#[derive(Debug, Clone, Default)]
pub struct SemanticTokensFullCapabilities {
    pub delta: Option<bool>,
}

/// Linked editing range capabilities.
#[derive(Debug, Clone, Default)]
pub struct LinkedEditingRangeCapabilities {
    pub dynamic_registration: Option<bool>,
}

/// Moniker capabilities.
#[derive(Debug, Clone, Default)]
pub struct MonikerCapabilities {
    pub dynamic_registration: Option<bool>,
}

/// Type hierarchy capabilities.
#[derive(Debug, Clone, Default)]
pub struct TypeHierarchyCapabilities {
    pub dynamic_registration: Option<bool>,
}

/// Inline value capabilities.
#[derive(Debug, Clone, Default)]
pub struct InlineValueCapabilities {
    pub dynamic_registration: Option<bool>,
}

/// Inlay hint capabilities.
#[derive(Debug, Clone, Default)]
pub struct InlayHintCapabilities {
    pub dynamic_registration: Option<bool>,
    pub resolve_support: Option<ResolveSupport>,
}

/// Diagnostic capabilities.
#[derive(Debug, Clone, Default)]
pub struct DiagnosticCapabilities {
    pub dynamic_registration: Option<bool>,
    pub related_document_support: Option<bool>,
}

/// Window client capabilities.
#[derive(Debug, Clone, Default)]
pub struct WindowClientCapabilities {
    pub work_done_progress: Option<bool>,
    pub show_message: Option<ShowMessageRequestCapabilities>,
    pub show_document: Option<ShowDocumentCapabilities>,
}

/// Show message request capabilities.
#[derive(Debug, Clone, Default)]
pub struct ShowMessageRequestCapabilities {
    pub message_action_item: Option<MessageActionItemCapabilities>,
}

/// Message action item capabilities.
#[derive(Debug, Clone, Default)]
pub struct MessageActionItemCapabilities {
    pub additional_properties_support: Option<bool>,
}

/// Show document capabilities.
#[derive(Debug, Clone, Default)]
pub struct ShowDocumentCapabilities {
    pub support: Option<bool>,
}

/// General client capabilities.
#[derive(Debug, Clone, Default)]
pub struct GeneralClientCapabilities {
    pub stale_request_support: Option<StaleRequestSupport>,
    pub regular_expressions: Option<RegularExpressionCapabilities>,
    pub markdown: Option<MarkdownCapabilities>,
    pub position_encodings: Option<Vec<String>>,
}

/// Stale request support.
#[derive(Debug, Clone, Default)]
pub struct StaleRequestSupport {
    pub cancel: bool,
    pub retry_on_content_modified: Vec<String>,
}

/// Regular expression capabilities.
#[derive(Debug, Clone, Default)]
pub struct RegularExpressionCapabilities {
    pub engine: String,
    pub version: Option<String>,
}

/// Markdown capabilities.
#[derive(Debug, Clone, Default)]
pub struct MarkdownCapabilities {
    pub parser: String,
    pub version: Option<String>,
    pub allowed_tags: Option<Vec<String>>,
}

/// Initialize result sent from server to client.
#[derive(Debug, Clone)]
pub struct InitializeResult {
    pub capabilities: ServerCapabilities,
    pub server_info: Option<ServerInfo>,
}

/// Server info.
#[derive(Debug, Clone)]
pub struct ServerInfo {
    pub name: String,
    pub version: Option<String>,
}

/// Server capabilities.
#[derive(Debug, Clone, Default)]
pub struct ServerCapabilities {
    pub text_document_sync: Option<TextDocumentSyncOptions>,
    pub completion_provider: Option<CompletionOptions>,
    pub hover_provider: Option<HoverOptions>,
    pub signature_help_provider: Option<SignatureHelpOptions>,
    pub declaration_provider: Option<DeclarationOptions>,
    pub definition_provider: Option<DefinitionOptions>,
    pub type_definition_provider: Option<TypeDefinitionOptions>,
    pub implementation_provider: Option<ImplementationOptions>,
    pub references_provider: Option<ReferenceOptions>,
    pub document_highlight_provider: Option<DocumentHighlightOptions>,
    pub document_symbol_provider: Option<DocumentSymbolOptions>,
    pub code_action_provider: Option<CodeActionOptions>,
    pub code_lens_provider: Option<CodeLensOptions>,
    pub document_link_provider: Option<DocumentLinkOptions>,
    pub color_provider: Option<ColorProviderOptions>,
    pub document_formatting_provider: Option<DocumentFormattingOptions>,
    pub document_range_formatting_provider: Option<DocumentRangeFormattingOptions>,
    pub document_on_type_formatting_provider: Option<DocumentOnTypeFormattingOptions>,
    pub rename_provider: Option<RenameOptions>,
    pub folding_range_provider: Option<FoldingRangeOptions>,
    pub selection_range_provider: Option<SelectionRangeOptions>,
    pub execute_command_provider: Option<ExecuteCommandOptions>,
    pub call_hierarchy_provider: Option<CallHierarchyOptions>,
    pub linked_editing_range_provider: Option<LinkedEditingRangeOptions>,
    pub semantic_tokens_provider: Option<SemanticTokensOptions>,
    pub moniker_provider: Option<MonikerOptions>,
    pub type_hierarchy_provider: Option<TypeHierarchyOptions>,
    pub inline_value_provider: Option<InlineValueOptions>,
    pub inlay_hint_provider: Option<InlayHintOptions>,
    pub diagnostic_provider: Option<DiagnosticOptions>,
    pub workspace_symbol_provider: Option<WorkspaceSymbolOptions>,
    pub workspace: Option<WorkspaceOptions>,
    pub experimental: Option<serde_json::Value>,
}

/// Text document sync options.
#[derive(Debug, Clone)]
pub enum TextDocumentSyncOptions {
    None,
    Full,
    Incremental,
    Kind(TextDocumentSyncKind),
}

/// Text document sync kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TextDocumentSyncKind {
    None,
    Full,
    Incremental,
}

/// Completion options.
#[derive(Debug, Clone, Default)]
pub struct CompletionOptions {
    pub trigger_characters: Option<Vec<String>>,
    pub all_commit_characters: Option<Vec<String>>,
    pub resolve_provider: Option<bool>,
    pub completion_item: Option<CompletionItemOptions>,
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Completion item options.
#[derive(Debug, Clone, Default)]
pub struct CompletionItemOptions {
    pub label_details_support: Option<bool>,
}

/// Work done progress options.
#[derive(Debug, Clone, Default)]
pub struct WorkDoneProgressOptions {
    pub work_done_progress: Option<bool>,
}

/// Hover options.
#[derive(Debug, Clone, Default)]
pub struct HoverOptions {
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Signature help options.
#[derive(Debug, Clone, Default)]
pub struct SignatureHelpOptions {
    pub trigger_characters: Option<Vec<String>>,
    pub retrigger_characters: Option<Vec<String>>,
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Declaration options.
#[derive(Debug, Clone, Default)]
pub struct DeclarationOptions {
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Definition options.
#[derive(Debug, Clone, Default)]
pub struct DefinitionOptions {
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Type definition options.
#[derive(Debug, Clone, Default)]
pub struct TypeDefinitionOptions {
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Implementation options.
#[derive(Debug, Clone, Default)]
pub struct ImplementationOptions {
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Reference options.
#[derive(Debug, Clone, Default)]
pub struct ReferenceOptions {
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Document highlight options.
#[derive(Debug, Clone, Default)]
pub struct DocumentHighlightOptions {
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Document symbol options.
#[derive(Debug, Clone, Default)]
pub struct DocumentSymbolOptions {
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
    pub label: Option<String>,
}

/// Code action options.
#[derive(Debug, Clone, Default)]
pub struct CodeActionOptions {
    pub code_action_kinds: Option<Vec<String>>,
    pub resolve_provider: Option<bool>,
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Code lens options.
#[derive(Debug, Clone, Default)]
pub struct CodeLensOptions {
    pub resolve_provider: Option<bool>,
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Document link options.
#[derive(Debug, Clone, Default)]
pub struct DocumentLinkOptions {
    pub resolve_provider: Option<bool>,
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Color provider options.
#[derive(Debug, Clone, Default)]
pub struct ColorProviderOptions {
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Document formatting options.
#[derive(Debug, Clone, Default)]
pub struct DocumentFormattingOptions {
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Document range formatting options.
#[derive(Debug, Clone, Default)]
pub struct DocumentRangeFormattingOptions {
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Document on type formatting options.
#[derive(Debug, Clone, Default)]
pub struct DocumentOnTypeFormattingOptions {
    pub first_trigger_character: String,
    pub more_trigger_character: Option<Vec<String>>,
}

/// Rename options.
#[derive(Debug, Clone, Default)]
pub struct RenameOptions {
    pub prepare_provider: Option<bool>,
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Folding range options.
#[derive(Debug, Clone, Default)]
pub struct FoldingRangeOptions {
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Selection range options.
#[derive(Debug, Clone, Default)]
pub struct SelectionRangeOptions {
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Execute command options.
#[derive(Debug, Clone, Default)]
pub struct ExecuteCommandOptions {
    pub commands: Vec<String>,
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Call hierarchy options.
#[derive(Debug, Clone, Default)]
pub struct CallHierarchyOptions {
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Linked editing range options.
#[derive(Debug, Clone, Default)]
pub struct LinkedEditingRangeOptions {
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Semantic tokens options.
#[derive(Debug, Clone, Default)]
pub struct SemanticTokensOptions {
    pub legend: SemanticTokensLegend,
    pub range: Option<bool>,
    pub full: Option<SemanticTokensFullOptions>,
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Semantic tokens legend.
#[derive(Debug, Clone)]
pub struct SemanticTokensLegend {
    pub token_types: Vec<String>,
    pub token_modifiers: Vec<String>,
}

/// Semantic tokens full options.
#[derive(Debug, Clone)]
pub struct SemanticTokensFullOptions {
    pub delta: Option<bool>,
}

/// Moniker options.
#[derive(Debug, Clone, Default)]
pub struct MonikerOptions {
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Type hierarchy options.
#[derive(Debug, Clone, Default)]
pub struct TypeHierarchyOptions {
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Inline value options.
#[derive(Debug, Clone, Default)]
pub struct InlineValueOptions {
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Inlay hint options.
#[derive(Debug, Clone, Default)]
pub struct InlayHintOptions {
    pub resolve_provider: Option<bool>,
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Diagnostic options.
#[derive(Debug, Clone, Default)]
pub struct DiagnosticOptions {
    pub identifier: Option<String>,
    pub inter_file_dependencies: bool,
    pub workspace_diagnostics: bool,
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Workspace symbol options.
#[derive(Debug, Clone, Default)]
pub struct WorkspaceSymbolOptions {
    pub resolve_provider: Option<bool>,
    pub work_done_progress_options: Option<WorkDoneProgressOptions>,
}

/// Workspace options.
#[derive(Debug, Clone)]
pub struct WorkspaceOptions {
    pub workspace_folders: Option<WorkspaceFoldersOptions>,
    pub file_operations: Option<FileOperationOptions>,
}

/// Workspace folders options.
#[derive(Debug, Clone, Default)]
pub struct WorkspaceFoldersOptions {
    pub supported: Option<bool>,
    pub change_notifications: Option<String>,
}

/// File operation options.
#[derive(Debug, Clone, Default)]
pub struct FileOperationOptions {
    pub did_create: Option<FileOperationRegistrationOptions>,
    pub will_create: Option<FileOperationRegistrationOptions>,
    pub did_rename: Option<FileOperationRegistrationOptions>,
    pub will_rename: Option<FileOperationRegistrationOptions>,
    pub did_delete: Option<FileOperationRegistrationOptions>,
    pub will_delete: Option<FileOperationRegistrationOptions>,
}

/// File operation registration options.
#[derive(Debug, Clone, Default)]
pub struct FileOperationRegistrationOptions {
    pub filters: Vec<FileOperationFilter>,
}

/// File operation filter.
#[derive(Debug, Clone, Default)]
pub struct FileOperationFilter {
    pub scheme: Option<String>,
    pub pattern: FileOperationPattern,
}

/// File operation pattern.
#[derive(Debug, Clone, Default)]
pub struct FileOperationPattern {
    pub glob: String,
    pub matches: Option<String>,
    pub options: Option<FileOperationPatternOptions>,
}

/// File operation pattern options.
#[derive(Debug, Clone, Default)]
pub struct FileOperationPatternOptions {
    pub ignore_case: Option<bool>,
}

// ============================================================================
// LSP — Text Document Operations
// ============================================================================

/// Did open text document notification parameters.
#[derive(Debug, Clone)]
pub struct DidOpenTextDocumentParams {
    pub text_document: TextDocumentItem,
}

/// Text document item.
#[derive(Debug, Clone)]
pub struct TextDocumentItem {
    pub uri: DocumentUri,
    pub language_id: String,
    pub version: LspInt,
    pub text: String,
}

/// Did change text document notification parameters.
#[derive(Debug, Clone)]
pub struct DidChangeTextDocumentParams {
    pub text_document: VersionedTextDocumentIdentifier,
    pub content_changes: Vec<TextDocumentContentChangeEvent>,
}

/// Text document content change event.
#[derive(Debug, Clone)]
pub struct TextDocumentContentChangeEvent {
    pub range: Option<Range>,
    pub range_length: Option<LspUint>,
    pub text: String,
}

/// Did close text document notification parameters.
#[derive(Debug, Clone)]
pub struct DidCloseTextDocumentParams {
    pub text_document: TextDocumentIdentifier,
}

/// Did save text document notification parameters.
#[derive(Debug, Clone)]
pub struct DidSaveTextDocumentParams {
    pub text_document: TextDocumentIdentifier,
    pub text: Option<String>,
}

/// Text document completion request parameters.
#[derive(Debug, Clone)]
pub struct CompletionParams {
    pub text_document: TextDocumentIdentifier,
    pub position: Position,
    pub context: Option<CompletionContext>,
}

/// Completion context.
#[derive(Debug, Clone)]
pub struct CompletionContext {
    pub trigger_kind: CompletionTriggerKind,
    pub trigger_character: Option<String>,
}

/// Completion trigger kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CompletionTriggerKind {
    Invoked,
    TriggerCharacter,
    TriggerForIncompleteCompletions,
}

/// Completion list response.
#[derive(Debug, Clone)]
pub struct CompletionList {
    pub is_incomplete: bool,
    pub items: Vec<CompletionItem>,
    pub item_defaults: Option<CompletionItemDefaults>,
}

/// Completion item defaults.
#[derive(Debug, Clone, Default)]
pub struct CompletionItemDefaults {
    pub commit_characters: Option<Vec<String>>,
    pub edit_range: Option<EditRange>,
    pub insert_text_format: Option<InsertTextFormat>,
    pub insert_text_mode: Option<InsertTextMode>,
    pub data: Option<serde_json::Value>,
}

/// Edit range.
#[derive(Debug, Clone)]
pub enum EditRange {
    Range(Range),
    InsertReplace { insert: Range, replace: Range },
}

/// Completion item.
#[derive(Debug, Clone)]
pub struct CompletionItem {
    pub label: String,
    pub label_details: Option<CompletionItemLabelDetails>,
    pub kind: Option<CompletionItemKind>,
    pub tags: Option<Vec<CompletionItemTag>>,
    pub detail: Option<String>,
    pub documentation: Option<MarkupContent>,
    pub deprecated: Option<bool>,
    pub preselect: Option<bool>,
    pub sort_text: Option<String>,
    pub filter_text: Option<String>,
    pub insert_text: Option<String>,
    pub insert_text_format: Option<InsertTextFormat>,
    pub insert_text_mode: Option<InsertTextMode>,
    pub text_edit: Option<TextEdit>,
    pub text_edit_text: Option<String>,
    pub additional_text_edits: Option<Vec<TextEdit>>,
    pub commit_characters: Option<Vec<String>>,
    pub command: Option<Command>,
    pub data: Option<serde_json::Value>,
}

/// Completion item label details.
#[derive(Debug, Clone)]
pub struct CompletionItemLabelDetails {
    pub detail: Option<String>,
    pub description: Option<String>,
}

/// Completion item kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CompletionItemKind {
    Text,
    Method,
    Function,
    Constructor,
    Field,
    Variable,
    Class,
    Interface,
    Module,
    Property,
    Unit,
    Value,
    Enum,
    Keyword,
    Snippet,
    Color,
    File,
    Reference,
    Folder,
    EnumMember,
    Constant,
    Struct,
    Event,
    Operator,
    TypeParameter,
}

/// Completion item tag.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CompletionItemTag {
    Deprecated,
}

/// Insert text format.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum InsertTextFormat {
    PlainText,
    Snippet,
}

/// Insert text mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum InsertTextMode {
    AsIs,
    AdjustIndentation,
}

/// Text edit.
#[derive(Debug, Clone)]
pub struct TextEdit {
    pub range: Range,
    pub new_text: String,
}

/// Markup content.
#[derive(Debug, Clone)]
pub struct MarkupContent {
    pub kind: MarkupKind,
    pub value: String,
}

/// Command.
#[derive(Debug, Clone)]
pub struct Command {
    pub title: String,
    pub command: String,
    pub arguments: Option<Vec<serde_json::Value>>,
}

/// Hover result.
#[derive(Debug, Clone)]
pub struct Hover {
    pub contents: MarkupContent,
    pub range: Option<Range>,
}

/// Definition result.
pub type DefinitionResult = Vec<Location>;

/// Reference parameters.
#[derive(Debug, Clone)]
pub struct ReferenceParams {
    pub text_document: TextDocumentIdentifier,
    pub position: Position,
    pub context: ReferenceContext,
}

/// Reference context.
#[derive(Debug, Clone)]
pub struct ReferenceContext {
    pub include_declaration: bool,
}

/// Rename parameters.
#[derive(Debug, Clone)]
pub struct RenameParams {
    pub text_document: TextDocumentIdentifier,
    pub position: Position,
    pub new_name: String,
}

/// Workspace edit.
#[derive(Debug, Clone)]
pub struct WorkspaceEdit {
    pub changes: Option<HashMap<DocumentUri, Vec<TextEdit>>>,
    pub document_changes: Option<Vec<TextDocumentEdit>>,
    pub change_annotations: Option<HashMap<String, ChangeAnnotation>>,
}

/// Text document edit.
#[derive(Debug, Clone)]
pub struct TextDocumentEdit {
    pub text_document: OptionalVersionedTextDocumentIdentifier,
    pub edits: Vec<TextEdit>,
}

/// Optional versioned text document identifier.
#[derive(Debug, Clone)]
pub struct OptionalVersionedTextDocumentIdentifier {
    pub uri: DocumentUri,
    pub version: Option<LspInt>,
}

/// Change annotation.
#[derive(Debug, Clone)]
pub struct ChangeAnnotation {
    pub label: String,
    pub needs_confirmation: Option<bool>,
    pub description: Option<String>,
}

/// Document formatting parameters.
#[derive(Debug, Clone)]
pub struct DocumentFormattingParams {
    pub text_document: TextDocumentIdentifier,
    pub options: FormattingOptions,
}

/// Formatting options.
#[derive(Debug, Clone)]
pub struct FormattingOptions {
    pub tab_size: LspUint,
    pub insert_spaces: bool,
    pub trim_trailing_whitespace: Option<bool>,
    pub insert_final_newline: Option<bool>,
    pub trim_final_newlines: Option<bool>,
    pub additional_properties: HashMap<String, serde_json::Value>,
}

/// Code action parameters.
#[derive(Debug, Clone)]
pub struct CodeActionParams {
    pub text_document: TextDocumentIdentifier,
    pub range: Range,
    pub context: CodeActionContext,
}

/// Code action context.
#[derive(Debug, Clone)]
pub struct CodeActionContext {
    pub diagnostics: Vec<Diagnostic>,
    pub only: Option<Vec<String>>,
    pub trigger_kind: Option<CodeActionTriggerKind>,
}

/// Code action trigger kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CodeActionTriggerKind {
    Invoked,
    Automatic,
}

/// Code action result.
#[derive(Debug, Clone)]
pub enum CodeActionResponse {
    Commands(Vec<Command>),
    CodeActions(Vec<CodeAction>),
}

/// Code action.
#[derive(Debug, Clone)]
pub struct CodeAction {
    pub title: String,
    pub kind: Option<String>,
    pub diagnostics: Option<Vec<Diagnostic>>,
    pub is_preferred: Option<bool>,
    pub disabled: Option<CodeActionDisabled>,
    pub edit: Option<WorkspaceEdit>,
    pub command: Option<Command>,
    pub data: Option<serde_json::Value>,
}

/// Code action disabled.
#[derive(Debug, Clone)]
pub struct CodeActionDisabled {
    pub reason: String,
}

/// Diagnostic.
#[derive(Debug, Clone)]
pub struct Diagnostic {
    pub range: Range,
    pub severity: Option<DiagnosticSeverity>,
    pub code: Option<DiagnosticCode>,
    pub code_description: Option<CodeDescription>,
    pub source: Option<String>,
    pub message: String,
    pub tags: Option<Vec<DiagnosticTag>>,
    pub related_information: Option<Vec<DiagnosticRelatedInformation>>,
    pub data: Option<serde_json::Value>,
}

/// Diagnostic severity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DiagnosticSeverity {
    Error,
    Warning,
    Information,
    Hint,
}

/// Diagnostic code (string or integer).
#[derive(Debug, Clone)]
pub enum DiagnosticCode {
    String(String),
    Number(LspInt),
}

/// Code description.
#[derive(Debug, Clone)]
pub struct CodeDescription {
    pub href: String,
}

/// Diagnostic tag.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DiagnosticTag {
    Unnecessary,
    Deprecated,
}

/// Diagnostic related information.
#[derive(Debug, Clone)]
pub struct DiagnosticRelatedInformation {
    pub location: Location,
    pub message: String,
}

/// Semantic tokens parameters.
#[derive(Debug, Clone)]
pub struct SemanticTokensParams {
    pub text_document: TextDocumentIdentifier,
}

/// Semantic tokens result.
#[derive(Debug, Clone)]
pub struct SemanticTokens {
    pub result_id: Option<String>,
    pub data: Vec<LspUint>,
}

/// Semantic tokens delta parameters.
#[derive(Debug, Clone)]
pub struct SemanticTokensDeltaParams {
    pub text_document: TextDocumentIdentifier,
    pub previous_result_id: String,
}

/// Semantic tokens delta result.
#[derive(Debug, Clone)]
pub struct SemanticTokensDelta {
    pub result_id: Option<String>,
    pub edits: Vec<SemanticTokensEdit>,
}

/// Semantic tokens edit.
#[derive(Debug, Clone)]
pub struct SemanticTokensEdit {
    pub start: LspUint,
    pub delete_count: LspUint,
    pub data: Option<Vec<LspUint>>,
}

/// Semantic token types for C/C++.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SemanticTokenType {
    Namespace,
    Type,
    Class,
    Enum,
    Interface,
    Struct,
    TypeParameter,
    Parameter,
    Variable,
    Property,
    EnumMember,
    Event,
    Function,
    Method,
    Macro,
    Keyword,
    Modifier,
    Comment,
    String,
    Number,
    Regexp,
    Operator,
    Decorator,
}

impl SemanticTokenType {
    pub fn as_index(&self) -> u32 {
        match self {
            Self::Namespace => 0,
            Self::Type => 1,
            Self::Class => 2,
            Self::Enum => 3,
            Self::Interface => 4,
            Self::Struct => 5,
            Self::TypeParameter => 6,
            Self::Parameter => 7,
            Self::Variable => 8,
            Self::Property => 9,
            Self::EnumMember => 10,
            Self::Event => 11,
            Self::Function => 12,
            Self::Method => 13,
            Self::Macro => 14,
            Self::Keyword => 15,
            Self::Modifier => 16,
            Self::Comment => 17,
            Self::String => 18,
            Self::Number => 19,
            Self::Regexp => 20,
            Self::Operator => 21,
            Self::Decorator => 22,
        }
    }
}

/// Semantic token modifiers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SemanticTokenModifier {
    Declaration,
    Definition,
    Readonly,
    Static,
    Deprecated,
    Abstract,
    Async,
    Modification,
    Documentation,
    DefaultLibrary,
}

impl SemanticTokenModifier {
    pub fn as_flag(&self) -> u32 {
        match self {
            Self::Declaration => 0,
            Self::Definition => 1,
            Self::Readonly => 2,
            Self::Static => 3,
            Self::Deprecated => 4,
            Self::Abstract => 5,
            Self::Async => 6,
            Self::Modification => 7,
            Self::Documentation => 8,
            Self::DefaultLibrary => 9,
        }
    }
}

// ============================================================================
// LSP — Document Symbols
// ============================================================================

/// Symbol kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SymbolKind {
    File,
    Module,
    Namespace,
    Package,
    Class,
    Method,
    Property,
    Field,
    Constructor,
    Enum,
    Interface,
    Function,
    Variable,
    Constant,
    String,
    Number,
    Boolean,
    Array,
    Object,
    Key,
    Null,
    EnumMember,
    Struct,
    Event,
    Operator,
    TypeParameter,
}

/// Symbol tag.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SymbolTag {
    Deprecated,
}

/// Document symbol response (hierarchical or flat).
#[derive(Debug, Clone)]
pub enum DocumentSymbolResponse {
    Flat(Vec<SymbolInformation>),
    Hierarchical(Vec<DocumentSymbol>),
}

/// Symbol information (flat).
#[derive(Debug, Clone)]
pub struct SymbolInformation {
    pub name: String,
    pub kind: SymbolKind,
    pub tags: Option<Vec<SymbolTag>>,
    pub deprecated: Option<bool>,
    pub location: Location,
    pub container_name: Option<String>,
}

/// Document symbol (hierarchical).
#[derive(Debug, Clone)]
pub struct DocumentSymbol {
    pub name: String,
    pub detail: Option<String>,
    pub kind: SymbolKind,
    pub tags: Option<Vec<SymbolTag>>,
    pub deprecated: Option<bool>,
    pub range: Range,
    pub selection_range: Range,
    pub children: Option<Vec<DocumentSymbol>>,
}

/// Workspace symbol parameters.
#[derive(Debug, Clone)]
pub struct WorkspaceSymbolParams {
    pub query: String,
}

// ============================================================================
// Clangd Language Server
// ============================================================================

/// The clangd language server state machine.
#[derive(Debug)]
pub struct ClangdServer {
    pub workspace_root: PathBuf,
    pub compilation_database: CompilationDatabase,
    pub documents: HashMap<DocumentUri, TextDocument>,
    pub index: CodeIndex,
    pub diagnostics: HashMap<DocumentUri, Vec<Diagnostic>>,
    pub config: ClangdConfig,
    pub status: ServerStatus,
    pub request_id: LspInt,
}

/// Clangd configuration.
#[derive(Debug, Clone)]
pub struct ClangdConfig {
    pub completion_style: CompletionStyle,
    pub header_insertion: HeaderInsertionPolicy,
    pub enable_auto_include: bool,
    pub cross_file_rename: CrossFileRename,
    pub enable_background_index: bool,
    pub background_index_priority: IndexPriority,
    pub clangd_tidy_enabled: bool,
    pub clangd_tidy_checks: Vec<String>,
    pub completion_all_scopes: bool,
    pub hover_show_akas: bool,
    pub inlay_hints_enabled: bool,
    pub inlay_hints_parameters: bool,
    pub inlay_hints_deduced_types: bool,
    pub inlay_hints_designators: bool,
    pub function_arg_placeholders: bool,
    pub insert_argument_placeholders: bool,
    pub limit_results: usize,
    pub limit_references: usize,
    pub use_dirty_headers: bool,
    pub compile_args: Vec<String>,
    pub fallback_flags: Vec<String>,
}

impl Default for ClangdConfig {
    fn default() -> Self {
        Self {
            completion_style: CompletionStyle::Detailed,
            header_insertion: HeaderInsertionPolicy::IWYU,
            enable_auto_include: true,
            cross_file_rename: CrossFileRename::Enabled,
            enable_background_index: true,
            background_index_priority: IndexPriority::Normal,
            clangd_tidy_enabled: true,
            clangd_tidy_checks: vec!["*".to_string(), "-modernize-use-trailing-return-type".to_string()],
            completion_all_scopes: true,
            hover_show_akas: true,
            inlay_hints_enabled: true,
            inlay_hints_parameters: true,
            inlay_hints_deduced_types: true,
            inlay_hints_designators: true,
            function_arg_placeholders: true,
            insert_argument_placeholders: true,
            limit_results: 100,
            limit_references: 1000,
            use_dirty_headers: true,
            compile_args: Vec::new(),
            fallback_flags: vec![
                "-std=c++17".to_string(),
                "-xc++".to_string(),
            ],
        }
    }
}

/// Completion style.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CompletionStyle {
    Detailed,
    Bundled,
}

/// Header insertion policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum HeaderInsertionPolicy {
    Never,
    IWYU,
    IncludeWhatYouUse,
}

/// Cross-file rename support.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CrossFileRename {
    None,
    Minimal,
    Enabled,
}

/// Index priority.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IndexPriority {
    Low,
    Normal,
    High,
    Background,
    Off,
}

/// Server status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ServerStatus {
    Starting,
    Initializing,
    BuildingIndex,
    Idle,
    ShuttingDown,
    Error(String),
}

/// A text document tracked by the server.
#[derive(Debug, Clone)]
pub struct TextDocument {
    pub uri: DocumentUri,
    pub language_id: String,
    pub version: LspInt,
    pub text: String,
    pub open: bool,
    pub modified: bool,
    pub parse_tree: Option<Box<serde_json::Value>>,
    pub ast: Option<Box<serde_json::Value>>,
    pub diagnostics: Vec<Diagnostic>,
}

impl TextDocument {
    pub fn new(uri: DocumentUri, language_id: String, text: String) -> Self {
        Self {
            uri,
            language_id,
            version: 0,
            text,
            open: true,
            modified: false,
            parse_tree: None,
            ast: None,
            diagnostics: Vec::new(),
        }
    }

    pub fn apply_changes(&mut self, changes: &[TextDocumentContentChangeEvent]) {
        for change in changes {
            match &change.range {
                Some(range) => {
                    // Apply incremental change
                    let start = Self::position_to_offset(&self.text, range.start);
                    let end = Self::position_to_offset(&self.text, range.end);
                    let mut new_text = String::with_capacity(
                        self.text.len() - (end - start) + change.text.len(),
                    );
                    new_text.push_str(&self.text[..start]);
                    new_text.push_str(&change.text);
                    new_text.push_str(&self.text[end..]);
                    self.text = new_text;
                }
                None => {
                    // Full document sync
                    self.text = change.text.clone();
                }
            }
        }
        self.modified = true;
    }

    fn position_to_offset(text: &str, pos: Position) -> usize {
        let mut offset = 0usize;
        let mut current_line = 0u64;
        for (i, ch) in text.char_indices() {
            if current_line == pos.line && offset == 0 {
                offset = i + pos.character as usize;
                break;
            }
            if ch == '\n' {
                current_line += 1;
                if current_line == pos.line {
                    offset = i + 1 + pos.character as usize;
                    break;
                }
            }
        }
        offset.min(text.len())
    }

    pub fn get_text_in_range(&self, range: Range) -> String {
        let start = Self::position_to_offset(&self.text, range.start);
        let end = Self::position_to_offset(&self.text, range.end);
        self.text[start..end].to_string()
    }

    pub fn get_line(&self, line: LspUint) -> Option<&str> {
        self.text.lines().nth(line as usize)
    }

    pub fn line_count(&self) -> usize {
        self.text.lines().count()
    }
}

impl ClangdServer {
    pub fn new(workspace_root: PathBuf) -> Self {
        Self {
            workspace_root: workspace_root.clone(),
            compilation_database: CompilationDatabase::new(workspace_root.join("compile_commands.json")),
            documents: HashMap::new(),
            index: CodeIndex::new(),
            diagnostics: HashMap::new(),
            config: ClangdConfig::default(),
            status: ServerStatus::Starting,
            request_id: 0,
        }
    }

    pub fn initialize(&mut self, params: &InitializeParams) -> InitializeResult {
        self.status = ServerStatus::Initializing;

        InitializeResult {
            capabilities: ServerCapabilities {
                text_document_sync: Some(TextDocumentSyncOptions::Kind(TextDocumentSyncKind::Incremental)),
                completion_provider: Some(CompletionOptions {
                    trigger_characters: Some(vec![
                        ".".to_string(), "->".to_string(), "::".to_string(),
                        ">".to_string(), ":".to_string(), "\"".to_string(),
                        "/".to_string(), "<".to_string(),
                    ]),
                    all_commit_characters: Some(vec![]),
                    resolve_provider: Some(true),
                    completion_item: Some(CompletionItemOptions { label_details_support: Some(true) }),
                    work_done_progress_options: Some(WorkDoneProgressOptions { work_done_progress: Some(false) }),
                }),
                hover_provider: Some(HoverOptions::default()),
                definition_provider: Some(DefinitionOptions::default()),
                references_provider: Some(ReferenceOptions::default()),
                document_highlight_provider: Some(DocumentHighlightOptions::default()),
                document_symbol_provider: Some(DocumentSymbolOptions::default()),
                workspace_symbol_provider: Some(WorkspaceSymbolOptions::default()),
                code_action_provider: Some(CodeActionOptions {
                    code_action_kinds: Some(vec![
                        "quickfix".to_string(),
                        "refactor".to_string(),
                        "refactor.extract".to_string(),
                        "refactor.inline".to_string(),
                    ]),
                    resolve_provider: Some(false),
                    work_done_progress_options: Some(WorkDoneProgressOptions { work_done_progress: Some(false) }),
                }),
                document_formatting_provider: Some(DocumentFormattingOptions::default()),
                document_range_formatting_provider: Some(DocumentRangeFormattingOptions::default()),
                document_on_type_formatting_provider: Some(DocumentOnTypeFormattingOptions {
                    first_trigger_character: "}".to_string(),
                    more_trigger_character: Some(vec![
                        ")".to_string(), "]".to_string(), ";".to_string(),
                    ]),
                }),
                rename_provider: Some(RenameOptions {
                    prepare_provider: Some(true),
                    work_done_progress_options: Some(WorkDoneProgressOptions::default()),
                }),
                semantic_tokens_provider: Some(SemanticTokensOptions {
                    legend: SemanticTokensLegend {
                        token_types: vec![
                            "namespace".to_string(), "type".to_string(), "class".to_string(),
                            "enum".to_string(), "interface".to_string(), "struct".to_string(),
                            "typeParameter".to_string(), "parameter".to_string(), "variable".to_string(),
                            "property".to_string(), "enumMember".to_string(), "event".to_string(),
                            "function".to_string(), "method".to_string(), "macro".to_string(),
                            "keyword".to_string(), "modifier".to_string(), "comment".to_string(),
                            "string".to_string(), "number".to_string(), "regexp".to_string(),
                            "operator".to_string(), "decorator".to_string(),
                        ],
                        token_modifiers: vec![
                            "declaration".to_string(), "definition".to_string(),
                            "readonly".to_string(), "static".to_string(),
                            "deprecated".to_string(), "abstract".to_string(),
                            "async".to_string(), "modification".to_string(),
                            "documentation".to_string(), "defaultLibrary".to_string(),
                        ],
                    },
                    range: Some(true),
                    full: Some(SemanticTokensFullOptions { delta: Some(true) }),
                    work_done_progress_options: Some(WorkDoneProgressOptions::default()),
                }),
                call_hierarchy_provider: Some(CallHierarchyOptions::default()),
                type_hierarchy_provider: Some(TypeHierarchyOptions::default()),
                inlay_hint_provider: Some(InlayHintOptions {
                    resolve_provider: Some(false),
                    work_done_progress_options: Some(WorkDoneProgressOptions::default()),
                }),
                ..Default::default()
            },
            server_info: Some(ServerInfo {
                name: "clangd-native".to_string(),
                version: Some("1.0.0".to_string()),
            }),
        }
    }

    pub fn did_open(&mut self, params: &DidOpenTextDocumentParams) {
        let doc = TextDocument::new(
            params.text_document.uri.clone(),
            params.text_document.language_id.clone(),
            params.text_document.text.clone(),
        );
        let uri = params.text_document.uri.clone();
        self.documents.insert(uri.clone(), doc);
        self.schedule_index(&uri);
    }

    pub fn did_change(&mut self, params: &DidChangeTextDocumentParams) {
        let uri = params.text_document.uri.clone();
        if let Some(doc) = self.documents.get_mut(&uri) {
            doc.version = params.text_document.version;
            doc.apply_changes(&params.content_changes);
        }
    }

    pub fn did_close(&mut self, params: &DidCloseTextDocumentParams) {
        let uri = params.text_document.uri.clone();
        if let Some(doc) = self.documents.get_mut(&uri) {
            doc.open = false;
        }
    }

    pub fn completion(&self, params: &CompletionParams) -> CompletionList {
        let uri = params.text_document.uri.clone();
        let mut items = Vec::new();

        // If we have the document, provide basic completions
        if let Some(_doc) = self.documents.get(&uri) {
            // C/C++ keyword completions
            let keywords = vec![
                "auto", "break", "case", "char", "const", "continue",
                "default", "do", "double", "else", "enum", "extern",
                "float", "for", "goto", "if", "int", "long", "register",
                "return", "short", "signed", "sizeof", "static", "struct",
                "switch", "typedef", "union", "unsigned", "void", "volatile",
                "while", "class", "namespace", "template", "typename",
                "public", "private", "protected", "virtual", "override",
                "final", "noexcept", "constexpr", "consteval", "decltype",
            ];
            for kw in keywords {
                items.push(CompletionItem {
                    label: kw.to_string(),
                    kind: Some(CompletionItemKind::Keyword),
                    insert_text: Some(kw.to_string()),
                    insert_text_format: Some(InsertTextFormat::PlainText),
                    sort_text: Some(format!("0_{}", kw)),
                    ..Default::default()
                });
            }

            // Also check the index for completions
            let indexed = self.index.find_completions(&uri, params.position);
            items.extend(indexed);
        }

        CompletionList {
            is_incomplete: true,
            items,
            item_defaults: None,
        }
    }

    pub fn hover(&self, params: &TextDocumentPositionParams) -> Option<Hover> {
        let uri = params.text_document.uri.clone();
        self.index
            .find_symbol_at_position(&uri, params.position)
            .map(|sym| Hover {
                contents: MarkupContent {
                    kind: MarkupKind::Markdown,
                    value: sym.hover_text(),
                },
                range: Some(sym.range),
            })
    }

    pub fn definition(&self, params: &TextDocumentPositionParams) -> Option<DefinitionResult> {
        let uri = params.text_document.uri.clone();
        self.index
            .find_definition(&uri, params.position)
            .map(|def| vec![def])
    }

    pub fn references(&self, params: &ReferenceParams) -> Option<Vec<Location>> {
        let uri = params.text_document.uri.clone();
        Some(self.index.find_references(&uri, params.position))
    }

    pub fn rename(&self, params: &RenameParams) -> Option<WorkspaceEdit> {
        let uri = params.text_document.uri.clone();
        let refs = self.index.find_references(&uri, params.position);
        if refs.is_empty() {
            return None;
        }

        let mut changes: HashMap<DocumentUri, Vec<TextEdit>> = HashMap::new();
        for loc in &refs {
            let edit = TextEdit {
                range: loc.range,
                new_text: params.new_name.clone(),
            };
            changes.entry(loc.uri.clone()).or_default().push(edit);
        }

        Some(WorkspaceEdit {
            changes: Some(changes),
            document_changes: None,
            change_annotations: None,
        })
    }

    pub fn formatting(&self, params: &DocumentFormattingParams) -> Option<Vec<TextEdit>> {
        let uri = params.text_document.uri.clone();
        if let Some(doc) = self.documents.get(&uri) {
            let edits = self.format_document(doc, &params.options);
            return Some(edits);
        }
        None
    }

    pub fn code_action(&self, params: &CodeActionParams) -> Option<CodeActionResponse> {
        let uri = params.text_document.uri.clone();
        let mut actions = Vec::new();

        // Generate quick fixes for diagnostics
        if let Some(diags) = self.diagnostics.get(&uri) {
            for diag in diags {
                if let Some(fix) = self.generate_quick_fix(diag) {
                    actions.push(fix);
                }
            }
        }

        if actions.is_empty() {
            None
        } else {
            Some(CodeActionResponse::CodeActions(actions))
        }
    }

    pub fn semantic_tokens_full(&self, params: &SemanticTokensParams) -> Option<SemanticTokens> {
        let uri = params.text_document.uri.clone();
        if let Some(doc) = self.documents.get(&uri) {
            let tokens = self.compute_semantic_tokens(doc);
            Some(SemanticTokens {
                result_id: Some(format!("{}", self.request_id)),
                data: tokens,
            })
        } else {
            None
        }
    }

    pub fn document_symbols(&self, uri: &DocumentUri) -> Option<DocumentSymbolResponse> {
        if let Some(_doc) = self.documents.get(uri) {
            let symbols = self.index.get_document_symbols(uri);
            if symbols.is_empty() {
                None
            } else {
                Some(DocumentSymbolResponse::Hierarchical(symbols))
            }
        } else {
            None
        }
    }

    pub fn workspace_symbols(&self, query: &str) -> Option<Vec<SymbolInformation>> {
        let results = self.index.search_workspace_symbols(query);
        if results.is_empty() {
            None
        } else {
            Some(results)
        }
    }

    fn schedule_index(&mut self, _uri: &DocumentUri) {
        if self.config.enable_background_index {
            // In a real implementation, this would spawn a background thread
            // to parse the file and update the index
        }
    }

    fn format_document(&self, _doc: &TextDocument, _options: &FormattingOptions) -> Vec<TextEdit> {
        Vec::new()
    }

    fn generate_quick_fix(&self, _diag: &Diagnostic) -> Option<CodeAction> {
        None
    }

    fn compute_semantic_tokens(&self, _doc: &TextDocument) -> Vec<LspUint> {
        Vec::new()
    }
}

impl CompletionItem {
    fn default() -> Self {
        Self {
            label: String::new(),
            label_details: None,
            kind: None,
            tags: None,
            detail: None,
            documentation: None,
            deprecated: None,
            preselect: None,
            sort_text: None,
            filter_text: None,
            insert_text: None,
            insert_text_format: None,
            insert_text_mode: None,
            text_edit: None,
            text_edit_text: None,
            additional_text_edits: None,
            commit_characters: None,
            command: None,
            data: None,
        }
    }
}

// ============================================================================
// Libclang C API — Full Wrapper
// ============================================================================

/// An opaque index object.
#[derive(Debug)]
pub struct CXIndex {
    pub exclude_declarations_from_pch: bool,
    pub display_diagnostics: bool,
    pub global_options: u32,
}

impl CXIndex {
    pub fn new(exclude_pch: bool, display_diags: bool) -> Self {
        Self {
            exclude_declarations_from_pch: exclude_pch,
            display_diagnostics: display_diags,
            global_options: 0,
        }
    }

    pub fn set_global_options(&mut self, options: u32) {
        self.global_options = options;
    }
}

/// A translation unit (parsed AST for a source file).
#[derive(Debug)]
pub struct ClangTranslationUnit {
    pub id: u64,
    pub source_file: PathBuf,
    pub clang_options: Vec<String>,
    pub unsaved_files: Vec<UnsavedFile>,
    pub diagnostics: Vec<ClangDiagnostic>,
    pub cursor: Option<ClangCursor>,
    pub tokens: Vec<ClangToken>,
}

/// An unsaved file in memory.
#[derive(Debug, Clone)]
pub struct UnsavedFile {
    pub filename: String,
    pub contents: String,
    pub length: usize,
}

/// A cursor representing an element in the AST.
#[derive(Debug, Clone)]
pub struct ClangCursor {
    pub kind: ClangCursorKind,
    pub spelling: String,
    pub display_name: String,
    pub usr: String,
    pub location: ClangSourceLocation,
    pub extent: ClangSourceRange,
    pub cursor_type: ClangCxType,
    pub linkage: ClangLinkageKind,
    pub availability: ClangAvailabilityKind,
    pub language: ClangLanguageKind,
    pub is_definition: bool,
    pub is_declaration: bool,
    pub is_reference: bool,
    pub is_expression: bool,
    pub is_statement: bool,
    pub is_attribute: bool,
    pub is_invalid: bool,
    pub is_translation_unit: bool,
    pub is_preprocessing: bool,
    pub is_unexposed: bool,
    pub hash: u64,
}

/// Cursor kinds (subset — full list has 200+ entries).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClangCursorKind {
    UnexposedDecl,
    StructDecl,
    UnionDecl,
    ClassDecl,
    EnumDecl,
    FieldDecl,
    EnumConstantDecl,
    FunctionDecl,
    VarDecl,
    ParmDecl,
    ObjCInterfaceDecl,
    ObjCCategoryDecl,
    ObjCProtocolDecl,
    ObjCPropertyDecl,
    ObjCIvarDecl,
    ObjCInstanceMethodDecl,
    ObjCClassMethodDecl,
    ObjCImplementationDecl,
    ObjCCategoryImplDecl,
    TypedefDecl,
    CXXMethod,
    Namespace,
    LinkageSpec,
    Constructor,
    Destructor,
    ConversionFunction,
    TemplateTypeParameter,
    TemplateTemplateParameter,
    TemplateNonTypeParameter,
    FunctionTemplate,
    ClassTemplate,
    ClassTemplatePartialSpecialization,
    NamespaceAlias,
    UsingDirective,
    UsingDeclaration,
    TypeAliasDecl,
    ObjCSynthesizeDecl,
    ObjCDynamicDecl,
    CXXAccessSpecifier,
    ObjCSuperClassRef,
    ObjCProtocolRef,
    ObjCClassRef,
    TypeRef,
    CXXBaseSpecifier,
    TemplateRef,
    NamespaceRef,
    MemberRef,
    LabelRef,
    OverloadedDeclRef,
    VariableRef,
    MacroDefinition,
    MacroExpansion,
    InclusionDirective,
    UnexposedExpr,
    DeclRefExpr,
    MemberRefExpr,
    CallExpr,
    ObjCMessageExpr,
    BlockExpr,
    IntegerLiteral,
    FloatingLiteral,
    ImaginaryLiteral,
    StringLiteral,
    CharacterLiteral,
    ParenExpr,
    UnaryOperator,
    ArraySubscriptExpr,
    BinaryOperator,
    CompoundAssignOperator,
    ConditionalOperator,
    CStyleCastExpr,
    CompoundLiteralExpr,
    InitListExpr,
    AddrLabelExpr,
    StmtExpr,
    GenericSelectionExpr,
    GNUNullExpr,
    CXXStaticCastExpr,
    CXXDynamicCastExpr,
    CXXReinterpretCastExpr,
    CXXConstCastExpr,
    CXXFunctionalCastExpr,
    CXXTypeidExpr,
    CXXBoolLiteralExpr,
    CXXNullPtrLiteralExpr,
    CXXThisExpr,
    CXXThrowExpr,
    CXXNewExpr,
    CXXDeleteExpr,
    UnaryExpr,
    ObjCStringLiteral,
    ObjCEncodeExpr,
    ObjCSelectorExpr,
    ObjCProtocolExpr,
    ObjCBridgedCastExpr,
    PackExpansionExpr,
    SizeOfPackExpr,
    LambdaExpr,
    ObjCBoolLiteralExpr,
    ObjCSelfExpr,
    OMPArraySectionExpr,
    ObjCAvailabilityCheckExpr,
    FixedPointLiteral,
    UnexposedStmt,
    LabelStmt,
    CompoundStmt,
    CaseStmt,
    DefaultStmt,
    IfStmt,
    SwitchStmt,
    WhileStmt,
    DoStmt,
    ForStmt,
    GotoStmt,
    IndirectGotoStmt,
    ContinueStmt,
    BreakStmt,
    ReturnStmt,
    AsmStmt,
    ObjCAtTryStmt,
    ObjCAtCatchStmt,
    ObjCAtFinallyStmt,
    ObjCAtThrowStmt,
    ObjCAtSynchronizedStmt,
    ObjCAutoreleasePoolStmt,
    ObjCForCollectionStmt,
    CXXCatchStmt,
    CXXTryStmt,
    CXXForRangeStmt,
    SEHTryStmt,
    SEHExceptStmt,
    SEHFinallyStmt,
    MSAsmStmt,
    NullStmt,
    DeclStmt,
    OMPParallelDirective,
    OMPSimdDirective,
    OMPForDirective,
    OMPSectionsDirective,
    OMPSectionDirective,
    OMPSingleDirective,
    OMPMasterDirective,
    OMPCriticalDirective,
    OMPTaskDirective,
    OMPParallelForDirective,
    OMPParallelSectionsDirective,
    OMPTaskyieldDirective,
    OMPBarrierDirective,
    OMPTaskwaitDirective,
    OMPFlushDirective,
    SEHLeaveStmt,
    OMPOrderedDirective,
    OMPAtomicDirective,
    OMPForSimdDirective,
    OMPParallelForSimdDirective,
    OMPTargetDirective,
    OMPTeamsDirective,
    OMPTaskgroupDirective,
    OMPCancellationPointDirective,
    OMPCancelDirective,
    OMPTargetDataDirective,
    OMPTaskLoopDirective,
    OMPTaskLoopSimdDirective,
    OMPDistributeDirective,
    OMPTargetEnterDataDirective,
    OMPTargetExitDataDirective,
    OMPTargetParallelDirective,
    OMPTargetParallelForDirective,
    OMPTargetUpdateDirective,
    OMPDistributeParallelForDirective,
    OMPDistributeParallelForSimdDirective,
    OMPDistributeSimdDirective,
    OMPTargetParallelForSimdDirective,
    OMPTargetSimdDirective,
    OMPTeamsDistributeDirective,
    OMPTeamsDistributeSimdDirective,
    OMPTeamsDistributeParallelForSimdDirective,
    OMPTeamsDistributeParallelForDirective,
    OMPTeamDirective,
    TranslationUnit,
    Attribute,
    ExtraDecl,
    OverloadCandidate,
}

/// Type representation.
#[derive(Debug, Clone)]
pub struct ClangCxType {
    pub kind: ClangTypeKind,
    pub spelling: String,
    pub size: usize,
    pub align: usize,
    pub is_const_qualified: bool,
    pub is_volatile_qualified: bool,
    pub is_restrict_qualified: bool,
    pub is_pod: bool,
    pub is_function_variadic: bool,
    pub is_null_ptr: bool,
    pub is_transparent_tag_typedef: bool,
    pub element_type: Option<Box<ClangCxType>>,
    pub num_elements: i64,
    pub result_type: Option<Box<ClangCxType>>,
    pub num_template_arguments: i32,
    pub template_argument_types: Vec<ClangCxType>,
    pub array_size: i64,
}

/// Type kinds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClangTypeKind {
    Invalid,
    Unexposed,
    Void,
    Bool,
    CharU,
    UChar,
    Char16,
    Char32,
    UShort,
    UInt,
    ULong,
    ULongLong,
    UInt128,
    CharS,
    SChar,
    WChar,
    Short,
    Int,
    Long,
    LongLong,
    Int128,
    Float,
    Double,
    LongDouble,
    NullPtr,
    Overload,
    Dependent,
    ObjCId,
    ObjCClass,
    ObjCSel,
    Float128,
    Half,
    Float16,
    ShortAccum,
    Accum,
    LongAccum,
    UShortAccum,
    UAccum,
    ULongAccum,
    BlockPointer,
    Pointer,
    LValueReference,
    RValueReference,
    Record,
    Enum,
    Typedef,
    ObjCInterface,
    ObjCObjectPointer,
    FunctionNoProto,
    FunctionProto,
    ConstantArray,
    Vector,
    IncompleteArray,
    VariableArray,
    DependentSizedArray,
    MemberPointer,
    Auto,
    Elaborated,
    Pipe,
    OCLImage1DRO,
    OCLImage1DArrayRO,
    OCLImage1DBufferRO,
    OCLImage2DRO,
    OCLImage2DArrayRO,
    OCLImage2DDepthRO,
    OCLImage2DArrayDepthRO,
    OCLImage2DMSAARO,
    OCLImage2DArrayMSAARO,
    OCLImage3DRO,
    OCLImage1DWO,
    OCLImage1DArrayWO,
    OCLImage1DBufferWO,
    OCLImage2DWO,
    OCLImage2DArrayWO,
    OCLImage2DDepthWO,
    OCLImage2DArrayDepthWO,
    OCLImage2DMSAAWO,
    OCLImage2DArrayMSAAWO,
    OCLImage3DWO,
    OCLImage1DRW,
    OCLImage1DArrayRW,
    OCLImage1DBufferRW,
    OCLImage2DRW,
    OCLImage2DArrayRW,
    OCLImage2DDepthRW,
    OCLImage2DArrayDepthRW,
    OCLImage2DMSAARW,
    OCLImage2DArrayMSAARW,
    OCLImage3DRW,
    OCLSampler,
    OCLEvent,
    OCLQueue,
    OCLReserveID,
    ObjCObject,
    ObjCTypeParam,
    Attributed,
    OCLIntelSubgroupAVCMcePayload,
    OCLIntelSubgroupAVCImePayload,
    OCLIntelSubgroupAVCRefPayload,
    OCLIntelSubgroupAVCSicPayload,
    OCLIntelSubgroupAVCMceResult,
    OCLIntelSubgroupAVCImeResult,
    OCLIntelSubgroupAVCRefResult,
    OCLIntelSubgroupAVCSicResult,
    OCLIntelSubgroupAVCImeResultSingleRefStreamOut,
    OCLIntelSubgroupAVCImeResultDualRefStreamOut,
    OCLIntelSubgroupAVCImeSingleRefStreamIn,
    OCLIntelSubgroupAVCImeDualRefStreamIn,
    ExtVector,
    Atomic,
    BTFTagAttributed,
}

/// Source location.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ClangSourceLocation {
    pub file: Option<&'static str>,
    pub line: u32,
    pub column: u32,
    pub offset: u32,
    pub is_in_system_header: bool,
    pub is_from_main_file: bool,
}

/// Source range.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ClangSourceRange {
    pub start: ClangSourceLocation,
    pub end: ClangSourceLocation,
}

/// Diagnostic.
#[derive(Debug, Clone)]
pub struct ClangDiagnostic {
    pub severity: ClangDiagnosticSeverity,
    pub message: String,
    pub location: ClangSourceLocation,
    pub spelling: String,
    pub option: String,
    pub category_text: String,
    pub fixits: Vec<ClangFixIt>,
    pub children: Vec<ClangDiagnostic>,
    pub ranges: Vec<ClangSourceRange>,
    pub format: ClangDiagnosticFormat,
}

/// Diagnostic severity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClangDiagnosticSeverity {
    Ignored,
    Note,
    Warning,
    Error,
    Fatal,
}

impl ClangDiagnosticSeverity {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Ignored => "ignored",
            Self::Note => "note",
            Self::Warning => "warning",
            Self::Error => "error",
            Self::Fatal => "fatal error",
        }
    }
}

/// Fix-it hint.
#[derive(Debug, Clone)]
pub struct ClangFixIt {
    pub range: ClangSourceRange,
    pub replacement: String,
}

/// Diagnostic format options.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClangDiagnosticFormat {
    Clang,
    MSVC,
    Vi,
}

/// Code completion results.
#[derive(Debug, Clone)]
pub struct ClangCodeCompleteResults {
    pub results: Vec<ClangCompletionResult>,
    pub num_diagnostics: u32,
    pub diagnostics: Vec<ClangDiagnostic>,
    pub context: u64,
}

/// Individual completion result.
#[derive(Debug, Clone)]
pub struct ClangCompletionResult {
    pub kind: ClangCursorKind,
    pub completion_string: ClangCompletionString,
    pub priority: u32,
}

/// Completion string with chunks.
#[derive(Debug, Clone)]
pub struct ClangCompletionString {
    pub text: String,
    pub kind: ClangCompletionChunkKind,
    pub chunks: Vec<ClangCompletionChunk>,
    pub availability: ClangAvailabilityKind,
    pub priority: u32,
}

/// Completion chunk.
#[derive(Debug, Clone)]
pub struct ClangCompletionChunk {
    pub kind: ClangCompletionChunkKind,
    pub text: String,
}

/// Completion chunk kinds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClangCompletionChunkKind {
    Optional,
    TypedText,
    Text,
    Placeholder,
    Informative,
    CurrentParameter,
    LeftParen,
    RightParen,
    LeftBracket,
    RightBracket,
    LeftBrace,
    RightBrace,
    LeftAngle,
    RightAngle,
    Comma,
    ResultType,
    Colon,
    SemiColon,
    Equal,
    HorizontalSpace,
    VerticalSpace,
}

/// Linkage kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClangLinkageKind {
    Invalid,
    NoLinkage,
    Internal,
    UniqueExternal,
    External,
}

/// Availability kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClangAvailabilityKind {
    Available,
    Deprecated,
    NotAvailable,
    NotAccessible,
}

/// Language kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClangLanguageKind {
    Invalid,
    C,
    CPlusPlus,
    ObjC,
}

/// Token representation.
#[derive(Debug, Clone)]
pub struct ClangToken {
    pub kind: ClangTokenKind,
    pub spelling: String,
    pub location: ClangSourceLocation,
    pub extent: ClangSourceRange,
}

/// Token kinds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClangTokenKind {
    Punctuation,
    Keyword,
    Identifier,
    Literal,
    Comment,
}

/// Module representation.
#[derive(Debug, Clone)]
pub struct ClangModule {
    pub name: String,
    pub full_name: String,
    pub is_system: bool,
    pub num_top_level_headers: u32,
    pub top_level_headers: Vec<String>,
    pub platform: Vec<String>,
    pub parent: Option<Box<ClangModule>>,
    pub ast_file: Option<PathBuf>,
}

// ============================================================================
// Compilation Database Watcher
// ============================================================================

/// Compilation database (compile_commands.json).
#[derive(Debug, Clone)]
pub struct CompilationDatabase {
    pub path: PathBuf,
    pub commands: Vec<CompileCommand>,
    pub last_modified: Option<SystemTime>,
    pub watcher_active: bool,
}

/// A single compilation command.
#[derive(Debug, Clone)]
pub struct CompileCommand {
    pub directory: PathBuf,
    pub file: PathBuf,
    pub arguments: Vec<String>,
    pub output: Option<PathBuf>,
}

impl CompilationDatabase {
    pub fn new(path: PathBuf) -> Self {
        Self {
            path,
            commands: Vec::new(),
            last_modified: None,
            watcher_active: false,
        }
    }

    pub fn load(&mut self) -> io::Result<()> {
        use std::fs;
        let content = fs::read_to_string(&self.path)?;
        let json: serde_json::Value = serde_json::from_str(&content)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;

        let mut commands = Vec::new();
        if let Some(arr) = json.as_array() {
            for entry in arr {
                let directory = entry["directory"]
                    .as_str()
                    .map(PathBuf::from)
                    .unwrap_or_default();
                let file = entry["file"]
                    .as_str()
                    .map(PathBuf::from)
                    .unwrap_or_default();
                let arguments: Vec<String> = if let Some(args) = entry["arguments"].as_array() {
                    args.iter()
                        .filter_map(|v| v.as_str().map(String::from))
                        .collect()
                } else if let Some(cmd) = entry["command"].as_str() {
                    cmd.split_whitespace().map(String::from).collect()
                } else {
                    Vec::new()
                };
                let output = entry["output"].as_str().map(PathBuf::from);

                commands.push(CompileCommand {
                    directory,
                    file,
                    arguments,
                    output,
                });
            }
        }

        self.commands = commands;
        self.last_modified = std::fs::metadata(&self.path)
            .ok()
            .and_then(|m| m.modified().ok());

        Ok(())
    }

    pub fn get_compile_args(&self, file: &PathBuf) -> Option<Vec<String>> {
        self.commands
            .iter()
            .find(|cmd| {
                cmd.file == *file
                    || cmd.file.ends_with(file.file_name().unwrap_or_default())
            })
            .map(|cmd| cmd.arguments.clone())
    }

    pub fn watch(&mut self) -> io::Result<()> {
        self.watcher_active = true;
        // In a real implementation: set up inotify/kqueue/FSEvents
        Ok(())
    }

    pub fn reload_if_changed(&mut self) -> io::Result<bool> {
        if let Ok(metadata) = std::fs::metadata(&self.path) {
            if let Ok(modified) = metadata.modified() {
                if self.last_modified != Some(modified) {
                    self.load()?;
                    return Ok(true);
                }
            }
        }
        Ok(false)
    }

    pub fn all_files(&self) -> Vec<PathBuf> {
        self.commands.iter().map(|c| c.file.clone()).collect()
    }

    pub fn find_commands_for_file(&self, file: &str) -> Vec<&CompileCommand> {
        self.commands
            .iter()
            .filter(|cmd| {
                cmd.file.to_string_lossy().contains(file)
            })
            .collect()
    }
}

// ============================================================================
// Background Indexing
// ============================================================================

/// Code index for fast symbol lookup.
#[derive(Debug)]
pub struct CodeIndex {
    pub symbols: HashMap<DocumentUri, Vec<IndexedSymbol>>,
    pub global_symbol_index: HashMap<String, Vec<IndexedSymbol>>,
    pub file_hashes: HashMap<DocumentUri, u64>,
    pub indexing_queue: VecDeque<IndexTask>,
    pub is_indexing: bool,
}

/// An indexed symbol entry.
#[derive(Debug, Clone)]
pub struct IndexedSymbol {
    pub name: String,
    pub qualified_name: String,
    pub kind: SymbolKind,
    pub range: Range,
    pub selection_range: Range,
    pub detail: Option<String>,
    pub documentation: Option<String>,
    pub parent: Option<String>,
    pub children: Vec<String>,
    pub usr: String,
    pub is_definition: bool,
    pub is_declaration: bool,
    pub references: Vec<Location>,
    pub definition_location: Option<Location>,
    pub type_info: Option<IndexedTypeInfo>,
}

/// Type information for indexed symbols.
#[derive(Debug, Clone)]
pub struct IndexedTypeInfo {
    pub type_name: String,
    pub pointee_type: Option<String>,
    pub return_type: Option<String>,
    pub param_types: Vec<String>,
    pub base_types: Vec<String>,
    pub is_const: bool,
    pub is_volatile: bool,
}

/// Background indexing task.
#[derive(Debug, Clone)]
pub struct IndexTask {
    pub uri: DocumentUri,
    pub priority: IndexPriority,
    pub created_at: Instant,
}

impl IndexedSymbol {
    pub fn hover_text(&self) -> String {
        let mut text = String::new();
        if let Some(detail) = &self.detail {
            text.push_str(&format!("```cpp\n{}\n```\n\n", detail));
        }
        if let Some(type_info) = &self.type_info {
            text.push_str(&format!("Type: `{}`\n\n", type_info.type_name));
        }
        if let Some(doc) = &self.documentation {
            text.push_str(doc);
        }
        if self.is_definition {
            text.push_str("\n\n*(Definition)*");
        }
        text
    }
}

impl CodeIndex {
    pub fn new() -> Self {
        Self {
            symbols: HashMap::new(),
            global_symbol_index: HashMap::new(),
            file_hashes: HashMap::new(),
            indexing_queue: VecDeque::new(),
            is_indexing: false,
        }
    }

    pub fn index_file(&mut self, uri: &DocumentUri, _content: &str) {
        // Parse the file and extract symbols
        let mut symbols = Vec::new();

        // Simple heuristic: look for C/C++ declarations
        let patterns = vec![
            ("class ", SymbolKind::Class),
            ("struct ", SymbolKind::Struct),
            ("enum ", SymbolKind::Enum),
            ("namespace ", SymbolKind::Namespace),
            ("void ", SymbolKind::Function),
            ("int ", SymbolKind::Function),
            ("bool ", SymbolKind::Function),
            ("auto ", SymbolKind::Function),
            ("float ", SymbolKind::Function),
            ("double ", SymbolKind::Function),
        ];

        for (pattern, kind) in patterns {
            if _content.contains(pattern) {
                symbols.push(IndexedSymbol {
                    name: format!("{}_{}", kind, symbols.len()),
                    qualified_name: format!("{}::{}", uri, kind),
                    kind,
                    range: Range::from_coords(0, 0, 0, 0),
                    selection_range: Range::from_coords(0, 0, 0, 0),
                    detail: Some(format!("Found {} declaration", pattern.trim())),
                    documentation: None,
                    parent: None,
                    children: Vec::new(),
                    usr: format!("c:@F@{}#I#", symbols.len()),
                    is_definition: false,
                    is_declaration: true,
                    references: Vec::new(),
                    definition_location: None,
                    type_info: None,
                });
            }
        }

        self.symbols.insert(uri.clone(), symbols);
    }

    pub fn find_completions(&self, _uri: &DocumentUri, _pos: Position) -> Vec<CompletionItem> {
        let mut items = Vec::new();
        // Look up local symbols
        if let Some(symbols) = self.symbols.get(_uri) {
            for sym in symbols {
                items.push(CompletionItem {
                    label: sym.name.clone(),
                    kind: Some(sym.kind_to_completion_kind()),
                    detail: sym.detail.clone(),
                    insert_text: Some(sym.name.clone()),
                    sort_text: Some(format!("1_{}", sym.name)),
                    ..Default::default()
                });
            }
        }
        items
    }

    pub fn find_symbol_at_position(&self, _uri: &DocumentUri, _pos: Position) -> Option<IndexedSymbol> {
        if let Some(symbols) = self.symbols.get(_uri) {
            symbols.iter().find(|s| s.range.covers(_pos)).cloned()
        } else {
            None
        }
    }

    pub fn find_definition(&self, _uri: &DocumentUri, _pos: Position) -> Option<Location> {
        self.find_symbol_at_position(_uri, _pos)
            .and_then(|sym| sym.definition_location.clone())
    }

    pub fn find_references(&self, _uri: &DocumentUri, _pos: Position) -> Vec<Location> {
        if let Some(sym) = self.find_symbol_at_position(_uri, _pos) {
            sym.references.clone()
        } else {
            Vec::new()
        }
    }

    pub fn get_document_symbols(&self, uri: &DocumentUri) -> Vec<DocumentSymbol> {
        if let Some(symbols) = self.symbols.get(uri) {
            symbols
                .iter()
                .map(|sym| DocumentSymbol {
                    name: sym.name.clone(),
                    detail: sym.detail.clone(),
                    kind: sym.kind,
                    tags: None,
                    deprecated: None,
                    range: sym.range,
                    selection_range: sym.selection_range,
                    children: None,
                })
                .collect()
        } else {
            Vec::new()
        }
    }

    pub fn search_workspace_symbols(&self, query: &str) -> Vec<SymbolInformation> {
        let query_lower = query.to_lowercase();
        let mut results = Vec::new();

        for (uri, symbols) in &self.symbols {
            for sym in symbols {
                if sym.name.to_lowercase().contains(&query_lower) {
                    results.push(SymbolInformation {
                        name: sym.name.clone(),
                        kind: sym.kind,
                        tags: None,
                        deprecated: None,
                        location: Location {
                            uri: uri.clone(),
                            range: sym.range,
                        },
                        container_name: sym.parent.clone(),
                    });
                }
            }
        }

        results.truncate(50);
        results
    }

    pub fn enqueue_index_task(&mut self, task: IndexTask) {
        self.indexing_queue.push_back(task);
    }

    pub fn process_index_queue(&mut self) -> usize {
        let mut processed = 0;
        while let Some(task) = self.indexing_queue.pop_front() {
            processed += 1;
            self.is_indexing = true;
            // Process task...
        }
        self.is_indexing = false;
        processed
    }
}

impl SymbolKind {
    pub fn kind_to_completion_kind(&self) -> CompletionItemKind {
        match self {
            Self::Class => CompletionItemKind::Class,
            Self::Struct => CompletionItemKind::Struct,
            Self::Enum => CompletionItemKind::Enum,
            Self::EnumMember => CompletionItemKind::EnumMember,
            Self::Function => CompletionItemKind::Function,
            Self::Method => CompletionItemKind::Method,
            Self::Property => CompletionItemKind::Property,
            Self::Field => CompletionItemKind::Field,
            Self::Variable => CompletionItemKind::Variable,
            Self::Constant => CompletionItemKind::Constant,
            Self::Interface => CompletionItemKind::Interface,
            Self::Module => CompletionItemKind::Module,
            Self::Namespace => CompletionItemKind::Module,
            Self::Constructor => CompletionItemKind::Constructor,
            Self::Operator => CompletionItemKind::Operator,
            Self::TypeParameter => CompletionItemKind::TypeParameter,
            _ => CompletionItemKind::Text,
        }
    }
}

impl fmt::Display for SymbolKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

// ============================================================================
// Inlay Hints
// ============================================================================

/// Inlay hint.
#[derive(Debug, Clone)]
pub struct InlayHint {
    pub position: Position,
    pub label: InlayHintLabel,
    pub kind: Option<InlayHintKind>,
    pub text_edits: Option<Vec<TextEdit>>,
    pub tooltip: Option<InlayHintTooltip>,
    pub padding_left: Option<bool>,
    pub padding_right: Option<bool>,
    pub data: Option<serde_json::Value>,
}

/// Inlay hint label.
#[derive(Debug, Clone)]
pub enum InlayHintLabel {
    String(String),
    Parts(Vec<InlayHintLabelPart>),
}

/// Inlay hint label part.
#[derive(Debug, Clone)]
pub struct InlayHintLabelPart {
    pub value: String,
    pub tooltip: Option<InlayHintTooltip>,
    pub location: Option<Location>,
    pub command: Option<Command>,
}

/// Inlay hint kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum InlayHintKind {
    Type,
    Parameter,
}

/// Inlay hint tooltip.
#[derive(Debug, Clone)]
pub enum InlayHintTooltip {
    String(String),
    MarkupContent(MarkupContent),
}

/// Compute inlay hints for a document.
pub fn compute_inlay_hints(config: &ClangdConfig, _document: &TextDocument) -> Vec<InlayHint> {
    let mut hints = Vec::new();

    if !config.inlay_hints_enabled {
        return hints;
    }

    // In a real implementation, we would:
    // 1. Parse the document's AST
    // 2. For each function call, add parameter name hints if enabled
    // 3. For each auto variable, add deduced type hints if enabled
    // 4. For each designated initializer, add field name hints if enabled

    if config.inlay_hints_parameters {
        // Add parameter hints
        // hints.push(...)
    }

    if config.inlay_hints_deduced_types {
        // Add auto deduction hints
        // hints.push(...)
    }

    if config.inlay_hints_designators {
        // Add designator hints
        // hints.push(...)
    }

    hints
}

// ============================================================================
// Call Hierarchy
// ============================================================================

/// Call hierarchy item.
#[derive(Debug, Clone)]
pub struct CallHierarchyItem {
    pub name: String,
    pub kind: SymbolKind,
    pub tags: Option<Vec<SymbolTag>>,
    pub detail: Option<String>,
    pub uri: DocumentUri,
    pub range: Range,
    pub selection_range: Range,
    pub data: Option<serde_json::Value>,
}

/// Call hierarchy incoming calls.
#[derive(Debug, Clone)]
pub struct CallHierarchyIncomingCall {
    pub from: CallHierarchyItem,
    pub from_ranges: Vec<Range>,
}

/// Call hierarchy outgoing calls.
#[derive(Debug, Clone)]
pub struct CallHierarchyOutgoingCall {
    pub to: CallHierarchyItem,
    pub from_ranges: Vec<Range>,
}

/// Type hierarchy item.
#[derive(Debug, Clone)]
pub struct TypeHierarchyItem {
    pub name: String,
    pub kind: SymbolKind,
    pub tags: Option<Vec<SymbolTag>>,
    pub detail: Option<String>,
    pub uri: DocumentUri,
    pub range: Range,
    pub selection_range: Range,
    pub data: Option<serde_json::Value>,
}

/// Type hierarchy subtypes/supertypes.
#[derive(Debug, Clone)]
pub struct TypeHierarchySubtype {
    pub item: TypeHierarchyItem,
}

/// Compute call hierarchy for a position.
pub fn compute_call_hierarchy(_index: &CodeIndex, _uri: &DocumentUri, _position: Position) -> Vec<CallHierarchyItem> {
    Vec::new()
}

/// Get incoming calls for a call hierarchy item.
pub fn call_hierarchy_incoming(_index: &CodeIndex, _item: &CallHierarchyItem) -> Vec<CallHierarchyIncomingCall> {
    Vec::new()
}

/// Get outgoing calls for a call hierarchy item.
pub fn call_hierarchy_outgoing(_index: &CodeIndex, _item: &CallHierarchyItem) -> Vec<CallHierarchyOutgoingCall> {
    Vec::new()
}

/// Compute type hierarchy for a position.
pub fn compute_type_hierarchy(_index: &CodeIndex, _uri: &DocumentUri, _position: Position) -> Vec<TypeHierarchyItem> {
    Vec::new()
}

/// Get supertypes for a type hierarchy item.
pub fn type_hierarchy_supertypes(_index: &CodeIndex, _item: &TypeHierarchyItem) -> Vec<TypeHierarchySubtype> {
    Vec::new()
}

/// Get subtypes for a type hierarchy item.
pub fn type_hierarchy_subtypes(_index: &CodeIndex, _item: &TypeHierarchyItem) -> Vec<TypeHierarchySubtype> {
    Vec::new()
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_position_display() {
        let pos = Position::new(10, 5);
        assert_eq!(format!("{}", pos), "10:5");
    }

    #[test]
    fn test_range_covers() {
        let range = Range::from_coords(1, 0, 5, 10);
        assert!(range.covers(Position::new(3, 5)));
        assert!(!range.covers(Position::new(0, 0)));
        assert!(!range.covers(Position::new(6, 0)));
        assert!(!range.covers(Position::new(1, 0)));
        assert!(range.covers(Position::new(1, 1)));
    }

    #[test]
    fn test_document_position_to_offset() {
        let doc = TextDocument::new(
            "file:///test.cpp".to_string(),
            "cpp".to_string(),
            "line one\nline two\nline three".to_string(),
        );
        let pos = Position::new(1, 1);
        let offset = TextDocument::position_to_offset(&doc.text, pos);
        assert!(offset > 0);
    }

    #[test]
    fn test_document_line_count() {
        let doc = TextDocument::new(
            "file:///test.cpp".to_string(),
            "cpp".to_string(),
            "line1\nline2\nline3".to_string(),
        );
        assert_eq!(doc.line_count(), 3);
    }

    #[test]
    fn test_document_apply_changes_full() {
        let mut doc = TextDocument::new(
            "file:///test.cpp".to_string(),
            "cpp".to_string(),
            "old content".to_string(),
        );
        let changes = vec![TextDocumentContentChangeEvent {
            range: None,
            range_length: None,
            text: "new content".to_string(),
        }];
        doc.apply_changes(&changes);
        assert_eq!(doc.text, "new content");
    }

    #[test]
    fn test_document_apply_changes_incremental() {
        let mut doc = TextDocument::new(
            "file:///test.cpp".to_string(),
            "cpp".to_string(),
            "hello world".to_string(),
        );
        let changes = vec![TextDocumentContentChangeEvent {
            range: Some(Range::from_coords(0, 6, 0, 11)),
            range_length: Some(5),
            text: "there".to_string(),
        }];
        doc.apply_changes(&changes);
        assert!(doc.text.contains("hello there"));
    }

    #[test]
    fn test_document_get_text_in_range() {
        let doc = TextDocument::new(
            "file:///test.cpp".to_string(),
            "cpp".to_string(),
            "hello world".to_string(),
        );
        let range = Range::from_coords(0, 0, 0, 5);
        let text = doc.get_text_in_range(range);
        assert_eq!(text, "hello");
    }

    #[test]
    fn test_compilation_database() {
        let mut db = CompilationDatabase::new(PathBuf::from("compile_commands.json"));
        assert!(!db.watcher_active);
        assert!(db.commands.is_empty());
    }

    #[test]
    fn test_clangd_server_initialize() {
        let server = ClangdServer::new(PathBuf::from("/tmp/test"));
        assert!(matches!(server.status, ServerStatus::Starting));
    }

    #[test]
    fn test_clangd_server_did_open() {
        let mut server = ClangdServer::new(PathBuf::from("/tmp/test"));
        let params = DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: "file:///test.cpp".to_string(),
                language_id: "cpp".to_string(),
                version: 1,
                text: "int main() { return 0; }".to_string(),
            },
        };
        server.did_open(&params);
        assert!(server.documents.contains_key("file:///test.cpp"));
    }

    #[test]
    fn test_clangd_server_completion() {
        let mut server = ClangdServer::new(PathBuf::from("/tmp/test"));
        let params = DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: "file:///test.cpp".to_string(),
                language_id: "cpp".to_string(),
                version: 1,
                text: "int main() { return 0; }".to_string(),
            },
        };
        server.did_open(&params);

        let comp_params = CompletionParams {
            text_document: TextDocumentIdentifier {
                uri: "file:///test.cpp".to_string(),
            },
            position: Position::new(0, 0),
            context: None,
        };
        let result = server.completion(&comp_params);
        assert!(!result.items.is_empty());
        assert!(result.is_incomplete);
    }

    #[test]
    fn test_clangd_config_default() {
        let config = ClangdConfig::default();
        assert!(config.enable_background_index);
        assert!(config.inlay_hints_enabled);
        assert_eq!(config.limit_results, 100);
    }

    #[test]
    fn test_initialize_result() {
        let mut server = ClangdServer::new(PathBuf::from("/tmp/test"));
        let params = InitializeParams {
            process_id: None,
            client_info: None,
            locale: None,
            root_path: None,
            root_uri: Some("file:///tmp/test".to_string()),
            initialization_options: None,
            capabilities: ClientCapabilities::default(),
            trace: Some(TraceValue::Off),
            workspace_folders: None,
        };
        let result = server.initialize(&params);
        assert!(result.server_info.is_some());
        assert!(result.capabilities.completion_provider.is_some());
        assert!(result.capabilities.semantic_tokens_provider.is_some());
    }

    #[test]
    fn test_cursor_kind_enum() {
        let kind = ClangCursorKind::FunctionDecl;
        assert_ne!(kind, ClangCursorKind::ClassDecl);
    }

    #[test]
    fn test_diagnostic_severity() {
        assert_eq!(ClangDiagnosticSeverity::Error.as_str(), "error");
        assert_eq!(ClangDiagnosticSeverity::Warning.as_str(), "warning");
        assert_eq!(ClangDiagnosticSeverity::Note.as_str(), "note");
    }

    #[test]
    fn test_completion_chunk_kind() {
        let kind = ClangCompletionChunkKind::TypedText;
        assert_ne!(kind, ClangCompletionChunkKind::Text);
    }

    #[test]
    fn test_symbol_kind_to_completion_kind() {
        assert_eq!(
            SymbolKind::Function.kind_to_completion_kind(),
            CompletionItemKind::Function
        );
        assert_eq!(
            SymbolKind::Class.kind_to_completion_kind(),
            CompletionItemKind::Class
        );
        assert_eq!(
            SymbolKind::Variable.kind_to_completion_kind(),
            CompletionItemKind::Variable
        );
    }

    #[test]
    fn test_code_index() {
        let mut index = CodeIndex::new();
        assert!(index.find_completions(&"test.cpp".to_string(), Position::new(0, 0)).is_empty());

        index.index_file(&"test.cpp".to_string(), "int main() { return 0; }");
        let syms = index.get_document_symbols(&"test.cpp".to_string());
        assert!(!syms.is_empty());
    }

    #[test]
    fn test_formatting_options() {
        let opts = FormattingOptions {
            tab_size: 4,
            insert_spaces: true,
            trim_trailing_whitespace: Some(true),
            insert_final_newline: Some(true),
            trim_final_newlines: Some(false),
            additional_properties: HashMap::new(),
        };
        assert_eq!(opts.tab_size, 4);
        assert!(opts.insert_spaces);
    }

    #[test]
    fn test_inlay_hint_creation() {
        let hint = InlayHint {
            position: Position::new(5, 10),
            label: InlayHintLabel::String("name:".to_string()),
            kind: Some(InlayHintKind::Parameter),
            text_edits: None,
            tooltip: None,
            padding_left: Some(true),
            padding_right: Some(false),
            data: None,
        };
        assert_eq!(hint.position.line, 5);
    }

    #[test]
    fn test_compilation_database_watch() {
        let mut db = CompilationDatabase::new(PathBuf::from("/tmp/nonexistent.json"));
        assert!(!db.watcher_active);
        let result = db.watch();
        assert!(result.is_ok());
        assert!(db.watcher_active);
    }

    #[test]
    fn test_compilation_database_find_files() {
        let mut db = CompilationDatabase::new(PathBuf::from("test.json"));
        db.commands = vec![
            CompileCommand {
                directory: PathBuf::from("/src"),
                file: PathBuf::from("/src/main.cpp"),
                arguments: vec!["clang++".to_string(), "-std=c++17".to_string(), "main.cpp".to_string()],
                output: Some(PathBuf::from("/src/main.o")),
            },
            CompileCommand {
                directory: PathBuf::from("/src"),
                file: PathBuf::from("/src/utils.cpp"),
                arguments: vec!["clang++".to_string(), "-std=c++17".to_string(), "utils.cpp".to_string()],
                output: None,
            },
        ];
        let files = db.all_files();
        assert_eq!(files.len(), 2);
        let cmds = db.find_commands_for_file("main");
        assert_eq!(cmds.len(), 1);
    }

    #[test]
    fn test_background_index_task() {
        let task = IndexTask {
            uri: "file:///test.cpp".to_string(),
            priority: IndexPriority::High,
            created_at: Instant::now(),
        };

        let mut index = CodeIndex::new();
        index.enqueue_index_task(task);
        assert_eq!(index.indexing_queue.len(), 1);

        let processed = index.process_index_queue();
        assert_eq!(processed, 1);
        assert!(index.indexing_queue.is_empty());
    }

    #[test]
    fn test_semantic_token_legend() {
        let legend = SemanticTokensLegend {
            token_types: vec!["namespace".to_string(), "type".to_string(), "function".to_string()],
            token_modifiers: vec!["declaration".to_string(), "definition".to_string()],
        };
        assert_eq!(legend.token_types.len(), 3);
        assert_eq!(legend.token_modifiers.len(), 2);
    }

    #[test]
    fn test_workspace_edit() {
        let mut changes = HashMap::new();
        changes.insert(
            "file:///test.cpp".to_string(),
            vec![TextEdit {
                range: Range::from_coords(0, 0, 0, 3),
                new_text: "foo".to_string(),
            }],
        );

        let edit = WorkspaceEdit {
            changes: Some(changes),
            document_changes: None,
            change_annotations: None,
        };
        assert!(edit.changes.is_some());
        assert_eq!(edit.changes.unwrap().len(), 1);
    }
}