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

use cfg::{CfgAtom, CfgDiff};
use dirs::config_dir;
use flycheck::{CargoOptions, FlycheckConfig};
use ide::{
    AssistConfig, CallableSnippets, CompletionConfig, DiagnosticsConfig, ExprFillDefaultMode,
    HighlightConfig, HighlightRelatedConfig, HoverConfig, HoverDocFormat, InlayFieldsToResolve,
    InlayHintsConfig, JoinLinesConfig, MemoryLayoutHoverConfig, MemoryLayoutHoverRenderKind,
    Snippet, SnippetScope, SourceRootId,
};
use ide_db::{
    imports::insert_use::{ImportGranularity, InsertUseConfig, PrefixKind},
    SnippetCap,
};
use indexmap::IndexMap;
use itertools::Itertools;
use lsp_types::{ClientCapabilities, MarkupKind};
use paths::{Utf8Path, Utf8PathBuf};
use project_model::{
    CargoConfig, CargoFeatures, ProjectJson, ProjectJsonData, ProjectManifest, RustLibSource,
};
use rustc_hash::{FxHashMap, FxHashSet};
use semver::Version;
use serde::{
    de::{DeserializeOwned, Error},
    Deserialize, Serialize,
};
use stdx::format_to_acc;
use triomphe::Arc;
use vfs::{AbsPath, AbsPathBuf, VfsPath};

use crate::{
    caps::completion_item_edit_resolve,
    diagnostics::DiagnosticsMapConfig,
    line_index::PositionEncoding,
    lsp_ext::{self, negotiated_encoding, WorkspaceSymbolSearchKind, WorkspaceSymbolSearchScope},
};

mod patch_old_style;

// Conventions for configuration keys to preserve maximal extendability without breakage:
//  - Toggles (be it binary true/false or with more options in-between) should almost always suffix as `_enable`
//    This has the benefit of namespaces being extensible, and if the suffix doesn't fit later it can be changed without breakage.
//  - In general be wary of using the namespace of something verbatim, it prevents us from adding subkeys in the future
//  - Don't use abbreviations unless really necessary
//  - foo_command = overrides the subcommand, foo_overrideCommand allows full overwriting, extra args only applies for foo_command

// Defines the server-side configuration of the rust-analyzer. We generate
// *parts* of VS Code's `package.json` config from this. Run `cargo test` to
// re-generate that file.
//
// However, editor specific config, which the server doesn't know about, should
// be specified directly in `package.json`.
//
// To deprecate an option by replacing it with another name use `new_name | `old_name` so that we keep
// parsing the old name.
config_data! {
    /// Configs that apply on a workspace-wide scope. There are 3 levels on which a global configuration can be configured
    // FIXME: 1. and 3. should be split, some configs do not make sense per project
    ///
    /// 1. `rust-analyzer.toml` file under user's config directory (e.g ~/.config/rust-analyzer.toml)
    /// 2. Client's own configurations (e.g `settings.json` on VS Code)
    /// 3. `rust-analyzer.toml` file located at the workspace root
    ///
    /// A config is searched for by traversing a "config tree" in a bottom up fashion. It is chosen by the nearest first principle.
    global: struct GlobalDefaultConfigData <- GlobalConfigInput -> {
        /// Warm up caches on project load.
        cachePriming_enable: bool = true,
        /// How many worker threads to handle priming caches. The default `0` means to pick automatically.
        cachePriming_numThreads: NumThreads = NumThreads::Physical,

        /// Pass `--all-targets` to cargo invocation.
        cargo_allTargets: bool           = true,
        /// Automatically refresh project info via `cargo metadata` on
        /// `Cargo.toml` or `.cargo/config.toml` changes.
        pub(crate) cargo_autoreload: bool           = true,
        /// Run build scripts (`build.rs`) for more precise code analysis.
        cargo_buildScripts_enable: bool  = true,
        /// Specifies the working directory for running build scripts.
        /// - "workspace": run build scripts for a workspace in the workspace's root directory.
        ///   This is incompatible with `#rust-analyzer.cargo.buildScripts.invocationStrategy#` set to `once`.
        /// - "root": run build scripts in the project's root directory.
        /// This config only has an effect when `#rust-analyzer.cargo.buildScripts.overrideCommand#`
        /// is set.
        cargo_buildScripts_invocationLocation: InvocationLocation = InvocationLocation::Workspace,
        /// Specifies the invocation strategy to use when running the build scripts command.
        /// If `per_workspace` is set, the command will be executed for each workspace.
        /// If `once` is set, the command will be executed once.
        /// This config only has an effect when `#rust-analyzer.cargo.buildScripts.overrideCommand#`
        /// is set.
        cargo_buildScripts_invocationStrategy: InvocationStrategy = InvocationStrategy::PerWorkspace,
        /// Override the command rust-analyzer uses to run build scripts and
        /// build procedural macros. The command is required to output json
        /// and should therefore include `--message-format=json` or a similar
        /// option.
        ///
        /// If there are multiple linked projects/workspaces, this command is invoked for
        /// each of them, with the working directory being the workspace root
        /// (i.e., the folder containing the `Cargo.toml`). This can be overwritten
        /// by changing `#rust-analyzer.cargo.buildScripts.invocationStrategy#` and
        /// `#rust-analyzer.cargo.buildScripts.invocationLocation#`.
        ///
        /// By default, a cargo invocation will be constructed for the configured
        /// targets and features, with the following base command line:
        ///
        /// ```bash
        /// cargo check --quiet --workspace --message-format=json --all-targets
        /// ```
        /// .
        cargo_buildScripts_overrideCommand: Option<Vec<String>> = None,
        /// Rerun proc-macros building/build-scripts running when proc-macro
        /// or build-script sources change and are saved.
        cargo_buildScripts_rebuildOnSave: bool = true,
        /// Use `RUSTC_WRAPPER=rust-analyzer` when running build scripts to
        /// avoid checking unnecessary things.
        cargo_buildScripts_useRustcWrapper: bool = true,
        /// List of cfg options to enable with the given values.
        cargo_cfgs: FxHashMap<String, Option<String>> = {
            let mut m = FxHashMap::default();
            m.insert("debug_assertions".to_owned(), None);
            m.insert("miri".to_owned(), None);
            m
        },
        /// Extra arguments that are passed to every cargo invocation.
        cargo_extraArgs: Vec<String> = vec![],
        /// Extra environment variables that will be set when running cargo, rustc
        /// or other commands within the workspace. Useful for setting RUSTFLAGS.
        cargo_extraEnv: FxHashMap<String, String> = FxHashMap::default(),
        /// List of features to activate.
        ///
        /// Set this to `"all"` to pass `--all-features` to cargo.
        cargo_features: CargoFeaturesDef      = CargoFeaturesDef::Selected(vec![]),
        /// Whether to pass `--no-default-features` to cargo.
        cargo_noDefaultFeatures: bool    = false,
        /// Relative path to the sysroot, or "discover" to try to automatically find it via
        /// "rustc --print sysroot".
        ///
        /// Unsetting this disables sysroot loading.
        ///
        /// This option does not take effect until rust-analyzer is restarted.
        cargo_sysroot: Option<String>    = Some("discover".to_owned()),
        /// Whether to run cargo metadata on the sysroot library allowing rust-analyzer to analyze
        /// third-party dependencies of the standard libraries.
        ///
        /// This will cause `cargo` to create a lockfile in your sysroot directory. rust-analyzer
        /// will attempt to clean up afterwards, but nevertheless requires the location to be
        /// writable to.
        cargo_sysrootQueryMetadata: bool     = false,
        /// Relative path to the sysroot library sources. If left unset, this will default to
        /// `{cargo.sysroot}/lib/rustlib/src/rust/library`.
        ///
        /// This option does not take effect until rust-analyzer is restarted.
        cargo_sysrootSrc: Option<String>    = None,
        /// Compilation target override (target triple).
        // FIXME(@poliorcetics): move to multiple targets here too, but this will need more work
        // than `checkOnSave_target`
        cargo_target: Option<String>     = None,
        /// Optional path to a rust-analyzer specific target directory.
        /// This prevents rust-analyzer's `cargo check` and initial build-script and proc-macro
        /// building from locking the `Cargo.lock` at the expense of duplicating build artifacts.
        ///
        /// Set to `true` to use a subdirectory of the existing target directory or
        /// set to a path relative to the workspace to use that path.
        cargo_targetDir | ra_ap_rust_analyzerTargetDir: Option<TargetDirectory> = None,

        /// Run the check command for diagnostics on save.
        checkOnSave | checkOnSave_enable: bool                         = true,

        /// Check all targets and tests (`--all-targets`). Defaults to
        /// `#rust-analyzer.cargo.allTargets#`.
        check_allTargets | checkOnSave_allTargets: Option<bool>          = None,
        /// Cargo command to use for `cargo check`.
        check_command | checkOnSave_command: String                      = "check".to_owned(),
        /// Extra arguments for `cargo check`.
        check_extraArgs | checkOnSave_extraArgs: Vec<String>             = vec![],
        /// Extra environment variables that will be set when running `cargo check`.
        /// Extends `#rust-analyzer.cargo.extraEnv#`.
        check_extraEnv | checkOnSave_extraEnv: FxHashMap<String, String> = FxHashMap::default(),
        /// List of features to activate. Defaults to
        /// `#rust-analyzer.cargo.features#`.
        ///
        /// Set to `"all"` to pass `--all-features` to Cargo.
        check_features | checkOnSave_features: Option<CargoFeaturesDef>  = None,
        /// List of `cargo check` (or other command specified in `check.command`) diagnostics to ignore.
        ///
        /// For example for `cargo check`: `dead_code`, `unused_imports`, `unused_variables`,...
        check_ignore: FxHashSet<String> = FxHashSet::default(),
        /// Specifies the working directory for running checks.
        /// - "workspace": run checks for workspaces in the corresponding workspaces' root directories.
        // FIXME: Ideally we would support this in some way
        ///   This falls back to "root" if `#rust-analyzer.check.invocationStrategy#` is set to `once`.
        /// - "root": run checks in the project's root directory.
        /// This config only has an effect when `#rust-analyzer.check.overrideCommand#`
        /// is set.
        check_invocationLocation | checkOnSave_invocationLocation: InvocationLocation = InvocationLocation::Workspace,
        /// Specifies the invocation strategy to use when running the check command.
        /// If `per_workspace` is set, the command will be executed for each workspace.
        /// If `once` is set, the command will be executed once.
        /// This config only has an effect when `#rust-analyzer.check.overrideCommand#`
        /// is set.
        check_invocationStrategy | checkOnSave_invocationStrategy: InvocationStrategy = InvocationStrategy::PerWorkspace,
        /// Whether to pass `--no-default-features` to Cargo. Defaults to
        /// `#rust-analyzer.cargo.noDefaultFeatures#`.
        check_noDefaultFeatures | checkOnSave_noDefaultFeatures: Option<bool>         = None,
        /// Override the command rust-analyzer uses instead of `cargo check` for
        /// diagnostics on save. The command is required to output json and
        /// should therefore include `--message-format=json` or a similar option
        /// (if your client supports the `colorDiagnosticOutput` experimental
        /// capability, you can use `--message-format=json-diagnostic-rendered-ansi`).
        ///
        /// If you're changing this because you're using some tool wrapping
        /// Cargo, you might also want to change
        /// `#rust-analyzer.cargo.buildScripts.overrideCommand#`.
        ///
        /// If there are multiple linked projects/workspaces, this command is invoked for
        /// each of them, with the working directory being the workspace root
        /// (i.e., the folder containing the `Cargo.toml`). This can be overwritten
        /// by changing `#rust-analyzer.check.invocationStrategy#` and
        /// `#rust-analyzer.check.invocationLocation#`.
        ///
        /// If `$saved_file` is part of the command, rust-analyzer will pass
        /// the absolute path of the saved file to the provided command. This is
        /// intended to be used with non-Cargo build systems.
        /// Note that `$saved_file` is experimental and may be removed in the future.
        ///
        /// An example command would be:
        ///
        /// ```bash
        /// cargo check --workspace --message-format=json --all-targets
        /// ```
        /// .
        check_overrideCommand | checkOnSave_overrideCommand: Option<Vec<String>>             = None,
        /// Check for specific targets. Defaults to `#rust-analyzer.cargo.target#` if empty.
        ///
        /// Can be a single target, e.g. `"x86_64-unknown-linux-gnu"` or a list of targets, e.g.
        /// `["aarch64-apple-darwin", "x86_64-apple-darwin"]`.
        ///
        /// Aliased as `"checkOnSave.targets"`.
        check_targets | checkOnSave_targets | checkOnSave_target: Option<CheckOnSaveTargets> = None,
        /// Whether `--workspace` should be passed to `cargo check`.
        /// If false, `-p <package>` will be passed instead.
        check_workspace: bool = true,

        /// List of rust-analyzer diagnostics to disable.
        diagnostics_disabled: FxHashSet<String> = FxHashSet::default(),
        /// Whether to show native rust-analyzer diagnostics.
        diagnostics_enable: bool                = true,
        /// Whether to show experimental rust-analyzer diagnostics that might
        /// have more false positives than usual.
        diagnostics_experimental_enable: bool    = false,
        /// Map of prefixes to be substituted when parsing diagnostic file paths.
        /// This should be the reverse mapping of what is passed to `rustc` as `--remap-path-prefix`.
        diagnostics_remapPrefix: FxHashMap<String, String> = FxHashMap::default(),
        /// Whether to run additional style lints.
        diagnostics_styleLints_enable: bool =    false,
        /// List of warnings that should be displayed with hint severity.
        ///
        /// The warnings will be indicated by faded text or three dots in code
        /// and will not show up in the `Problems Panel`.
        diagnostics_warningsAsHint: Vec<String> = vec![],
        /// List of warnings that should be displayed with info severity.
        ///
        /// The warnings will be indicated by a blue squiggly underline in code
        /// and a blue icon in the `Problems Panel`.
        diagnostics_warningsAsInfo: Vec<String> = vec![],

        /// These directories will be ignored by rust-analyzer. They are
        /// relative to the workspace root, and globs are not supported. You may
        /// also need to add the folders to Code's `files.watcherExclude`.
        files_excludeDirs: Vec<Utf8PathBuf> = vec![],


        /// Disable project auto-discovery in favor of explicitly specified set
        /// of projects.
        ///
        /// Elements must be paths pointing to `Cargo.toml`,
        /// `rust-project.json`, `.rs` files (which will be treated as standalone files) or JSON
        /// objects in `rust-project.json` format.
        linkedProjects: Vec<ManifestOrProjectJson> = vec![],

        /// Number of syntax trees rust-analyzer keeps in memory. Defaults to 128.
        lru_capacity: Option<usize>                 = None,
        /// Sets the LRU capacity of the specified queries.
        lru_query_capacities: FxHashMap<Box<str>, usize> = FxHashMap::default(),

        /// These proc-macros will be ignored when trying to expand them.
        ///
        /// This config takes a map of crate names with the exported proc-macro names to ignore as values.
        procMacro_ignored: FxHashMap<Box<str>, Box<[Box<str>]>>          = FxHashMap::default(),

        /// Command to be executed instead of 'cargo' for runnables.
        runnables_command: Option<String> = None,
        /// Additional arguments to be passed to cargo for runnables such as
        /// tests or binaries. For example, it may be `--release`.
        runnables_extraArgs: Vec<String>   = vec![],
        /// Additional arguments to be passed through Cargo to launched tests, benchmarks, or
        /// doc-tests.
        ///
        /// Unless the launched target uses a
        /// [custom test harness](https://doc.rust-lang.org/cargo/reference/cargo-targets.html#the-harness-field),
        /// they will end up being interpreted as options to
        /// [`rustc`’s built-in test harness (“libtest”)](https://doc.rust-lang.org/rustc/tests/index.html#cli-arguments).
        runnables_extraTestBinaryArgs: Vec<String> = vec!["--show-output".to_owned()],

        /// Path to the Cargo.toml of the rust compiler workspace, for usage in rustc_private
        /// projects, or "discover" to try to automatically find it if the `rustc-dev` component
        /// is installed.
        ///
        /// Any project which uses rust-analyzer with the rustcPrivate
        /// crates must set `[package.metadata.rust-analyzer] rustc_private=true` to use it.
        ///
        /// This option does not take effect until rust-analyzer is restarted.
        rustc_source: Option<String> = None,

        /// Additional arguments to `rustfmt`.
        rustfmt_extraArgs: Vec<String>               = vec![],
        /// Advanced option, fully override the command rust-analyzer uses for
        /// formatting. This should be the equivalent of `rustfmt` here, and
        /// not that of `cargo fmt`. The file contents will be passed on the
        /// standard input and the formatted result will be read from the
        /// standard output.
        rustfmt_overrideCommand: Option<Vec<String>> = None,
        /// Enables the use of rustfmt's unstable range formatting command for the
        /// `textDocument/rangeFormatting` request. The rustfmt option is unstable and only
        /// available on a nightly build.
        rustfmt_rangeFormatting_enable: bool = false,
    }
}

config_data! {
    /// Local configurations can be defined per `SourceRoot`. This almost always corresponds to a `Crate`.
    local: struct LocalDefaultConfigData <- LocalConfigInput ->  {
        /// Whether to insert #[must_use] when generating `as_` methods
        /// for enum variants.
        assist_emitMustUse: bool               = false,
        /// Placeholder expression to use for missing expressions in assists.
        assist_expressionFillDefault: ExprFillDefaultDef              = ExprFillDefaultDef::Todo,
        /// Term search fuel in "units of work" for assists (Defaults to 400).
        assist_termSearch_fuel: usize = 400,

        /// Whether to enforce the import granularity setting for all files. If set to false rust-analyzer will try to keep import styles consistent per file.
        imports_granularity_enforce: bool              = false,
        /// How imports should be grouped into use statements.
        imports_granularity_group: ImportGranularityDef  = ImportGranularityDef::Crate,
        /// Group inserted imports by the https://rust-analyzer.github.io/manual.html#auto-import[following order]. Groups are separated by newlines.
        imports_group_enable: bool                           = true,
        /// Whether to allow import insertion to merge new imports into single path glob imports like `use std::fmt::*;`.
        imports_merge_glob: bool           = true,
        /// Prefer to unconditionally use imports of the core and alloc crate, over the std crate.
        imports_preferNoStd | imports_prefer_no_std: bool = false,
         /// Whether to prefer import paths containing a `prelude` module.
        imports_preferPrelude: bool                       = false,
        /// The path structure for newly inserted paths to use.
        imports_prefix: ImportPrefixDef               = ImportPrefixDef::Plain,
    }
}

config_data! {
    /// Configs that only make sense when they are set by a client. As such they can only be defined
    /// by setting them using client's settings (e.g `settings.json` on VS Code).
    client: struct ClientDefaultConfigData <- ClientConfigInput -> {
        /// Toggles the additional completions that automatically add imports when completed.
        /// Note that your client must specify the `additionalTextEdits` LSP client capability to truly have this feature enabled.
        completion_autoimport_enable: bool       = true,
        /// Toggles the additional completions that automatically show method calls and field accesses
        /// with `self` prefixed to them when inside a method.
        completion_autoself_enable: bool        = true,
        /// Whether to add parenthesis and argument snippets when completing function.
        completion_callable_snippets: CallableCompletionDef  = CallableCompletionDef::FillArguments,
        /// Whether to show full function/method signatures in completion docs.
        completion_fullFunctionSignatures_enable: bool = false,
        /// Maximum number of completions to return. If `None`, the limit is infinite.
        completion_limit: Option<usize> = None,
        /// Whether to show postfix snippets like `dbg`, `if`, `not`, etc.
        completion_postfix_enable: bool         = true,
        /// Enables completions of private items and fields that are defined in the current workspace even if they are not visible at the current position.
        completion_privateEditable_enable: bool = false,
        /// Custom completion snippets.
        // NOTE: we use IndexMap for deterministic serialization ordering
        completion_snippets_custom: IndexMap<String, SnippetDef> = serde_json::from_str(r#"{
            "Arc::new": {
                "postfix": "arc",
                "body": "Arc::new(${receiver})",
                "requires": "std::sync::Arc",
                "description": "Put the expression into an `Arc`",
                "scope": "expr"
            },
            "Rc::new": {
                "postfix": "rc",
                "body": "Rc::new(${receiver})",
                "requires": "std::rc::Rc",
                "description": "Put the expression into an `Rc`",
                "scope": "expr"
            },
            "Box::pin": {
                "postfix": "pinbox",
                "body": "Box::pin(${receiver})",
                "requires": "std::boxed::Box",
                "description": "Put the expression into a pinned `Box`",
                "scope": "expr"
            },
            "Ok": {
                "postfix": "ok",
                "body": "Ok(${receiver})",
                "description": "Wrap the expression in a `Result::Ok`",
                "scope": "expr"
            },
            "Err": {
                "postfix": "err",
                "body": "Err(${receiver})",
                "description": "Wrap the expression in a `Result::Err`",
                "scope": "expr"
            },
            "Some": {
                "postfix": "some",
                "body": "Some(${receiver})",
                "description": "Wrap the expression in an `Option::Some`",
                "scope": "expr"
            }
        }"#).unwrap(),
        /// Whether to enable term search based snippets like `Some(foo.bar().baz())`.
        completion_termSearch_enable: bool = false,
        /// Term search fuel in "units of work" for autocompletion (Defaults to 200).
        completion_termSearch_fuel: usize = 200,

        /// Controls file watching implementation.
        files_watcher: FilesWatcherDef = FilesWatcherDef::Client,

        /// Enables highlighting of related references while the cursor is on `break`, `loop`, `while`, or `for` keywords.
        highlightRelated_breakPoints_enable: bool = true,
        /// Enables highlighting of all captures of a closure while the cursor is on the `|` or move keyword of a closure.
        highlightRelated_closureCaptures_enable: bool = true,
        /// Enables highlighting of all exit points while the cursor is on any `return`, `?`, `fn`, or return type arrow (`->`).
        highlightRelated_exitPoints_enable: bool = true,
        /// Enables highlighting of related references while the cursor is on any identifier.
        highlightRelated_references_enable: bool = true,
        /// Enables highlighting of all break points for a loop or block context while the cursor is on any `async` or `await` keywords.
        highlightRelated_yieldPoints_enable: bool = true,

        /// Whether to show `Debug` action. Only applies when
        /// `#rust-analyzer.hover.actions.enable#` is set.
        hover_actions_debug_enable: bool           = true,
        /// Whether to show HoverActions in Rust files.
        hover_actions_enable: bool          = true,
        /// Whether to show `Go to Type Definition` action. Only applies when
        /// `#rust-analyzer.hover.actions.enable#` is set.
        hover_actions_gotoTypeDef_enable: bool     = true,
        /// Whether to show `Implementations` action. Only applies when
        /// `#rust-analyzer.hover.actions.enable#` is set.
        hover_actions_implementations_enable: bool = true,
        /// Whether to show `References` action. Only applies when
        /// `#rust-analyzer.hover.actions.enable#` is set.
        hover_actions_references_enable: bool      = false,
        /// Whether to show `Run` action. Only applies when
        /// `#rust-analyzer.hover.actions.enable#` is set.
        hover_actions_run_enable: bool             = true,

        /// Whether to show documentation on hover.
        hover_documentation_enable: bool           = true,
        /// Whether to show keyword hover popups. Only applies when
        /// `#rust-analyzer.hover.documentation.enable#` is set.
        hover_documentation_keywords_enable: bool  = true,
        /// Use markdown syntax for links on hover.
        hover_links_enable: bool = true,
        /// How to render the align information in a memory layout hover.
        hover_memoryLayout_alignment: Option<MemoryLayoutHoverRenderKindDef> = Some(MemoryLayoutHoverRenderKindDef::Hexadecimal),
        /// Whether to show memory layout data on hover.
        hover_memoryLayout_enable: bool = true,
        /// How to render the niche information in a memory layout hover.
        hover_memoryLayout_niches: Option<bool> = Some(false),
        /// How to render the offset information in a memory layout hover.
        hover_memoryLayout_offset: Option<MemoryLayoutHoverRenderKindDef> = Some(MemoryLayoutHoverRenderKindDef::Hexadecimal),
        /// How to render the size information in a memory layout hover.
        hover_memoryLayout_size: Option<MemoryLayoutHoverRenderKindDef> = Some(MemoryLayoutHoverRenderKindDef::Both),

        /// How many variants of an enum to display when hovering on. Show none if empty.
        hover_show_enumVariants: Option<usize> = Some(5),
        /// How many fields of a struct, variant or union to display when hovering on. Show none if empty.
        hover_show_fields: Option<usize> = Some(5),
        /// How many associated items of a trait to display when hovering a trait.
        hover_show_traitAssocItems: Option<usize> = None,

        /// Whether to show inlay type hints for binding modes.
        inlayHints_bindingModeHints_enable: bool                   = false,
        /// Whether to show inlay type hints for method chains.
        inlayHints_chainingHints_enable: bool                      = true,
        /// Whether to show inlay hints after a closing `}` to indicate what item it belongs to.
        inlayHints_closingBraceHints_enable: bool                  = true,
        /// Minimum number of lines required before the `}` until the hint is shown (set to 0 or 1
        /// to always show them).
        inlayHints_closingBraceHints_minLines: usize               = 25,
        /// Whether to show inlay hints for closure captures.
        inlayHints_closureCaptureHints_enable: bool                          = false,
        /// Whether to show inlay type hints for return types of closures.
        inlayHints_closureReturnTypeHints_enable: ClosureReturnTypeHintsDef  = ClosureReturnTypeHintsDef::Never,
        /// Closure notation in type and chaining inlay hints.
        inlayHints_closureStyle: ClosureStyle                                = ClosureStyle::ImplFn,
        /// Whether to show enum variant discriminant hints.
        inlayHints_discriminantHints_enable: DiscriminantHintsDef            = DiscriminantHintsDef::Never,
        /// Whether to show inlay hints for type adjustments.
        inlayHints_expressionAdjustmentHints_enable: AdjustmentHintsDef = AdjustmentHintsDef::Never,
        /// Whether to hide inlay hints for type adjustments outside of `unsafe` blocks.
        inlayHints_expressionAdjustmentHints_hideOutsideUnsafe: bool = false,
        /// Whether to show inlay hints as postfix ops (`.*` instead of `*`, etc).
        inlayHints_expressionAdjustmentHints_mode: AdjustmentHintsModeDef = AdjustmentHintsModeDef::Prefix,
        /// Whether to show implicit drop hints.
        inlayHints_implicitDrops_enable: bool                      = false,
        /// Whether to show inlay type hints for elided lifetimes in function signatures.
        inlayHints_lifetimeElisionHints_enable: LifetimeElisionDef = LifetimeElisionDef::Never,
        /// Whether to prefer using parameter names as the name for elided lifetime hints if possible.
        inlayHints_lifetimeElisionHints_useParameterNames: bool    = false,
        /// Maximum length for inlay hints. Set to null to have an unlimited length.
        inlayHints_maxLength: Option<usize>                        = Some(25),
        /// Whether to show function parameter name inlay hints at the call
        /// site.
        inlayHints_parameterHints_enable: bool                     = true,
        /// Whether to show exclusive range inlay hints.
        inlayHints_rangeExclusiveHints_enable: bool                = false,
        /// Whether to show inlay hints for compiler inserted reborrows.
        /// This setting is deprecated in favor of #rust-analyzer.inlayHints.expressionAdjustmentHints.enable#.
        inlayHints_reborrowHints_enable: ReborrowHintsDef          = ReborrowHintsDef::Never,
        /// Whether to render leading colons for type hints, and trailing colons for parameter hints.
        inlayHints_renderColons: bool                              = true,
        /// Whether to show inlay type hints for variables.
        inlayHints_typeHints_enable: bool                          = true,
        /// Whether to hide inlay type hints for `let` statements that initialize to a closure.
        /// Only applies to closures with blocks, same as `#rust-analyzer.inlayHints.closureReturnTypeHints.enable#`.
        inlayHints_typeHints_hideClosureInitialization: bool       = false,
        /// Whether to hide inlay type hints for constructors.
        inlayHints_typeHints_hideNamedConstructor: bool            = false,

        /// Enables the experimental support for interpreting tests.
        interpret_tests: bool = false,

        /// Join lines merges consecutive declaration and initialization of an assignment.
        joinLines_joinAssignments: bool = true,
        /// Join lines inserts else between consecutive ifs.
        joinLines_joinElseIf: bool = true,
        /// Join lines removes trailing commas.
        joinLines_removeTrailingComma: bool = true,
        /// Join lines unwraps trivial blocks.
        joinLines_unwrapTrivialBlock: bool = true,

        /// Whether to show `Debug` lens. Only applies when
        /// `#rust-analyzer.lens.enable#` is set.
        lens_debug_enable: bool            = true,
        /// Whether to show CodeLens in Rust files.
        lens_enable: bool           = true,
        /// Internal config: use custom client-side commands even when the
        /// client doesn't set the corresponding capability.
        lens_forceCustomCommands: bool = true,
        /// Whether to show `Implementations` lens. Only applies when
        /// `#rust-analyzer.lens.enable#` is set.
        lens_implementations_enable: bool  = true,
        /// Where to render annotations.
        lens_location: AnnotationLocation = AnnotationLocation::AboveName,
        /// Whether to show `References` lens for Struct, Enum, and Union.
        /// Only applies when `#rust-analyzer.lens.enable#` is set.
        lens_references_adt_enable: bool = false,
        /// Whether to show `References` lens for Enum Variants.
        /// Only applies when `#rust-analyzer.lens.enable#` is set.
        lens_references_enumVariant_enable: bool = false,
        /// Whether to show `Method References` lens. Only applies when
        /// `#rust-analyzer.lens.enable#` is set.
        lens_references_method_enable: bool = false,
        /// Whether to show `References` lens for Trait.
        /// Only applies when `#rust-analyzer.lens.enable#` is set.
        lens_references_trait_enable: bool = false,
        /// Whether to show `Run` lens. Only applies when
        /// `#rust-analyzer.lens.enable#` is set.
        lens_run_enable: bool              = true,

        /// Whether to show `can't find Cargo.toml` error message.
        notifications_cargoTomlNotFound: bool      = true,

        /// Whether to send an UnindexedProject notification to the client.
        notifications_unindexedProject: bool      = false,

        /// How many worker threads in the main loop. The default `null` means to pick automatically.
        numThreads: Option<NumThreads> = None,

        /// Expand attribute macros. Requires `#rust-analyzer.procMacro.enable#` to be set.
        procMacro_attributes_enable: bool = true,
        /// Enable support for procedural macros, implies `#rust-analyzer.cargo.buildScripts.enable#`.
        procMacro_enable: bool                     = true,
        /// Internal config, path to proc-macro server executable.
        procMacro_server: Option<Utf8PathBuf>          = None,

        /// Exclude imports from find-all-references.
        references_excludeImports: bool = false,

        /// Exclude tests from find-all-references.
        references_excludeTests: bool = false,

        /// Inject additional highlighting into doc comments.
        ///
        /// When enabled, rust-analyzer will highlight rust source in doc comments as well as intra
        /// doc links.
        semanticHighlighting_doc_comment_inject_enable: bool = true,
        /// Whether the server is allowed to emit non-standard tokens and modifiers.
        semanticHighlighting_nonStandardTokens: bool = true,
        /// Use semantic tokens for operators.
        ///
        /// When disabled, rust-analyzer will emit semantic tokens only for operator tokens when
        /// they are tagged with modifiers.
        semanticHighlighting_operator_enable: bool = true,
        /// Use specialized semantic tokens for operators.
        ///
        /// When enabled, rust-analyzer will emit special token types for operator tokens instead
        /// of the generic `operator` token type.
        semanticHighlighting_operator_specialization_enable: bool = false,
        /// Use semantic tokens for punctuation.
        ///
        /// When disabled, rust-analyzer will emit semantic tokens only for punctuation tokens when
        /// they are tagged with modifiers or have a special role.
        semanticHighlighting_punctuation_enable: bool = false,
        /// When enabled, rust-analyzer will emit a punctuation semantic token for the `!` of macro
        /// calls.
        semanticHighlighting_punctuation_separate_macro_bang: bool = false,
        /// Use specialized semantic tokens for punctuation.
        ///
        /// When enabled, rust-analyzer will emit special token types for punctuation tokens instead
        /// of the generic `punctuation` token type.
        semanticHighlighting_punctuation_specialization_enable: bool = false,
        /// Use semantic tokens for strings.
        ///
        /// In some editors (e.g. vscode) semantic tokens override other highlighting grammars.
        /// By disabling semantic tokens for strings, other grammars can be used to highlight
        /// their contents.
        semanticHighlighting_strings_enable: bool = true,

        /// Show full signature of the callable. Only shows parameters if disabled.
        signatureInfo_detail: SignatureDetail                           = SignatureDetail::Full,
        /// Show documentation.
        signatureInfo_documentation_enable: bool                       = true,

        /// Whether to insert closing angle brackets when typing an opening angle bracket of a generic argument list.
        typing_autoClosingAngleBrackets_enable: bool = false,

        /// Workspace symbol search kind.
        workspace_symbol_search_kind: WorkspaceSymbolSearchKindDef = WorkspaceSymbolSearchKindDef::OnlyTypes,
        /// Limits the number of items returned from a workspace symbol search (Defaults to 128).
        /// Some clients like vs-code issue new searches on result filtering and don't require all results to be returned in the initial search.
        /// Other clients requires all results upfront and might require a higher limit.
        workspace_symbol_search_limit: usize = 128,
        /// Workspace symbol search scope.
        workspace_symbol_search_scope: WorkspaceSymbolSearchScopeDef = WorkspaceSymbolSearchScopeDef::Workspace,
    }
}

#[derive(Debug, Clone)]
pub struct Config {
    discovered_projects: Vec<ProjectManifest>,
    /// The workspace roots as registered by the LSP client
    workspace_roots: Vec<AbsPathBuf>,
    caps: lsp_types::ClientCapabilities,
    root_path: AbsPathBuf,
    snippets: Vec<Snippet>,
    visual_studio_code_version: Option<Version>,

    default_config: &'static DefaultConfigData,
    /// Config node that obtains its initial value during the server initialization and
    /// by receiving a `lsp_types::notification::DidChangeConfiguration`.
    client_config: (FullConfigInput, ConfigErrors),

    /// Path to the root configuration file. This can be seen as a generic way to define what would be `$XDG_CONFIG_HOME/rust-analyzer/rust-analyzer.toml` in Linux.
    /// If not specified by init of a `Config` object this value defaults to :
    ///
    /// |Platform | Value                                 | Example                                  |
    /// | ------- | ------------------------------------- | ---------------------------------------- |
    /// | Linux   | `$XDG_CONFIG_HOME` or `$HOME`/.config | /home/alice/.config                      |
    /// | macOS   | `$HOME`/Library/Application Support   | /Users/Alice/Library/Application Support |
    /// | Windows | `{FOLDERID_RoamingAppData}`           | C:\Users\Alice\AppData\Roaming           |
    user_config_path: VfsPath,

    /// FIXME @alibektas : Change this to sth better.
    /// Config node whose values apply to **every** Rust project.
    user_config: Option<(GlobalLocalConfigInput, ConfigErrors)>,

    /// A special file for this session whose path is set to `self.root_path.join("rust-analyzer.toml")`
    root_ratoml_path: VfsPath,

    /// This file can be used to make global changes while having only a workspace-wide scope.
    root_ratoml: Option<(GlobalLocalConfigInput, ConfigErrors)>,

    /// For every `SourceRoot` there can be at most one RATOML file.
    ratoml_files: FxHashMap<SourceRootId, (LocalConfigInput, ConfigErrors)>,

    /// Clone of the value that is stored inside a `GlobalState`.
    source_root_parent_map: Arc<FxHashMap<SourceRootId, SourceRootId>>,

    detached_files: Vec<AbsPathBuf>,
}

impl Config {
    pub fn user_config_path(&self) -> &VfsPath {
        &self.user_config_path
    }

    pub fn same_source_root_parent_map(
        &self,
        other: &Arc<FxHashMap<SourceRootId, SourceRootId>>,
    ) -> bool {
        Arc::ptr_eq(&self.source_root_parent_map, other)
    }

    // FIXME @alibektas : Server's health uses error sink but in other places it is not used atm.
    /// Changes made to client and global configurations will partially not be reflected even after `.apply_change()` was called.
    /// The return tuple's bool component signals whether the `GlobalState` should call its `update_configuration()` method.
    fn apply_change_with_sink(&self, change: ConfigChange) -> (Config, bool) {
        let mut config = self.clone();

        let mut should_update = false;

        if let Some(change) = change.user_config_change {
            if let Ok(table) = toml::from_str(&change) {
                let mut toml_errors = vec![];
                validate_toml_table(
                    GlobalLocalConfigInput::FIELDS,
                    &table,
                    &mut String::new(),
                    &mut toml_errors,
                );
                config.user_config = Some((
                    GlobalLocalConfigInput::from_toml(table, &mut toml_errors),
                    ConfigErrors(
                        toml_errors
                            .into_iter()
                            .map(|(a, b)| ConfigErrorInner::Toml { config_key: a, error: b })
                            .map(Arc::new)
                            .collect(),
                    ),
                ));
                should_update = true;
            }
        }

        if let Some(mut json) = change.client_config_change {
            tracing::info!("updating config from JSON: {:#}", json);
            if !(json.is_null() || json.as_object().map_or(false, |it| it.is_empty())) {
                let mut json_errors = vec![];
                let detached_files = get_field::<Vec<Utf8PathBuf>>(
                    &mut json,
                    &mut json_errors,
                    "detachedFiles",
                    None,
                )
                .unwrap_or_default()
                .into_iter()
                .map(AbsPathBuf::assert)
                .collect();

                patch_old_style::patch_json_for_outdated_configs(&mut json);

                config.client_config = (
                    FullConfigInput::from_json(json, &mut json_errors),
                    ConfigErrors(
                        json_errors
                            .into_iter()
                            .map(|(a, b)| ConfigErrorInner::Json { config_key: a, error: b })
                            .map(Arc::new)
                            .collect(),
                    ),
                );
                config.detached_files = detached_files;
            }
            should_update = true;
        }

        if let Some(change) = change.root_ratoml_change {
            tracing::info!("updating root ra-toml config: {:#}", change);
            #[allow(clippy::single_match)]
            match toml::from_str(&change) {
                Ok(table) => {
                    let mut toml_errors = vec![];
                    validate_toml_table(
                        GlobalLocalConfigInput::FIELDS,
                        &table,
                        &mut String::new(),
                        &mut toml_errors,
                    );
                    config.root_ratoml = Some((
                        GlobalLocalConfigInput::from_toml(table, &mut toml_errors),
                        ConfigErrors(
                            toml_errors
                                .into_iter()
                                .map(|(a, b)| ConfigErrorInner::Toml { config_key: a, error: b })
                                .map(Arc::new)
                                .collect(),
                        ),
                    ));
                    should_update = true;
                }
                // FIXME
                Err(_) => (),
            }
        }

        if let Some(change) = change.ratoml_file_change {
            for (source_root_id, (_, text)) in change {
                if let Some(text) = text {
                    let mut toml_errors = vec![];
                    tracing::info!("updating ra-toml config: {:#}", text);
                    #[allow(clippy::single_match)]
                    match toml::from_str(&text) {
                        Ok(table) => {
                            validate_toml_table(
                                &[LocalConfigInput::FIELDS],
                                &table,
                                &mut String::new(),
                                &mut toml_errors,
                            );
                            config.ratoml_files.insert(
                                source_root_id,
                                (
                                    LocalConfigInput::from_toml(&table, &mut toml_errors),
                                    ConfigErrors(
                                        toml_errors
                                            .into_iter()
                                            .map(|(a, b)| ConfigErrorInner::Toml {
                                                config_key: a,
                                                error: b,
                                            })
                                            .map(Arc::new)
                                            .collect(),
                                    ),
                                ),
                            );
                        }
                        // FIXME
                        Err(_) => (),
                    }
                }
            }
        }

        if let Some(source_root_map) = change.source_map_change {
            config.source_root_parent_map = source_root_map;
        }

        let snips = self.completion_snippets_custom().to_owned();

        for (name, def) in snips.iter() {
            if def.prefix.is_empty() && def.postfix.is_empty() {
                continue;
            }
            let scope = match def.scope {
                SnippetScopeDef::Expr => SnippetScope::Expr,
                SnippetScopeDef::Type => SnippetScope::Type,
                SnippetScopeDef::Item => SnippetScope::Item,
            };
            #[allow(clippy::single_match)]
            match Snippet::new(
                &def.prefix,
                &def.postfix,
                &def.body,
                def.description.as_ref().unwrap_or(name),
                &def.requires,
                scope,
            ) {
                Some(snippet) => config.snippets.push(snippet),
                // FIXME
                // None => error_sink.0.push(ConfigErrorInner::Json {
                //     config_key: "".to_owned(),
                //     error: <serde_json::Error as serde::de::Error>::custom(format!(
                //         "snippet {name} is invalid or triggers are missing",
                //     )),
                // }),
                None => (),
            }
        }

        // FIXME: bring this back
        // if config.check_command().is_empty() {
        //     error_sink.0.push(ConfigErrorInner::Json {
        //         config_key: "/check/command".to_owned(),
        //         error: serde_json::Error::custom("expected a non-empty string"),
        //     });
        // }
        (config, should_update)
    }

    /// Given `change` this generates a new `Config`, thereby collecting errors of type `ConfigError`.
    /// If there are changes that have global/client level effect, the last component of the return type
    /// will be set to `true`, which should be used by the `GlobalState` to update itself.
    pub fn apply_change(&self, change: ConfigChange) -> (Config, ConfigErrors, bool) {
        let (config, should_update) = self.apply_change_with_sink(change);
        let e = ConfigErrors(
            config
                .client_config
                .1
                 .0
                .iter()
                .chain(config.root_ratoml.as_ref().into_iter().flat_map(|it| it.1 .0.iter()))
                .chain(config.user_config.as_ref().into_iter().flat_map(|it| it.1 .0.iter()))
                .chain(config.ratoml_files.values().flat_map(|it| it.1 .0.iter()))
                .cloned()
                .collect(),
        );
        (config, e, should_update)
    }
}

#[derive(Default, Debug)]
pub struct ConfigChange {
    user_config_change: Option<Arc<str>>,
    root_ratoml_change: Option<Arc<str>>,
    client_config_change: Option<serde_json::Value>,
    ratoml_file_change: Option<FxHashMap<SourceRootId, (VfsPath, Option<Arc<str>>)>>,
    source_map_change: Option<Arc<FxHashMap<SourceRootId, SourceRootId>>>,
}

impl ConfigChange {
    pub fn change_ratoml(
        &mut self,
        source_root: SourceRootId,
        vfs_path: VfsPath,
        content: Option<Arc<str>>,
    ) -> Option<(VfsPath, Option<Arc<str>>)> {
        self.ratoml_file_change
            .get_or_insert_with(Default::default)
            .insert(source_root, (vfs_path, content))
    }

    pub fn change_user_config(&mut self, content: Option<Arc<str>>) {
        assert!(self.user_config_change.is_none()); // Otherwise it is a double write.
        self.user_config_change = content;
    }

    pub fn change_root_ratoml(&mut self, content: Option<Arc<str>>) {
        assert!(self.root_ratoml_change.is_none()); // Otherwise it is a double write.
        self.root_ratoml_change = content;
    }

    pub fn change_client_config(&mut self, change: serde_json::Value) {
        self.client_config_change = Some(change);
    }

    pub fn change_source_root_parent_map(
        &mut self,
        source_root_map: Arc<FxHashMap<SourceRootId, SourceRootId>>,
    ) {
        assert!(self.source_map_change.is_none());
        self.source_map_change = Some(source_root_map.clone());
    }
}

macro_rules! try_ {
    ($expr:expr) => {
        || -> _ { Some($expr) }()
    };
}
macro_rules! try_or {
    ($expr:expr, $or:expr) => {
        try_!($expr).unwrap_or($or)
    };
}

macro_rules! try_or_def {
    ($expr:expr) => {
        try_!($expr).unwrap_or_default()
    };
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum LinkedProject {
    ProjectManifest(ProjectManifest),
    InlineJsonProject(ProjectJson),
}

impl From<ProjectManifest> for LinkedProject {
    fn from(v: ProjectManifest) -> Self {
        LinkedProject::ProjectManifest(v)
    }
}

impl From<ProjectJson> for LinkedProject {
    fn from(v: ProjectJson) -> Self {
        LinkedProject::InlineJsonProject(v)
    }
}

pub struct CallInfoConfig {
    pub params_only: bool,
    pub docs: bool,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LensConfig {
    // runnables
    pub run: bool,
    pub debug: bool,
    pub interpret: bool,

    // implementations
    pub implementations: bool,

    // references
    pub method_refs: bool,
    pub refs_adt: bool,   // for Struct, Enum, Union and Trait
    pub refs_trait: bool, // for Struct, Enum, Union and Trait
    pub enum_variant_refs: bool,

    // annotations
    pub location: AnnotationLocation,
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AnnotationLocation {
    AboveName,
    AboveWholeItem,
}

impl From<AnnotationLocation> for ide::AnnotationLocation {
    fn from(location: AnnotationLocation) -> Self {
        match location {
            AnnotationLocation::AboveName => ide::AnnotationLocation::AboveName,
            AnnotationLocation::AboveWholeItem => ide::AnnotationLocation::AboveWholeItem,
        }
    }
}

impl LensConfig {
    pub fn any(&self) -> bool {
        self.run
            || self.debug
            || self.implementations
            || self.method_refs
            || self.refs_adt
            || self.refs_trait
            || self.enum_variant_refs
    }

    pub fn none(&self) -> bool {
        !self.any()
    }

    pub fn runnable(&self) -> bool {
        self.run || self.debug
    }

    pub fn references(&self) -> bool {
        self.method_refs || self.refs_adt || self.refs_trait || self.enum_variant_refs
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HoverActionsConfig {
    pub implementations: bool,
    pub references: bool,
    pub run: bool,
    pub debug: bool,
    pub goto_type_def: bool,
}

impl HoverActionsConfig {
    pub const NO_ACTIONS: Self = Self {
        implementations: false,
        references: false,
        run: false,
        debug: false,
        goto_type_def: false,
    };

    pub fn any(&self) -> bool {
        self.implementations || self.references || self.runnable() || self.goto_type_def
    }

    pub fn none(&self) -> bool {
        !self.any()
    }

    pub fn runnable(&self) -> bool {
        self.run || self.debug
    }
}

#[derive(Debug, Clone)]
pub struct FilesConfig {
    pub watcher: FilesWatcher,
    pub exclude: Vec<AbsPathBuf>,
}

#[derive(Debug, Clone)]
pub enum FilesWatcher {
    Client,
    Server,
}

#[derive(Debug, Clone)]
pub struct NotificationsConfig {
    pub cargo_toml_not_found: bool,
    pub unindexed_project: bool,
}

#[derive(Debug, Clone)]
pub enum RustfmtConfig {
    Rustfmt { extra_args: Vec<String>, enable_range_formatting: bool },
    CustomCommand { command: String, args: Vec<String> },
}

/// Configuration for runnable items, such as `main` function or tests.
#[derive(Debug, Clone)]
pub struct RunnablesConfig {
    /// Custom command to be executed instead of `cargo` for runnables.
    pub override_cargo: Option<String>,
    /// Additional arguments for the `cargo`, e.g. `--release`.
    pub cargo_extra_args: Vec<String>,
    /// Additional arguments for the binary being run, if it is a test or benchmark.
    pub extra_test_binary_args: Vec<String>,
}

/// Configuration for workspace symbol search requests.
#[derive(Debug, Clone)]
pub struct WorkspaceSymbolConfig {
    /// In what scope should the symbol be searched in.
    pub search_scope: WorkspaceSymbolSearchScope,
    /// What kind of symbol is being searched for.
    pub search_kind: WorkspaceSymbolSearchKind,
    /// How many items are returned at most.
    pub search_limit: usize,
}

pub struct ClientCommandsConfig {
    pub run_single: bool,
    pub debug_single: bool,
    pub show_reference: bool,
    pub goto_location: bool,
    pub trigger_parameter_hints: bool,
}

#[derive(Debug)]
pub enum ConfigErrorInner {
    Json { config_key: String, error: serde_json::Error },
    Toml { config_key: String, error: toml::de::Error },
}

#[derive(Clone, Debug)]
pub struct ConfigErrors(Vec<Arc<ConfigErrorInner>>);

impl ConfigErrors {
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl fmt::Display for ConfigErrors {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let errors = self.0.iter().format_with("\n", |inner, f| match &**inner {
            ConfigErrorInner::Json { config_key: key, error: e } => {
                f(key)?;
                f(&": ")?;
                f(e)
            }
            ConfigErrorInner::Toml { config_key: key, error: e } => {
                f(key)?;
                f(&": ")?;
                f(e)
            }
        });
        write!(f, "invalid config value{}:\n{}", if self.0.len() == 1 { "" } else { "s" }, errors)
    }
}

impl std::error::Error for ConfigErrors {}

impl Config {
    pub fn new(
        root_path: AbsPathBuf,
        caps: ClientCapabilities,
        workspace_roots: Vec<AbsPathBuf>,
        visual_studio_code_version: Option<Version>,
        user_config_path: Option<Utf8PathBuf>,
    ) -> Self {
        static DEFAULT_CONFIG_DATA: OnceLock<&'static DefaultConfigData> = OnceLock::new();
        let user_config_path = if let Some(user_config_path) = user_config_path {
            user_config_path.join("rust-analyzer").join("rust-analyzer.toml")
        } else {
            let p = config_dir()
                .expect("A config dir is expected to existed on all platforms ra supports.")
                .join("rust-analyzer")
                .join("rust-analyzer.toml");
            Utf8PathBuf::from_path_buf(p).expect("Config dir expected to be abs.")
        };

        // A user config cannot be a virtual path as rust-analyzer cannot support watching changes in virtual paths.
        // See `GlobalState::process_changes` to get more info.
        // FIXME @alibektas : Temporary solution. I don't think this is right as at some point we may allow users to specify
        // custom USER_CONFIG_PATHs which may also be relative.
        let user_config_path = VfsPath::from(AbsPathBuf::assert(user_config_path));
        let root_ratoml_path = {
            let mut p = root_path.clone();
            p.push("rust-analyzer.toml");
            VfsPath::new_real_path(p.to_string())
        };

        Config {
            caps,
            discovered_projects: Vec::new(),
            root_path,
            snippets: Default::default(),
            workspace_roots,
            visual_studio_code_version,
            client_config: (FullConfigInput::default(), ConfigErrors(vec![])),
            ratoml_files: FxHashMap::default(),
            default_config: DEFAULT_CONFIG_DATA.get_or_init(|| Box::leak(Box::default())),
            source_root_parent_map: Arc::new(FxHashMap::default()),
            user_config: None,
            user_config_path,
            root_ratoml: None,
            root_ratoml_path,
            detached_files: Default::default(),
        }
    }

    pub fn rediscover_workspaces(&mut self) {
        let discovered = ProjectManifest::discover_all(&self.workspace_roots);
        tracing::info!("discovered projects: {:?}", discovered);
        if discovered.is_empty() {
            tracing::error!("failed to find any projects in {:?}", &self.workspace_roots);
        }
        self.discovered_projects = discovered;
    }

    pub fn remove_workspace(&mut self, path: &AbsPath) {
        if let Some(position) = self.workspace_roots.iter().position(|it| it == path) {
            self.workspace_roots.remove(position);
        }
    }

    pub fn add_workspaces(&mut self, paths: impl Iterator<Item = AbsPathBuf>) {
        self.workspace_roots.extend(paths);
    }

    pub fn json_schema() -> serde_json::Value {
        FullConfigInput::json_schema()
    }

    pub fn root_path(&self) -> &AbsPathBuf {
        &self.root_path
    }

    pub fn root_ratoml_path(&self) -> &VfsPath {
        &self.root_ratoml_path
    }

    pub fn caps(&self) -> &lsp_types::ClientCapabilities {
        &self.caps
    }
}

impl Config {
    pub fn assist(&self, source_root: Option<SourceRootId>) -> AssistConfig {
        AssistConfig {
            snippet_cap: self.snippet_cap(),
            allowed: None,
            insert_use: self.insert_use_config(source_root),
            prefer_no_std: self.imports_preferNoStd(source_root).to_owned(),
            assist_emit_must_use: self.assist_emitMustUse(source_root).to_owned(),
            prefer_prelude: self.imports_preferPrelude(source_root).to_owned(),
            term_search_fuel: self.assist_termSearch_fuel(source_root).to_owned() as u64,
        }
    }

    pub fn completion(&self, source_root: Option<SourceRootId>) -> CompletionConfig {
        CompletionConfig {
            enable_postfix_completions: self.completion_postfix_enable().to_owned(),
            enable_imports_on_the_fly: self.completion_autoimport_enable().to_owned()
                && completion_item_edit_resolve(&self.caps),
            enable_self_on_the_fly: self.completion_autoself_enable().to_owned(),
            enable_private_editable: self.completion_privateEditable_enable().to_owned(),
            full_function_signatures: self.completion_fullFunctionSignatures_enable().to_owned(),
            callable: match self.completion_callable_snippets() {
                CallableCompletionDef::FillArguments => Some(CallableSnippets::FillArguments),
                CallableCompletionDef::AddParentheses => Some(CallableSnippets::AddParentheses),
                CallableCompletionDef::None => None,
            },
            snippet_cap: SnippetCap::new(try_or_def!(
                self.caps
                    .text_document
                    .as_ref()?
                    .completion
                    .as_ref()?
                    .completion_item
                    .as_ref()?
                    .snippet_support?
            )),
            insert_use: self.insert_use_config(source_root),
            prefer_no_std: self.imports_preferNoStd(source_root).to_owned(),
            prefer_prelude: self.imports_preferPrelude(source_root).to_owned(),
            snippets: self.snippets.clone().to_vec(),
            limit: self.completion_limit().to_owned(),
            enable_term_search: self.completion_termSearch_enable().to_owned(),
            term_search_fuel: self.completion_termSearch_fuel().to_owned() as u64,
        }
    }

    pub fn detached_files(&self) -> &Vec<AbsPathBuf> {
        // FIXME @alibektas : This is the only config that is confusing. If it's a proper configuration
        // why is it not among the others? If it's client only which I doubt it is current state should be alright
        &self.detached_files
    }

    pub fn diagnostics(&self, source_root: Option<SourceRootId>) -> DiagnosticsConfig {
        DiagnosticsConfig {
            enabled: *self.diagnostics_enable(),
            proc_attr_macros_enabled: self.expand_proc_attr_macros(),
            proc_macros_enabled: *self.procMacro_enable(),
            disable_experimental: !self.diagnostics_experimental_enable(),
            disabled: self.diagnostics_disabled().clone(),
            expr_fill_default: match self.assist_expressionFillDefault(source_root) {
                ExprFillDefaultDef::Todo => ExprFillDefaultMode::Todo,
                ExprFillDefaultDef::Default => ExprFillDefaultMode::Default,
            },
            snippet_cap: self.snippet_cap(),
            insert_use: self.insert_use_config(source_root),
            prefer_no_std: self.imports_preferNoStd(source_root).to_owned(),
            prefer_prelude: self.imports_preferPrelude(source_root).to_owned(),
            style_lints: self.diagnostics_styleLints_enable().to_owned(),
            term_search_fuel: self.assist_termSearch_fuel(source_root).to_owned() as u64,
        }
    }
    pub fn expand_proc_attr_macros(&self) -> bool {
        self.procMacro_enable().to_owned() && self.procMacro_attributes_enable().to_owned()
    }

    pub fn highlight_related(&self, _source_root: Option<SourceRootId>) -> HighlightRelatedConfig {
        HighlightRelatedConfig {
            references: self.highlightRelated_references_enable().to_owned(),
            break_points: self.highlightRelated_breakPoints_enable().to_owned(),
            exit_points: self.highlightRelated_exitPoints_enable().to_owned(),
            yield_points: self.highlightRelated_yieldPoints_enable().to_owned(),
            closure_captures: self.highlightRelated_closureCaptures_enable().to_owned(),
        }
    }

    pub fn hover_actions(&self) -> HoverActionsConfig {
        let enable = self.experimental("hoverActions") && self.hover_actions_enable().to_owned();
        HoverActionsConfig {
            implementations: enable && self.hover_actions_implementations_enable().to_owned(),
            references: enable && self.hover_actions_references_enable().to_owned(),
            run: enable && self.hover_actions_run_enable().to_owned(),
            debug: enable && self.hover_actions_debug_enable().to_owned(),
            goto_type_def: enable && self.hover_actions_gotoTypeDef_enable().to_owned(),
        }
    }

    pub fn hover(&self) -> HoverConfig {
        let mem_kind = |kind| match kind {
            MemoryLayoutHoverRenderKindDef::Both => MemoryLayoutHoverRenderKind::Both,
            MemoryLayoutHoverRenderKindDef::Decimal => MemoryLayoutHoverRenderKind::Decimal,
            MemoryLayoutHoverRenderKindDef::Hexadecimal => MemoryLayoutHoverRenderKind::Hexadecimal,
        };
        HoverConfig {
            links_in_hover: self.hover_links_enable().to_owned(),
            memory_layout: self.hover_memoryLayout_enable().then_some(MemoryLayoutHoverConfig {
                size: self.hover_memoryLayout_size().map(mem_kind),
                offset: self.hover_memoryLayout_offset().map(mem_kind),
                alignment: self.hover_memoryLayout_alignment().map(mem_kind),
                niches: self.hover_memoryLayout_niches().unwrap_or_default(),
            }),
            documentation: self.hover_documentation_enable().to_owned(),
            format: {
                let is_markdown = try_or_def!(self
                    .caps
                    .text_document
                    .as_ref()?
                    .hover
                    .as_ref()?
                    .content_format
                    .as_ref()?
                    .as_slice())
                .contains(&MarkupKind::Markdown);
                if is_markdown {
                    HoverDocFormat::Markdown
                } else {
                    HoverDocFormat::PlainText
                }
            },
            keywords: self.hover_documentation_keywords_enable().to_owned(),
            max_trait_assoc_items_count: self.hover_show_traitAssocItems().to_owned(),
            max_fields_count: self.hover_show_fields().to_owned(),
            max_enum_variants_count: self.hover_show_enumVariants().to_owned(),
        }
    }

    pub fn inlay_hints(&self) -> InlayHintsConfig {
        let client_capability_fields = self
            .caps
            .text_document
            .as_ref()
            .and_then(|text| text.inlay_hint.as_ref())
            .and_then(|inlay_hint_caps| inlay_hint_caps.resolve_support.as_ref())
            .map(|inlay_resolve| inlay_resolve.properties.iter())
            .into_iter()
            .flatten()
            .cloned()
            .collect::<FxHashSet<_>>();

        InlayHintsConfig {
            render_colons: self.inlayHints_renderColons().to_owned(),
            type_hints: self.inlayHints_typeHints_enable().to_owned(),
            parameter_hints: self.inlayHints_parameterHints_enable().to_owned(),
            chaining_hints: self.inlayHints_chainingHints_enable().to_owned(),
            discriminant_hints: match self.inlayHints_discriminantHints_enable() {
                DiscriminantHintsDef::Always => ide::DiscriminantHints::Always,
                DiscriminantHintsDef::Never => ide::DiscriminantHints::Never,
                DiscriminantHintsDef::Fieldless => ide::DiscriminantHints::Fieldless,
            },
            closure_return_type_hints: match self.inlayHints_closureReturnTypeHints_enable() {
                ClosureReturnTypeHintsDef::Always => ide::ClosureReturnTypeHints::Always,
                ClosureReturnTypeHintsDef::Never => ide::ClosureReturnTypeHints::Never,
                ClosureReturnTypeHintsDef::WithBlock => ide::ClosureReturnTypeHints::WithBlock,
            },
            lifetime_elision_hints: match self.inlayHints_lifetimeElisionHints_enable() {
                LifetimeElisionDef::Always => ide::LifetimeElisionHints::Always,
                LifetimeElisionDef::Never => ide::LifetimeElisionHints::Never,
                LifetimeElisionDef::SkipTrivial => ide::LifetimeElisionHints::SkipTrivial,
            },
            hide_named_constructor_hints: self
                .inlayHints_typeHints_hideNamedConstructor()
                .to_owned(),
            hide_closure_initialization_hints: self
                .inlayHints_typeHints_hideClosureInitialization()
                .to_owned(),
            closure_style: match self.inlayHints_closureStyle() {
                ClosureStyle::ImplFn => hir::ClosureStyle::ImplFn,
                ClosureStyle::RustAnalyzer => hir::ClosureStyle::RANotation,
                ClosureStyle::WithId => hir::ClosureStyle::ClosureWithId,
                ClosureStyle::Hide => hir::ClosureStyle::Hide,
            },
            closure_capture_hints: self.inlayHints_closureCaptureHints_enable().to_owned(),
            adjustment_hints: match self.inlayHints_expressionAdjustmentHints_enable() {
                AdjustmentHintsDef::Always => ide::AdjustmentHints::Always,
                AdjustmentHintsDef::Never => match self.inlayHints_reborrowHints_enable() {
                    ReborrowHintsDef::Always | ReborrowHintsDef::Mutable => {
                        ide::AdjustmentHints::ReborrowOnly
                    }
                    ReborrowHintsDef::Never => ide::AdjustmentHints::Never,
                },
                AdjustmentHintsDef::Reborrow => ide::AdjustmentHints::ReborrowOnly,
            },
            adjustment_hints_mode: match self.inlayHints_expressionAdjustmentHints_mode() {
                AdjustmentHintsModeDef::Prefix => ide::AdjustmentHintsMode::Prefix,
                AdjustmentHintsModeDef::Postfix => ide::AdjustmentHintsMode::Postfix,
                AdjustmentHintsModeDef::PreferPrefix => ide::AdjustmentHintsMode::PreferPrefix,
                AdjustmentHintsModeDef::PreferPostfix => ide::AdjustmentHintsMode::PreferPostfix,
            },
            adjustment_hints_hide_outside_unsafe: self
                .inlayHints_expressionAdjustmentHints_hideOutsideUnsafe()
                .to_owned(),
            binding_mode_hints: self.inlayHints_bindingModeHints_enable().to_owned(),
            param_names_for_lifetime_elision_hints: self
                .inlayHints_lifetimeElisionHints_useParameterNames()
                .to_owned(),
            max_length: self.inlayHints_maxLength().to_owned(),
            closing_brace_hints_min_lines: if self.inlayHints_closingBraceHints_enable().to_owned()
            {
                Some(self.inlayHints_closingBraceHints_minLines().to_owned())
            } else {
                None
            },
            fields_to_resolve: InlayFieldsToResolve {
                resolve_text_edits: client_capability_fields.contains("textEdits"),
                resolve_hint_tooltip: client_capability_fields.contains("tooltip"),
                resolve_label_tooltip: client_capability_fields.contains("label.tooltip"),
                resolve_label_location: client_capability_fields.contains("label.location"),
                resolve_label_command: client_capability_fields.contains("label.command"),
            },
            implicit_drop_hints: self.inlayHints_implicitDrops_enable().to_owned(),
            range_exclusive_hints: self.inlayHints_rangeExclusiveHints_enable().to_owned(),
        }
    }

    fn insert_use_config(&self, source_root: Option<SourceRootId>) -> InsertUseConfig {
        InsertUseConfig {
            granularity: match self.imports_granularity_group(source_root) {
                ImportGranularityDef::Preserve => ImportGranularity::Preserve,
                ImportGranularityDef::Item => ImportGranularity::Item,
                ImportGranularityDef::Crate => ImportGranularity::Crate,
                ImportGranularityDef::Module => ImportGranularity::Module,
                ImportGranularityDef::One => ImportGranularity::One,
            },
            enforce_granularity: self.imports_granularity_enforce(source_root).to_owned(),
            prefix_kind: match self.imports_prefix(source_root) {
                ImportPrefixDef::Plain => PrefixKind::Plain,
                ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
                ImportPrefixDef::BySelf => PrefixKind::BySelf,
            },
            group: self.imports_group_enable(source_root).to_owned(),
            skip_glob_imports: !self.imports_merge_glob(source_root),
        }
    }

    pub fn join_lines(&self) -> JoinLinesConfig {
        JoinLinesConfig {
            join_else_if: self.joinLines_joinElseIf().to_owned(),
            remove_trailing_comma: self.joinLines_removeTrailingComma().to_owned(),
            unwrap_trivial_blocks: self.joinLines_unwrapTrivialBlock().to_owned(),
            join_assignments: self.joinLines_joinAssignments().to_owned(),
        }
    }

    pub fn highlighting_non_standard_tokens(&self) -> bool {
        self.semanticHighlighting_nonStandardTokens().to_owned()
    }

    pub fn highlighting_config(&self) -> HighlightConfig {
        HighlightConfig {
            strings: self.semanticHighlighting_strings_enable().to_owned(),
            punctuation: self.semanticHighlighting_punctuation_enable().to_owned(),
            specialize_punctuation: self
                .semanticHighlighting_punctuation_specialization_enable()
                .to_owned(),
            macro_bang: self.semanticHighlighting_punctuation_separate_macro_bang().to_owned(),
            operator: self.semanticHighlighting_operator_enable().to_owned(),
            specialize_operator: self
                .semanticHighlighting_operator_specialization_enable()
                .to_owned(),
            inject_doc_comment: self.semanticHighlighting_doc_comment_inject_enable().to_owned(),
            syntactic_name_ref_highlighting: false,
        }
    }

    pub fn has_linked_projects(&self) -> bool {
        !self.linkedProjects().is_empty()
    }
    pub fn linked_manifests(&self) -> impl Iterator<Item = &Utf8Path> + '_ {
        self.linkedProjects().iter().filter_map(|it| match it {
            ManifestOrProjectJson::Manifest(p) => Some(&**p),
            ManifestOrProjectJson::ProjectJson(_) => None,
        })
    }
    pub fn has_linked_project_jsons(&self) -> bool {
        self.linkedProjects().iter().any(|it| matches!(it, ManifestOrProjectJson::ProjectJson(_)))
    }
    pub fn linked_or_discovered_projects(&self) -> Vec<LinkedProject> {
        match self.linkedProjects().as_slice() {
            [] => {
                let exclude_dirs: Vec<_> =
                    self.files_excludeDirs().iter().map(|p| self.root_path.join(p)).collect();
                self.discovered_projects
                    .iter()
                    .filter(|project| {
                        !exclude_dirs.iter().any(|p| project.manifest_path().starts_with(p))
                    })
                    .cloned()
                    .map(LinkedProject::from)
                    .collect()
            }
            linked_projects => linked_projects
                .iter()
                .filter_map(|linked_project| match linked_project {
                    ManifestOrProjectJson::Manifest(it) => {
                        let path = self.root_path.join(it);
                        ProjectManifest::from_manifest_file(path)
                            .map_err(|e| tracing::error!("failed to load linked project: {}", e))
                            .ok()
                            .map(Into::into)
                    }
                    ManifestOrProjectJson::ProjectJson(it) => {
                        Some(ProjectJson::new(None, &self.root_path, it.clone()).into())
                    }
                })
                .collect(),
        }
    }

    pub fn did_save_text_document_dynamic_registration(&self) -> bool {
        let caps = try_or_def!(self.caps.text_document.as_ref()?.synchronization.clone()?);
        caps.did_save == Some(true) && caps.dynamic_registration == Some(true)
    }

    pub fn did_change_watched_files_dynamic_registration(&self) -> bool {
        try_or_def!(
            self.caps.workspace.as_ref()?.did_change_watched_files.as_ref()?.dynamic_registration?
        )
    }

    pub fn did_change_watched_files_relative_pattern_support(&self) -> bool {
        try_or_def!(
            self.caps
                .workspace
                .as_ref()?
                .did_change_watched_files
                .as_ref()?
                .relative_pattern_support?
        )
    }

    pub fn prefill_caches(&self) -> bool {
        self.cachePriming_enable().to_owned()
    }

    pub fn location_link(&self) -> bool {
        try_or_def!(self.caps.text_document.as_ref()?.definition?.link_support?)
    }

    pub fn line_folding_only(&self) -> bool {
        try_or_def!(self.caps.text_document.as_ref()?.folding_range.as_ref()?.line_folding_only?)
    }

    pub fn hierarchical_symbols(&self) -> bool {
        try_or_def!(
            self.caps
                .text_document
                .as_ref()?
                .document_symbol
                .as_ref()?
                .hierarchical_document_symbol_support?
        )
    }

    pub fn code_action_literals(&self) -> bool {
        try_!(self
            .caps
            .text_document
            .as_ref()?
            .code_action
            .as_ref()?
            .code_action_literal_support
            .as_ref()?)
        .is_some()
    }

    pub fn work_done_progress(&self) -> bool {
        try_or_def!(self.caps.window.as_ref()?.work_done_progress?)
    }

    pub fn will_rename(&self) -> bool {
        try_or_def!(self.caps.workspace.as_ref()?.file_operations.as_ref()?.will_rename?)
    }

    pub fn change_annotation_support(&self) -> bool {
        try_!(self
            .caps
            .workspace
            .as_ref()?
            .workspace_edit
            .as_ref()?
            .change_annotation_support
            .as_ref()?)
        .is_some()
    }

    pub fn code_action_resolve(&self) -> bool {
        try_or_def!(self
            .caps
            .text_document
            .as_ref()?
            .code_action
            .as_ref()?
            .resolve_support
            .as_ref()?
            .properties
            .as_slice())
        .iter()
        .any(|it| it == "edit")
    }

    pub fn signature_help_label_offsets(&self) -> bool {
        try_or_def!(
            self.caps
                .text_document
                .as_ref()?
                .signature_help
                .as_ref()?
                .signature_information
                .as_ref()?
                .parameter_information
                .as_ref()?
                .label_offset_support?
        )
    }

    pub fn completion_label_details_support(&self) -> bool {
        try_!(self
            .caps
            .text_document
            .as_ref()?
            .completion
            .as_ref()?
            .completion_item
            .as_ref()?
            .label_details_support
            .as_ref()?)
        .is_some()
    }

    pub fn semantics_tokens_augments_syntax_tokens(&self) -> bool {
        try_!(self.caps.text_document.as_ref()?.semantic_tokens.as_ref()?.augments_syntax_tokens?)
            .unwrap_or(false)
    }

    pub fn position_encoding(&self) -> PositionEncoding {
        negotiated_encoding(&self.caps)
    }

    fn experimental(&self, index: &'static str) -> bool {
        try_or_def!(self.caps.experimental.as_ref()?.get(index)?.as_bool()?)
    }

    pub fn code_action_group(&self) -> bool {
        self.experimental("codeActionGroup")
    }

    pub fn local_docs(&self) -> bool {
        self.experimental("localDocs")
    }

    pub fn open_server_logs(&self) -> bool {
        self.experimental("openServerLogs")
    }

    pub fn server_status_notification(&self) -> bool {
        self.experimental("serverStatusNotification")
    }

    /// Whether the client supports colored output for full diagnostics from `checkOnSave`.
    pub fn color_diagnostic_output(&self) -> bool {
        self.experimental("colorDiagnosticOutput")
    }

    pub fn test_explorer(&self) -> bool {
        self.experimental("testExplorer")
    }

    pub fn publish_diagnostics(&self) -> bool {
        self.diagnostics_enable().to_owned()
    }

    pub fn diagnostics_map(&self) -> DiagnosticsMapConfig {
        DiagnosticsMapConfig {
            remap_prefix: self.diagnostics_remapPrefix().clone(),
            warnings_as_info: self.diagnostics_warningsAsInfo().clone(),
            warnings_as_hint: self.diagnostics_warningsAsHint().clone(),
            check_ignore: self.check_ignore().clone(),
        }
    }

    pub fn extra_args(&self) -> &Vec<String> {
        self.cargo_extraArgs()
    }

    pub fn extra_env(&self) -> &FxHashMap<String, String> {
        self.cargo_extraEnv()
    }

    pub fn check_extra_args(&self) -> Vec<String> {
        let mut extra_args = self.extra_args().clone();
        extra_args.extend_from_slice(self.check_extraArgs());
        extra_args
    }

    pub fn check_extra_env(&self) -> FxHashMap<String, String> {
        let mut extra_env = self.cargo_extraEnv().clone();
        extra_env.extend(self.check_extraEnv().clone());
        extra_env
    }

    pub fn lru_parse_query_capacity(&self) -> Option<usize> {
        self.lru_capacity().to_owned()
    }

    pub fn lru_query_capacities_config(&self) -> Option<&FxHashMap<Box<str>, usize>> {
        self.lru_query_capacities().is_empty().not().then(|| self.lru_query_capacities())
    }

    pub fn proc_macro_srv(&self) -> Option<AbsPathBuf> {
        let path = self.procMacro_server().clone()?;
        Some(AbsPathBuf::try_from(path).unwrap_or_else(|path| self.root_path.join(path)))
    }

    pub fn ignored_proc_macros(&self) -> &FxHashMap<Box<str>, Box<[Box<str>]>> {
        self.procMacro_ignored()
    }

    pub fn expand_proc_macros(&self) -> bool {
        self.procMacro_enable().to_owned()
    }

    pub fn files(&self) -> FilesConfig {
        FilesConfig {
            watcher: match self.files_watcher() {
                FilesWatcherDef::Client if self.did_change_watched_files_dynamic_registration() => {
                    FilesWatcher::Client
                }
                _ => FilesWatcher::Server,
            },
            exclude: self.files_excludeDirs().iter().map(|it| self.root_path.join(it)).collect(),
        }
    }

    pub fn notifications(&self) -> NotificationsConfig {
        NotificationsConfig {
            cargo_toml_not_found: self.notifications_cargoTomlNotFound().to_owned(),
            unindexed_project: self.notifications_unindexedProject().to_owned(),
        }
    }

    pub fn cargo_autoreload_config(&self) -> bool {
        self.cargo_autoreload().to_owned()
    }

    pub fn run_build_scripts(&self) -> bool {
        self.cargo_buildScripts_enable().to_owned() || self.procMacro_enable().to_owned()
    }

    pub fn cargo(&self) -> CargoConfig {
        let rustc_source = self.rustc_source().as_ref().map(|rustc_src| {
            if rustc_src == "discover" {
                RustLibSource::Discover
            } else {
                RustLibSource::Path(self.root_path.join(rustc_src))
            }
        });
        let sysroot = self.cargo_sysroot().as_ref().map(|sysroot| {
            if sysroot == "discover" {
                RustLibSource::Discover
            } else {
                RustLibSource::Path(self.root_path.join(sysroot))
            }
        });
        let sysroot_src =
            self.cargo_sysrootSrc().as_ref().map(|sysroot| self.root_path.join(sysroot));
        let sysroot_query_metadata = self.cargo_sysrootQueryMetadata();

        CargoConfig {
            all_targets: *self.cargo_allTargets(),
            features: match &self.cargo_features() {
                CargoFeaturesDef::All => CargoFeatures::All,
                CargoFeaturesDef::Selected(features) => CargoFeatures::Selected {
                    features: features.clone(),
                    no_default_features: self.cargo_noDefaultFeatures().to_owned(),
                },
            },
            target: self.cargo_target().clone(),
            sysroot,
            sysroot_query_metadata: *sysroot_query_metadata,
            sysroot_src,
            rustc_source,
            cfg_overrides: project_model::CfgOverrides {
                global: CfgDiff::new(
                    self.cargo_cfgs()
                        .iter()
                        .map(|(key, val)| match val {
                            Some(val) => CfgAtom::KeyValue { key: key.into(), value: val.into() },
                            None => CfgAtom::Flag(key.into()),
                        })
                        .collect(),
                    vec![],
                )
                .unwrap(),
                selective: Default::default(),
            },
            wrap_rustc_in_build_scripts: *self.cargo_buildScripts_useRustcWrapper(),
            invocation_strategy: match self.cargo_buildScripts_invocationStrategy() {
                InvocationStrategy::Once => project_model::InvocationStrategy::Once,
                InvocationStrategy::PerWorkspace => project_model::InvocationStrategy::PerWorkspace,
            },
            invocation_location: match self.cargo_buildScripts_invocationLocation() {
                InvocationLocation::Root => {
                    project_model::InvocationLocation::Root(self.root_path.clone())
                }
                InvocationLocation::Workspace => project_model::InvocationLocation::Workspace,
            },
            run_build_script_command: self.cargo_buildScripts_overrideCommand().clone(),
            extra_args: self.cargo_extraArgs().clone(),
            extra_env: self.cargo_extraEnv().clone(),
            target_dir: self.target_dir_from_config(),
        }
    }

    pub fn rustfmt(&self) -> RustfmtConfig {
        match &self.rustfmt_overrideCommand() {
            Some(args) if !args.is_empty() => {
                let mut args = args.clone();
                let command = args.remove(0);
                RustfmtConfig::CustomCommand { command, args }
            }
            Some(_) | None => RustfmtConfig::Rustfmt {
                extra_args: self.rustfmt_extraArgs().clone(),
                enable_range_formatting: *self.rustfmt_rangeFormatting_enable(),
            },
        }
    }

    pub fn flycheck_workspace(&self) -> bool {
        *self.check_workspace()
    }

    pub fn cargo_test_options(&self) -> CargoOptions {
        CargoOptions {
            target_triples: self.cargo_target().clone().into_iter().collect(),
            all_targets: false,
            no_default_features: *self.cargo_noDefaultFeatures(),
            all_features: matches!(self.cargo_features(), CargoFeaturesDef::All),
            features: match self.cargo_features().clone() {
                CargoFeaturesDef::All => vec![],
                CargoFeaturesDef::Selected(it) => it,
            },
            extra_args: self.extra_args().clone(),
            extra_env: self.extra_env().clone(),
            target_dir: self.target_dir_from_config(),
        }
    }

    pub fn flycheck(&self) -> FlycheckConfig {
        match &self.check_overrideCommand() {
            Some(args) if !args.is_empty() => {
                let mut args = args.clone();
                let command = args.remove(0);
                FlycheckConfig::CustomCommand {
                    command,
                    args,
                    extra_env: self.check_extra_env(),
                    invocation_strategy: match self.check_invocationStrategy() {
                        InvocationStrategy::Once => flycheck::InvocationStrategy::Once,
                        InvocationStrategy::PerWorkspace => {
                            flycheck::InvocationStrategy::PerWorkspace
                        }
                    },
                    invocation_location: match self.check_invocationLocation() {
                        InvocationLocation::Root => {
                            flycheck::InvocationLocation::Root(self.root_path.clone())
                        }
                        InvocationLocation::Workspace => flycheck::InvocationLocation::Workspace,
                    },
                }
            }
            Some(_) | None => FlycheckConfig::CargoCommand {
                command: self.check_command().clone(),
                options: CargoOptions {
                    target_triples: self
                        .check_targets()
                        .clone()
                        .and_then(|targets| match &targets.0[..] {
                            [] => None,
                            targets => Some(targets.into()),
                        })
                        .unwrap_or_else(|| self.cargo_target().clone().into_iter().collect()),
                    all_targets: self.check_allTargets().unwrap_or(*self.cargo_allTargets()),
                    no_default_features: self
                        .check_noDefaultFeatures()
                        .unwrap_or(*self.cargo_noDefaultFeatures()),
                    all_features: matches!(
                        self.check_features().as_ref().unwrap_or(self.cargo_features()),
                        CargoFeaturesDef::All
                    ),
                    features: match self
                        .check_features()
                        .clone()
                        .unwrap_or_else(|| self.cargo_features().clone())
                    {
                        CargoFeaturesDef::All => vec![],
                        CargoFeaturesDef::Selected(it) => it,
                    },
                    extra_args: self.check_extra_args(),
                    extra_env: self.check_extra_env(),
                    target_dir: self.target_dir_from_config(),
                },
                ansi_color_output: self.color_diagnostic_output(),
            },
        }
    }

    fn target_dir_from_config(&self) -> Option<Utf8PathBuf> {
        self.cargo_targetDir().as_ref().and_then(|target_dir| match target_dir {
            TargetDirectory::UseSubdirectory(true) => {
                Some(Utf8PathBuf::from("target/rust-analyzer"))
            }
            TargetDirectory::UseSubdirectory(false) => None,
            TargetDirectory::Directory(dir) if dir.is_relative() => Some(dir.clone()),
            TargetDirectory::Directory(_) => None,
        })
    }

    pub fn check_on_save(&self) -> bool {
        *self.checkOnSave()
    }

    pub fn script_rebuild_on_save(&self) -> bool {
        *self.cargo_buildScripts_rebuildOnSave()
    }

    pub fn runnables(&self) -> RunnablesConfig {
        RunnablesConfig {
            override_cargo: self.runnables_command().clone(),
            cargo_extra_args: self.runnables_extraArgs().clone(),
            extra_test_binary_args: self.runnables_extraTestBinaryArgs().clone(),
        }
    }

    pub fn find_all_refs_exclude_imports(&self) -> bool {
        *self.references_excludeImports()
    }

    pub fn find_all_refs_exclude_tests(&self) -> bool {
        *self.references_excludeTests()
    }

    pub fn snippet_cap(&self) -> Option<SnippetCap> {
        // FIXME: Also detect the proposed lsp version at caps.workspace.workspaceEdit.snippetEditSupport
        // once lsp-types has it.
        SnippetCap::new(self.experimental("snippetTextEdit"))
    }

    pub fn call_info(&self) -> CallInfoConfig {
        CallInfoConfig {
            params_only: matches!(self.signatureInfo_detail(), SignatureDetail::Parameters),
            docs: *self.signatureInfo_documentation_enable(),
        }
    }

    pub fn lens(&self) -> LensConfig {
        LensConfig {
            run: *self.lens_enable() && *self.lens_run_enable(),
            debug: *self.lens_enable() && *self.lens_debug_enable(),
            interpret: *self.lens_enable() && *self.lens_run_enable() && *self.interpret_tests(),
            implementations: *self.lens_enable() && *self.lens_implementations_enable(),
            method_refs: *self.lens_enable() && *self.lens_references_method_enable(),
            refs_adt: *self.lens_enable() && *self.lens_references_adt_enable(),
            refs_trait: *self.lens_enable() && *self.lens_references_trait_enable(),
            enum_variant_refs: *self.lens_enable() && *self.lens_references_enumVariant_enable(),
            location: *self.lens_location(),
        }
    }

    pub fn workspace_symbol(&self) -> WorkspaceSymbolConfig {
        WorkspaceSymbolConfig {
            search_scope: match self.workspace_symbol_search_scope() {
                WorkspaceSymbolSearchScopeDef::Workspace => WorkspaceSymbolSearchScope::Workspace,
                WorkspaceSymbolSearchScopeDef::WorkspaceAndDependencies => {
                    WorkspaceSymbolSearchScope::WorkspaceAndDependencies
                }
            },
            search_kind: match self.workspace_symbol_search_kind() {
                WorkspaceSymbolSearchKindDef::OnlyTypes => WorkspaceSymbolSearchKind::OnlyTypes,
                WorkspaceSymbolSearchKindDef::AllSymbols => WorkspaceSymbolSearchKind::AllSymbols,
            },
            search_limit: *self.workspace_symbol_search_limit(),
        }
    }

    pub fn semantic_tokens_refresh(&self) -> bool {
        try_or_def!(self.caps.workspace.as_ref()?.semantic_tokens.as_ref()?.refresh_support?)
    }

    pub fn code_lens_refresh(&self) -> bool {
        try_or_def!(self.caps.workspace.as_ref()?.code_lens.as_ref()?.refresh_support?)
    }

    pub fn inlay_hints_refresh(&self) -> bool {
        try_or_def!(self.caps.workspace.as_ref()?.inlay_hint.as_ref()?.refresh_support?)
    }

    pub fn insert_replace_support(&self) -> bool {
        try_or_def!(
            self.caps
                .text_document
                .as_ref()?
                .completion
                .as_ref()?
                .completion_item
                .as_ref()?
                .insert_replace_support?
        )
    }

    pub fn client_commands(&self) -> ClientCommandsConfig {
        let commands =
            try_or!(self.caps.experimental.as_ref()?.get("commands")?, &serde_json::Value::Null);
        let commands: Option<lsp_ext::ClientCommandOptions> =
            serde_json::from_value(commands.clone()).ok();
        let force = commands.is_none() && *self.lens_forceCustomCommands();
        let commands = commands.map(|it| it.commands).unwrap_or_default();

        let get = |name: &str| commands.iter().any(|it| it == name) || force;

        ClientCommandsConfig {
            run_single: get("rust-analyzer.runSingle"),
            debug_single: get("rust-analyzer.debugSingle"),
            show_reference: get("rust-analyzer.showReferences"),
            goto_location: get("rust-analyzer.gotoLocation"),
            trigger_parameter_hints: get("editor.action.triggerParameterHints"),
        }
    }

    pub fn prime_caches_num_threads(&self) -> usize {
        match self.cachePriming_numThreads() {
            NumThreads::Concrete(0) | NumThreads::Physical => num_cpus::get_physical(),
            &NumThreads::Concrete(n) => n,
            NumThreads::Logical => num_cpus::get(),
        }
    }

    pub fn main_loop_num_threads(&self) -> usize {
        match self.numThreads() {
            Some(NumThreads::Concrete(0)) | None | Some(NumThreads::Physical) => {
                num_cpus::get_physical()
            }
            &Some(NumThreads::Concrete(n)) => n,
            Some(NumThreads::Logical) => num_cpus::get(),
        }
    }

    pub fn typing_autoclose_angle(&self) -> bool {
        *self.typing_autoClosingAngleBrackets_enable()
    }

    // VSCode is our reference implementation, so we allow ourselves to work around issues by
    // special casing certain versions
    pub fn visual_studio_code_version(&self) -> Option<&Version> {
        self.visual_studio_code_version.as_ref()
    }
}
// Deserialization definitions

macro_rules! create_bool_or_string_serde {
    ($ident:ident<$bool:literal, $string:literal>) => {
        mod $ident {
            pub(super) fn deserialize<'de, D>(d: D) -> Result<(), D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                struct V;
                impl<'de> serde::de::Visitor<'de> for V {
                    type Value = ();

                    fn expecting(
                        &self,
                        formatter: &mut std::fmt::Formatter<'_>,
                    ) -> std::fmt::Result {
                        formatter.write_str(concat!(
                            stringify!($bool),
                            " or \"",
                            stringify!($string),
                            "\""
                        ))
                    }

                    fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
                    where
                        E: serde::de::Error,
                    {
                        match v {
                            $bool => Ok(()),
                            _ => Err(serde::de::Error::invalid_value(
                                serde::de::Unexpected::Bool(v),
                                &self,
                            )),
                        }
                    }

                    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
                    where
                        E: serde::de::Error,
                    {
                        match v {
                            $string => Ok(()),
                            _ => Err(serde::de::Error::invalid_value(
                                serde::de::Unexpected::Str(v),
                                &self,
                            )),
                        }
                    }

                    fn visit_enum<A>(self, a: A) -> Result<Self::Value, A::Error>
                    where
                        A: serde::de::EnumAccess<'de>,
                    {
                        use serde::de::VariantAccess;
                        let (variant, va) = a.variant::<&'de str>()?;
                        va.unit_variant()?;
                        match variant {
                            $string => Ok(()),
                            _ => Err(serde::de::Error::invalid_value(
                                serde::de::Unexpected::Str(variant),
                                &self,
                            )),
                        }
                    }
                }
                d.deserialize_any(V)
            }

            pub(super) fn serialize<S>(serializer: S) -> Result<S::Ok, S::Error>
            where
                S: serde::Serializer,
            {
                serializer.serialize_str($string)
            }
        }
    };
}
create_bool_or_string_serde!(true_or_always<true, "always">);
create_bool_or_string_serde!(false_or_never<false, "never">);

#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
enum SnippetScopeDef {
    #[default]
    Expr,
    Item,
    Type,
}

#[derive(Serialize, Deserialize, Debug, Clone, Default)]
#[serde(default)]
pub(crate) struct SnippetDef {
    #[serde(with = "single_or_array")]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    prefix: Vec<String>,

    #[serde(with = "single_or_array")]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    postfix: Vec<String>,

    #[serde(with = "single_or_array")]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    body: Vec<String>,

    #[serde(with = "single_or_array")]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    requires: Vec<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    description: Option<String>,

    scope: SnippetScopeDef,
}

mod single_or_array {
    use serde::{Deserialize, Serialize};

    pub(super) fn deserialize<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct SingleOrVec;

        impl<'de> serde::de::Visitor<'de> for SingleOrVec {
            type Value = Vec<String>;

            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                formatter.write_str("string or array of strings")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(vec![value.to_owned()])
            }

            fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
            where
                A: serde::de::SeqAccess<'de>,
            {
                Deserialize::deserialize(serde::de::value::SeqAccessDeserializer::new(seq))
            }
        }

        deserializer.deserialize_any(SingleOrVec)
    }

    pub(super) fn serialize<S>(vec: &[String], serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match vec {
            // []  case is handled by skip_serializing_if
            [single] => serializer.serialize_str(single),
            slice => slice.serialize(serializer),
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
enum ManifestOrProjectJson {
    Manifest(Utf8PathBuf),
    ProjectJson(ProjectJsonData),
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum ExprFillDefaultDef {
    Todo,
    Default,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum ImportGranularityDef {
    Preserve,
    Item,
    Crate,
    Module,
    One,
}

#[derive(Serialize, Deserialize, Debug, Copy, Clone)]
#[serde(rename_all = "snake_case")]
pub(crate) enum CallableCompletionDef {
    FillArguments,
    AddParentheses,
    None,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum CargoFeaturesDef {
    All,
    #[serde(untagged)]
    Selected(Vec<String>),
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub(crate) enum InvocationStrategy {
    Once,
    PerWorkspace,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
struct CheckOnSaveTargets(#[serde(with = "single_or_array")] Vec<String>);

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum InvocationLocation {
    Root,
    Workspace,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum LifetimeElisionDef {
    SkipTrivial,
    #[serde(with = "true_or_always")]
    #[serde(untagged)]
    Always,
    #[serde(with = "false_or_never")]
    #[serde(untagged)]
    Never,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum ClosureReturnTypeHintsDef {
    WithBlock,
    #[serde(with = "true_or_always")]
    #[serde(untagged)]
    Always,
    #[serde(with = "false_or_never")]
    #[serde(untagged)]
    Never,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum ClosureStyle {
    ImplFn,
    RustAnalyzer,
    WithId,
    Hide,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum ReborrowHintsDef {
    Mutable,
    #[serde(with = "true_or_always")]
    #[serde(untagged)]
    Always,
    #[serde(with = "false_or_never")]
    #[serde(untagged)]
    Never,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum AdjustmentHintsDef {
    Reborrow,
    #[serde(with = "true_or_always")]
    #[serde(untagged)]
    Always,
    #[serde(with = "false_or_never")]
    #[serde(untagged)]
    Never,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum DiscriminantHintsDef {
    Fieldless,
    #[serde(with = "true_or_always")]
    #[serde(untagged)]
    Always,
    #[serde(with = "false_or_never")]
    #[serde(untagged)]
    Never,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum AdjustmentHintsModeDef {
    Prefix,
    Postfix,
    PreferPrefix,
    PreferPostfix,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum FilesWatcherDef {
    Client,
    Notify,
    Server,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum ImportPrefixDef {
    Plain,
    #[serde(rename = "self")]
    #[serde(alias = "by_self")]
    BySelf,
    #[serde(rename = "crate")]
    #[serde(alias = "by_crate")]
    ByCrate,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum WorkspaceSymbolSearchScopeDef {
    Workspace,
    WorkspaceAndDependencies,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum SignatureDetail {
    Full,
    Parameters,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
enum WorkspaceSymbolSearchKindDef {
    OnlyTypes,
    AllSymbols,
}

#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq)]
#[serde(rename_all = "snake_case")]
enum MemoryLayoutHoverRenderKindDef {
    Decimal,
    Hexadecimal,
    Both,
}

#[test]
fn untagged_option_hover_render_kind() {
    let hex = MemoryLayoutHoverRenderKindDef::Hexadecimal;

    let ser = serde_json::to_string(&Some(hex)).unwrap();
    assert_eq!(&ser, "\"hexadecimal\"");

    let opt: Option<_> = serde_json::from_str("\"hexadecimal\"").unwrap();
    assert_eq!(opt, Some(hex));
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "snake_case")]
#[serde(untagged)]
pub enum TargetDirectory {
    UseSubdirectory(bool),
    Directory(Utf8PathBuf),
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum NumThreads {
    Physical,
    Logical,
    #[serde(untagged)]
    Concrete(usize),
}

macro_rules! _default_val {
    (@verbatim: $s:literal, $ty:ty) => {{
        let default_: $ty = serde_json::from_str(&$s).unwrap();
        default_
    }};
    ($default:expr, $ty:ty) => {{
        let default_: $ty = $default;
        default_
    }};
}
use _default_val as default_val;

macro_rules! _default_str {
    (@verbatim: $s:literal, $_ty:ty) => {
        $s.to_owned()
    };
    ($default:expr, $ty:ty) => {{
        let val = default_val!($default, $ty);
        serde_json::to_string_pretty(&val).unwrap()
    }};
}
use _default_str as default_str;

macro_rules! _impl_for_config_data {
    (local, $(
            $(#[doc=$doc:literal])*
            $vis:vis $field:ident : $ty:ty = $default:expr,
        )*
    ) => {
        impl Config {
            $(
                $($doc)*
                #[allow(non_snake_case)]
                $vis fn $field(&self, source_root: Option<SourceRootId>) -> &$ty {
                    let mut par: Option<SourceRootId> = source_root;
                    let mut traversals = 0;
                    while let Some(source_root_id) = par {
                        par = self.source_root_parent_map.get(&source_root_id).copied();
                        if let Some((config, _)) = self.ratoml_files.get(&source_root_id) {
                            if let Some(value) = config.$field.as_ref() {
                                return value;
                            }
                        }
                        // Prevent infinite loops caused by cycles by giving up when it's
                        // clear that we must have either visited all source roots or
                        // encountered a cycle.
                        traversals += 1;
                        if traversals >= self.source_root_parent_map.len() {
                            // i.e. no source root contains the config we're looking for
                            break;
                        }
                    }

                    if let Some((root_path_ratoml, _)) = self.root_ratoml.as_ref() {
                        if let Some(v) = root_path_ratoml.local.$field.as_ref() {
                            return &v;
                        }
                    }

                    if let Some(v) = self.client_config.0.local.$field.as_ref() {
                        return &v;
                    }

                    if let Some((user_config, _)) = self.user_config.as_ref() {
                        if let Some(v) = user_config.local.$field.as_ref() {
                            return &v;
                        }
                    }

                    &self.default_config.local.$field
                }
            )*
        }
    };
    (global, $(
            $(#[doc=$doc:literal])*
            $vis:vis $field:ident : $ty:ty = $default:expr,
        )*
    ) => {
        impl Config {
            $(
                $($doc)*
                #[allow(non_snake_case)]
                $vis fn $field(&self) -> &$ty {

                    if let Some((root_path_ratoml, _)) = self.root_ratoml.as_ref() {
                        if let Some(v) = root_path_ratoml.global.$field.as_ref() {
                            return &v;
                        }
                    }

                    if let Some(v) = self.client_config.0.global.$field.as_ref() {
                        return &v;
                    }

                    if let Some((user_config, _)) = self.user_config.as_ref() {
                        if let Some(v) = user_config.global.$field.as_ref() {
                            return &v;
                        }
                    }

                    &self.default_config.global.$field
                }
            )*
        }
    };
    (client, $(
            $(#[doc=$doc:literal])*
            $vis:vis $field:ident : $ty:ty = $default:expr,
       )*
    ) => {
        impl Config {
            $(
                $($doc)*
                #[allow(non_snake_case)]
                $vis fn $field(&self) -> &$ty {
                    if let Some(v) = self.client_config.0.client.$field.as_ref() {
                        return &v;
                    }

                    &self.default_config.client.$field
                }
            )*
        }
    };
}
use _impl_for_config_data as impl_for_config_data;

macro_rules! _config_data {
    // modname is for the tests
    ($(#[doc=$dox:literal])* $modname:ident: struct $name:ident <- $input:ident -> {
        $(
            $(#[doc=$doc:literal])*
            $vis:vis $field:ident $(| $alias:ident)*: $ty:ty = $(@$marker:ident: )? $default:expr,
        )*
    }) => {
        /// Default config values for this grouping.
        #[allow(non_snake_case)]
        #[derive(Debug, Clone )]
        struct $name { $($field: $ty,)* }

        impl_for_config_data!{
            $modname,
            $(
                $vis $field : $ty = $default,
            )*
        }

        /// All fields `Option<T>`, `None` representing fields not set in a particular JSON/TOML blob.
        #[allow(non_snake_case)]
        #[derive(Clone, Serialize, Default)]
        struct $input { $(
            #[serde(skip_serializing_if = "Option::is_none")]
            $field: Option<$ty>,
        )* }

        impl std::fmt::Debug for $input {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                let mut s = f.debug_struct(stringify!($input));
                $(
                    if let Some(val) = self.$field.as_ref() {
                        s.field(stringify!($field), val);
                    }
                )*
                s.finish()
            }
        }

        impl Default for $name {
            fn default() -> Self {
                $name {$(
                    $field: default_val!($(@$marker:)? $default, $ty),
                )*}
            }
        }

        #[allow(unused, clippy::ptr_arg)]
        impl $input {
            const FIELDS: &'static [&'static str] = &[$(stringify!($field)),*];

            fn from_json(json: &mut serde_json::Value, error_sink: &mut Vec<(String, serde_json::Error)>) -> Self {
                Self {$(
                    $field: get_field(
                        json,
                        error_sink,
                        stringify!($field),
                        None$(.or(Some(stringify!($alias))))*,
                    ),
                )*}
            }

            fn from_toml(toml: &toml::Table, error_sink: &mut Vec<(String, toml::de::Error)>) -> Self {
                Self {$(
                    $field: get_field_toml::<$ty>(
                        toml,
                        error_sink,
                        stringify!($field),
                        None$(.or(Some(stringify!($alias))))*,
                    ),
                )*}
            }

            fn schema_fields(sink: &mut Vec<SchemaField>) {
                sink.extend_from_slice(&[
                    $({
                        let field = stringify!($field);
                        let ty = stringify!($ty);
                        let default = default_str!($(@$marker:)? $default, $ty);

                        (field, ty, &[$($doc),*], default)
                    },)*
                ])
            }
        }

        mod $modname {
            #[test]
            fn fields_are_sorted() {
                super::$input::FIELDS.windows(2).for_each(|w| assert!(w[0] <= w[1], "{} <= {} does not hold", w[0], w[1]));
            }
        }
    };
}
use _config_data as config_data;

#[derive(Default, Debug, Clone)]
struct DefaultConfigData {
    global: GlobalDefaultConfigData,
    local: LocalDefaultConfigData,
    client: ClientDefaultConfigData,
}

/// All of the config levels, all fields `Option<T>`, to describe fields that are actually set by
/// some rust-analyzer.toml file or JSON blob. An empty rust-analyzer.toml corresponds to
/// all fields being None.
#[derive(Debug, Clone, Default, Serialize)]
struct FullConfigInput {
    global: GlobalConfigInput,
    local: LocalConfigInput,
    client: ClientConfigInput,
}

impl FullConfigInput {
    fn from_json(
        mut json: serde_json::Value,
        error_sink: &mut Vec<(String, serde_json::Error)>,
    ) -> FullConfigInput {
        FullConfigInput {
            global: GlobalConfigInput::from_json(&mut json, error_sink),
            local: LocalConfigInput::from_json(&mut json, error_sink),
            client: ClientConfigInput::from_json(&mut json, error_sink),
        }
    }

    fn schema_fields() -> Vec<SchemaField> {
        let mut fields = Vec::new();
        GlobalConfigInput::schema_fields(&mut fields);
        LocalConfigInput::schema_fields(&mut fields);
        ClientConfigInput::schema_fields(&mut fields);
        fields.sort_by_key(|&(x, ..)| x);
        fields
            .iter()
            .tuple_windows()
            .for_each(|(a, b)| assert!(a.0 != b.0, "{a:?} duplicate field"));
        fields
    }

    fn json_schema() -> serde_json::Value {
        schema(&Self::schema_fields())
    }

    #[cfg(test)]
    fn manual() -> String {
        manual(&Self::schema_fields())
    }
}

/// All of the config levels, all fields `Option<T>`, to describe fields that are actually set by
/// some rust-analyzer.toml file or JSON blob. An empty rust-analyzer.toml corresponds to
/// all fields being None.
#[derive(Debug, Clone, Default, Serialize)]
struct GlobalLocalConfigInput {
    global: GlobalConfigInput,
    local: LocalConfigInput,
}

impl GlobalLocalConfigInput {
    const FIELDS: &'static [&'static [&'static str]] =
        &[GlobalConfigInput::FIELDS, LocalConfigInput::FIELDS];
    fn from_toml(
        toml: toml::Table,
        error_sink: &mut Vec<(String, toml::de::Error)>,
    ) -> GlobalLocalConfigInput {
        GlobalLocalConfigInput {
            global: GlobalConfigInput::from_toml(&toml, error_sink),
            local: LocalConfigInput::from_toml(&toml, error_sink),
        }
    }
}

fn get_field<T: DeserializeOwned>(
    json: &mut serde_json::Value,
    error_sink: &mut Vec<(String, serde_json::Error)>,
    field: &'static str,
    alias: Option<&'static str>,
) -> Option<T> {
    // XXX: check alias first, to work around the VS Code where it pre-fills the
    // defaults instead of sending an empty object.
    alias
        .into_iter()
        .chain(iter::once(field))
        .filter_map(move |field| {
            let mut pointer = field.replace('_', "/");
            pointer.insert(0, '/');
            json.pointer_mut(&pointer)
                .map(|it| serde_json::from_value(it.take()).map_err(|e| (e, pointer)))
        })
        .find(Result::is_ok)
        .and_then(|res| match res {
            Ok(it) => Some(it),
            Err((e, pointer)) => {
                tracing::warn!("Failed to deserialize config field at {}: {:?}", pointer, e);
                error_sink.push((pointer, e));
                None
            }
        })
}

fn get_field_toml<T: DeserializeOwned>(
    toml: &toml::Table,
    error_sink: &mut Vec<(String, toml::de::Error)>,
    field: &'static str,
    alias: Option<&'static str>,
) -> Option<T> {
    // XXX: check alias first, to work around the VS Code where it pre-fills the
    // defaults instead of sending an empty object.
    alias
        .into_iter()
        .chain(iter::once(field))
        .filter_map(move |field| {
            let mut pointer = field.replace('_', "/");
            pointer.insert(0, '/');
            toml_pointer(toml, &pointer)
                .map(|it| <_>::deserialize(it.clone()).map_err(|e| (e, pointer)))
        })
        .find(Result::is_ok)
        .and_then(|res| match res {
            Ok(it) => Some(it),
            Err((e, pointer)) => {
                tracing::warn!("Failed to deserialize config field at {}: {:?}", pointer, e);
                error_sink.push((pointer, e));
                None
            }
        })
}

fn toml_pointer<'a>(toml: &'a toml::Table, pointer: &str) -> Option<&'a toml::Value> {
    fn parse_index(s: &str) -> Option<usize> {
        if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) {
            return None;
        }
        s.parse().ok()
    }

    if pointer.is_empty() {
        return None;
    }
    if !pointer.starts_with('/') {
        return None;
    }
    let mut parts = pointer.split('/').skip(1);
    let first = parts.next()?;
    let init = toml.get(first)?;
    parts.map(|x| x.replace("~1", "/").replace("~0", "~")).try_fold(init, |target, token| {
        match target {
            toml::Value::Table(table) => table.get(&token),
            toml::Value::Array(list) => parse_index(&token).and_then(move |x| list.get(x)),
            _ => None,
        }
    })
}

type SchemaField = (&'static str, &'static str, &'static [&'static str], String);

fn schema(fields: &[SchemaField]) -> serde_json::Value {
    let map = fields
        .iter()
        .map(|(field, ty, doc, default)| {
            let name = field.replace('_', ".");
            let category =
                name.find('.').map(|end| String::from(&name[..end])).unwrap_or("general".into());
            let name = format!("rust-analyzer.{name}");
            let props = field_props(field, ty, doc, default);
            serde_json::json!({
                "title": category,
                "properties": {
                    name: props
                }
            })
        })
        .collect::<Vec<_>>();
    map.into()
}

fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value {
    let doc = doc_comment_to_string(doc);
    let doc = doc.trim_end_matches('\n');
    assert!(
        doc.ends_with('.') && doc.starts_with(char::is_uppercase),
        "bad docs for {field}: {doc:?}"
    );
    let default = default.parse::<serde_json::Value>().unwrap();

    let mut map = serde_json::Map::default();
    macro_rules! set {
        ($($key:literal: $value:tt),*$(,)?) => {{$(
            map.insert($key.into(), serde_json::json!($value));
        )*}};
    }
    set!("markdownDescription": doc);
    set!("default": default);

    match ty {
        "bool" => set!("type": "boolean"),
        "usize" => set!("type": "integer", "minimum": 0),
        "String" => set!("type": "string"),
        "Vec<String>" => set! {
            "type": "array",
            "items": { "type": "string" },
        },
        "Vec<Utf8PathBuf>" => set! {
            "type": "array",
            "items": { "type": "string" },
        },
        "FxHashSet<String>" => set! {
            "type": "array",
            "items": { "type": "string" },
            "uniqueItems": true,
        },
        "FxHashMap<Box<str>, Box<[Box<str>]>>" => set! {
            "type": "object",
        },
        "IndexMap<String, SnippetDef>" => set! {
            "type": "object",
        },
        "FxHashMap<String, String>" => set! {
            "type": "object",
        },
        "FxHashMap<Box<str>, usize>" => set! {
            "type": "object",
        },
        "FxHashMap<String, Option<String>>" => set! {
            "type": "object",
        },
        "Option<usize>" => set! {
            "type": ["null", "integer"],
            "minimum": 0,
        },
        "Option<String>" => set! {
            "type": ["null", "string"],
        },
        "Option<Utf8PathBuf>" => set! {
            "type": ["null", "string"],
        },
        "Option<bool>" => set! {
            "type": ["null", "boolean"],
        },
        "Option<Vec<String>>" => set! {
            "type": ["null", "array"],
            "items": { "type": "string" },
        },
        "ExprFillDefaultDef" => set! {
            "type": "string",
            "enum": ["todo", "default"],
            "enumDescriptions": [
                "Fill missing expressions with the `todo` macro",
                "Fill missing expressions with reasonable defaults, `new` or `default` constructors."
            ],
        },
        "ImportGranularityDef" => set! {
            "type": "string",
            "enum": ["preserve", "crate", "module", "item", "one"],
            "enumDescriptions": [
                "Do not change the granularity of any imports and preserve the original structure written by the developer.",
                "Merge imports from the same crate into a single use statement. Conversely, imports from different crates are split into separate statements.",
                "Merge imports from the same module into a single use statement. Conversely, imports from different modules are split into separate statements.",
                "Flatten imports so that each has its own use statement.",
                "Merge all imports into a single use statement as long as they have the same visibility and attributes."
            ],
        },
        "ImportPrefixDef" => set! {
            "type": "string",
            "enum": [
                "plain",
                "self",
                "crate"
            ],
            "enumDescriptions": [
                "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.",
                "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item. Prefixes `self` in front of the path if it starts with a module.",
                "Force import paths to be absolute by always starting them with `crate` or the extern crate name they come from."
            ],
        },
        "Vec<ManifestOrProjectJson>" => set! {
            "type": "array",
            "items": { "type": ["string", "object"] },
        },
        "WorkspaceSymbolSearchScopeDef" => set! {
            "type": "string",
            "enum": ["workspace", "workspace_and_dependencies"],
            "enumDescriptions": [
                "Search in current workspace only.",
                "Search in current workspace and dependencies."
            ],
        },
        "WorkspaceSymbolSearchKindDef" => set! {
            "type": "string",
            "enum": ["only_types", "all_symbols"],
            "enumDescriptions": [
                "Search for types only.",
                "Search for all symbols kinds."
            ],
        },
        "LifetimeElisionDef" => set! {
            "type": "string",
            "enum": [
                "always",
                "never",
                "skip_trivial"
            ],
            "enumDescriptions": [
                "Always show lifetime elision hints.",
                "Never show lifetime elision hints.",
                "Only show lifetime elision hints if a return type is involved."
            ]
        },
        "ClosureReturnTypeHintsDef" => set! {
            "type": "string",
            "enum": [
                "always",
                "never",
                "with_block"
            ],
            "enumDescriptions": [
                "Always show type hints for return types of closures.",
                "Never show type hints for return types of closures.",
                "Only show type hints for return types of closures with blocks."
            ]
        },
        "ReborrowHintsDef" => set! {
            "type": "string",
            "enum": [
                "always",
                "never",
                "mutable"
            ],
            "enumDescriptions": [
                "Always show reborrow hints.",
                "Never show reborrow hints.",
                "Only show mutable reborrow hints."
            ]
        },
        "AdjustmentHintsDef" => set! {
            "type": "string",
            "enum": [
                "always",
                "never",
                "reborrow"
            ],
            "enumDescriptions": [
                "Always show all adjustment hints.",
                "Never show adjustment hints.",
                "Only show auto borrow and dereference adjustment hints."
            ]
        },
        "DiscriminantHintsDef" => set! {
            "type": "string",
            "enum": [
                "always",
                "never",
                "fieldless"
            ],
            "enumDescriptions": [
                "Always show all discriminant hints.",
                "Never show discriminant hints.",
                "Only show discriminant hints on fieldless enum variants."
            ]
        },
        "AdjustmentHintsModeDef" => set! {
            "type": "string",
            "enum": [
                "prefix",
                "postfix",
                "prefer_prefix",
                "prefer_postfix",
            ],
            "enumDescriptions": [
                "Always show adjustment hints as prefix (`*expr`).",
                "Always show adjustment hints as postfix (`expr.*`).",
                "Show prefix or postfix depending on which uses less parenthesis, preferring prefix.",
                "Show prefix or postfix depending on which uses less parenthesis, preferring postfix.",
            ]
        },
        "CargoFeaturesDef" => set! {
            "anyOf": [
                {
                    "type": "string",
                    "enum": [
                        "all"
                    ],
                    "enumDescriptions": [
                        "Pass `--all-features` to cargo",
                    ]
                },
                {
                    "type": "array",
                    "items": { "type": "string" }
                }
            ],
        },
        "Option<CargoFeaturesDef>" => set! {
            "anyOf": [
                {
                    "type": "string",
                    "enum": [
                        "all"
                    ],
                    "enumDescriptions": [
                        "Pass `--all-features` to cargo",
                    ]
                },
                {
                    "type": "array",
                    "items": { "type": "string" }
                },
                { "type": "null" }
            ],
        },
        "CallableCompletionDef" => set! {
            "type": "string",
            "enum": [
                "fill_arguments",
                "add_parentheses",
                "none",
            ],
            "enumDescriptions": [
                "Add call parentheses and pre-fill arguments.",
                "Add call parentheses.",
                "Do no snippet completions for callables."
            ]
        },
        "SignatureDetail" => set! {
            "type": "string",
            "enum": ["full", "parameters"],
            "enumDescriptions": [
                "Show the entire signature.",
                "Show only the parameters."
            ],
        },
        "FilesWatcherDef" => set! {
            "type": "string",
            "enum": ["client", "server"],
            "enumDescriptions": [
                "Use the client (editor) to watch files for changes",
                "Use server-side file watching",
            ],
        },
        "AnnotationLocation" => set! {
            "type": "string",
            "enum": ["above_name", "above_whole_item"],
            "enumDescriptions": [
                "Render annotations above the name of the item.",
                "Render annotations above the whole item, including documentation comments and attributes."
            ],
        },
        "InvocationStrategy" => set! {
            "type": "string",
            "enum": ["per_workspace", "once"],
            "enumDescriptions": [
                "The command will be executed for each workspace.",
                "The command will be executed once."
            ],
        },
        "InvocationLocation" => set! {
            "type": "string",
            "enum": ["workspace", "root"],
            "enumDescriptions": [
                "The command will be executed in the corresponding workspace root.",
                "The command will be executed in the project root."
            ],
        },
        "Option<CheckOnSaveTargets>" => set! {
            "anyOf": [
                {
                    "type": "null"
                },
                {
                    "type": "string",
                },
                {
                    "type": "array",
                    "items": { "type": "string" }
                },
            ],
        },
        "ClosureStyle" => set! {
            "type": "string",
            "enum": ["impl_fn", "ra_ap_rust_analyzer", "with_id", "hide"],
            "enumDescriptions": [
                "`impl_fn`: `impl FnMut(i32, u64) -> i8`",
                "`ra_ap_rust_analyzer`: `|i32, u64| -> i8`",
                "`with_id`: `{closure#14352}`, where that id is the unique number of the closure in r-a internals",
                "`hide`: Shows `...` for every closure type",
            ],
        },
        "Option<MemoryLayoutHoverRenderKindDef>" => set! {
            "anyOf": [
                {
                    "type": "null"
                },
                {
                    "type": "string",
                    "enum": ["both", "decimal", "hexadecimal", ],
                    "enumDescriptions": [
                        "Render as 12 (0xC)",
                        "Render as 12",
                        "Render as 0xC"
                    ],
                },
            ],
        },
        "Option<TargetDirectory>" => set! {
            "anyOf": [
                {
                    "type": "null"
                },
                {
                    "type": "boolean"
                },
                {
                    "type": "string"
                },
            ],
        },
        "NumThreads" => set! {
            "anyOf": [
                {
                    "type": "number",
                    "minimum": 0,
                    "maximum": 255
                },
                {
                    "type": "string",
                    "enum": ["physical", "logical", ],
                    "enumDescriptions": [
                        "Use the number of physical cores",
                        "Use the number of logical cores",
                    ],
                },
            ],
        },
        "Option<NumThreads>" => set! {
            "anyOf": [
                {
                    "type": "null"
                },
                {
                    "type": "number",
                    "minimum": 0,
                    "maximum": 255
                },
                {
                    "type": "string",
                    "enum": ["physical", "logical", ],
                    "enumDescriptions": [
                        "Use the number of physical cores",
                        "Use the number of logical cores",
                    ],
                },
            ],
        },
        _ => panic!("missing entry for {ty}: {default} (field {field})"),
    }

    map.into()
}

fn validate_toml_table(
    known_ptrs: &[&[&'static str]],
    toml: &toml::Table,
    ptr: &mut String,
    error_sink: &mut Vec<(String, toml::de::Error)>,
) {
    let verify = |ptr: &String| known_ptrs.iter().any(|ptrs| ptrs.contains(&ptr.as_str()));

    let l = ptr.len();
    for (k, v) in toml {
        if !ptr.is_empty() {
            ptr.push('_');
        }
        ptr.push_str(k);

        match v {
            // This is a table config, any entry in it is therefor valid
            toml::Value::Table(_) if verify(ptr) => (),
            toml::Value::Table(table) => validate_toml_table(known_ptrs, table, ptr, error_sink),
            _ if !verify(ptr) => error_sink
                .push((ptr.replace('_', "/"), toml::de::Error::custom("unexpected field"))),
            _ => (),
        }

        ptr.truncate(l);
    }
}

#[cfg(test)]
fn manual(fields: &[SchemaField]) -> String {
    fields.iter().fold(String::new(), |mut acc, (field, _ty, doc, default)| {
        let name = format!("rust-analyzer.{}", field.replace('_', "."));
        let doc = doc_comment_to_string(doc);
        if default.contains('\n') {
            format_to_acc!(
                acc,
                r#"[[{name}]]{name}::
+
--
Default:
----
{default}
----
{doc}
--
"#
            )
        } else {
            format_to_acc!(acc, "[[{name}]]{name} (default: `{default}`)::\n+\n--\n{doc}--\n")
        }
    })
}

fn doc_comment_to_string(doc: &[&str]) -> String {
    doc.iter()
        .map(|it| it.strip_prefix(' ').unwrap_or(it))
        .fold(String::new(), |mut acc, it| format_to_acc!(acc, "{it}\n"))
}

#[cfg(test)]
mod tests {
    use std::fs;

    use test_utils::{ensure_file_contents, project_root};

    use super::*;

    #[test]
    fn generate_package_json_config() {
        let s = Config::json_schema();
        let schema = format!("{s:#}");
        let mut schema = schema
            .trim_start_matches('[')
            .trim_end_matches(']')
            .replace("  ", "    ")
            .replace('\n', "\n        ")
            .trim_start_matches('\n')
            .trim_end()
            .to_owned();
        schema.push_str(",\n");

        // Transform the asciidoc form link to markdown style.
        //
        // https://link[text] => [text](https://link)
        let url_matches = schema.match_indices("https://");
        let mut url_offsets = url_matches.map(|(idx, _)| idx).collect::<Vec<usize>>();
        url_offsets.reverse();
        for idx in url_offsets {
            let link = &schema[idx..];
            // matching on whitespace to ignore normal links
            if let Some(link_end) = link.find(|c| c == ' ' || c == '[') {
                if link.chars().nth(link_end) == Some('[') {
                    if let Some(link_text_end) = link.find(']') {
                        let link_text = link[link_end..(link_text_end + 1)].to_string();

                        schema.replace_range((idx + link_end)..(idx + link_text_end + 1), "");
                        schema.insert(idx, '(');
                        schema.insert(idx + link_end + 1, ')');
                        schema.insert_str(idx, &link_text);
                    }
                }
            }
        }

        let package_json_path = project_root().join("editors/code/package.json");
        let mut package_json = fs::read_to_string(&package_json_path).unwrap();

        let start_marker =
            "            {\n                \"title\": \"$generated-start\"\n            },\n";
        let end_marker =
            "            {\n                \"title\": \"$generated-end\"\n            }\n";

        let start = package_json.find(start_marker).unwrap() + start_marker.len();
        let end = package_json.find(end_marker).unwrap();

        let p = remove_ws(&package_json[start..end]);
        let s = remove_ws(&schema);
        if !p.contains(&s) {
            package_json.replace_range(start..end, &schema);
            ensure_file_contents(&package_json_path, &package_json)
        }
    }

    #[test]
    fn generate_config_documentation() {
        let docs_path = project_root().join("docs/user/generated_config.adoc");
        let expected = FullConfigInput::manual();
        ensure_file_contents(&docs_path, &expected);
    }

    fn remove_ws(text: &str) -> String {
        text.replace(char::is_whitespace, "")
    }

    #[test]
    fn proc_macro_srv_null() {
        let mut config = Config::new(
            AbsPathBuf::try_from(project_root()).unwrap(),
            Default::default(),
            vec![],
            None,
            None,
        );

        let mut change = ConfigChange::default();
        change.change_client_config(serde_json::json!({
            "procMacro" : {
                "server": null,
        }}));

        (config, _, _) = config.apply_change(change);
        assert_eq!(config.proc_macro_srv(), None);
    }

    #[test]
    fn proc_macro_srv_abs() {
        let mut config = Config::new(
            AbsPathBuf::try_from(project_root()).unwrap(),
            Default::default(),
            vec![],
            None,
            None,
        );
        let mut change = ConfigChange::default();
        change.change_client_config(serde_json::json!({
        "procMacro" : {
            "server": project_root().display().to_string(),
        }}));

        (config, _, _) = config.apply_change(change);
        assert_eq!(config.proc_macro_srv(), Some(AbsPathBuf::try_from(project_root()).unwrap()));
    }

    #[test]
    fn proc_macro_srv_rel() {
        let mut config = Config::new(
            AbsPathBuf::try_from(project_root()).unwrap(),
            Default::default(),
            vec![],
            None,
            None,
        );

        let mut change = ConfigChange::default();

        change.change_client_config(serde_json::json!({
        "procMacro" : {
            "server": "./server"
        }}));

        (config, _, _) = config.apply_change(change);

        assert_eq!(
            config.proc_macro_srv(),
            Some(AbsPathBuf::try_from(project_root().join("./server")).unwrap())
        );
    }

    #[test]
    fn cargo_target_dir_unset() {
        let mut config = Config::new(
            AbsPathBuf::try_from(project_root()).unwrap(),
            Default::default(),
            vec![],
            None,
            None,
        );

        let mut change = ConfigChange::default();

        change.change_client_config(serde_json::json!({
            "rust" : { "analyzerTargetDir" : null }
        }));

        (config, _, _) = config.apply_change(change);
        assert_eq!(config.cargo_targetDir(), &None);
        assert!(
            matches!(config.flycheck(), FlycheckConfig::CargoCommand { options, .. } if options.target_dir.is_none())
        );
    }

    #[test]
    fn cargo_target_dir_subdir() {
        let mut config = Config::new(
            AbsPathBuf::try_from(project_root()).unwrap(),
            Default::default(),
            vec![],
            None,
            None,
        );

        let mut change = ConfigChange::default();
        change.change_client_config(serde_json::json!({
            "rust" : { "analyzerTargetDir" : true }
        }));

        (config, _, _) = config.apply_change(change);

        assert_eq!(config.cargo_targetDir(), &Some(TargetDirectory::UseSubdirectory(true)));
        assert!(
            matches!(config.flycheck(), FlycheckConfig::CargoCommand { options, .. } if options.target_dir == Some(Utf8PathBuf::from("target/rust-analyzer")))
        );
    }

    #[test]
    fn cargo_target_dir_relative_dir() {
        let mut config = Config::new(
            AbsPathBuf::try_from(project_root()).unwrap(),
            Default::default(),
            vec![],
            None,
            None,
        );

        let mut change = ConfigChange::default();
        change.change_client_config(serde_json::json!({
            "rust" : { "analyzerTargetDir" : "other_folder" }
        }));

        (config, _, _) = config.apply_change(change);

        assert_eq!(
            config.cargo_targetDir(),
            &Some(TargetDirectory::Directory(Utf8PathBuf::from("other_folder")))
        );
        assert!(
            matches!(config.flycheck(), FlycheckConfig::CargoCommand { options, .. } if options.target_dir == Some(Utf8PathBuf::from("other_folder")))
        );
    }

    #[test]
    fn toml_unknown_key() {
        let config = Config::new(
            AbsPathBuf::try_from(project_root()).unwrap(),
            Default::default(),
            vec![],
            None,
            None,
        );

        let mut change = ConfigChange::default();

        change.change_root_ratoml(Some(
            toml::toml! {
                [cargo.cfgs]
                these = "these"
                should = "should"
                be = "be"
                valid = "valid"

                [invalid.config]
                err = "error"

                [cargo]
                target = "ok"

                // FIXME: This should be an error
                [cargo.sysroot]
                non-table = "expected"
            }
            .to_string()
            .into(),
        ));

        let (config, e, _) = config.apply_change(change);
        expect_test::expect![[r#"
            ConfigErrors(
                [
                    Toml {
                        config_key: "invalid/config/err",
                        error: Error {
                            inner: Error {
                                inner: TomlError {
                                    message: "unexpected field",
                                    raw: None,
                                    keys: [],
                                    span: None,
                                },
                            },
                        },
                    },
                ],
            )
        "#]]
        .assert_debug_eq(&e);
        let mut change = ConfigChange::default();

        change.change_user_config(Some(
            toml::toml! {
                [cargo.cfgs]
                these = "these"
                should = "should"
                be = "be"
                valid = "valid"
            }
            .to_string()
            .into(),
        ));
        let (_, e, _) = config.apply_change(change);
        expect_test::expect![[r#"
            ConfigErrors(
                [
                    Toml {
                        config_key: "invalid/config/err",
                        error: Error {
                            inner: Error {
                                inner: TomlError {
                                    message: "unexpected field",
                                    raw: None,
                                    keys: [],
                                    span: None,
                                },
                            },
                        },
                    },
                ],
            )
        "#]]
        .assert_debug_eq(&e);
    }
}