1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462 | ------------------------------------------------------------------------------
-- Language Server Protocol --
-- --
-- Copyright (C) 2018-2022, AdaCore --
-- --
-- This is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. This software is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- --
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public --
-- License for more details. You should have received a copy of the GNU --
-- General Public License distributed with this software; see file --
-- COPYING3. If not, go to http://www.gnu.org/licenses for a complete copy --
-- of the license. --
------------------------------------------------------------------------------
with Ada.Calendar; use Ada.Calendar;
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Ada.Characters.Latin_1;
with Ada.Characters.Wide_Wide_Latin_1;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Exceptions;
with Ada.Strings.Wide_Wide_Unbounded;
with Ada.Strings.UTF_Encoding;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Unchecked_Deallocation;
with GNAT.OS_Lib; use GNAT.OS_Lib;
with GNAT.Strings;
with GNATCOLL.JSON;
with GNATCOLL.Utils; use GNATCOLL.Utils;
with VSS.Characters.Latin;
with VSS.Strings.Character_Iterators;
with VSS.Strings.Conversions;
with VSS.Unicode;
with LSP.Ada_Documents; use LSP.Ada_Documents;
with LSP.Search; use LSP.Search;
with LSP.Ada_Contexts; use LSP.Ada_Contexts;
with LSP.Ada_Completions;
with LSP.Ada_Completions.Aspects;
with LSP.Ada_Completions.Attributes;
with LSP.Ada_Completions.End_Names;
with LSP.Ada_Completions.Keywords;
with LSP.Ada_Completions.Names;
with LSP.Ada_Completions.Parameters;
with LSP.Ada_Completions.Pragmas;
with LSP.Ada_Handlers.Invisibles;
with LSP.Ada_Handlers.Named_Parameters_Commands;
with LSP.Ada_Handlers.Refactor_Change_Parameter_Mode;
with LSP.Ada_Handlers.Refactor_Change_Parameters_Type;
with LSP.Ada_Handlers.Refactor_Change_Parameters_Default_Value;
with LSP.Ada_Handlers.Refactor_Add_Parameter;
with LSP.Ada_Handlers.Refactor_Introduce_Parameter;
with LSP.Ada_Handlers.Refactor_Extract_Subprogram;
with LSP.Ada_Handlers.Refactor_Imports_Commands;
with LSP.Ada_Handlers.Refactor_Move_Parameter;
with LSP.Ada_Handlers.Refactor_Remove_Parameter;
with LSP.Ada_Handlers.Refactor_Suppress_Seperate;
with LSP.Ada_Handlers.Refactor_Pull_Up_Declaration;
with LSP.Ada_Handlers.Project_Diagnostics;
with LSP.Ada_Project_Environments;
with LSP.Client_Side_File_Monitors;
with LSP.Commands;
with LSP.Common; use LSP.Common;
with LSP.Ada_Handlers.File_Readers;
with LSP.Diagnostic_Sources;
with LSP.Errors;
with LSP.Lal_Utils; use LSP.Lal_Utils;
with LSP.Messages.Client_Requests;
with LSP.Messages.Server_Notifications;
with LSP.Servers.FS_Watch;
with LSP.Types; use LSP.Types;
with LSP.Generic_Cancel_Check;
with Langkit_Support.Slocs;
with Langkit_Support.Text;
with Laltools.Common;
with Laltools.Refactor_Imports;
with Laltools.Refactor.Subprogram_Signature;
with Laltools.Refactor.Safe_Rename;
with Laltools.Refactor.Suppress_Separate;
with Laltools.Refactor.Extract_Subprogram;
with Laltools.Refactor.Introduce_Parameter;
with Laltools.Refactor.Pull_Up_Declaration;
with Laltools.Refactor.Subprogram_Signature.Change_Parameters_Type;
with Laltools.Refactor.Subprogram_Signature.Change_Parameters_Default_Value;
with Laltools.Refactor.Subprogram_Signature.Remove_Parameter;
with Libadalang.Analysis;
with Libadalang.Common; use Libadalang.Common;
with Libadalang.Doc_Utils;
with Libadalang.Helpers;
with Libadalang.Preprocessing;
with GNATdoc.Comments.Helpers;
with URIs;
package body LSP.Ada_Handlers is
type Cancel_Countdown is mod 128;
-- Counter to restrict frequency of Request.Canceled checks
Allow_Incremental_Text_Changes : constant GNATCOLL.Traces.Trace_Handle :=
GNATCOLL.Traces.Create ("ALS.ALLOW_INCREMENTAL_TEXT_CHANGES",
GNATCOLL.Traces.On);
-- Trace to activate the support for incremental text changes.
Notifications_For_Imprecise : constant GNATCOLL.Traces.Trace_Handle :=
GNATCOLL.Traces.Create ("ALS.NOTIFICATIONS_FOR_IMPRECISE_NAVIGATION",
GNATCOLL.Traces.Off);
Runtime_Indexing : constant GNATCOLL.Traces.Trace_Handle :=
GNATCOLL.Traces.Create ("ALS.RUNTIME_INDEXING",
GNATCOLL.Traces.On);
-- Trace to enable/disable runtime indexing. Useful for the testsuite.
Partial_GNATpp : constant GNATCOLL.Traces.Trace_Handle :=
GNATCOLL.Traces.Create ("ALS.PARTIAL_GNATPP",
GNATCOLL.Traces.On);
-- Use partial formatting mode of gnatpp if On. Otherwise, use diff
-- algorithm.
Is_Parent : constant LSP.Messages.AlsReferenceKind_Set :=
(Is_Server_Side => True,
As_Flags => [LSP.Messages.Parent => True, others => False]);
Is_Child : constant LSP.Messages.AlsReferenceKind_Set :=
(Is_Server_Side => True,
As_Flags => [LSP.Messages.Child => True, others => False]);
-- Convenient constants
Line_Feed : constant Wide_Wide_Character :=
Ada.Characters.Wide_Wide_Latin_1.LF;
-- Backspace : constant Character := Ada.Characters.Latin_1.BS;
procedure Log_Imprecise_Xref_Message
(Self : access Message_Handler;
URI : LSP.Messages.DocumentUri;
Position : LSP.Messages.Position);
-- Log a message to record that we have made an imprecise navigation
procedure Log_Unexpected_Null_Document
(Self : access Message_Handler;
Where : String);
-- Log a message saying we unexpectedly couldn't find an open document
procedure Imprecise_Resolve_Name
(Self : access Message_Handler;
In_Context : Context_Access;
Position : LSP.Messages.TextDocumentPositionParams'Class;
Definition : out Libadalang.Analysis.Defining_Name);
-- If node at given Position is a name, then resolve it.
-- Send a message in case of a possible imprecise result.
-- See description of Msg_Type in Send_Imprecise_Xref_Message comments.
procedure Show_Message
(Self : access Message_Handler;
Text : VSS.Strings.Virtual_String;
Mode : LSP.Messages.MessageType := LSP.Messages.Error);
-- Convenience function to send a message to the user.
procedure Show_Imprecise_Reference_Warning
(Self : access Message_Handler;
Operation : String);
-- Convenience function to send the warning that the navigation is
-- imprecise.
function Get_Unique_Progress_Token
(Self : access Message_Handler;
Operation : String := "") return LSP_Number_Or_String;
-- Return an unique token for indicating progress
procedure Index_Files (Self : access Message_Handler);
-- Index all loaded files in each context. Emit progresormation.
procedure Release_Contexts_And_Project_Info (Self : access Message_Handler);
-- Release the memory associated to project information in Self
function Contexts_For_File
(Self : access Message_Handler;
File : Virtual_File)
return LSP.Ada_Context_Sets.Context_Lists.List;
function Contexts_For_URI
(Self : access Message_Handler;
URI : LSP.Messages.DocumentUri)
return LSP.Ada_Context_Sets.Context_Lists.List;
-- Return a list of contexts that are suitable for the given File/URI:
-- a list of all contexts where the file is known to be part of the
-- project tree, or is a runtime file for this project. If the file
-- is not known to any project, return an empty list.
-- The result should not be freed.
procedure Reload_Implicit_Project_Dirs (Self : access Message_Handler);
-- Reload as project source dirs the directories in
-- Self.Project_Dirs_Loaded.
procedure Publish_Diagnostics
(Self : access Message_Handler'Class;
Document : not null LSP.Ada_Documents.Document_Access);
-- Publish diagnostic messages for given document if needed
function Is_Ada_Source
(Self : access Message_Handler;
File : GNATCOLL.VFS.Virtual_File)
return Boolean
is (Is_Ada_File (Self.Project_Tree, File));
-- Checks if File is an Ada source of Self's project. This is needed
-- to filter non Ada sources on notifications like
-- DidCreate/Rename/DeleteFiles and DidChangeWatchedFiles since it's not
-- possible to filter them in the FileOperationRegistrationOptions.
function Compute_File_Operations_Server_Capabilities
(Self : access Message_Handler)
return LSP.Messages.Optional_FileOperationsServerCapabilities;
-- Computes FileOperationsServerCapabilities based on the client's
-- capabilities. If the client does have any, then this function returns
-- an unset object.
function Compute_File_Operation_Registration_Options
(Self : access Message_Handler)
return LSP.Messages.FileOperationRegistrationOptions;
-- Computes FileOperationRegistrationOptions based on the project held by
-- Self. These registration options will include any file that is in a
-- source folder of Self's project. We can't filter non Ada sources here,
-- only on the DidCreate/Rename/DeleteFiles and DidChangeWatchedFiles
-- notifications.
function Format
(Self : in out LSP.Ada_Contexts.Context;
Document : LSP.Ada_Documents.Document_Access;
Span : LSP.Messages.Span;
Options : LSP.Messages.FormattingOptions;
Handler : access Message_Handler)
return LSP.Messages.Server_Responses.Formatting_Response;
-- Format the text of the given document in the given range (span).
function Range_Format
(Self : in out LSP.Ada_Contexts.Context;
Document : LSP.Ada_Documents.Document_Access;
Span : LSP.Messages.Span;
Options : LSP.Messages.FormattingOptions)
return LSP.Messages.Server_Responses.Formatting_Response;
-- Format the text of the given document in the given range (span).
type File_Span is record
File : GNATCOLL.VFS.Virtual_File;
Span : LSP.Messages.Span;
end record;
-- A text range in a file
function Hash (Value : File_Span) return Ada.Containers.Hash_Type;
package File_Span_Sets is new Ada.Containers.Hashed_Sets
(Element_Type => File_Span,
Hash => Hash,
Equivalent_Elements => "=");
---------------------
-- Project loading --
---------------------
-- The heuristics that is used for loading a project is the following:
--
-- * if a project (and optionally a scenario) was specified by
-- the user via the workspace/didChangeConfiguration request,
-- attempt to use this. If this fails to load, report an error
-- but do not attempt to load another project.
-- => This case is handled by a call to Load_Project in
-- On_DidChangeConfiguration_Notification.
--
-- * if no project was specified by the user, then look in the Root
-- directory, mimicking the behavior of gprbuild:
-- * if there are zero .gpr files in this directory, load the
-- implicit project
-- * if there is exactly one .gpr file in this directory, load
-- it, returning an error if this failed
-- * if there are more than one .gpr files in this directory,
-- display an error
-- => These cases are handled by Ensure_Project_Loaded
--
-- At any point where requests are made, Self.Contexts should
-- contain one or more contexts, each one containing a non-aggregate
-- project hierarchy.
--
-- The attempt to load a project should be done in reaction to
-- On_DidChangeConfiguration_Notification. However, the IDEs that
-- are not configured specifically for this language server might
-- not pass a .gpr file to didChangeConfiguration: for these IDEs,
-- we fallback to loading the project the first time an editor is
-- open or a request on non-openned file.
procedure Ensure_Project_Loaded (Self : access Message_Handler);
procedure Ensure_Project_Loaded
(Self : access Message_Handler;
URI : LSP.Types.LSP_URI);
-- This function makes sure that the contexts in Self are properly
-- initialized and a project is loaded. If they are not initialized,
-- initialize them. Use URI to find a custom root directory if provided.
procedure Load_Implicit_Project
(Self : access Message_Handler;
Status : Implicit_Project_Loaded);
-- Load the implicit project
procedure Load_Project
(Self : access Message_Handler;
GPR : Virtual_File;
Scenario : LSP.Types.LSP_Any;
Charset : String;
Status : Load_Project_Status;
Relocate_Build_Tree : Virtual_File := No_File;
Root_Dir : Virtual_File := No_File);
-- Attempt to load the given project file, with the scenario provided.
-- This unloads all currently loaded project contexts.
procedure Mark_Source_Files_For_Indexing (Self : access Message_Handler);
-- Mark all sources in all projects for indexing. This factorizes code
-- between Load_Project and Load_Implicit_Project.
function URI_To_File
(Self : Message_Handler'Class;
URI : VSS.Strings.Virtual_String) return VSS.Strings.Virtual_String;
-- Turn URI into path
-----------------------
-- Contexts_For_File --
-----------------------
function Contexts_For_File
(Self : access Message_Handler;
File : Virtual_File)
return LSP.Ada_Context_Sets.Context_Lists.List
is
function Is_A_Source (Self : LSP.Ada_Contexts.Context) return Boolean is
(Self.Is_Part_Of_Project (File));
-- Return True if File is a source of the project held by Context
begin
-- If the file does not exist on disk, assume this is a file
-- being created and, as a special convenience in this case,
-- assume it could belong to any project.
if not File.Is_Regular_File
-- If the file is a runtime file for the loaded project environment,
-- all projects can see it.
or else Self.Project_Predefined_Sources.Contains (File)
then
return Self.Contexts.Each_Context;
end if;
-- List contexts where File is a source of the project hierarchy
return Self.Contexts.Each_Context (Is_A_Source'Unrestricted_Access);
end Contexts_For_File;
----------------------
-- Contexts_For_URI --
----------------------
function Contexts_For_URI
(Self : access Message_Handler;
URI : LSP.Messages.DocumentUri)
return LSP.Ada_Context_Sets.Context_Lists.List
is
File : constant Virtual_File := Self.To_File (URI);
begin
return Self.Contexts_For_File (File);
end Contexts_For_URI;
-----------------------
-- Get_Open_Document --
-----------------------
overriding function Get_Open_Document
(Self : access Message_Handler;
URI : LSP.Messages.DocumentUri;
Force : Boolean := False)
return LSP.Ada_Documents.Document_Access
is
File : constant GNATCOLL.VFS.Virtual_File := Self.To_File (URI);
begin
Self.Ensure_Project_Loaded;
if Self.Open_Documents.Contains (File) then
return LSP.Ada_Documents.Document_Access
(Self.Open_Documents.Element (File));
elsif Force then
declare
Document : constant Internal_Document_Access :=
new LSP.Ada_Documents.Document (Self.Trace);
begin
Document.Initialize (URI, VSS.Strings.Empty_Virtual_String, null);
return LSP.Ada_Documents.Document_Access (Document);
end;
else
return null;
end if;
end Get_Open_Document;
-------------------------------
-- Get_Open_Document_Version --
-------------------------------
overriding
function Get_Open_Document_Version
(Self : access Message_Handler;
URI : LSP.Messages.DocumentUri)
return LSP.Messages.OptionalVersionedTextDocumentIdentifier
is
Target_Text_Document : constant LSP.Ada_Documents.Document_Access :=
Self.Get_Open_Document (URI);
begin
-- If the target textDocument hasn't been opened in the editor
-- then ALS hasn't received an open notification before. Therefore
-- Target_Text_Document will be null.
-- In that case, its VersionedTextDocumentIdentifier.version will
-- be null.
if Target_Text_Document = null then
return (URI, LSP.Messages.Nullable_Number'(Is_Set => False));
else
return
(uri => Target_Text_Document.Versioned_Identifier.uri,
version =>
(True, Target_Text_Document.Versioned_Identifier.version));
end if;
end Get_Open_Document_Version;
----------------------------------
-- Log_Unexpected_Null_Document --
----------------------------------
procedure Log_Unexpected_Null_Document
(Self : access Message_Handler;
Where : String) is
begin
Self.Trace.Trace ("Unexpected null document in " & Where);
end Log_Unexpected_Null_Document;
--------------------------------
-- Log_Imprecise_Xref_Message --
--------------------------------
procedure Log_Imprecise_Xref_Message
(Self : access Message_Handler;
URI : LSP.Messages.DocumentUri;
Position : LSP.Messages.Position)
is
File : constant GNATCOLL.VFS.Virtual_File := Self.To_File (URI);
begin
Self.Trace.Trace
("Imprecise fallback used to compute cross-references on entity at "
& File.Display_Base_Name
& ":" & Integer'Image (Integer (Position.line) + 1)
& ":" & Integer'Image (Integer (Position.character) + 1));
end Log_Imprecise_Xref_Message;
----------------------------
-- Imprecise_Resolve_Name --
----------------------------
procedure Imprecise_Resolve_Name
(Self : access Message_Handler;
In_Context : Context_Access;
Position : LSP.Messages.TextDocumentPositionParams'Class;
Definition : out Libadalang.Analysis.Defining_Name)
is
use type Libadalang.Analysis.Name;
Name_Node : constant Libadalang.Analysis.Name :=
Laltools.Common.Get_Node_As_Name
(In_Context.Get_Node_At
(Get_Open_Document (Self, Position.textDocument.uri),
Position,
Project_Only => False));
Imprecise : Boolean;
begin
if Name_Node = Libadalang.Analysis.No_Name then
return;
end if;
Definition := Laltools.Common.Resolve_Name
(Name_Node,
Self.Trace,
Imprecise => Imprecise);
-- If we used the imprecise fallback to get to the definition, log it
if Imprecise then
Self.Log_Imprecise_Xref_Message
(URI => Position.textDocument.uri,
Position => Position.position);
end if;
end Imprecise_Resolve_Name;
---------------------------------------
-- Release_Contexts_And_Project_Info --
---------------------------------------
procedure Release_Contexts_And_Project_Info
(Self : access Message_Handler)
is
use GNATCOLL.Projects;
begin
Self.Contexts.Cleanup;
if Self.Project_Tree /= null then
Self.Project_Tree.Unload;
Free (Self.Project_Tree);
end if;
if Self.Project_Environment /= null then
Free (Self.Project_Environment);
end if;
Self.Project_Predefined_Sources.Clear;
Self.Project_Dirs_Loaded.Clear;
-- Clear indexing data
Self.Files_To_Index.Clear;
Self.Total_Files_To_Index := 1;
Self.Total_Files_Indexed := 0;
end Release_Contexts_And_Project_Info;
--------------------------
-- Stop_File_Monitoring --
--------------------------
procedure Stop_File_Monitoring (Self : access Message_Handler) is
begin
if Self.File_Monitor.Assigned then
Self.File_Monitor.Stop_Monitoring_Directories;
end if;
end Stop_File_Monitoring;
-------------
-- Cleanup --
-------------
procedure Cleanup (Self : access Message_Handler)
is
begin
-- Cleanup documents
for Document of Self.Open_Documents loop
Free (Document);
end loop;
Self.Open_Documents.Clear;
-- Cleanup contexts, project and environment
Self.Release_Contexts_And_Project_Info;
-- Free the file monitor
LSP.File_Monitors.Unchecked_Free (Self.File_Monitor);
end Cleanup;
----------------
-- Clean_Logs --
----------------
procedure Clean_Logs (Self : access Message_Handler; Dir : Virtual_File) is
Files : File_Array_Access := Read_Dir (Dir, Files_Only);
Dummy : Boolean;
Cpt : Integer := 0;
begin
Sort (Files.all);
-- Browse the log files in reverse timestamp order
for F of reverse Files.all loop
-- Filter out files like traces.cfg
if GNATCOLL.Utils.Ends_With (+F.Base_Name, ".log") then
Cpt := Cpt + 1;
-- Delete the old logs
if Cpt > Self.Log_Threshold then
Delete (F, Dummy);
end if;
end if;
end loop;
Unchecked_Free (Files);
end Clean_Logs;
-----------------------
-- Exit_Notification --
-----------------------
overriding procedure On_Exit_Notification (Self : access Message_Handler) is
begin
Self.Server.Stop;
end On_Exit_Notification;
----------------------------------
-- Reload_Implicit_Project_Dirs --
----------------------------------
procedure Reload_Implicit_Project_Dirs (Self : access Message_Handler) is
Attr : GNAT.Strings.String_List
(1 .. Natural (Self.Project_Dirs_Loaded.Length));
Index : Natural := 1;
use GNATCOLL.Projects;
begin
for Dir of Self.Project_Dirs_Loaded loop
Attr (Index) := new String'(Dir.Display_Full_Name);
Index := Index + 1;
end loop;
Set_Attribute
(Self.Project_Tree.Root_Project,
Source_Dirs_Attribute,
Attr);
Self.Project_Tree.Recompute_View;
for J in Attr'Range loop
GNAT.Strings.Free (Attr (J));
end loop;
end Reload_Implicit_Project_Dirs;
---------------------------
-- Load_Implicit_Project --
---------------------------
procedure Load_Implicit_Project
(Self : access Message_Handler;
Status : Implicit_Project_Loaded)
is
C : constant Context_Access := new Context (Self.Trace);
Attr : GNAT.Strings.String_List (1 .. 1);
use GNATCOLL.Projects;
Reader : LSP.Ada_Handlers.File_Readers.LSP_Reader_Interface (Self);
begin
Self.Trace.Trace ("Loading the implicit project");
Self.Project_Status := Status;
Self.Release_Contexts_And_Project_Info;
Self.Project_Environment :=
new LSP.Ada_Project_Environments.LSP_Project_Environment;
Initialize (Self.Project_Environment);
Self.Project_Environment.Set_Trusted_Mode (not Self.Follow_Symlinks);
Self.Project_Tree := new Project_Tree;
C.Initialize (Reader, Self.Follow_Symlinks,
As_Fallback_Context => True);
-- Note: we would call Load_Implicit_Project here, but this has
-- two problems:
-- - there is a bug under Windows where the files returned by
-- Source_Files have an extraneous directory separator
-- - the implicit project relies on the current working
-- of the ALS, which imposes a restriction on clients, and
-- is an extra pitfall for developers of this server
--
-- Instead, use Load_Empty_Project and set the source dir and
-- language manually: this does not have these inconvenients.
Load_Empty_Project
(Self.Project_Tree.all, Self.Project_Environment);
Attr := [1 => new String'("Ada")];
Set_Attribute
(Self.Project_Tree.Root_Project, Languages_Attribute, Attr);
GNAT.Strings.Free (Attr (1));
-- When there is no .gpr, create a project which loads the
-- root directory in the workspace.
Self.Project_Dirs_Loaded.Include (Self.Root);
Self.Reload_Implicit_Project_Dirs;
C.Load_Project (Self.Project_Tree,
Self.Project_Tree.Root_Project,
"iso-8859-1");
for File of Self.Project_Environment.Predefined_Source_Files loop
Self.Project_Predefined_Sources.Include (File);
end loop;
Self.Contexts.Prepend (C);
-- Reindex the files from disk in the background after a project reload
Self.Mark_Source_Files_For_Indexing;
end Load_Implicit_Project;
---------------------------
-- Ensure_Project_Loaded --
---------------------------
procedure Ensure_Project_Loaded
(Self : access Message_Handler;
URI : LSP.Types.LSP_URI)
is
begin
if not Self.Contexts.Is_Empty then
-- Rely on the fact that there is at least one context initialized
-- as a guarantee that the initialization has been done.
return;
end if;
Self.Root := Self.To_File (URI).Dir;
Self.Ensure_Project_Loaded;
end Ensure_Project_Loaded;
---------------------------
-- Ensure_Project_Loaded --
---------------------------
procedure Ensure_Project_Loaded (Self : access Message_Handler) is
GPRs_Found : Natural := 0;
Files : File_Array_Access;
GPR : Virtual_File;
begin
if not Self.Contexts.Is_Empty then
-- Rely on the fact that there is at least one context initialized
-- as a guarantee that the initialization has been done.
return;
end if;
Self.Trace.Trace ("Project loading ...");
Self.Trace.Trace ("Root : " & Self.Root.Display_Full_Name);
-- We're going to look for a project in Root: list all the files
-- in this directory, looking for .gpr files.
Files := Self.Root.Read_Dir (Files_Only);
if Files /= null then
for X of Files.all loop
if Ends_With (+X.Base_Name, ".gpr") then
GPRs_Found := GPRs_Found + 1;
exit when GPRs_Found > 1;
GPR := X;
end if;
end loop;
Unchecked_Free (Files);
end if;
-- What we do depends on the number of .gpr files found:
if GPRs_Found = 0 then
-- We have found zero .gpr files: load the implicit project
Self.Load_Implicit_Project (No_Project_Found);
elsif GPRs_Found = 1 then
-- We have not found exactly one .gpr file: load the default
-- project.
Self.Trace.Trace ("Loading " & GPR.Display_Base_Name);
Self.Load_Project (GPR, No_Any, "iso-8859-1", Single_Project_Found);
else
-- We have found more than one project: warn the user!
Self.Show_Message
(VSS.Strings.To_Virtual_String
("More than one .gpr found." & Line_Feed &
"Note: you can configure a project " &
" through the ada.projectFile setting."));
Self.Load_Implicit_Project (Multiple_Projects_Found);
end if;
end Ensure_Project_Loaded;
-------------------------------------------------
-- Compute_File_Operations_Server_Capabilities --
-------------------------------------------------
function Compute_File_Operations_Server_Capabilities
(Self : access Message_Handler)
return LSP.Messages.Optional_FileOperationsServerCapabilities
is
use LSP.Messages;
Client_Capabilities :
LSP.Messages.Optional_FileOperationsClientCapabilities
renames Self.Client.capabilities.workspace.fileOperations;
begin
if Client_Capabilities.Is_Set
and then not Self.Contexts.Each_Context.Is_Empty
then
declare
Registration_Options :
constant Optional_FileOperationRegistrationOptions :=
(Is_Set => True,
Value => Self.Compute_File_Operation_Registration_Options);
begin
return Server_Capabilities :
Optional_FileOperationsServerCapabilities (Is_Set => True)
do
if Client_Capabilities.Value.didCreate = True then
Server_Capabilities.Value.didCreate := Registration_Options;
end if;
if Client_Capabilities.Value.willCreate = True then
Server_Capabilities.Value.willCreate := Registration_Options;
end if;
if Client_Capabilities.Value.didRename = True then
Server_Capabilities.Value.didRename := Registration_Options;
end if;
if Client_Capabilities.Value.willRename = True then
Server_Capabilities.Value.willRename := Registration_Options;
end if;
if Client_Capabilities.Value.didDelete = True then
Server_Capabilities.Value.didDelete := Registration_Options;
end if;
if Client_Capabilities.Value.willDelete = True then
Server_Capabilities.Value.willDelete := Registration_Options;
end if;
end return;
end;
else
return Optional_FileOperationsServerCapabilities'(Is_Set => False);
end if;
end Compute_File_Operations_Server_Capabilities;
-------------------------------------------------
-- Compute_File_Operation_Registration_Options --
-------------------------------------------------
function Compute_File_Operation_Registration_Options
(Self : access Message_Handler)
return LSP.Messages.FileOperationRegistrationOptions
is
use LSP.Messages;
File_Operation_Filters : LSP.Messages.FileOperationFilter_Vector;
begin
for Context of Self.Contexts.Each_Context loop
for Source_Dir of Context.List_Source_Directories loop
declare
Dir_Full_Name : constant GNATCOLL.VFS.Filesystem_String :=
GNATCOLL.VFS."/" (Source_Dir, "*").Full_Name;
Scheme : constant VSS.Strings.Virtual_String := "file";
Sources_Glob : constant VSS.Strings.Virtual_String :=
VSS.Strings.Conversions.To_Virtual_String (+Dir_Full_Name);
File_Operation_Filter :
constant LSP.Messages.FileOperationFilter :=
(scheme => (Is_Set => True, Value => Scheme),
pattern => (glob => Sources_Glob, others => <>));
begin
File_Operation_Filters.Append (File_Operation_Filter);
end;
end loop;
end loop;
return
FileOperationRegistrationOptions'(filters => File_Operation_Filters);
end Compute_File_Operation_Registration_Options;
------------
-- Format --
------------
function Format
(Self : in out LSP.Ada_Contexts.Context;
Document : LSP.Ada_Documents.Document_Access;
Span : LSP.Messages.Span;
Options : LSP.Messages.FormattingOptions;
Handler : access Message_Handler)
return LSP.Messages.Server_Responses.Formatting_Response
is
Response : LSP.Messages.Server_Responses.Formatting_Response
(Is_Error => False);
Success : Boolean;
Messages : VSS.String_Vectors.Virtual_String_Vector;
begin
Self.Format
(Document => Document,
Span => Span,
Options => Options,
Edit => Response.result,
Success => Success,
Messages => Messages);
if not Success then
declare
use VSS.Strings;
Response : LSP.Messages.Server_Responses.Formatting_Response
(Is_Error => True);
Error_Msg : VSS.Strings.Virtual_String;
begin
-- Display error messages from gnatpp, if any
for Msg of Messages loop
Error_Msg := Error_Msg & Msg;
end loop;
Response.error :=
(True,
(code => LSP.Errors.InternalError,
message => Error_Msg,
data => <>));
return Response;
end;
else
-- If the formntting succeeded, still display messages in the client
-- if any.
for Msg of Messages loop
Show_Message
(Self => Handler,
Text => Msg,
Mode => LSP.Messages.Info);
end loop;
end if;
return Response;
end Format;
------------------
-- Range_Format --
------------------
function Range_Format
(Self : in out LSP.Ada_Contexts.Context;
Document : LSP.Ada_Documents.Document_Access;
Span : LSP.Messages.Span;
Options : LSP.Messages.FormattingOptions)
return LSP.Messages.Server_Responses.Formatting_Response
is
Response : LSP.Messages.Server_Responses.Formatting_Response
(Is_Error => False);
Success : Boolean;
Messages : VSS.String_Vectors.Virtual_String_Vector;
begin
Self.Range_Format
(Document => Document,
Span => Span,
Options => Options,
Edit => Response.result,
Success => Success,
Messages => Messages);
if not Success then
declare
use VSS.Strings;
Response : LSP.Messages.Server_Responses.Formatting_Response
(Is_Error => True);
Error_Msg : VSS.Strings.Virtual_String;
begin
-- Display error messages from gnatpp, if any
for Msg of Messages loop
Error_Msg := Error_Msg & Msg;
end loop;
Response.error :=
(True,
(code => LSP.Errors.InternalError,
message => Error_Msg,
data => <>));
return Response;
end;
end if;
return Response;
end Range_Format;
------------------------
-- Initialize_Request --
------------------------
overriding function On_Initialize_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Initialize_Request)
return LSP.Messages.Server_Responses.Initialize_Response
is
use LSP.Messages;
Value : LSP.Messages.InitializeParams renames Request.params;
Code_Action : LSP.Messages.Optional_CodeActionClientCapabilities
renames Value.capabilities.textDocument.codeAction;
Has_Rename : LSP.Messages.Optional_RenameClientCapabilities
renames Value.capabilities.textDocument.rename;
Semantic_Tokens : LSP.Messages.Optional_SemanticTokensClientCapabilities
renames Value.capabilities.textDocument.semanticTokens;
Experimental_Client_Capabilities : LSP.Types.Optional_LSP_Any renames
Value.capabilities.experimental;
Response : LSP.Messages.Server_Responses.Initialize_Response
(Is_Error => False);
Root : VSS.Strings.Virtual_String;
codeActionKinds : LSP.Messages.CodeActionKindSet;
Backspace_String : VSS.Strings.Virtual_String;
Retrigger_Vector : VSS.String_Vectors.Virtual_String_Vector;
begin
Backspace_String.Append (VSS.Characters.Latin.Backspace);
Retrigger_Vector.Append (Backspace_String);
Response.result.capabilities.declarationProvider :=
(Is_Set => True,
Value => (Is_Boolean => True, Bool => True));
Response.result.capabilities.definitionProvider :=
(Is_Set => True,
Value => (workDoneProgress => LSP.Types.None));
Response.result.capabilities.typeDefinitionProvider :=
(Is_Set => True,
Value => (Is_Boolean => True, Bool => True));
Response.result.capabilities.implementationProvider :=
(Is_Set => True,
Value => (Is_Boolean => True, Bool => True));
Response.result.capabilities.referencesProvider :=
(Is_Set => True,
Value => (workDoneProgress => LSP.Types.None));
Response.result.capabilities.documentFormattingProvider :=
(Is_Set => True,
Value => (workDoneProgress => LSP.Types.None));
if Partial_GNATpp.Is_Active then
Response.result.capabilities.documentRangeFormattingProvider :=
(Is_Set => True,
Value => (workDoneProgress => LSP.Types.None));
end if;
Response.result.capabilities.callHierarchyProvider :=
(Is_Set => True,
Value => (Is_Boolean => False, Options => <>));
Response.result.capabilities.documentHighlightProvider :=
(Is_Set => True,
Value => (workDoneProgress => LSP.Types.None));
Response.result.capabilities.workspaceSymbolProvider :=
(Is_Set => True,
Value => (workDoneProgress => LSP.Types.None));
Response.result.capabilities.documentSymbolProvider :=
(Is_Set => True,
Value => (workDoneProgress => LSP.Types.None, label => <>));
Response.result.capabilities.renameProvider :=
(Is_Set => True,
Value => (prepareProvider =>
(if Has_Rename.Is_Set
and then Has_Rename.Value.prepareSupport = True
then LSP.Types.True else LSP.Types.None),
workDoneProgress => LSP.Types.None));
Response.result.capabilities.textDocumentSync :=
(Is_Set => True, Is_Number => True,
Value =>
(if Allow_Incremental_Text_Changes.Active then
LSP.Messages.Incremental
else
LSP.Messages.Full));
Response.result.capabilities.signatureHelpProvider :=
(True,
(triggerCharacters => (True, [",", "("]),
retriggerCharacters => (True, Retrigger_Vector),
workDoneProgress => LSP.Types.None));
Response.result.capabilities.completionProvider :=
(True,
(resolveProvider => LSP.Types.True,
triggerCharacters => (True, [".", ",", "'", "("]),
allCommitCharacters => (Is_Set => False),
workDoneProgress => LSP.Types.None));
Response.result.capabilities.hoverProvider :=
(Is_Set => True,
Value => (workDoneProgress => LSP.Types.None));
Response.result.capabilities.executeCommandProvider :=
(Is_Set => True,
Value => (commands => LSP.Commands.All_Commands,
workDoneProgress => LSP.Types.None));
if Code_Action.Is_Set and then
Code_Action.Value.codeActionLiteralSupport.Is_Set
then
LSP.Messages.Include (codeActionKinds, LSP.Messages.QuickFix);
LSP.Messages.Include (codeActionKinds, LSP.Messages.RefactorRewrite);
Response.result.capabilities.codeActionProvider :=
(Is_Set => True,
Value =>
(codeActionKinds => (True, codeActionKinds),
workDoneProgress => LSP.Types.None,
resolveProvider => LSP.Types.None));
else
Response.result.capabilities.codeActionProvider :=
(Is_Set => True, Value => <>);
end if;
Response.result.capabilities.alsShowDepsProvider := True;
Response.result.capabilities.alsReferenceKinds :=
(Is_Set => True,
Value => (Is_Server_Side => True, As_Flags => [others => True]));
Response.result.capabilities.foldingRangeProvider :=
(Is_Set => True,
Value => (Is_Boolean => True, Bool => True));
Self.Resource_Operations :=
Value.capabilities.workspace.workspaceEdit.resourceOperations;
Response.result.capabilities.alsCheckSyntaxProvider := True;
-- Client capability to support versioned document changes in
-- `WorkspaceEdit`s.
Self.Versioned_Documents :=
Value.capabilities.workspace.workspaceEdit.documentChanges = True;
if Value.capabilities.textDocument.documentSymbol.Is_Set
and then Value.capabilities.textDocument.documentSymbol.Value
.hierarchicalDocumentSymbolSupport = True
then
Self.Get_Symbols := LSP.Ada_Documents.Get_Symbol_Hierarchy'Access;
else
Self.Get_Symbols := LSP.Ada_Documents.Get_Symbols'Access;
end if;
if Value.capabilities.textDocument.foldingRange.Is_Set
and then Value.capabilities.textDocument.foldingRange.Value.
lineFoldingOnly = True
then
-- Client capability to fold only entire lines
Self.Line_Folding_Only := True;
end if;
if Value.capabilities.textDocument.completion.completionItem.Is_Set
and then Value.capabilities.textDocument.completion.
completionItem.Value.snippetSupport = True
then
-- Client capability to support snippets for completion
Self.Completion_Snippets_Enabled := True;
end if;
if Value.capabilities.textDocument.completion.completionItem.Is_Set
and then Value.capabilities.textDocument.completion.
completionItem.Value.resolveSupport.Is_Set
then
Self.Completion_Resolve_Properties :=
Value.capabilities.textDocument.completion.
completionItem.Value.resolveSupport.Value.properties;
end if;
if Value.capabilities.workspace.didChangeWatchedFiles.Is_Set
and then Value.capabilities.workspace.didChangeWatchedFiles.Value
.dynamicRegistration = True
then
Self.File_Monitor := new LSP.Client_Side_File_Monitors.File_Monitor
(Self.Server);
end if;
if Semantic_Tokens.Is_Set then
declare
Legend : LSP.Messages.SemanticTokensLegend;
begin
Self.Highlighter.Initialize (Semantic_Tokens.Value, Legend);
Response.result.capabilities.semanticTokensProvider :=
(True,
(legend => Legend,
full => (True, (diff => <>)),
span => LSP.Types.True,
others => <>));
end;
end if;
if Value.rootUri.Is_Set
and then not Value.rootUri.Value.Is_Empty
then
Root := Self.URI_To_File (Value.rootUri.Value);
elsif Value.rootPath.Is_Set and then Value.rootPath.Value.Is_Set then
-- URI isn't provided, rollback to deprecated rootPath
Root := Value.rootPath.Value.Value;
end if;
-- Some clients - notably VS Code as of version 33, when opening a file
-- rather than a workspace - don't provide a root at all. In that case
-- use the current directory as root.
if Root.Is_Empty then
Root := ".";
end if;
Self.Root :=
Create_From_UTF8 (VSS.Strings.Conversions.To_UTF_8_String (Root));
Self.Client := Value;
-- Log the context root
Self.Trace.Trace
("Context root: " & VSS.Strings.Conversions.To_UTF_8_String (Root));
-- Client/ServerCapabilities.workspace.fileOperations capabilities
declare
File_Operation_Capabilities :
constant Optional_FileOperationsServerCapabilities :=
Self.Compute_File_Operations_Server_Capabilities;
begin
if File_Operation_Capabilities.Is_Set then
Response.result.capabilities.workspace :=
(Is_Set => True,
Value =>
(workspaceFolders => (Is_Set => False),
fileOperations => File_Operation_Capabilities));
end if;
end;
Response.result.serverInfo := LSP.Messages.Optional_ProgramInfo'
(True,
(log_filename =>
(True, VSS.Strings.Conversions.To_Virtual_String
(Runtime_Indexing.Get_Stream_File.Display_Full_Name)),
others => <>));
-- Experimental Client Capabilities
Self.Experimental_Client_Capabilities :=
Parse (Experimental_Client_Capabilities);
return Response;
end On_Initialize_Request;
-------------------------
-- On_Shutdown_Request --
-------------------------
overriding function On_Shutdown_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Shutdown_Request)
return LSP.Messages.Server_Responses.Shutdown_Response
is
pragma Unreferenced (Request);
begin
-- Suspend files/runtime indexing after shutdown requst
Self.Indexing_Enabled := False;
return Response : LSP.Messages.Server_Responses.Shutdown_Response
(Is_Error => False);
end On_Shutdown_Request;
---------------------------
-- On_CodeAction_Request --
---------------------------
overriding function On_CodeAction_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.CodeAction_Request)
return LSP.Messages.Server_Responses.CodeAction_Response
is
Params : LSP.Messages.CodeActionParams renames Request.params;
procedure Analyse_In_Context
(Context : Context_Access;
Document : LSP.Ada_Documents.Document_Access;
Result : out LSP.Messages.CodeAction_Vector;
Found : in out Boolean);
-- Perform refactoring ananlysis given Document in the Context.
-- Return Found = True if some refactoring is possible. Populate
-- Result with Code_Actions in this case.
function Has_Assoc_Without_Designator
(Node : Libadalang.Analysis.Basic_Assoc_List) return Boolean;
-- Check if Node is Basic_Assoc_List that contains at least one
-- ParamAssoc without a designator.
procedure Analyse_Node
(Context : Context_Access;
Node : Libadalang.Analysis.Ada_Node;
Result : out LSP.Messages.CodeAction_Vector;
Found : in out Boolean);
-- Look for a possible refactoring in given Node.
-- Return Found = True if some refactoring is possible. Populate
-- Result with Code_Actions in this case. Return Done = True if futher
-- analysis has no sense.
procedure Append_Project_Status_Code_Actions
(Result : in out LSP.Messages.CodeAction_Vector);
-- Append project status code action if needed
----------------------------------
-- Has_Assoc_Without_Designator --
----------------------------------
function Has_Assoc_Without_Designator
(Node : Libadalang.Analysis.Basic_Assoc_List) return Boolean
is
Found : Boolean := False;
function Process_Type_Expr
(TE : Libadalang.Analysis.Type_Expr)
return Boolean;
-- Returns True if TE is associated to an access of a subprogram
-----------------------
-- Process_Type_Expr --
-----------------------
function Process_Type_Expr
(TE : Libadalang.Analysis.Type_Expr)
return Boolean
is
TD : Libadalang.Analysis.Base_Type_Decl;
-- If TE is not an anonymous type then we'll need to know its
-- declaration.
begin
case TE.Kind is
when Ada_Subtype_Indication_Range =>
TD := TE.As_Subtype_Indication.P_Designated_Type_Decl;
if TD.Is_Null
or else not (TD.Kind in Ada_Type_Decl)
then
return False;
end if;
case TD.As_Type_Decl.F_Type_Def.Kind is
when Ada_Access_To_Subp_Def_Range =>
-- Confirmation that TD is an access to a subprogram
return True;
when Ada_Array_Type_Def_Range =>
-- If TD is an array type, then it might be an array
-- of accesses to subprograms. Therefore, recursively
-- call Process_Type_Expr to check the type of the
-- components of the array.
return Process_Type_Expr
(TD.As_Type_Decl.F_Type_Def.As_Array_Type_Def.
F_Component_Type.F_Type_Expr);
when others =>
return False;
end case;
when Ada_Anonymous_Type_Range =>
return TE.As_Anonymous_Type.F_Type_Decl.F_Type_Def.Kind in
Ada_Access_To_Subp_Def_Range;
when others =>
return False;
end case;
end Process_Type_Expr;
begin
for J of Node loop
if J.Kind in Libadalang.Common.Ada_Param_Assoc and then
J.As_Param_Assoc.F_Designator.Is_Null
then
Found := True;
exit;
end if;
end loop;
if not Found then
return False;
end if;
declare
Expr : constant Libadalang.Analysis.Ada_Node := Node.Parent;
Name : Libadalang.Analysis.Name;
Decl : Libadalang.Analysis.Basic_Decl;
begin
case Expr.Kind is
when Libadalang.Common.Ada_Call_Expr =>
Name := Expr.As_Call_Expr.F_Name;
when others =>
return False;
end case;
Decl := Name.P_Referenced_Decl;
if Decl.Is_Null then
return False;
end if;
-- For Ada_Param_Spec, Ada_Component_Decl or Object_Decl nodes,
-- check the type definition of Decl. Named parameters can be
-- added if Decl's type is a (possibly anonymous) access to a
-- subprogram.
case Decl.Kind is
when Libadalang.Common.Ada_Base_Subp_Body
| Libadalang.Common.Ada_Basic_Subp_Decl =>
return True;
when Libadalang.Common.Ada_Param_Spec_Range =>
return Process_Type_Expr (Decl.As_Param_Spec.F_Type_Expr);
when Libadalang.Common.Ada_Component_Decl_Range =>
return Process_Type_Expr
(Decl.As_Component_Decl.F_Component_Def.F_Type_Expr);
when Libadalang.Common.Ada_Object_Decl_Range =>
-- This can either be an object which type is an access
-- to a subprogram or an array of accesses to
-- subprograms.
return Process_Type_Expr (Decl.As_Object_Decl.F_Type_Expr);
when others =>
return False;
end case;
end;
end Has_Assoc_Without_Designator;
------------------
-- Analyse_Node --
------------------
procedure Analyse_Node
(Context : Context_Access;
Node : Libadalang.Analysis.Ada_Node;
Result : out LSP.Messages.CodeAction_Vector;
Found : in out Boolean)
is
procedure Change_Parameters_Type_Code_Action;
-- Checks if the Change Parameters Type refactoring tool is avaiable,
-- and if so, appends a Code Action with its Command.
procedure Change_Parameters_Default_Value_Code_Action;
-- Checks if the Change Parameters Default Value refactoring tool is
-- avaiable, and if so, appends a Code Action with its Command.
procedure Extract_Subprogram_Code_Action;
-- Checks if the Extract Subprogram refactoring tool is available,
-- and if so, appends a Code Action with its Command.
procedure Introduce_Parameter_Code_Action;
-- Checks if the Introduce Parameter refactoring tool is available,
-- and if so, appends a Code Action with its Command.
procedure Import_Package_Code_Action;
-- Checks if the Import Package code assist is available,
-- and if so, appends a Code Aciton with its Command.
procedure Named_Parameters_Code_Action;
-- Checks if the Named Parameters refactoring is available, and if
-- so, appends a Code Action with its Command.
procedure Pull_Up_Declaration_Code_Action;
-- Checks if the Pull Up Declaration refactoring tool is available,
-- and if so, appends a Code Action with its Command.
----------------------------------------
-- Change_Parameters_Type_Code_Action --
----------------------------------------
procedure Change_Parameters_Type_Code_Action is
use Langkit_Support.Slocs;
use Laltools.Refactor.Subprogram_Signature.Change_Parameters_Type;
use LSP.Ada_Handlers.Refactor_Change_Parameters_Type;
Span : constant Source_Location_Range :=
(Langkit_Support.Slocs.Line_Number (Params.span.first.line) + 1,
Langkit_Support.Slocs.Line_Number (Params.span.last.line) + 1,
Column_Number (Params.span.first.character) + 1,
Column_Number (Params.span.last.character) + 1);
Syntax_Rules : Laltools.Common.Grammar_Rule_Vector;
Change_Parameters_Type_Command : Command;
begin
if Is_Change_Parameters_Type_Available
(Unit => Node.Unit,
Parameters_Source_Location_Range => Span,
New_Parameter_Syntax_Rules => Syntax_Rules)
then
Change_Parameters_Type_Command.Append_Code_Action
(Context => Context,
Commands_Vector => Result,
Where =>
(uri => Params.textDocument.uri,
span => Params.span,
alsKind => LSP.Messages.Empty_Set),
Syntax_Rules => Syntax_Rules);
Found := True;
end if;
end Change_Parameters_Type_Code_Action;
-------------------------------------------------
-- Change_Parameters_Default_Value_Code_Action --
-------------------------------------------------
procedure Change_Parameters_Default_Value_Code_Action is
use Langkit_Support.Slocs;
use Laltools.Refactor.Subprogram_Signature.
Change_Parameters_Default_Value;
use LSP.Ada_Handlers.Refactor_Change_Parameters_Default_Value;
Span : constant Source_Location_Range :=
(Langkit_Support.Slocs.Line_Number (Params.span.first.line) + 1,
Langkit_Support.Slocs.Line_Number (Params.span.last.line) + 1,
Column_Number (Params.span.first.character) + 1,
Column_Number (Params.span.last.character) + 1);
Change_Parameters_Default_Value_Command : Command;
begin
if Is_Change_Parameters_Default_Value_Available
(Unit => Node.Unit,
Parameters_Source_Location_Range => Span)
then
Change_Parameters_Default_Value_Command.Append_Code_Action
(Context => Context,
Commands_Vector => Result,
Where =>
(uri => Params.textDocument.uri,
span => Params.span,
alsKind => LSP.Messages.Empty_Set));
Found := True;
end if;
end Change_Parameters_Default_Value_Code_Action;
------------------------------------
-- Extract_Subprogram_Code_Action --
------------------------------------
procedure Extract_Subprogram_Code_Action is
use LSP.Ada_Handlers.Refactor_Extract_Subprogram;
use Langkit_Support.Slocs;
use Laltools.Refactor.Extract_Subprogram;
use type LSP.Messages.Position;
Single_Location : constant Boolean :=
Params.span.first = Params.span.last;
Section_To_Extract_SLOC : constant Source_Location_Range :=
(Langkit_Support.Slocs.Line_Number (Params.span.first.line) + 1,
Langkit_Support.Slocs.Line_Number (Params.span.last.line) + 1,
Column_Number (Params.span.first.character) + 1,
Column_Number (Params.span.last.character) + 1);
Available_Subprogram_Kinds : Available_Subprogram_Kinds_Type;
Extract_Subprogram_Command : Command;
begin
if not Single_Location then
if Is_Extract_Subprogram_Available
(Node.Unit,
Section_To_Extract_SLOC,
Available_Subprogram_Kinds)
then
if Available_Subprogram_Kinds (Ada_Subp_Kind_Procedure) then
Extract_Subprogram_Command.Append_Code_Action
(Context => Context,
Commands_Vector => Result,
Where =>
(Params.textDocument.uri,
Params.span,
LSP.Messages.Empty_Set),
Subprogram_Kind =>
Ada_Subp_Kind_Procedure);
end if;
if Available_Subprogram_Kinds (Ada_Subp_Kind_Function) then
Extract_Subprogram_Command.Append_Code_Action
(Context => Context,
Commands_Vector => Result,
Where =>
(Params.textDocument.uri,
Params.span,
LSP.Messages.Empty_Set),
Subprogram_Kind =>
Ada_Subp_Kind_Function);
end if;
Found := True;
end if;
end if;
end Extract_Subprogram_Code_Action;
-------------------------------------
-- Introduce_Parameter_Code_Action --
-------------------------------------
procedure Introduce_Parameter_Code_Action is
use Langkit_Support.Slocs;
use Laltools.Refactor.Introduce_Parameter;
use LSP.Ada_Handlers.Refactor_Introduce_Parameter;
Span : constant Source_Location_Range :=
(Langkit_Support.Slocs.Line_Number (Params.span.first.line) + 1,
Langkit_Support.Slocs.Line_Number (Params.span.last.line) + 1,
Column_Number (Params.span.first.character) + 1,
Column_Number (Params.span.last.character) + 1);
Introduce_Parameter_Command : Command;
begin
if Is_Introduce_Parameter_Available
(Unit => Node.Unit,
SLOC_Range => Span)
then
Introduce_Parameter_Command.Append_Code_Action
(Context => Context,
Commands_Vector => Result,
Where =>
(uri => Params.textDocument.uri,
span => Params.span,
alsKind => LSP.Messages.Empty_Set));
Found := True;
end if;
end Introduce_Parameter_Code_Action;
--------------------------------
-- Import_Package_Code_Action --
--------------------------------
procedure Import_Package_Code_Action is
use Libadalang.Analysis;
use Laltools.Refactor_Imports;
use LSP.Messages;
Single_Location : constant Boolean :=
Params.span.first = Params.span.last;
Units_Vector : Libadalang.Helpers.Unit_Vectors.Vector;
Units_Array : constant Analysis_Unit_Array :=
Context.Analysis_Units;
Import_Suggestions : Import_Suggestions_Vector.Vector;
function Is_Import_Suggestions_Available
(This_Node : Ada_Node'Class)
return Boolean;
-- Checks if This_Node is a suitable node to get import
-- suggestions. A suitable node must be an identifier, non
-- defining and if it resolves, it must be to a declaration not
-- declared in the standard package.
-- This function also prepares Units_Vector with the right units
-- where suggestions should be searched for.
-------------------------------------
-- Is_Import_Suggestions_Available --
-------------------------------------
function Is_Import_Suggestions_Available
(This_Node : Ada_Node'Class)
return Boolean
is
Aux_Node : Ada_Node :=
(if This_Node.Is_Null then No_Ada_Node
else This_Node.As_Ada_Node);
Referenced_Definition : Defining_Name := No_Defining_Name;
begin
-- Only get suggestions for Identifiers or Dotted_Names
if Aux_Node.Is_Null
or else Aux_Node.Kind not in
Ada_Identifier_Range | Ada_Dotted_Name_Range
then
return False;
end if;
-- Get the full Dotted_Name if applicable
while not Aux_Node.Is_Null
and then not Aux_Node.Parent.Is_Null
and then Aux_Node.Parent.Kind in Ada_Dotted_Name_Range
loop
Aux_Node := Aux_Node.Parent;
end loop;
-- Defining names do not need prefixes
if Aux_Node.Is_Null or else Aux_Node.As_Name.P_Is_Defining then
return False;
end if;
Referenced_Definition :=
Aux_Node.As_Name.P_Referenced_Defining_Name;
-- Declarations in the standard package do not need prefixes
if not Referenced_Definition.Is_Null then
if Referenced_Definition.Unit = Node.P_Standard_Unit then
return False;
end if;
end if;
if Referenced_Definition.Is_Null then
-- The name could not be resolved so a full search needs to
-- be done.
for U of Units_Array loop
Units_Vector.Append (U);
end loop;
-- Add runtime analysis units for this context
-- ??? If possible, this should be cached.
for F in Self.Project_Predefined_Sources.Iterate loop
declare
VF : GNATCOLL.VFS.Virtual_File renames
LSP.Ada_File_Sets.File_Sets.Element (F);
begin
Units_Vector.Append
(Context.LAL_Context.Get_From_File
(VF.Display_Full_Name,
-- ??? What is the charset for predefined
-- files?
""));
end;
end loop;
else
-- Libadalang sometimes can resolve names that are not
-- withed.
-- For instance, with Ada.Text_IO, resolve
-- Ada.Text_IO.Put_Line, remove the Ada.Text_IO and then
-- resolve again Ada.Text_IO.Put_Line. Even though
-- Ada.Text_IO is no longer withed, Libadalang is still
-- able to resolve Put_Line.
-- For such cases, include only Referenced_Definition's
-- Analysis_Units and the tool will suggest the prefixes
-- (there can be more than one, for instance, when there
-- are nested packages.
Units_Vector.Append (Referenced_Definition.Unit);
end if;
return True;
exception
when others => return False;
end Is_Import_Suggestions_Available;
begin
if not Single_Location
or else not Is_Import_Suggestions_Available (Node)
then
return;
end if;
-- Get suggestions for all reachable declarations.
-- Each suggestion contains a with clause and a
-- prefix.
Import_Suggestions :=
Get_Import_Suggestions (Node, Units_Vector);
-- Create a new codeAction command for each suggestion
for Suggestion of Import_Suggestions loop
declare
Command : LSP.Ada_Handlers.
Refactor_Imports_Commands.Command;
begin
Command.Append_Suggestion
(Context => Context,
Where =>
LSP.Lal_Utils.Get_Node_Location (Node),
Commands_Vector => Result,
Suggestion => Suggestion);
end;
end loop;
if not Import_Suggestions.Is_Empty then
Found := True;
end if;
end Import_Package_Code_Action;
----------------------------------
-- Named_Parameters_Code_Action --
----------------------------------
procedure Named_Parameters_Code_Action is
Aux_Node : Libadalang.Analysis.Ada_Node := Node;
Done : Boolean := False;
-- We propose only one choice of Named_Parameters refactoring per
-- request. So, if a user clicks on `1` in `A (B (1))` we propose
-- the refactoring for B (1), but not for A (...) call. We
-- consider this as better user experience.
--
-- This boolean filter to detect such refactoring duplication.
procedure Append_Command (Node : Libadalang.Analysis.Ada_Node);
-- Contruct a command and append it to Result
--------------------
-- Append_Command --
--------------------
procedure Append_Command (Node : Libadalang.Analysis.Ada_Node) is
Command : LSP.Ada_Handlers.Named_Parameters_Commands.Command;
Pointer : LSP.Commands.Command_Pointer;
Item : LSP.Messages.CodeAction;
Where : constant LSP.Messages.Location :=
LSP.Lal_Utils.Get_Node_Location (Node);
begin
Command.Initialize
(Context => Context.all,
Where => ((uri => Where.uri), Where.span.first));
Pointer.Set (Command);
Item :=
(title => "Name parameters in the call",
kind => (Is_Set => True,
Value => LSP.Messages.RefactorRewrite),
diagnostics => (Is_Set => False),
disabled => (Is_Set => False),
edit => (Is_Set => False),
isPreferred => (Is_Set => False),
command => (Is_Set => True,
Value =>
(Is_Unknown => False,
title => <>,
Custom => Pointer)));
Result.Append (Item);
Done := True;
Found := True;
end Append_Command;
begin
while not Done and then not Aux_Node.Is_Null loop
case Aux_Node.Kind is
when Libadalang.Common.Ada_Stmt
| Libadalang.Common.Ada_Basic_Decl =>
Done := True;
when Libadalang.Common.Ada_Basic_Assoc_List =>
if Has_Assoc_Without_Designator
(Aux_Node.As_Basic_Assoc_List)
then
Append_Command (Aux_Node);
end if;
when Libadalang.Common.Ada_Call_Expr =>
declare
List : constant Libadalang.Analysis.Ada_Node :=
Aux_Node.As_Call_Expr.F_Suffix;
begin
if not List.Is_Null
and then List.Kind in
Libadalang.Common.Ada_Basic_Assoc_List
and then Has_Assoc_Without_Designator
(List.As_Basic_Assoc_List)
then
Append_Command (List);
end if;
end;
when others =>
null;
end case;
Aux_Node := Aux_Node.Parent;
end loop;
end Named_Parameters_Code_Action;
-------------------------------------
-- Pull_Up_Declaration_Code_Action --
-------------------------------------
procedure Pull_Up_Declaration_Code_Action is
use Langkit_Support.Slocs;
use Libadalang.Analysis;
use Laltools.Refactor.Pull_Up_Declaration;
use LSP.Ada_Handlers.Refactor_Pull_Up_Declaration;
use LSP.Messages;
-- This code action is not available when a range of text is
-- selected.
Single_Location : constant Boolean :=
Params.span.first = Params.span.last;
Location : constant Source_Location :=
(Langkit_Support.Slocs.Line_Number (Params.span.first.line) + 1,
Column_Number (Params.span.first.character) + 1);
Pull_Up_Declaration_Command :
LSP.Ada_Handlers.Refactor_Pull_Up_Declaration.Command;
begin
if Single_Location
and then Is_Pull_Up_Declaration_Available (Node.Unit, Location)
then
Pull_Up_Declaration_Command.Append_Code_Action
(Context => Context,
Commands_Vector => Result,
Where =>
(uri => Params.textDocument.uri,
span => Params.span,
alsKind => Empty_Set));
Found := True;
end if;
end Pull_Up_Declaration_Code_Action;
begin
Named_Parameters_Code_Action;
Import_Package_Code_Action;
-- Refactoring Code Actions
-- Extract Subprogram
Extract_Subprogram_Code_Action;
-- Pull Up Declaration
Pull_Up_Declaration_Code_Action;
-- These refactorings are only available for clients that can
-- provide user inputs:
-- - Add Parameter
-- - Change Parameters Type
-- - Change Parameters Default Value
-- Add Parameter
if Self.Experimental_Client_Capabilities.
Advanced_Refactorings (Add_Parameter)
then
declare
use LSP.Ada_Handlers.Refactor_Add_Parameter;
use Libadalang.Analysis;
use Laltools.Refactor.Subprogram_Signature;
use Langkit_Support.Slocs;
use type LSP.Messages.Position;
-- This code action is not available when a range of text is
-- selected.
Single_Location : constant Boolean :=
Params.span.first = Params.span.last;
Location : constant Source_Location :=
(if Single_Location then
(Langkit_Support.Slocs.Line_Number
(Params.span.first.line) + 1,
Column_Number (Params.span.first.character) + 1)
else
No_Source_Location);
Requires_Full_Specification : Boolean;
Add_Parameter_Commad : Command;
begin
if Single_Location
and then Is_Add_Parameter_Available
(Node.Unit,
Location,
Requires_Full_Specification)
then
Add_Parameter_Commad.Append_Code_Action
(Context => Context,
Commands_Vector => Result,
Where =>
(Params.textDocument.uri,
Params.span,
LSP.Messages.Empty_Set),
Requires_Full_Specification =>
Requires_Full_Specification);
Found := True;
end if;
end;
end if;
-- Change Parameters Type
if Self.Experimental_Client_Capabilities.
Advanced_Refactorings (Change_Parameters_Type)
then
Change_Parameters_Type_Code_Action;
end if;
-- Change Parameters Default Value
if Self.Experimental_Client_Capabilities.
Advanced_Refactorings (Change_Parameters_Default_Value)
then
Change_Parameters_Default_Value_Code_Action;
end if;
-- Remove Parameter
declare
use LSP.Ada_Handlers.Refactor_Remove_Parameter;
use Libadalang.Analysis;
use Laltools.Refactor.Subprogram_Signature;
use Laltools.Refactor.Subprogram_Signature.Remove_Parameter;
Target_Subp : Basic_Decl := No_Basic_Decl;
Parameter_Indices_Range : Parameter_Indices_Range_Type;
Remove_Parameter_Command : Command;
begin
if Is_Remove_Parameter_Available
(Node, Target_Subp, Parameter_Indices_Range)
then
Remove_Parameter_Command.Append_Code_Action
(Context => Context,
Commands_Vector => Result,
Target_Subp => Target_Subp,
Parameters_Indices => Parameter_Indices_Range);
Found := True;
end if;
end;
-- Move Parameter
declare
use LSP.Ada_Handlers.Refactor_Move_Parameter;
use Libadalang.Analysis;
use Laltools.Refactor.Subprogram_Signature;
Target_Subp : Basic_Decl := No_Basic_Decl;
Parameter_Index : Positive;
Move_Directions : Move_Direction_Availability_Type;
Move_Parameter_Command : Command;
begin
if Is_Move_Parameter_Available
(Node, Target_Subp, Parameter_Index, Move_Directions)
then
for Direction in Move_Direction_Type loop
if Move_Directions (Direction) then
Move_Parameter_Command.Append_Code_Action
(Context => Context,
Commands_Vector => Result,
Target_Subp => Target_Subp,
Parameter_Index => Parameter_Index,
Move_Direction => Direction);
end if;
end loop;
Found := True;
end if;
end;
-- Change Parameter Mode
declare
use LSP.Ada_Handlers.Refactor_Change_Parameter_Mode;
use Libadalang.Analysis;
use Laltools.Refactor.Subprogram_Signature;
Target_Subp : Basic_Decl := No_Basic_Decl;
Target_Parameters_Indices : Parameter_Indices_Range_Type;
Mode_Alternatives : Mode_Alternatives_Type;
Change_Parameter_Mode_Command : Command;
begin
if Is_Change_Mode_Available
(Node, Target_Subp, Target_Parameters_Indices, Mode_Alternatives)
then
for Alternative of Mode_Alternatives loop
Change_Parameter_Mode_Command.Append_Code_Action
(Context => Context,
Commands_Vector => Result,
Target_Subp => Target_Subp,
Parameters_Indices => Target_Parameters_Indices,
New_Mode => Alternative);
end loop;
Found := True;
end if;
end;
-- Introduce Parameter
Introduce_Parameter_Code_Action;
-- Suppress Subprogram
declare
use LSP.Ada_Handlers.Refactor_Suppress_Seperate;
use Libadalang.Analysis;
use Laltools.Refactor.Suppress_Separate;
Target_Separate : Basic_Decl := No_Basic_Decl;
Suppress_Separate_Command : Command;
begin
if Is_Suppress_Separate_Available (Node, Target_Separate) then
Suppress_Separate_Command.Append_Code_Action
(Context => Context,
Commands_Vector => Result,
Target_Separate => Target_Separate);
Found := True;
end if;
end;
end Analyse_Node;
------------------------
-- Analyse_In_Context --
------------------------
procedure Analyse_In_Context
(Context : Context_Access;
Document : LSP.Ada_Documents.Document_Access;
Result : out LSP.Messages.CodeAction_Vector;
Found : in out Boolean)
is
Node : constant Libadalang.Analysis.Ada_Node :=
Document.Get_Node_At (Context.all, Params.span.first);
begin
if Node.Is_Null then
Found := False;
return;
end if;
Analyse_Node (Context, Node, Result, Found);
end Analyse_In_Context;
----------------------------------------
-- Append_Project_Status_Code_Actions --
----------------------------------------
procedure Append_Project_Status_Code_Actions
(Result : in out LSP.Messages.CodeAction_Vector)
is
use type VSS.Strings.Virtual_String;
Diagnostics : LSP.Messages.Diagnostic_Vector;
begin
for Item of Params.context.diagnostics loop
if Item.source.Is_Set and then Item.source.Value = "project" then
Diagnostics.Append (Item);
end if;
end loop;
case Self.Project_Status is
when Valid_Project_Configured =>
null;
when Single_Project_Found | Multiple_Projects_Found =>
declare
Item : LSP.Messages.CodeAction;
Command : LSP.Messages.Command (Is_Unknown => True);
Arg : constant LSP.Types.LSP_Any :=
LSP.Types.Create ("ada.projectFile");
begin
Command.title := "Open settings for ada.projectFile";
Command.command := "workbench.action.openSettings";
Command.arguments := (Is_Set => True, Value => <>);
Command.arguments.Value.Append (Arg);
Item :=
(title => Command.title,
kind => (True, LSP.Messages.QuickFix),
diagnostics => (True, Diagnostics),
disabled => (Is_Set => False),
edit => (Is_Set => False),
isPreferred => LSP.Types.True,
command => (True, Command));
Result.Append (Item);
end;
when No_Project_Found =>
declare
Title : constant VSS.Strings.Virtual_String :=
"Create a default project file (default.gpr)";
URI : constant LSP.Messages.DocumentUri :=
LSP.Types.File_To_URI
(Self.Root.Join ("default.gpr").Display_Full_Name);
Create : constant LSP.Messages.Document_Change :=
(LSP.Messages.Create_File,
(kind => LSP.Messages.create,
uri => URI,
others => <>));
Text : constant LSP.Messages.AnnotatedTextEdit :=
((span => ((0, 0), (0, 0)),
newText => "project Default is end Default;",
others => <>));
Insert : constant LSP.Messages.Document_Change :=
(LSP.Messages.Text_Document_Edit,
(textDocument => (uri => URI, others => <>),
edits => LSP.Messages.To_Vector (Text, 1)));
Item : LSP.Messages.CodeAction;
Edit : LSP.Messages.WorkspaceEdit;
begin
Edit.documentChanges.Append (Create);
Edit.documentChanges.Append (Insert);
Item :=
(title => Title,
kind => (True, LSP.Messages.QuickFix),
diagnostics => (True, Diagnostics),
disabled => (Is_Set => False),
edit => (True, Edit),
isPreferred => LSP.Types.True,
command => (Is_Set => False));
Result.Append (Item);
end;
when Invalid_Project_Configured =>
null;
end case;
end Append_Project_Status_Code_Actions;
use type LSP.Messages.Position;
Document : constant LSP.Ada_Documents.Document_Access :=
Get_Open_Document (Self, Params.textDocument.uri);
Response : LSP.Messages.Server_Responses.CodeAction_Response
(Is_Error => False);
Found : Boolean := False;
begin
if Document = null then
Self.Log_Unexpected_Null_Document ("On_CodeAction_Request");
return Response;
end if;
-- Find any context where we can do some refactoring
for C of Self.Contexts_For_URI (Params.textDocument.uri) loop
Analyse_In_Context (C, Document, Response.result, Found);
exit when Request.Canceled or else Found;
end loop;
if Params.span.first = (0, 0) then
Append_Project_Status_Code_Actions (Response.result);
end if;
return Response;
end On_CodeAction_Request;
--------------------------------
-- On_Execute_Command_Request --
--------------------------------
overriding function On_Execute_Command_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Execute_Command_Request)
return LSP.Messages.Server_Responses.ExecuteCommand_Response
is
Error : LSP.Errors.Optional_ResponseError;
Params : LSP.Messages.ExecuteCommandParams renames
Request.params;
Response : LSP.Messages.Server_Responses.ExecuteCommand_Response
(Is_Error => True);
begin
if Params.Is_Unknown or else Params.Custom.Is_Null then
Response.error :=
(True,
(code => LSP.Errors.InternalError,
message => "Not implemented",
data => <>));
return Response;
end if;
Params.Custom.Unchecked_Get.Execute
(Handler => Self,
Client => Self.Server,
Error => Error);
if Error.Is_Set then
Response.error := Error;
return Response;
end if;
-- No particular response in case of success.
return (Is_Error => False,
error => (Is_Set => False),
others => <>);
end On_Execute_Command_Request;
----------------------------
-- On_Declaration_Request --
----------------------------
overriding function On_Declaration_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Declaration_Request)
return LSP.Messages.Server_Responses.Location_Link_Response
is
Value : LSP.Messages.DeclarationParams renames
Request.params;
Response : LSP.Messages.Server_Responses.Location_Link_Response
(Is_Error => False);
Imprecise : Boolean := False;
Display_Method_Ancestry_Policy :
LSP.Messages.AlsDisplayMethodAncestryOnNavigationPolicy :=
Self.Display_Method_Ancestry_Policy;
Document : constant LSP.Ada_Documents.Document_Access :=
Get_Open_Document (Self, Value.textDocument.uri);
begin
-- Override the displayMethodAncestryOnNavigation global configuration
-- flag if there is on embedded in the request.
if Value.alsDisplayMethodAncestryOnNavigation.Is_Set then
Display_Method_Ancestry_Policy :=
Value.alsDisplayMethodAncestryOnNavigation.Value;
end if;
for C of Self.Contexts_For_URI (Value.textDocument.uri) loop
C.Append_Declarations
(Document,
LSP.Messages.TextDocumentPositionParams (Value),
Display_Method_Ancestry_Policy,
Response.result,
Imprecise);
exit when Request.Canceled;
end loop;
if Imprecise then
Self.Show_Imprecise_Reference_Warning ("declaration");
end if;
Sort_And_Remove_Duplicates (Response.result.Locations);
return Response;
end On_Declaration_Request;
-------------------------------
-- On_Implementation_Request --
-------------------------------
overriding function On_Implementation_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Implementation_Request)
return LSP.Messages.Server_Responses.Location_Link_Response
is
use Libadalang.Analysis;
use LSP.Messages;
Value : LSP.Messages.ImplementationParams renames
Request.params;
Response : LSP.Messages.Server_Responses.Location_Link_Response
(Is_Error => False);
Imprecise : Boolean := False;
Display_Method_Ancestry_Policy :
LSP.Messages.AlsDisplayMethodAncestryOnNavigationPolicy :=
Self.Display_Method_Ancestry_Policy;
Document : constant LSP.Ada_Documents.Document_Access :=
Get_Open_Document (Self, Value.textDocument.uri);
procedure Resolve_In_Context (C : Context_Access);
-- Utility function to gather results on one context
------------------------
-- Resolve_In_Context --
------------------------
procedure Resolve_In_Context (C : Context_Access) is
Name_Node : constant Name := Laltools.Common.Get_Node_As_Name
(C.Get_Node_At (Document, Value));
procedure Update_Response
(Bodies : Laltools.Common.Bodies_List.List;
Kind : LSP.Messages.AlsReferenceKind_Set);
-- Utility function to update response with the bodies
---------------------
-- Update_Response --
---------------------
procedure Update_Response
(Bodies : Laltools.Common.Bodies_List.List;
Kind : LSP.Messages.AlsReferenceKind_Set)
is
begin
for E of Bodies loop
Append_Location
(Response.result,
E,
Kind);
end loop;
end Update_Response;
Definition : Defining_Name;
This_Imprecise : Boolean;
Find_All_Imprecise : Boolean;
Decl : Basic_Decl;
begin
if Name_Node = No_Name then
return;
end if;
-- Find the definition
Definition := Laltools.Common.Resolve_Name
(Name_Node, Self.Trace, This_Imprecise);
Imprecise := Imprecise or This_Imprecise;
-- If we didn't find a definition, give up for this context
if Definition = No_Defining_Name then
return;
end if;
-- First list the bodies of this definition
Update_Response
(Laltools.Common.List_Bodies_Of
(Definition, Self.Trace, Imprecise),
LSP.Messages.Empty_Set);
-- Then list the bodies of the parent implementations
Decl := Definition.P_Basic_Decl;
-- Display overriding/overridden subprograms depending on the
-- displayMethodAncestryOnNavigation flag.
if Display_Method_Ancestry_Policy in Definition_Only | Always
or else
(Display_Method_Ancestry_Policy = Usage_And_Abstract_Only
and then Decl.Kind in Ada_Abstract_Subp_Decl_Range)
then
for Subp of C.Find_All_Base_Declarations (Decl, Find_All_Imprecise)
loop
Update_Response
(Laltools.Common.List_Bodies_Of
(Subp.P_Defining_Name, Self.Trace, This_Imprecise),
Is_Parent);
Imprecise := Imprecise or This_Imprecise;
end loop;
Imprecise := Imprecise or Find_All_Imprecise;
-- And finally the bodies of child implementations
for Subp of C.Find_All_Overrides (Decl, Find_All_Imprecise) loop
Update_Response
(Laltools.Common.List_Bodies_Of
(Subp.P_Defining_Name, Self.Trace, This_Imprecise),
Is_Child);
Imprecise := Imprecise or This_Imprecise;
end loop;
Imprecise := Imprecise or Find_All_Imprecise;
end if;
end Resolve_In_Context;
begin
-- Override the displayMethodAncestryOnNavigation global configuration
-- flag if there is on embedded in the request.
if Value.alsDisplayMethodAncestryOnNavigation.Is_Set then
Display_Method_Ancestry_Policy :=
Value.alsDisplayMethodAncestryOnNavigation.Value;
end if;
for C of Self.Contexts_For_URI (Value.textDocument.uri) loop
Resolve_In_Context (C);
exit when Request.Canceled;
end loop;
if Imprecise then
Self.Show_Imprecise_Reference_Warning ("implementation");
end if;
Sort_And_Remove_Duplicates (Response.result.Locations);
return Response;
end On_Implementation_Request;
---------------------------
-- On_Definition_Request --
---------------------------
overriding function On_Definition_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Definition_Request)
return LSP.Messages.Server_Responses.Location_Link_Response
is
use Libadalang.Analysis;
use LSP.Messages;
Value : LSP.Messages.DefinitionParams renames
Request.params;
Response : LSP.Messages.Server_Responses.Location_Link_Response
(Is_Error => False);
Imprecise : Boolean := False;
Display_Method_Ancestry_Policy :
LSP.Messages.AlsDisplayMethodAncestryOnNavigationPolicy :=
Self.Display_Method_Ancestry_Policy;
Document : constant LSP.Ada_Documents.Document_Access :=
Get_Open_Document (Self, Value.textDocument.uri);
procedure Resolve_In_Context (C : Context_Access);
-- Utility function, appends to Resonse.result all results of the
-- definition requests found in context C.
------------------------
-- Resolve_In_Context --
------------------------
procedure Resolve_In_Context (C : Context_Access) is
Name_Node : constant Name :=
Laltools.Common.Get_Node_As_Name
(C.Get_Node_At (Document, Value));
Definition : Defining_Name;
Other_Part : Defining_Name;
Manual_Fallback : Defining_Name;
Definition_Node : Basic_Decl := No_Basic_Decl;
Decl_For_Find_Overrides : Basic_Decl := No_Basic_Decl;
Entry_Decl_Node : Entry_Decl := No_Entry_Decl;
begin
if Name_Node = No_Name then
return;
end if;
-- Check if we are on some defining name
Definition := Laltools.Common.Get_Name_As_Defining (Name_Node);
if Definition = No_Defining_Name then
Self.Imprecise_Resolve_Name (C, Value, Definition);
if Definition /= No_Defining_Name then
Append_Location (Response.result, Definition);
if Display_Method_Ancestry_Policy
in Usage_And_Abstract_Only | Always
then
Decl_For_Find_Overrides := Definition.P_Basic_Decl;
end if;
end if;
else -- If we are on a defining_name already
Other_Part := Laltools.Common.Find_Next_Part
(Definition, Self.Trace);
Definition_Node := Definition.P_Basic_Decl;
-- Search for overriding subprograms only if we are on an
-- abstract subprogram.
if Display_Method_Ancestry_Policy = Never
or else
(Display_Method_Ancestry_Policy = Usage_And_Abstract_Only
and then Definition_Node.Kind
not in Ada_Abstract_Subp_Decl_Range)
then
Decl_For_Find_Overrides := No_Basic_Decl;
else
Decl_For_Find_Overrides := Definition_Node;
end if;
-- Search for accept statements only if we are on an entry
if Definition_Node.Kind in Ada_Entry_Decl_Range then
Entry_Decl_Node := Definition_Node.As_Entry_Decl;
elsif Definition_Node.Kind in
Ada_Single_Task_Type_Decl_Range | Ada_Protected_Type_Decl_Range
then
-- These node types are not handled by Find_Next_Part
-- (LAL design limitations)
declare
Other_Part_For_Decl : constant Basic_Decl :=
Laltools.Common.Find_Next_Part_For_Decl
(Definition_Node, Self.Trace);
begin
if Other_Part_For_Decl /= No_Basic_Decl then
Other_Part := Other_Part_For_Decl.P_Defining_Name;
end if;
end;
end if;
if Other_Part = No_Defining_Name then
-- No next part is found. Check first defining name
Other_Part := Laltools.Common.Find_Canonical_Part
(Definition, Self.Trace);
end if;
if Other_Part /= No_Defining_Name then
Append_Location (Response.result, Other_Part);
else
-- We were on a defining name, but did not manage to find
-- an answer using Find_Next_Part / Find_Canonical_Part.
-- Use the manual fallback to attempt to find a good enough
-- result.
Manual_Fallback := Laltools.Common.Find_Other_Part_Fallback
(Definition, Self.Trace);
if Manual_Fallback /= No_Defining_Name then
-- We have found a result using the imprecise heuristics.
-- We'll warn the user and send the result.
Imprecise := True;
Append_Location (Response.result, Manual_Fallback);
end if;
end if;
end if;
if Decl_For_Find_Overrides /= Libadalang.Analysis.No_Basic_Decl then
declare
Imprecise_Over : Boolean;
Imprecise_Base : Boolean;
Overriding_Subps : constant Basic_Decl_Array :=
C.Find_All_Overrides
(Decl_For_Find_Overrides,
Imprecise_Results => Imprecise_Over);
Base_Subps : constant Basic_Decl_Array :=
C.Find_All_Base_Declarations
(Decl_For_Find_Overrides,
Imprecise_Results => Imprecise_Base);
begin
for Subp of Base_Subps loop
Append_Location
(Response.result, Subp.P_Defining_Name, Is_Parent);
end loop;
for Subp of Overriding_Subps loop
Append_Location
(Response.result, Subp.P_Defining_Name, Is_Child);
end loop;
Imprecise := Imprecise or Imprecise_Over or Imprecise_Base;
end;
end if;
if Entry_Decl_Node /= Libadalang.Analysis.No_Entry_Decl then
for Accept_Node of Entry_Decl_Node.P_Accept_Stmts loop
Append_Location (Response.result, Accept_Node.F_Name);
end loop;
end if;
end Resolve_In_Context;
begin
-- Override the displayMethodAncestryOnNavigation global configuration
-- flag if there is on embedded in the request.
if Value.alsDisplayMethodAncestryOnNavigation.Is_Set then
Display_Method_Ancestry_Policy :=
Value.alsDisplayMethodAncestryOnNavigation.Value;
end if;
for C of Self.Contexts_For_URI (Value.textDocument.uri) loop
Resolve_In_Context (C);
exit when Request.Canceled;
end loop;
if Imprecise then
Self.Show_Imprecise_Reference_Warning ("definition");
end if;
Sort_And_Remove_Duplicates (Response.result.Locations);
return Response;
end On_Definition_Request;
--------------------------------
-- On_Type_Definition_Request --
--------------------------------
overriding function On_Type_Definition_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Type_Definition_Request)
return LSP.Messages.Server_Responses.Location_Link_Response
is
use Libadalang.Analysis;
Position : LSP.Messages.TextDocumentPositionParams renames
Request.params;
Response : LSP.Messages.Server_Responses.Location_Link_Response
(Is_Error => False);
Imprecise : Boolean := False;
Document : constant LSP.Ada_Documents.Document_Access :=
Get_Open_Document (Self, Position.textDocument.uri);
procedure Resolve_In_Context (C : Context_Access);
-- Utility function to gather results on one context
------------------------
-- Resolve_In_Context --
------------------------
procedure Resolve_In_Context (C : Context_Access) is
Name_Node : constant Name := Laltools.Common.Get_Node_As_Name
(C.Get_Node_At (Document, Position));
Definition : Defining_Name;
Type_Decl : Base_Type_Decl;
begin
if Name_Node = No_Name then
return;
end if;
if Name_Node.P_Is_Defining then
-- Special case if Name_Node is defining, for instance on the X in
-- X : My_Type;
declare
Def_Name : constant Defining_Name :=
Name_Node.P_Enclosing_Defining_Name;
Type_Expr : constant Libadalang.Analysis.Type_Expr :=
Def_Name.P_Basic_Decl.P_Type_Expression;
begin
if not Type_Expr.Is_Null then
Definition := Laltools.Common.Resolve_Name
(Type_Expr.P_Type_Name, Self.Trace, Imprecise);
end if;
end;
else
-- Name_Node is not defining. In this case we can rely on
-- P_Expression_Type.
Type_Decl := Name_Node.P_Expression_Type;
-- P_Expression_Type returns the entire expression: narrow the
-- result down to the type declaration. Here we assume that the
-- first defining name in this expression is the name of the type.
if Type_Decl /= No_Type_Decl then
Definition := Type_Decl.P_Defining_Name;
end if;
end if;
if Definition /= No_Defining_Name then
Append_Location (Response.result, Definition);
end if;
end Resolve_In_Context;
begin
for C of Self.Contexts_For_URI (Position.textDocument.uri) loop
Resolve_In_Context (C);
exit when Request.Canceled;
end loop;
return Response;
end On_Type_Definition_Request;
-------------------------------------------
-- On_DidChangeTextDocument_Notification --
-------------------------------------------
overriding procedure On_DidChangeTextDocument_Notification
(Self : access Message_Handler;
Value : LSP.Messages.DidChangeTextDocumentParams)
is
function Skip_Did_Change return Boolean;
-- Check if the following message in the queue is didChange for
-- the same document
---------------------
-- Skip_Did_Change --
---------------------
function Skip_Did_Change return Boolean is
use type LSP.Servers.Message_Access;
subtype DidChangeTextDocument_Notification is LSP.Messages
.Server_Notifications.DidChangeTextDocument_Notification;
Next : constant LSP.Servers.Message_Access :=
Self.Server.Look_Ahead_Message;
begin
if Next = null
or else Next.all not in
DidChangeTextDocument_Notification'Class
then
return False;
end if;
declare
Object : DidChangeTextDocument_Notification'Class renames
DidChangeTextDocument_Notification'Class (Next.all);
Object_File : constant GNATCOLL.VFS.Virtual_File :=
Self.To_File (Object.params.textDocument.uri);
Value_File : constant GNATCOLL.VFS.Virtual_File :=
Self.To_File (Value.textDocument.uri);
begin
if Object_File /= Value_File then
return False;
end if;
end;
return True;
end Skip_Did_Change;
Document : constant LSP.Ada_Documents.Document_Access :=
Get_Open_Document (Self, Value.textDocument.uri);
begin
if Document = null then
Self.Log_Unexpected_Null_Document
("On_DidChangeTextDocument_Notification");
end if;
if Allow_Incremental_Text_Changes.Active then
-- If we are applying incremental changes, we can't skip the
-- call to Apply_Changes, since this would break synchronization.
Document.Apply_Changes
(Value.textDocument.version,
Value.contentChanges);
-- However, we should skip the Indexing part if the next change in
-- the queue will re-change the text document.
if Skip_Did_Change then
return;
end if;
else
-- If we are not applying incremental changes, we can skip
-- Apply_Changes: the next change will contain the full text.
if Skip_Did_Change then
return;
end if;
Document.Apply_Changes
(Value.textDocument.version,
Value.contentChanges);
end if;
-- Reindex the document in each of the contexts where it is relevant
for Context of Self.Contexts_For_URI (Value.textDocument.uri) loop
Context.Index_Document (Document.all);
end loop;
-- Emit diagnostics
Self.Publish_Diagnostics (Document);
end On_DidChangeTextDocument_Notification;
------------------------------------------
-- On_DidCloseTextDocument_Notification --
------------------------------------------
overriding procedure On_DidCloseTextDocument_Notification
(Self : access Message_Handler;
Value : LSP.Messages.DidCloseTextDocumentParams)
is
URI : LSP.Messages.DocumentUri renames Value.textDocument.uri;
File : constant GNATCOLL.VFS.Virtual_File := Self.To_File (URI);
Diag : LSP.Messages.PublishDiagnosticsParams;
Document : Internal_Document_Access;
begin
if Self.Open_Documents.Contains (File) then
Document := Self.Open_Documents.Element (File);
-- Remove the URI from the set of open documents now: this way,
-- the call to Flush_Document below will not attempt to reindex
-- from an open document, but from the file on disk.
Self.Open_Documents.Delete (File);
for Context of Self.Contexts_For_URI (URI) loop
Context.Flush_Document (File);
end loop;
Free (Document);
else
-- We have received a didCloseTextDocument but the document was
-- not open: this is not supposed to happen, log it.
Self.Trace.Trace
("received a didCloseTextDocument for non-open document with uri: "
& To_UTF_8_String (URI));
end if;
-- Clean diagnostics up on closing document
if Self.Diagnostics_Enabled then
Diag.uri := URI;
Self.Server.On_Publish_Diagnostics (Diag);
end if;
end On_DidCloseTextDocument_Notification;
-----------------------------------------
-- On_DidOpenTextDocument_Notification --
-----------------------------------------
overriding procedure On_DidOpenTextDocument_Notification
(Self : access Message_Handler;
Value : LSP.Messages.DidOpenTextDocumentParams)
is
URI : LSP.Messages.DocumentUri renames Value.textDocument.uri;
File : constant GNATCOLL.VFS.Virtual_File := Self.To_File (URI);
Object : constant Internal_Document_Access :=
new LSP.Ada_Documents.Document (Self.Trace);
Diag : constant LSP.Diagnostic_Sources.Diagnostic_Source_Access :=
new LSP.Ada_Handlers.Project_Diagnostics.Diagnostic_Source (Self);
begin
Self.Trace.Trace ("In Text_Document_Did_Open");
Self.Trace.Trace ("Uri : " & To_UTF_8_String (URI));
-- Some clients don't properly call initialize, or don't pass the
-- project to didChangeConfiguration: fallback here on loading a
-- project in this directory, if needed.
Self.Ensure_Project_Loaded (URI);
-- We have received a document: add it to the documents container
Object.Initialize (URI, Value.textDocument.text, Diag);
Self.Open_Documents.Include (File, Object);
-- Handle the case where we're loading the implicit project: do
-- we need to add the directory in which the document is open?
if Self.Project_Status in Implicit_Project_Loaded then
declare
Dir : constant Virtual_File := Self.To_File (URI).Dir;
begin
if not Self.Project_Dirs_Loaded.Contains (Dir) then
-- We do need to add this directory
Self.Project_Dirs_Loaded.Insert (Dir);
Self.Reload_Implicit_Project_Dirs;
end if;
end;
end if;
-- Index the document in all the contexts where it is relevant
for Context of Self.Contexts_For_URI (URI) loop
Context.Index_Document (Object.all);
end loop;
-- Emit diagnostics
Self.Publish_Diagnostics (LSP.Ada_Documents.Document_Access (Object));
Self.Trace.Trace ("Finished Text_Document_Did_Open");
end On_DidOpenTextDocument_Notification;
------------------------------
-- On_Folding_Range_Request --
------------------------------
overriding function On_Folding_Range_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Folding_Range_Request)
return LSP.Messages.Server_Responses.FoldingRange_Response
is
Value : LSP.Messages.FoldingRangeParams renames
Request.params;
Context : constant Context_Access :=
Self.Contexts.Get_Best_Context (Value.textDocument.uri);
Document : constant LSP.Ada_Documents.Document_Access :=
Get_Open_Document (Self, Value.textDocument.uri);
Result : LSP.Messages.FoldingRange_Vector;
package Canceled is new LSP.Generic_Cancel_Check (Request'Access, 127);
begin
if Document /= null then
Document.Get_Folding_Blocks
(Context.all,
Self.Line_Folding_Only,
Self.Options.Folding.Comments,
Canceled.Has_Been_Canceled'Access,
Result);
return Response : LSP.Messages.Server_Responses.FoldingRange_Response
(Is_Error => False)
do
if not Canceled.Has_Been_Canceled then
Response.result := Result;
end if;
end return;
else
return Response : LSP.Messages.Server_Responses.FoldingRange_Response
(Is_Error => True)
do
Response.error :=
(True,
(code => LSP.Errors.InternalError,
message => "Document is not opened",
data => <>));
end return;
end if;
end On_Folding_Range_Request;
--------------------------------
-- On_Selection_Range_Request --
--------------------------------
overriding function On_Selection_Range_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Selection_Range_Request)
return LSP.Messages.Server_Responses.SelectionRange_Response
is
pragma Unreferenced (Self, Request);
Response : LSP.Messages.Server_Responses.SelectionRange_Response
(Is_Error => True);
begin
Response.error :=
(True,
(code => LSP.Errors.InternalError,
message => "Not implemented",
data => <>));
return Response;
end On_Selection_Range_Request;
--------------------------
-- On_Highlight_Request --
--------------------------
overriding function On_Highlight_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Highlight_Request)
return LSP.Messages.Server_Responses.Highlight_Response
is
use Libadalang.Analysis;
use LSP.Messages;
Value : LSP.Messages.TextDocumentPositionParams renames
Request.params;
Context : constant Context_Access :=
Self.Contexts.Get_Best_Context (Value.textDocument.uri);
Document : constant LSP.Ada_Documents.Document_Access :=
Get_Open_Document (Self, Value.textDocument.uri);
File : constant GNATCOLL.VFS.Virtual_File :=
Self.To_File (Value.textDocument.uri);
Response : LSP.Messages.Server_Responses.Highlight_Response
(Is_Error => False);
Definition : Defining_Name;
procedure Callback
(Node : Libadalang.Analysis.Base_Id;
Kind : Libadalang.Common.Ref_Result_Kind;
Cancel : in out Boolean);
-- Called on each found reference. Used to append the reference to the
-- final result.
function Get_Highlight_Kind
(Node : Ada_Node) return LSP.Messages.Optional_DocumentHighlightKind;
-- Fetch highlight kind for given node
------------------------
-- Get_Highlight_Kind --
------------------------
function Get_Highlight_Kind
(Node : Ada_Node) return LSP.Messages.Optional_DocumentHighlightKind
is
Id : constant Name := Laltools.Common.Get_Node_As_Name (Node);
begin
if Id.P_Is_Write_Reference then
return LSP.Messages.Optional_DocumentHighlightKind'
(Is_Set => True, Value => Write);
else
return LSP.Messages.Optional_DocumentHighlightKind'
(Is_Set => True, Value => Read);
end if;
end Get_Highlight_Kind;
--------------
-- Callback --
--------------
procedure Callback
(Node : Libadalang.Analysis.Base_Id;
Kind : Libadalang.Common.Ref_Result_Kind;
Cancel : in out Boolean)
is
pragma Unreferenced (Kind);
pragma Unreferenced (Cancel);
begin
if not Laltools.Common.Is_End_Label (Node.As_Ada_Node) then
Append_Location
(Result => Response.result,
Document => Document,
File => File,
Node => Node,
Kind => Get_Highlight_Kind (Node.As_Ada_Node));
end if;
end Callback;
begin
if Document /= null then
Self.Imprecise_Resolve_Name (Context, Value, Definition);
if Definition = No_Defining_Name or else Request.Canceled then
return Response;
end if;
-- Find all references will return all the references except the
-- declaration ...
Document.Find_All_References
(Context => Context.all,
Definition => Definition,
Callback => Callback'Access);
-- ... add it manually
Append_Location
(Result => Response.result,
Document => Document,
File => File,
Node => Definition,
Kind => Get_Highlight_Kind (Definition.As_Ada_Node));
end if;
return Response;
end On_Highlight_Request;
----------------------
-- On_Hover_Request --
----------------------
overriding function On_Hover_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Hover_Request)
return LSP.Messages.Server_Responses.Hover_Response
is
use Libadalang.Analysis;
Value : LSP.Messages.TextDocumentPositionParams renames
Request.params;
Response : LSP.Messages.Server_Responses.Hover_Response
(Is_Error => False);
Defining_Name_Node : Defining_Name;
Decl : Basic_Decl;
Decl_Lines : VSS.String_Vectors.Virtual_String_Vector;
Decl_Text : VSS.Strings.Virtual_String;
Comments_Lines : VSS.String_Vectors.Virtual_String_Vector;
Comments_Text : VSS.Strings.Virtual_String;
Location_Text : VSS.Strings.Virtual_String;
C : constant Context_Access :=
Self.Contexts.Get_Best_Context (Value.textDocument.uri);
-- For the Hover request, we're only interested in the "best"
-- response value, not in the list of values for all contexts
Options : constant
GNATdoc.Comments.Options.Extractor_Options :=
(Style => Self.Options.Documentation.Style,
Fallback => True);
begin
Self.Imprecise_Resolve_Name (C, Value, Defining_Name_Node);
if Defining_Name_Node = No_Defining_Name then
return Response;
end if;
-- Get the associated basic declaration
Decl := Defining_Name_Node.P_Basic_Decl;
if Decl = No_Basic_Decl or else Request.Canceled then
return Response;
end if;
-- Extract documentation with GNATdoc when supported.
GNATdoc.Comments.Helpers.Get_Plain_Text_Documentation
(Defining_Name_Node, Options, Decl_Lines, Comments_Lines);
Decl_Text := Decl_Lines.Join_Lines (VSS.Strings.LF, False);
Comments_Text := Comments_Lines.Join_Lines (VSS.Strings.LF, False);
-- Obtain documentation when GNATdoc support is missing.
if Comments_Text.Is_Empty then
Comments_Text :=
VSS.Strings.To_Virtual_String
(Libadalang.Doc_Utils.Get_Documentation (Decl).Doc.To_String);
end if;
if Decl_Text.Is_Empty
or else not Decl.P_Subp_Spec_Or_Null.Is_Null
then
-- For subprograms additional information is added, use old code to
-- obtain it yet.
Decl_Text := Get_Hover_Text (Decl, Decl_Lines);
end if;
if Decl_Text.Is_Empty then
return Response;
end if;
-- Append the whole declaration text to the response
Response.result := (Is_Set => True, others => <>);
Response.result.Value.contents.Vector.Append
(LSP.Messages.MarkedString'
(Is_String => False,
value => Decl_Text,
language => "ada"));
-- Append the declaration's location.
-- In addition, append the project's name if we are dealing with an
-- aggregate project.
Location_Text := LSP.Lal_Utils.Node_Location_Image (Decl);
if Self.Project_Tree.Root_Project.Is_Aggregate_Project then
Location_Text.Append (" in project ");
Location_Text.Append (C.Id);
end if;
Response.result.Value.contents.Vector.Append
(LSP.Messages.MarkedString'
(Is_String => True,
value => Location_Text));
-- Append the comments associated with the basic declaration
-- if any.
if not Comments_Text.Is_Empty then
Response.result.Value.contents.Vector.Append
(LSP.Messages.MarkedString'
(Is_String => False,
language => "plaintext",
value => Comments_Text));
end if;
return Response;
end On_Hover_Request;
---------------------------
-- On_References_Request --
---------------------------
overriding function On_References_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.References_Request)
return LSP.Messages.Server_Responses.Location_Response
is
use Libadalang.Analysis;
Value : LSP.Messages.ReferenceParams renames Request.params;
Response : LSP.Messages.Server_Responses.Location_Response
(Is_Error => False);
Imprecise : Boolean := False;
Additional_Kinds : LSP.Messages.AlsReferenceKind_Array :=
[others => False];
procedure Process_Context (C : Context_Access);
-- Process the references found in one context and append
-- them to Response.results.
function Get_Reference_Kind
(Node : Ada_Node;
Is_Overriding_Decl : Boolean := False)
return LSP.Messages.AlsReferenceKind_Set;
-- Fetch reference kind for given node.
------------------------
-- Get_Reference_Kind --
------------------------
function Get_Reference_Kind
(Node : Ada_Node;
Is_Overriding_Decl : Boolean := False)
return LSP.Messages.AlsReferenceKind_Set
is
use LSP.Messages;
Id : constant Name := Laltools.Common.Get_Node_As_Name (Node);
Result : LSP.Messages.AlsReferenceKind_Set := LSP.Messages.Empty_Set;
begin
begin
Result.As_Flags (LSP.Messages.Write) := Id.P_Is_Write_Reference;
exception
when E : Libadalang.Common.Property_Error =>
Log (Self.Trace, E);
end;
begin
Result.As_Flags (LSP.Messages.Access_Ref) :=
Laltools.Common.Is_Access_Ref (Id.As_Ada_Node);
exception
when E : Libadalang.Common.Property_Error =>
Log (Self.Trace, E);
end;
begin
Result.As_Flags (LSP.Messages.Static_Call) := Id.P_Is_Static_Call;
exception
when E : Libadalang.Common.Property_Error =>
Log (Self.Trace, E);
end;
begin
Result.As_Flags (LSP.Messages.Dispatching_Call) :=
Id.P_Is_Dispatching_Call;
exception
when E : Libadalang.Common.Property_Error =>
Log (Self.Trace, E);
end;
begin
Result.As_Flags (LSP.Messages.Child) :=
Laltools.Common.Is_Type_Derivation (Id.As_Ada_Node);
exception
when E : Libadalang.Common.Property_Error =>
Log (Self.Trace, E);
end;
Result.As_Flags (LSP.Messages.Overriding_Decl) := Is_Overriding_Decl;
-- If the result has not any set flags at this point, flag it as a
-- simple reference.
if Result.As_Flags = AlsReferenceKind_Array'(others => False) then
Result.As_Flags (LSP.Messages.Simple) := True;
end if;
-- Apply additional kinds
Result.As_Flags := Result.As_Flags or Additional_Kinds;
return Result;
end Get_Reference_Kind;
---------------------
-- Process_Context --
---------------------
procedure Process_Context (C : Context_Access) is
procedure Callback
(Node : Libadalang.Analysis.Base_Id;
Kind : Libadalang.Common.Ref_Result_Kind;
Cancel : in out Boolean);
Count : Cancel_Countdown := 0;
procedure Callback
(Node : Libadalang.Analysis.Base_Id;
Kind : Libadalang.Common.Ref_Result_Kind;
Cancel : in out Boolean) is
begin
Imprecise := Imprecise or Kind = Libadalang.Common.Imprecise;
if not Laltools.Common.Is_End_Label (Node.As_Ada_Node) then
Count := Count - 1;
Append_Location
(Response.result,
Node,
Get_Reference_Kind (Node.As_Ada_Node));
end if;
Cancel := Count = 0 and then Request.Canceled;
end Callback;
Definition : Defining_Name;
begin
Self.Imprecise_Resolve_Name (C, Value, Definition);
if Definition = No_Defining_Name or else Request.Canceled then
return;
end if;
-- Set additional "reference" kind for enumeration literal
declare
Decl : constant Basic_Decl := P_Basic_Decl (Definition);
begin
if Decl /= No_Basic_Decl
and then Kind (Decl) = Ada_Enum_Literal_Decl
then
Additional_Kinds (LSP.Messages.Simple) := True;
end if;
-- Find all the references
C.Find_All_References (Definition, Callback'Access);
-- Find all the overriding declarations, if any
for Subp of C.Find_All_Overrides (Decl, Imprecise) loop
Append_Location
(Response.result,
Subp.P_Defining_Name,
Get_Reference_Kind
(Definition.As_Ada_Node,
Is_Overriding_Decl => True));
end loop;
if Value.context.includeDeclaration then
Append_Location
(Response.result,
Definition,
Get_Reference_Kind (Definition.As_Ada_Node));
end if;
end;
end Process_Context;
begin
for C of Self.Contexts_For_URI (Value.textDocument.uri) loop
Process_Context (C);
exit when Request.Canceled;
end loop;
if Imprecise then
Self.Show_Imprecise_Reference_Warning ("references");
end if;
Sort_And_Remove_Duplicates (Response.result);
return Response;
end On_References_Request;
--------------------------------
-- On_ALS_Source_Dirs_Request --
--------------------------------
overriding function On_ALS_Source_Dirs_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.ALS_Source_Dirs_Request)
return LSP.Messages.Server_Responses.ALS_SourceDirs_Response
is
Response : LSP.Messages.Server_Responses.ALS_SourceDirs_Response
(Is_Error => False);
Unit_Desc : LSP.Messages.ALS_Source_Dir_Description;
Source_Dirs : constant GNATCOLL.VFS.File_Array :=
Self.Contexts.All_Source_Directories
(Include_Externally_Built => True);
begin
for Dir of Source_Dirs loop
Unit_Desc :=
(name => VSS.Strings.Conversions.To_Virtual_String
(+Dir.Base_Dir_Name),
uri =>
File_To_URI (Dir.Display_Full_Name));
Response.result.Append (Unit_Desc);
end loop;
Self.Trace.Trace
("Response.result.length: " & Response.result.Length'Img);
return Response;
end On_ALS_Source_Dirs_Request;
--------------------------------------
-- On_ALS_Show_Dependencies_Request --
--------------------------------------
overriding function On_ALS_Show_Dependencies_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.ALS_Show_Dependencies_Request)
return LSP.Messages.Server_Responses.ALS_ShowDependencies_Response
is
use LSP.Messages;
Params : LSP.Messages.ALS_ShowDependenciesParams renames
Request.params;
Response : LSP.Messages.Server_Responses.ALS_ShowDependencies_Response
(Is_Error => False);
Document : constant LSP.Ada_Documents.Document_Access :=
Get_Open_Document (Self, Params.textDocument.uri, Force => False);
Context : constant Context_Access :=
Self.Contexts.Get_Best_Context (Params.textDocument.uri);
begin
if Document = null then
Self.Log_Unexpected_Null_Document
("On_ALS_Show_Dependencies_Request");
return Response;
end if;
case Params.kind is
when LSP.Messages.Show_Imported =>
Document.Get_Imported_Units
(Context => Context.all,
Project_URI => Self.From_File (Self.Root),
Show_Implicit => Params.showImplicit,
Result => Response.result);
when LSP.Messages.Show_Importing => null;
declare
Contexts : constant LSP.Ada_Context_Sets.Context_Lists.List :=
Self.Contexts_For_URI (Params.textDocument.uri);
begin
for Context of Contexts loop
Document.Get_Importing_Units
(Context => Context.all,
Project_URI => Self.From_File (Self.Root),
Show_Implicit => Params.showImplicit,
Result => Response.result);
end loop;
end;
end case;
return Response;
end On_ALS_Show_Dependencies_Request;
--------------------------
-- On_ALS_Debug_Request --
--------------------------
overriding function On_ALS_Debug_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.ALS_Debug_Request)
return LSP.Messages.Server_Responses.ALS_Debug_Response is
begin
case Request.params.Kind is
when LSP.Messages.Suspend_Execution =>
declare
Limit : constant LSP_Number := Request.params.inputQueueLength;
begin
while Self.Server.Input_Queue_Length < Integer (Limit) loop
delay 0.1;
end loop;
end;
end case;
return Response : LSP.Messages.Server_Responses.ALS_Debug_Response
(Is_Error => False);
end On_ALS_Debug_Request;
-------------------------------
-- On_Signature_Help_Request --
-------------------------------
overriding function On_Signature_Help_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Signature_Help_Request)
return LSP.Messages.Server_Responses.SignatureHelp_Response
is
use Libadalang.Analysis;
use Langkit_Support.Slocs;
use LSP.Messages;
use type VSS.Strings.Virtual_String;
Value : LSP.Messages.SignatureHelpParams renames
Request.params;
Response : LSP.Messages.Server_Responses.SignatureHelp_Response
(Is_Error => False);
C : constant Context_Access :=
Self.Contexts.Get_Best_Context (Value.textDocument.uri);
Document : constant LSP.Ada_Documents.Document_Access :=
Get_Open_Document (Self, Value.textDocument.uri);
Node : Libadalang.Analysis.Ada_Node;
Sloc : Langkit_Support.Slocs.Source_Location;
Name_Node : Libadalang.Analysis.Name;
Prev_Designators : Laltools.Common.Node_Vectors.Vector;
Designator : Libadalang.Analysis.Ada_Node;
Active_Position : LSP.Types.LSP_Number;
Active_Signature : LSP.Types.LSP_Number := 0;
procedure Add_Signature (Decl_Node : Libadalang.Analysis.Basic_Decl);
-- Add the signature of Decl_Node if it matches the current context.
procedure Filter_Signature
(Signature_Info : SignatureInformation;
Designator : Libadalang.Analysis.Ada_Node;
Position : LSP.Types.LSP_Number;
Is_Active : Boolean);
-- Filter the signatures returned by the client using the current
-- current Position and designator.
-- Set Active_Signature to 0 when Is_Active and filtered out.
function Is_Signature_Active
(Parameters : ParameterInformation_Vector;
Sig_Label : VSS.Strings.Virtual_String;
Position : LSP.Types.LSP_Number;
Designator : Libadalang.Analysis.Ada_Node;
Active_Position : out LSP.Types.LSP_Number)
return Boolean;
-- Return True if Parameters is valid for the current Position and
-- Designator.
-- Active_Position will point to the active parameter inside Parameters.
-------------------
-- Add_Signature --
-------------------
procedure Add_Signature (Decl_Node : Libadalang.Analysis.Basic_Decl)
is
Param_Index : constant LSP.Types.LSP_Number :=
Get_Active_Parameter
(Node => Decl_Node,
Designator => Designator,
Prev_Designators => Prev_Designators,
Position => Active_Position);
begin
if Param_Index = -1 then
return;
end if;
declare
Signature : LSP.Messages.SignatureInformation :=
(label => Get_Hover_Text (Decl_Node),
documentation =>
(Is_Set => True,
Value =>
(Is_String => True,
String =>
VSS.Strings.To_Virtual_String
(Libadalang.Doc_Utils.Get_Documentation
(Decl_Node).Doc.To_String))),
activeParameter =>
(Is_Set => True,
Value => Param_Index),
others => <>
);
begin
Get_Parameters (Decl_Node, Signature.parameters);
Response.result.signatures.Append (Signature);
end;
end Add_Signature;
----------------------
-- Filter_Signature --
----------------------
procedure Filter_Signature
(Signature_Info : SignatureInformation;
Designator : Libadalang.Analysis.Ada_Node;
Position : LSP.Types.LSP_Number;
Is_Active : Boolean)
is
Active_Position : LSP.Types.LSP_Number;
begin
if Is_Signature_Active
(Parameters => Signature_Info.parameters,
Sig_Label => Signature_Info.label,
Position => Position,
Designator => Designator,
Active_Position => Active_Position)
then
declare
New_Signature : SignatureInformation := Signature_Info;
begin
-- Reuse Signature_Info after updating the active_position
New_Signature.activeParameter := (Is_Set => True,
Value => Active_Position);
Response.result.signatures.Append (New_Signature);
end;
elsif Is_Active then
Active_Signature := 0;
end if;
end Filter_Signature;
-------------------------
-- Is_Signature_Active --
-------------------------
function Is_Signature_Active
(Parameters : ParameterInformation_Vector;
Sig_Label : VSS.Strings.Virtual_String;
Position : LSP.Types.LSP_Number;
Designator : Libadalang.Analysis.Ada_Node;
Active_Position : out LSP.Types.LSP_Number)
return Boolean is
begin
Active_Position := 0;
if Designator = No_Ada_Node then
-- Check if Position is valid in Parameters (Note: Position starts
-- at 0)
Active_Position := Position;
return Position < LSP_Number (Parameters.Length);
else
declare
Name : constant VSS.Strings.Virtual_String :=
LSP.Lal_Utils.To_Virtual_String (Designator.Text);
begin
for Param of Parameters loop
declare
use type VSS.Unicode.UTF16_Code_Unit_Offset;
First :
VSS.Strings.Character_Iterators.Character_Iterator
:= Sig_Label.At_First_Character;
Last :
VSS.Strings.Character_Iterators.Character_Iterator
:= Sig_Label.At_First_Character;
Success : Boolean with Unreferenced;
begin
-- Convert to lower case?
if Param.label.Is_String then
if Param.label.String = Name then
return True;
end if;
else
while First.First_UTF16_Offset < Param.label.From
and then First.Forward
loop
null;
end loop;
-- 'till' is exclusive offset, thus lookup for it
-- location and move backward to point to last
-- character of the slice
while Last.First_UTF16_Offset < Param.label.Till
and then Last.Forward
loop
null;
end loop;
Success := Last.Backward;
if Sig_Label.Slice (First, Last) = Name then
return True;
end if;
end if;
Active_Position := Active_Position + 1;
end;
end loop;
end;
end if;
return False;
end Is_Signature_Active;
begin
Response.result := (others => <>);
Node := C.Get_Node_At (Document, Value, Previous => True);
Sloc := Document.Get_Source_Location (Value.position);
-- Check if we are inside a function call and get the caller name
Get_Call_Expr_Name
(Node => Node,
Cursor => Sloc,
Active_Position => Active_Position,
Designator => Designator,
Prev_Designators => Prev_Designators,
Name_Node => Name_Node);
if Name_Node = Libadalang.Analysis.No_Name then
-- Try again with the current position
Node := C.Get_Node_At (Document, Value, Previous => False);
Get_Call_Expr_Name
(Node => Node,
Cursor => Sloc,
Active_Position => Active_Position,
Designator => Designator,
Prev_Designators => Prev_Designators,
Name_Node => Name_Node);
if Name_Node = Libadalang.Analysis.No_Name then
return Response;
end if;
end if;
-- Is this a type cast?
if Name_Node.P_Name_Designated_Type /= No_Ada_Node
-- Does the cast make sense?
and then Active_Position = 0
-- Do we have the previous signatures?
and then Value.context.Is_Set
and then Value.context.Value.activeSignatureHelp.Is_Set
then
-- At this point, the user is writing a typecast in a previous
-- signature => keep showing the previous signatures.
Response.result := Value.context.Value.activeSignatureHelp.Value;
return Response;
end if;
if Value.context.Is_Set
and then Value.context.Value.isRetrigger
and then Value.context.Value.activeSignatureHelp.Is_Set
and then
(Value.context.Value.triggerKind /= TriggerCharacter
or else
-- Adding a ',' will not add new results only filter the previous
(Value.context.Value.triggerCharacter.Is_Set
and then Value.context.Value.triggerCharacter.Value = ","))
then
-- At this point, we are filtering the previous signatures:
-- * Don't recompute the list of signature
-- * Keep the previous activeSignature if not filtered out
declare
Prev_Res : SignatureHelp renames
Value.context.Value.activeSignatureHelp.Value;
-- Use index to find the activeSignature
Index : LSP.Types.LSP_Number := 0;
begin
if Prev_Res.activeSignature.Is_Set then
Active_Signature := Prev_Res.activeSignature.Value;
else
Active_Signature := 0;
end if;
for Signature_Info of Prev_Res.signatures loop
Filter_Signature
(Signature_Info => Signature_Info,
Designator => Designator,
Position => Active_Position,
Is_Active => Index = Active_Signature);
Index := Index + 1;
end loop;
end;
else
for N of C.Find_All_Env_Elements (Name_Node) loop
if N.Kind in Ada_Subp_Decl_Range
| Ada_Null_Subp_Decl_Range
| Ada_Expr_Function_Range
then
Add_Signature (N.As_Basic_Decl);
end if;
end loop;
end if;
-- Set the active values to default
Response.result.activeSignature := (Is_Set => True,
Value => Active_Signature);
-- activeParameter will be ignored because it is properly set in
-- the signatures.
Response.result.activeParameter := (Is_Set => True,
Value => 0);
return Response;
end On_Signature_Help_Request;
-----------------------------------
-- On_Color_Presentation_Request --
-----------------------------------
overriding function On_Color_Presentation_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Color_Presentation_Request)
return LSP.Messages.Server_Responses.ColorPresentation_Response
is
pragma Unreferenced (Self, Request);
Response : LSP.Messages.Server_Responses.ColorPresentation_Response
(Is_Error => True);
begin
Response.error :=
(True,
(code => LSP.Errors.InternalError,
message => "Not implemented",
data => <>));
return Response;
end On_Color_Presentation_Request;
-------------------------------
-- On_Document_Color_Request --
-------------------------------
overriding function On_Document_Color_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Document_Color_Request)
return LSP.Messages.Server_Responses.DocumentColor_Response
is
pragma Unreferenced (Self, Request);
Response : LSP.Messages.Server_Responses.DocumentColor_Response
(Is_Error => True);
begin
Response.error :=
(True,
(code => LSP.Errors.InternalError,
message => "Not implemented",
data => <>));
return Response;
end On_Document_Color_Request;
-------------------------------
-- On_Document_Links_Request --
-------------------------------
overriding function On_Document_Links_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Document_Links_Request)
return LSP.Messages.Server_Responses.Links_Response
is
pragma Unreferenced (Self, Request);
Response : LSP.Messages.Server_Responses.Links_Response
(Is_Error => True);
begin
Response.error :=
(True,
(code => LSP.Errors.InternalError,
message => "Not implemented",
data => <>));
return Response;
end On_Document_Links_Request;
-------------------------------------
-- On_Document_Tokens_Full_Request --
-------------------------------------
overriding function On_Document_Tokens_Full_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Document_Tokens_Full_Request)
return LSP.Messages.Server_Responses.SemanticTokens_Response
is
Value : LSP.Messages.SemanticTokensParams renames Request.params;
Document : constant LSP.Ada_Documents.Document_Access :=
Get_Open_Document (Self, Value.textDocument.uri, Force => False);
Context : constant Context_Access :=
Self.Contexts.Get_Best_Context (Value.textDocument.uri);
Response : LSP.Messages.Server_Responses.SemanticTokens_Response
(Is_Error => False);
Result : LSP.Messages.uinteger_Vector;
begin
if Document = null then
Self.Log_Unexpected_Null_Document
("On_Document_Tokens_Full_Request");
return Response;
end if;
Result := Document.Get_Tokens (Context.all, Self.Highlighter);
Response.result.data.Move (Result);
return Response;
end On_Document_Tokens_Full_Request;
--------------------------------------
-- On_Document_Tokens_Range_Request --
--------------------------------------
overriding function On_Document_Tokens_Range_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Document_Tokens_Range_Request)
return LSP.Messages.Server_Responses.SemanticTokens_Response
is
Value : LSP.Messages.SemanticTokensRangeParams renames Request.params;
Document : constant LSP.Ada_Documents.Document_Access :=
Get_Open_Document (Self, Value.textDocument.uri, Force => False);
Context : constant Context_Access :=
Self.Contexts.Get_Best_Context (Value.textDocument.uri);
Response : LSP.Messages.Server_Responses.SemanticTokens_Response
(Is_Error => False);
Result : LSP.Messages.uinteger_Vector;
begin
if Document = null then
Self.Log_Unexpected_Null_Document
("On_Document_Tokens_Range_Request");
return Response;
end if;
Result := Document.Get_Tokens
(Context.all, Self.Highlighter, Value.span);
Response.result.data.Move (Result);
return Response;
end On_Document_Tokens_Range_Request;
---------------------------------
-- On_Document_Symbols_Request --
---------------------------------
overriding function On_Document_Symbols_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Document_Symbols_Request)
return LSP.Messages.Server_Responses.Symbol_Response
is
-- The list of symbols for one document shouldn't depend
-- on the project: we can just choose the best context for this.
Value : LSP.Messages.DocumentSymbolParams renames Request.params;
Document : constant LSP.Ada_Documents.Document_Access :=
Get_Open_Document (Self, Value.textDocument.uri, Force => False);
Context : constant Context_Access :=
Self.Contexts.Get_Best_Context (Value.textDocument.uri);
Result : LSP.Messages.Server_Responses.Symbol_Response :=
(Is_Error => False,
result => <>,
error => (Is_Set => False),
others => <>);
Pattern : constant Search_Pattern'Class := Build
(Pattern => Value.query,
Case_Sensitive => Value.case_sensitive = LSP.Types.True,
Whole_Word => Value.whole_word = LSP.Types.True,
Negate => Value.negate = LSP.Types.True,
Kind =>
(if Value.kind.Is_Set
then Value.kind.Value
else LSP.Messages.Start_Word_Text));
package Canceled is new LSP.Generic_Cancel_Check (Request'Access, 127);
begin
if Document = null then
declare
Document : LSP.Ada_Documents.Document_Access :=
Get_Open_Document (Self, Value.textDocument.uri, Force => True);
begin
Self.Get_Symbols
(Document.all, Context.all, Pattern,
Canceled.Has_Been_Canceled'Access, Result.result);
Free (Internal_Document_Access (Document));
end;
else
Self.Get_Symbols
(Document.all, Context.all, Pattern,
Canceled.Has_Been_Canceled'Access, Result.result);
end if;
return Result;
end On_Document_Symbols_Request;
-----------------------
-- On_Rename_Request --
-----------------------
overriding function On_Rename_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Rename_Request)
return LSP.Messages.Server_Responses.Rename_Response
is
use Libadalang.Analysis;
Value : LSP.Messages.RenameParams renames Request.params;
Position : constant LSP.Messages.TextDocumentPositionParams :=
(Value.textDocument, Value.position);
Response : LSP.Messages.Server_Responses.Rename_Response
(Is_Error => False);
-- If a rename problem is found when Process_Context is called,
-- then Edits.Diagnotics will not be empty. This Response will be
-- discarded and a new response with an error meessage is returned
-- instead.
-- If no problems are found, then this Response will contain all the
-- references to be renamed and is returned by this function.
Document : constant LSP.Ada_Documents.Document_Access :=
Get_Open_Document (Self, Value.textDocument.uri);
Safe_Renamer : Laltools.Refactor.Safe_Rename.Safe_Renamer;
Algorithm : constant Laltools.Refactor.Safe_Rename.
Problem_Finder_Algorithm_Kind :=
Laltools.Refactor.Safe_Rename.Analyse_AST;
Context_Edits : Laltools.Refactor.Refactoring_Edits;
-- Edits found for a particular context
All_Edits : Laltools.Refactor.Refactoring_Edits;
-- When iterating over all contexts (and therefore all projects), it's
-- possible to encounter the same Text_Edit more than once, so this
-- stores all the unique edits
procedure Process_Context (C : Context_Access);
-- Process the rename request for the given context, and add the
-- edits to `All_Edits`.
---------------------
-- Process_Context --
---------------------
procedure Process_Context (C : Context_Access) is
use GNATCOLL.Projects;
use Laltools.Refactor.Safe_Rename;
Node : constant Ada_Node := C.Get_Node_At (Document, Position);
Name_Node : constant Libadalang.Analysis.Name :=
Laltools.Common.Get_Node_As_Name (Node);
Definition : constant Defining_Name :=
Laltools.Common.Resolve_Name_Precisely (Name_Node);
function Attribute_Value_Provider_Callback
(Attribute : GNATCOLL.Projects.Attribute_Pkg_String;
Index : String := "";
Default : String := "";
Use_Extended : Boolean := False)
return String
is (C.Project_Attribute_Value
(Attribute, Index, Default, Use_Extended));
Attribute_Value_Provider : constant Attribute_Value_Provider_Access :=
Attribute_Value_Provider_Callback'Unrestricted_Access;
function Analysis_Units return Analysis_Unit_Array is
(C.Analysis_Units);
-- Callback needed to provide the analysis units to the safe rename
-- tool.
procedure Process_Comments (Node : Ada_Node);
-- Iterate over all comments and include them in the response when
-- they contain a renamed word.
procedure Process_File_Renames;
-- Merges Context_Edits.File_Renames into All_Edits.File_Renames
procedure Process_References;
-- Merges Context_Edits.Text_Edits into All_Edits.Text_Edits and for
-- each Text_Edit (which represents a reference) processes its
-- references in comments.
-----------------------
-- Process_Comments --
-----------------------
procedure Process_Comments (Node : Ada_Node)
is
use Laltools.Refactor;
File_Name : constant File_Name_Type :=
Node.Unit.Get_Filename;
Token : Token_Reference := First_Token (Node.Unit);
Name : constant Wide_Wide_String :=
Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String
(Laltools.Common.Get_Last_Name (Name_Node));
Text_Edit : Laltools.Refactor.Text_Edit;
Span : Langkit_Support.Slocs.Source_Location_Range;
Current : Token_Reference;
Diff : Integer;
function Process_Box return Boolean;
-- Check whether Current is box header/footer and modify it.
-- Return False when the searching cycle should be stopped.
-----------------
-- Process_Box --
-----------------
function Process_Box return Boolean is
use Langkit_Support.Text;
use Langkit_Support.Slocs;
begin
if Current = No_Token then
return False;
end if;
case Kind (Data (Current)) is
when Ada_Whitespace =>
return True;
when Ada_Comment =>
declare
Value : constant Text_Type := Text (Current);
begin
for Idx in Value'Range loop
if Value (Idx) /= '-' then
return False;
end if;
end loop;
if Diff > 0 then
-- Increase '-', Diff is positive
declare
Sloc : Source_Location_Range :=
Sloc_Range (Data (Current));
begin
Sloc.Start_Column := Sloc.End_Column;
Laltools.Refactor.Safe_Insert
(All_Edits.Text_Edits,
File_Name,
Laltools.Refactor.Text_Edit'
(Sloc,
Ada.Strings.Unbounded."*" (Diff, '-')));
end;
else
-- Decrease '-', Diff is negative
declare
Sloc : Source_Location_Range :=
Sloc_Range (Data (Current));
begin
Sloc.Start_Column :=
Sloc.End_Column - Column_Number (abs Diff);
Laltools.Refactor.Safe_Insert
(All_Edits.Text_Edits,
File_Name,
Laltools.Refactor.Text_Edit'
(Sloc, Null_Unbounded_String));
end;
end if;
return False;
end;
when others =>
return False;
end case;
end Process_Box;
begin
Diff := Natural (Value.newName.Character_Length) - Name'Length;
while Token /= No_Token loop
declare
This_Span : Langkit_Support.Slocs.Source_Location_Range;
begin
if Kind (Data (Token)) = Ada_Comment
and then Laltools.Common.Contains
(Token, Name, True, This_Span)
then
Text_Edit.Location := This_Span;
Text_Edit.Text :=
VSS.Strings.Conversions.To_Unbounded_UTF_8_String
(Value.newName);
if Diff /= 0
and then Laltools.Common.Contains
(Token, "-- " & Name & " --", False, Span)
then
-- Can be a comment box
Current := Previous (Token);
loop
-- Looking for the box header
exit when not Process_Box;
Current := Previous (Current);
end loop;
-- Include corrected comment itself
Laltools.Refactor.Safe_Insert
(All_Edits.Text_Edits,
Node.Unit.Get_Filename,
Text_Edit);
Current := Next (Token);
loop
-- Looking for the box footer
exit when not Process_Box;
Current := Next (Current);
end loop;
else
Laltools.Refactor.Safe_Insert
(All_Edits.Text_Edits,
Node.Unit.Get_Filename,
Text_Edit);
end if;
end if;
end;
Token := Next (Token);
end loop;
end Process_Comments;
--------------------------
-- Process_File_Renames --
--------------------------
procedure Process_File_Renames is
begin
All_Edits.File_Renames.Union (Context_Edits.File_Renames);
end Process_File_Renames;
------------------------
-- Process_References --
------------------------
procedure Process_References
is
use Laltools.Refactor;
Text_Edits_Cursor : Text_Edit_Ordered_Maps.Cursor :=
Context_Edits.Text_Edits.First;
Unit : Analysis_Unit; -- Reference Unit
Node : Ada_Node; -- Reference Node
begin
Text_Edits_Cursor := Context_Edits.Text_Edits.First;
while Text_Edit_Ordered_Maps.Has_Element (Text_Edits_Cursor) loop
for Text_Edit of
Text_Edit_Ordered_Maps.Element (Text_Edits_Cursor)
loop
-- Check if we've already seen this reference from another
-- context.
if not Contains
(All_Edits.Text_Edits,
Text_Edit_Ordered_Maps.Key (Text_Edits_Cursor),
Text_Edit)
then
-- First time we see this reference, so add it All_Edits
-- and process comments.
Safe_Insert
(All_Edits.Text_Edits,
Text_Edit_Ordered_Maps.Key (Text_Edits_Cursor),
Text_Edit);
Unit := C.Get_AU
(GNATCOLL.VFS.Create_From_UTF8
(String (Text_Edit_Ordered_Maps.Key
(Text_Edits_Cursor))));
Node := Unit.Root.Lookup
((Text_Edit.Location.Start_Line,
Text_Edit.Location.Start_Column));
if Self.Options.Refactoring.Renaming.In_Comments then
Process_Comments (Node);
end if;
end if;
end loop;
Text_Edits_Cursor :=
Text_Edit_Ordered_Maps.Next (Text_Edits_Cursor);
end loop;
end Process_References;
begin
if Definition.Is_Null then
return;
end if;
Safe_Renamer := Laltools.Refactor.Safe_Rename.Create_Safe_Renamer
(Definition => Definition,
New_Name =>
Libadalang.Text.To_Unbounded_Text
(VSS.Strings.Conversions.To_Wide_Wide_String (Value.newName)),
Algorithm => Algorithm,
Attribute_Value_Provider => Attribute_Value_Provider);
Context_Edits := Safe_Renamer.Refactor (Analysis_Units'Access);
-- If problems were found, do not continue processing references
if not Context_Edits.Diagnostics.Is_Empty then
return;
end if;
Process_References;
Process_File_Renames;
end Process_Context;
begin
for C of Self.Contexts_For_URI (Value.textDocument.uri) loop
Process_Context (C);
-- If problems were found, send an error message and do not proceed
-- with the renames.
if not Context_Edits.Diagnostics.Is_Empty then
return Response : LSP.Messages.Server_Responses.Rename_Response
(Is_Error => True)
do
declare
Error_Message : VSS.String_Vectors.Virtual_String_Vector;
begin
for Problem of Context_Edits.Diagnostics loop
Error_Message.Append
(VSS.Strings.Conversions.To_Virtual_String
(Problem.Info));
end loop;
Response.error :=
(True,
(code => LSP.Errors.InvalidRequest,
message => Error_Message.Join_Lines (VSS.Strings.LF),
data => Empty));
end;
end return;
end if;
exit when Request.Canceled;
end loop;
-- All contexts were processed, and no rename problems were found
Response.result := To_Workspace_Edit
(All_Edits, Self.Resource_Operations, Self.Versioned_Documents, Self);
return Response;
exception
when E : others =>
return Response : LSP.Messages.Server_Responses.Rename_Response
(Is_Error => True)
do
Response.error :=
(True,
(code => LSP.Errors.InternalError,
message => VSS.Strings.Conversions.To_Virtual_String
(Ada.Exceptions.Exception_Information (E)),
data => <>));
end return;
end On_Rename_Request;
--------------------------------------------
-- On_DidChangeConfiguration_Notification --
--------------------------------------------
overriding procedure On_DidChangeConfiguration_Notification
(Self : access Message_Handler;
Value : LSP.Messages.DidChangeConfigurationParams)
is
use type GNATCOLL.JSON.JSON_Value_Type;
relocateBuildTree : constant String :=
"relocateBuildTree";
rootDir : constant String :=
"rootDir";
projectFile : constant String :=
"projectFile";
scenarioVariables : constant String :=
"scenarioVariables";
defaultCharset : constant String :=
"defaultCharset";
enableDiagnostics : constant String :=
"enableDiagnostics";
enableIndexing : constant String :=
"enableIndexing";
renameInComments : constant String :=
"renameInComments";
namedNotationThreshold : constant String :=
"namedNotationThreshold";
foldComments : constant String :=
"foldComments";
displayMethodAncestryOnNavigation : constant String :=
"displayMethodAncestryOnNavigation";
followSymlinks : constant String :=
"followSymlinks";
documentationStyle : constant String :=
"documentationStyle";
useCompletionSnippets : constant String :=
"useCompletionSnippets";
logThreshold : constant String :=
"logThreshold";
Ada : constant LSP.Types.LSP_Any := Value.settings.Get ("ada");
File : VSS.Strings.Virtual_String;
Charset : Unbounded_String;
Variables : LSP.Types.LSP_Any;
Relocate : Virtual_File := No_File;
Root : Virtual_File := No_File;
-- Is client capable of dynamically registering file operations?
Dynamically_Register_File_Operations : constant Boolean :=
Self.Client.capabilities.workspace.fileOperations.Is_Set
and then Self.Client.capabilities.workspace.fileOperations.
Value.dynamicRegistration.Is_Set = True;
begin
if Ada.Kind = GNATCOLL.JSON.JSON_Object_Type then
if Ada.Has_Field (relocateBuildTree) then
Relocate := Create_From_UTF8 (Get (Get (Ada, relocateBuildTree)));
end if;
if Ada.Has_Field (rootDir) then
Root := Create_From_UTF8 (Get (Get (Ada, rootDir)));
end if;
if Ada.Has_Field (projectFile) then
File :=
VSS.Strings.Conversions.To_Virtual_String
(String'(Get (Get (Ada, projectFile))));
-- Drop uri scheme if present
if File.Starts_With ("file:") then
File := Self.URI_To_File (File);
end if;
end if;
if Ada.Has_Field (scenarioVariables) and then
Ada.Get (scenarioVariables).Kind = GNATCOLL.JSON.JSON_Object_Type
then
Variables := Ada.Get (scenarioVariables);
end if;
if Ada.Has_Field (defaultCharset) then
Charset := Ada.Get (defaultCharset);
end if;
-- It looks like the protocol does not allow clients to say whether
-- or not they want diagnostics as part of
-- InitializeParams.capabilities.textDocument. So we support
-- deactivating of diagnostics via a setting here.
if Ada.Has_Field (enableDiagnostics) then
Self.Diagnostics_Enabled := Ada.Get (enableDiagnostics);
end if;
-- Similarly to diagnostics, we support selectively activating
-- indexing in the parameters to this request.
if Ada.Has_Field (enableIndexing) then
Self.Indexing_Enabled := Ada.Get (enableIndexing);
end if;
-- Retrieve the different textDocument/rename options if specified
if Ada.Has_Field (renameInComments) then
Self.Options.Refactoring.Renaming.In_Comments :=
Ada.Get (renameInComments);
end if;
if Ada.Has_Field (foldComments) then
Self.Options.Folding.Comments := Ada.Get (foldComments);
end if;
-- Retrieve the number of parameters / components at which point
-- named notation is used for subprogram/aggregate completion
-- snippets.
if Ada.Has_Field (namedNotationThreshold) then
Self.Named_Notation_Threshold := Ada.Get (namedNotationThreshold);
end if;
if Ada.Has_Field (logThreshold) then
Self.Log_Threshold := Ada.Get (logThreshold);
end if;
-- Check the 'useCompletionSnippets' flag to see if we should use
-- snippets in completion (if the client supports it).
if not Self.Completion_Snippets_Enabled then
Self.Use_Completion_Snippets := False;
elsif Ada.Has_Field (useCompletionSnippets) then
Self.Use_Completion_Snippets := Ada.Get (useCompletionSnippets);
end if;
-- Retrieve the policy for displaying type hierarchy on navigation
-- requests.
if Ada.Has_Field (displayMethodAncestryOnNavigation) then
Self.Display_Method_Ancestry_Policy :=
LSP.Messages.AlsDisplayMethodAncestryOnNavigationPolicy'Value
(Ada.Get (displayMethodAncestryOnNavigation));
end if;
-- Retrieve the follow symlinks policy.
if Ada.Has_Field (followSymlinks) then
Self.Follow_Symlinks := Ada.Get (followSymlinks);
end if;
if Ada.Has_Field (documentationStyle) then
begin
Self.Options.Documentation.Style :=
GNATdoc.Comments.Options.Documentation_Style'Value
(Ada.Get (documentationStyle));
exception
when Constraint_Error =>
Self.Options.Documentation.Style :=
GNATdoc.Comments.Options.GNAT;
end;
end if;
end if;
if not File.Is_Empty then
-- The projectFile may be either an absolute path or a
-- relative path; if so, we're assuming it's relative
-- to Self.Root.
declare
Project_File : constant String :=
VSS.Strings.Conversions.To_UTF_8_String (File);
GPR : Virtual_File;
begin
if Is_Absolute_Path (Project_File) then
GPR := Create_From_UTF8 (Project_File);
else
GPR := Join (Self.Root, Create_From_UTF8 (Project_File));
end if;
Self.Load_Project
(GPR,
Variables,
To_String (Charset),
Valid_Project_Configured,
Relocate,
Root);
end;
end if;
Self.Ensure_Project_Loaded;
-- Register rangeFormatting provider is the client supports
-- dynamic registration for it (and we haven't done it before).
if not Self.Range_Formatting_Enabled
and then Self.Client.capabilities.textDocument.rangeFormatting.Is_Set
and then Self.Client.capabilities.textDocument.rangeFormatting.Value
.dynamicRegistration = True
then
declare
Request : LSP.Messages.Client_Requests.RegisterCapability_Request;
Registration : LSP.Messages.Registration;
Selector : LSP.Messages.DocumentSelector;
Filter : constant LSP.Messages.DocumentFilter :=
(language => (True, "ada"),
others => <>);
begin
Selector.Append (Filter);
Registration.method := "textDocument/rangeFormatting";
Registration.registerOptions :=
(LSP.Types.Text_Document_Registration_Option,
(documentSelector => Selector));
Registration.id := "rf";
Request.params.registrations.Append (Registration);
Self.Server.On_RegisterCapability_Request (Request);
Self.Range_Formatting_Enabled := True;
end;
end if;
-- Dynamically register file operations if supported by the client
if Dynamically_Register_File_Operations
and then not Self.Contexts.Each_Context.Is_Empty
then
declare
Request : LSP.Messages.Client_Requests.RegisterCapability_Request;
Registration : LSP.Messages.Registration;
Registration_Options :
constant LSP.Messages.FileOperationRegistrationOptions :=
Self.Compute_File_Operation_Registration_Options;
File_Operations_Client_Capabilities :
constant LSP.Messages.FileOperationsClientCapabilities :=
Self.Client.capabilities.workspace.fileOperations.Value;
begin
Registration.registerOptions :=
(LSP.Types.File_Operation_Registration_Option,
FileOperation => Registration_Options);
if File_Operations_Client_Capabilities.willCreate = True then
Registration.id := "Will_Create";
Registration.method := "workspace/willCreateFiles";
Request.params.registrations.Append (Registration);
end if;
if File_Operations_Client_Capabilities.didCreate = True then
Registration.id := "Did_Create";
Registration.method := "workspace/didCreateFiles";
Request.params.registrations.Append (Registration);
end if;
if File_Operations_Client_Capabilities.willRename = True then
Registration.id := "Will_Rename";
Registration.method := "workspace/willRenameFiles";
Request.params.registrations.Append (Registration);
end if;
if File_Operations_Client_Capabilities.didRename = True then
Registration.id := "Did_Rename";
Registration.method := "workspace/didRenameFiles";
Request.params.registrations.Append (Registration);
end if;
if File_Operations_Client_Capabilities.willDelete = True then
Registration.id := "Will_Delete";
Registration.method := "workspace/willDeleteFiles";
Request.params.registrations.Append (Registration);
end if;
if File_Operations_Client_Capabilities.didDelete = True then
Registration.id := "Did_Delete";
Registration.method := "workspace/didDeleteFiles";
Request.params.registrations.Append (Registration);
end if;
Self.Server.On_RegisterCapability_Request (Request);
end;
end if;
end On_DidChangeConfiguration_Notification;
-------------------------------------------
-- On_DidChangeWatchedFiles_Notification --
-------------------------------------------
overriding procedure On_DidChangeWatchedFiles_Notification
(Self : access Message_Handler;
Value : LSP.Messages.DidChangeWatchedFilesParams)
is
URI : LSP.Messages.DocumentUri;
File : GNATCOLL.VFS.Virtual_File;
procedure Process_Created_File;
-- Processes a created file
procedure Process_Deleted_File;
-- Processes a deleted file
procedure Process_Changed_File;
-- Processes a changed file
--------------------------
-- Process_Created_File --
--------------------------
procedure Process_Created_File
is
use VSS.Strings.Conversions;
Contexts : constant LSP.Ada_Context_Sets.Context_Lists.List :=
Self.Contexts_For_File (File);
function Has_Dir
(Context : LSP.Ada_Contexts.Context)
return Boolean
is (Context.List_Source_Directories.Contains (File.Dir));
-- Return True if File is in a source directory of the project held
-- by Context.
begin
-- If the file was created by the client, then the DidCreateFiles
-- notification might have been received from it. In that case,
-- Contexts wont be empty, and all we need to do is check if
-- there's an open document. If there is, it takes precedence over
-- the filesystem.
-- If Contexts is empty, then we need to check if is a new source
-- that needs to be added. For instance, a source that was moved
-- to the the project source directories.
if Contexts.Is_Empty then
for Context of Self.Contexts.Each_Context
(Has_Dir'Unrestricted_Access)
loop
Context.Include_File (File);
Context.Index_File (File);
Self.Trace.Trace
("Included " & File.Display_Base_Name
& " in context " & To_UTF_8_String (Context.Id));
end loop;
else
if Self.Get_Open_Document (URI) = null then
for Context of Contexts loop
Context.Index_File (File);
end loop;
end if;
end if;
end Process_Created_File;
---------------------------
-- Process_Deleted_Files --
---------------------------
procedure Process_Deleted_File is
begin
if Self.Get_Open_Document (URI) = null then
-- If there is no document, remove from the sources list
-- and reindex the file for each context where it is
-- relevant.
File := Self.To_File (URI);
for C of Self.Contexts_For_File (File) loop
C.Exclude_File (File);
C.Index_File (File);
end loop;
end if;
end Process_Deleted_File;
--------------------------
-- Process_Changed_File --
--------------------------
procedure Process_Changed_File is
begin
if Self.Get_Open_Document (URI) = null then
-- If there is no document, reindex the file for each
-- context where it is relevant.
File := Self.To_File (URI);
for C of Self.Contexts_For_File (File) loop
C.Index_File (File);
end loop;
end if;
end Process_Changed_File;
begin
-- Look through each change, filtering non Ada source files
for Change of Value.changes loop
URI := Change.uri;
File := Self.To_File (URI);
if Self.Is_Ada_Source (File) then
case Change.a_type is
when LSP.Messages.Created =>
Process_Created_File;
when LSP.Messages.Deleted =>
Process_Deleted_File;
when LSP.Messages.Changed =>
Process_Changed_File;
end case;
end if;
end loop;
end On_DidChangeWatchedFiles_Notification;
------------------------------------
-- Mark_Source_Files_For_Indexing --
------------------------------------
procedure Mark_Source_Files_For_Indexing (Self : access Message_Handler) is
begin
Self.Files_To_Index.Clear;
-- Mark all the project's source files
for C of Self.Contexts.Each_Context loop
for F in C.List_Files loop
Self.Files_To_Index.Include
(LSP.Ada_File_Sets.File_Sets.Element (F));
end loop;
end loop;
if Runtime_Indexing.Is_Active then
-- Mark all the predefined sources too (runtime)
for F in Self.Project_Predefined_Sources.Iterate loop
declare
File : GNATCOLL.VFS.Virtual_File renames
LSP.Ada_File_Sets.File_Sets.Element (F);
begin
for Context of Self.Contexts_For_File (File) loop
Self.Files_To_Index.Include (File);
end loop;
end;
end loop;
end if;
Self.Total_Files_Indexed := 0;
Self.Total_Files_To_Index := Positive'Max
(1, Natural (Self.Files_To_Index.Length));
end Mark_Source_Files_For_Indexing;
------------------
-- Load_Project --
------------------
procedure Load_Project
(Self : access Message_Handler;
GPR : Virtual_File;
Scenario : LSP.Types.LSP_Any;
Charset : String;
Status : Load_Project_Status;
Relocate_Build_Tree : Virtual_File := No_File;
Root_Dir : Virtual_File := No_File)
is
use GNATCOLL.Projects;
Errors : LSP.Messages.ShowMessageParams;
Error_Text : VSS.String_Vectors.Virtual_String_Vector;
procedure Create_Context_For_Non_Aggregate (P : Project_Type);
procedure Add_Variable (Name : String; Value : GNATCOLL.JSON.JSON_Value);
procedure On_Error (Text : String);
------------------
-- Add_Variable --
------------------
procedure Add_Variable
(Name : String; Value : GNATCOLL.JSON.JSON_Value)
is
use type GNATCOLL.JSON.JSON_Value_Type;
begin
if Value.Kind = GNATCOLL.JSON.JSON_String_Type then
Self.Project_Environment.Change_Environment (Name, Value.Get);
end if;
end Add_Variable;
--------------
-- On_Error --
--------------
procedure On_Error (Text : String) is
begin
Error_Text.Append (VSS.Strings.Conversions.To_Virtual_String (Text));
end On_Error;
--------------------------------------
-- Create_Context_For_Non_Aggregate --
--------------------------------------
procedure Create_Context_For_Non_Aggregate (P : Project_Type) is
C : constant Context_Access := new Context (Self.Trace);
Reader : LSP.Ada_Handlers.File_Readers.LSP_Reader_Interface (Self);
Default_Config : Libadalang.Preprocessing.File_Config;
File_Configs : Libadalang.Preprocessing.File_Config_Maps.Map;
procedure Set_Line_Mode
(Config : in out Libadalang.Preprocessing.File_Config);
-- Used to force the preprocessing line mode to Blank_Lines, which
-- is needed to preserve the number of lines after preprocessing a
-- source file, otherwise LSP requests based on SLOCs will fail.
-------------------
-- Set_Line_Mode --
-------------------
procedure Set_Line_Mode
(Config : in out Libadalang.Preprocessing.File_Config) is
begin
if Config.Enabled then
Config.Line_Mode := Libadalang.Preprocessing.Blank_Lines;
end if;
end Set_Line_Mode;
begin
-- Extract the preprocessing options from the context's project
-- and create the file reader which will preprocess the files
-- accordingly.
Libadalang.Preprocessing.Extract_Preprocessor_Data_From_Project
(Tree => Self.Project_Tree.all,
Project => P,
Default_Config => Default_Config,
File_Configs => File_Configs);
Libadalang.Preprocessing.Iterate
(Default_Config => Default_Config,
File_Configs => File_Configs,
Process => Set_Line_Mode'Access);
Reader.Preprocessing_Data :=
Libadalang.Preprocessing.Create_Preprocessor_Data
(Default_Config, File_Configs);
C.Initialize (Reader, Self.Follow_Symlinks);
C.Load_Project (Tree => Self.Project_Tree,
Root => P,
Charset => Charset);
Self.Contexts.Prepend (C);
end Create_Context_For_Non_Aggregate;
begin
-- Unload the project tree and the project environment
Self.Release_Contexts_And_Project_Info;
-- We're loading an actual project
Self.Project_Status := Status;
-- Now load the new project
Errors.a_type := LSP.Messages.Warning;
Self.Project_Environment :=
new LSP.Ada_Project_Environments.LSP_Project_Environment;
Initialize (Self.Project_Environment);
Self.Project_Environment.Set_Trusted_Mode (not Self.Follow_Symlinks);
if Relocate_Build_Tree /= No_File then
Self.Project_Environment.Set_Build_Tree_Dir
(Relocate_Build_Tree.Full_Name);
end if;
if Root_Dir /= No_File then
Self.Project_Environment.Set_Root_Dir
(Root_Dir.Full_Name);
end if;
if not Scenario.Is_Empty then
Scenario.Map_JSON_Object (Add_Variable'Access);
end if;
begin
Self.Project_Tree := new Project_Tree;
Self.Project_Tree.Load
(GPR,
Self.Project_Environment,
Report_Missing_Dirs => False,
Errors => On_Error'Unrestricted_Access);
for File of Self.Project_Environment.Predefined_Source_Files loop
if Self.Is_Ada_Source (File) then
Self.Project_Predefined_Sources.Include (File);
end if;
end loop;
if Self.Project_Tree.Root_Project.Is_Aggregate_Project then
declare
Aggregated : Project_Array_Access :=
Self.Project_Tree.Root_Project.Aggregated_Projects;
begin
for X of Aggregated.all loop
Create_Context_For_Non_Aggregate (X);
end loop;
Unchecked_Free (Aggregated);
end;
else
Create_Context_For_Non_Aggregate (Self.Project_Tree.Root_Project);
end if;
exception
when E : Invalid_Project =>
Self.Release_Contexts_And_Project_Info;
Self.Trace.Trace (E);
Errors.a_type := LSP.Messages.Error;
Errors.message.Append
(VSS.Strings.Conversions.To_Virtual_String
("Unable to load project file: " &
String (GPR.Full_Name.all) & Ada.Characters.Latin_1.LF));
-- The project was invalid: fallback on loading the implicit
-- project.
Self.Load_Implicit_Project (Invalid_Project_Configured);
end;
-- Report the errors, if any
if not Error_Text.Is_Empty then
for Line of Error_Text loop
Errors.message.Append (Line);
end loop;
Self.Server.On_Show_Message (Errors);
end if;
-- Reindex all open documents immediately after project reload, so
-- that navigation from editors is accurate.
for Document of Self.Open_Documents loop
for Context of Self.Contexts_For_URI (Document.URI) loop
Context.Index_Document (Document.all);
end loop;
Self.Publish_Diagnostics (Document_Access (Document));
end loop;
if not Self.File_Monitor.Assigned then
Self.File_Monitor :=
new LSP.Servers.FS_Watch.FS_Watch_Monitor (Self.Server);
end if;
-- We have successfully loaded a real project: monitor the filesystem
-- for any changes on the sources of the project
Self.File_Monitor.Monitor_Directories
(Self.Contexts.All_Source_Directories);
-- Reindex the files from disk in the background after a project reload
Self.Mark_Source_Files_For_Indexing;
end Load_Project;
-------------------------------
-- Get_Unique_Progress_Token --
-------------------------------
function Get_Unique_Progress_Token
(Self : access Message_Handler;
Operation : String := "") return LSP_Number_Or_String
is
Pid : constant String :=
GNATCOLL.Utils.Image (Pid_To_Integer (Current_Process_Id), 1);
begin
Self.Token_Id := Self.Token_Id + 1;
-- Generate an identifier that has little risk of collision with
-- other language servers, or other occurrences of this server.
-- (There is still a very small risk of collision with PID recyclings,
-- but the consequences are acceptable.)
return
(Is_Number => False,
String => VSS.Strings.Conversions.To_Virtual_String
("ada_ls-"
& Pid & "-" & Operation & "-"
& GNATCOLL.Utils.Image (Self.Token_Id, 1)));
end Get_Unique_Progress_Token;
-----------------
-- Index_Files --
-----------------
procedure Index_Files (Self : access Message_Handler) is
procedure Emit_Progress_Begin;
procedure Emit_Progress_Report (Files_Indexed, Total_Files : Natural);
procedure Emit_Progress_End;
-- Emit a message to inform that the indexing has begun / is in
-- progress / has finished.
Progress_Report_Sent : Time := Clock;
-------------------------
-- Emit_Progress_Begin --
-------------------------
procedure Emit_Progress_Begin is
P : LSP.Messages.Progress_Params (LSP.Messages.Progress_Begin);
Create_Progress : constant LSP.Messages.Client_Requests
.WorkDoneProgressCreate_Request :=
(params => (token => Self.Indexing_Token), others => <>);
begin
Self.Server.On_WorkDoneProgress_Create_Request
(Create_Progress);
-- FIXME: wait response before sending progress notifications.
-- Currenctly, we just send a `window/workDoneProgress/create`
-- request and immediately after this start sending notifications.
-- We could do better, send request, wait for client response and
-- start progress-report sending only after response.
P.Begin_Param.token := Self.Indexing_Token;
P.Begin_Param.value.title := "Indexing";
P.Begin_Param.value.percentage := (Is_Set => True, Value => 0);
Self.Server.On_Progress (P);
end Emit_Progress_Begin;
--------------------------
-- Emit_Progress_Report --
--------------------------
procedure Emit_Progress_Report (Files_Indexed, Total_Files : Natural) is
P : LSP.Messages.Progress_Params (LSP.Messages.Progress_Report);
function Image (N : Natural) return Wide_Wide_String;
function Image (N : Natural) return Wide_Wide_String is
S : constant Wide_Wide_String := Natural'Wide_Wide_Image (N);
begin
return S (S'First + 1 .. S'Last);
end Image;
Current : constant Time := Clock;
begin
if Current - Progress_Report_Sent < 0.5 then
-- Send only 2 notifications per second
return;
end if;
Progress_Report_Sent := Current;
P.Report_Param.token := Self.Indexing_Token;
P.Report_Param.value.percentage :=
(Is_Set => True, Value => LSP_Number
((Files_Indexed * 100) / Total_Files));
P.Report_Param.value.message :=
(Is_Set => True,
Value => VSS.Strings.To_Virtual_String
(Image (Files_Indexed) & "/" & Image (Total_Files) & " files"));
Self.Server.On_Progress (P);
end Emit_Progress_Report;
-----------------------
-- Emit_Progress_End --
-----------------------
procedure Emit_Progress_End is
P : LSP.Messages.Progress_Params (LSP.Messages.Progress_End);
begin
P.End_Param.token := Self.Indexing_Token;
Self.Server.On_Progress (P);
end Emit_Progress_End;
begin
-- Prevent work if the indexing has been explicitly disabled or
-- if we have other messages to process.
if not Self.Indexing_Enabled or Self.Server.Has_Pending_Work then
return;
end if;
if Self.Indexing_Token = Empty_Token then
Self.Indexing_Token := Self.Get_Unique_Progress_Token ("indexing");
Emit_Progress_Begin;
end if;
while not Self.Files_To_Index.Is_Empty loop
declare
Cursor : File_Sets.Cursor := Self.Files_To_Index.First;
File : constant GNATCOLL.VFS.Virtual_File :=
File_Sets.Element (Cursor);
begin
Self.Files_To_Index.Delete (Cursor);
Self.Total_Files_Indexed := Self.Total_Files_Indexed + 1;
if not Self.Open_Documents.Contains (File) then
Emit_Progress_Report
(Self.Total_Files_Indexed, Self.Total_Files_To_Index);
for Context of Self.Contexts_For_File (File) loop
-- Set Reparse to False to avoid issues with LAL envs
-- for now (see T226-048 for more info).
Context.Index_File (File, Reparse => False);
end loop;
-- Check whether another request is pending. If so, pause
-- the indexing; it will be resumed later as part of
-- After_Request.
if not Self.Files_To_Index.Is_Empty
and then Self.Server.Has_Pending_Work
then
return;
end if;
end if;
end;
end loop;
Emit_Progress_End;
Self.Indexing_Token := Empty_Token;
end Index_Files;
------------------------------------------
-- On_Workspace_Execute_Command_Request --
------------------------------------------
overriding function On_Workspace_Execute_Command_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Workspace_Execute_Command_Request)
return LSP.Messages.Server_Responses.ExecuteCommand_Response
is
Error : LSP.Errors.Optional_ResponseError;
Params : LSP.Messages.ExecuteCommandParams renames
Request.params;
Response : LSP.Messages.Server_Responses.ExecuteCommand_Response
(Is_Error => True);
begin
if Params.Is_Unknown or else Params.Custom.Is_Null then
Response.error :=
(True,
(code => LSP.Errors.InternalError,
message => "Not implemented",
data => <>));
return Response;
end if;
Params.Custom.Unchecked_Get.Execute
(Handler => Self,
Client => Self.Server,
Error => Error);
if Error.Is_Set then
Response.error := Error;
return Response;
end if;
-- No particular response in case of success.
return (Is_Error => False,
error => (Is_Set => False),
others => <>);
end On_Workspace_Execute_Command_Request;
--------------------------------------------
-- On_Workspace_Will_Create_Files_Request --
--------------------------------------------
overriding function On_Workspace_Will_Create_Files_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.
Workspace_Will_Create_Files_Request)
return LSP.Messages.Server_Responses.WillCreateFiles_Response
is
Response : LSP.Messages.Server_Responses.WillCreateFiles_Response
(Is_Error => False);
begin
Self.Trace.Trace
("Message_Handler On_Workspace_Will_Create_Files_Request");
return Response;
end On_Workspace_Will_Create_Files_Request;
------------------------------------
-- On_DidCreateFiles_Notification --
------------------------------------
overriding procedure On_DidCreateFiles_Notification
(Self : access Message_Handler;
Value : LSP.Messages.CreateFilesParams) is
begin
Self.Trace.Trace
("Message_Handler On_DidCreateFiles_Notification");
-- New sources were created on this project, so recompute its view
Self.Project_Tree.Recompute_View;
-- For each created file of Value.files:
-- - find the contexts that contains its directory
-- - add it to those contexts
-- - index it on those contexts
for File of Value.files loop
declare
use VSS.Strings.Conversions;
Created_File : constant Virtual_File :=
Self.To_File (To_LSP_URI (File.uri));
function Has_Dir
(Context : LSP.Ada_Contexts.Context)
return Boolean
is (Context.List_Source_Directories.Contains
(Created_File.Dir));
-- Return True if Old_File is a source of the project held by
-- Context.
begin
if Self.Is_Ada_Source (Created_File) then
for Context of Self.Contexts.Each_Context
(Has_Dir'Unrestricted_Access)
loop
Context.Include_File (Created_File);
Context.Index_File (Created_File);
Self.Trace.Trace
("Included " & Created_File.Display_Base_Name
& " in context " & To_UTF_8_String (Context.Id));
end loop;
end if;
end;
end loop;
Self.Trace.Trace
("Finished Message_Handler On_DidCreateFiles_Notification");
end On_DidCreateFiles_Notification;
--------------------------------------------
-- On_Workspace_Will_Rename_Files_Request --
--------------------------------------------
overriding function On_Workspace_Will_Rename_Files_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.
Workspace_Will_Rename_Files_Request)
return LSP.Messages.Server_Responses.WillRenameFiles_Response
is
Response : LSP.Messages.Server_Responses.WillRenameFiles_Response
(Is_Error => False);
begin
Self.Trace.Trace
("Message_Handler On_Workspace_Will_Rename_Files_Request");
return Response;
end On_Workspace_Will_Rename_Files_Request;
------------------------------------
-- On_DidRenameFiles_Notification --
------------------------------------
overriding procedure On_DidRenameFiles_Notification
(Self : access Message_Handler;
Value : LSP.Messages.RenameFilesParams)
is
use LSP.Ada_Context_Sets;
package URI_Contexts_Maps is new
Ada.Containers.Indefinite_Hashed_Maps
(Key_Type => LSP_URI,
Element_Type => Context_Lists.List,
Hash => Hash,
Equivalent_Keys => Equal,
"=" => Context_Lists."=");
subtype URI_Contexts_Map is URI_Contexts_Maps.Map;
URIs_Contexts : URI_Contexts_Map;
begin
Self.Trace.Trace
("Message_Handler On_DidRenameFiles_Notification");
-- Some project sources were renamed, so recompute its view
Self.Project_Tree.Recompute_View;
-- For each oldUri of Value.files:
-- - map it to a list of context that contains it
-- - remove it from those contexts
-- - re-index it on those contexts so that an empty unit is reparsed
for File_Rename of Value.files loop
declare
use VSS.Strings.Conversions;
Old_File : constant Virtual_File :=
Self.To_File (To_LSP_URI (File_Rename.oldUri));
function Has_File
(Context : LSP.Ada_Contexts.Context)
return Boolean
is (Context.Is_Part_Of_Project (Old_File));
-- Return True if Old_File is a source of the project held by
-- Context.
URI_Contexts : Context_Lists.List;
begin
if Self.Is_Ada_Source (Old_File) then
for Context of Self.Contexts.Each_Context
(Has_File'Unrestricted_Access)
loop
URI_Contexts.Append (Context);
Context.Exclude_File (Old_File);
Context.Index_File (Old_File);
Self.Trace.Trace
("Excluded " & Old_File.Display_Full_Name
& " from context " & To_UTF_8_String (Context.Id));
end loop;
URIs_Contexts.Insert
(To_LSP_URI (File_Rename.oldUri), URI_Contexts);
end if;
end;
end loop;
-- For each (oldUri, newUri) tuple:
-- - add newUri to all contexts that contained oldUri
-- - index the newUri (using the appriate method depending if
-- (there's an open document of not)
for File_Rename of Value.files loop
declare
use VSS.Strings.Conversions;
New_File : constant GNATCOLL.VFS.Virtual_File :=
Self.To_File (LSP.Types.To_LSP_URI (File_Rename.newUri));
Document : constant LSP.Ada_Documents.Document_Access :=
Get_Open_Document
(Self,
LSP.Messages.DocumentUri
(LSP.Types.To_LSP_URI (File_Rename.newUri)));
Is_Document_Open : constant Boolean := Document /= null;
begin
if Self.Is_Ada_Source (New_File) then
for Context of
URIs_Contexts.Constant_Reference
(To_LSP_URI (File_Rename.oldUri))
loop
Context.Include_File (New_File);
if Is_Document_Open then
Context.Index_Document (Document.all);
else
Context.Index_File (New_File);
end if;
Self.Trace.Trace
("Included " & New_File.Display_Base_Name & " in context "
& To_UTF_8_String (Context.Id));
end loop;
end if;
end;
end loop;
Self.Trace.Trace
("Finished Message_Handler On_DidRenameFiles_Notification");
end On_DidRenameFiles_Notification;
--------------------------------------------
-- On_Workspace_Will_Delete_Files_Request --
--------------------------------------------
overriding function On_Workspace_Will_Delete_Files_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.
Workspace_Will_Delete_Files_Request)
return LSP.Messages.Server_Responses.WillDeleteFiles_Response
is
Response : LSP.Messages.Server_Responses.WillDeleteFiles_Response
(Is_Error => False);
begin
Self.Trace.Trace
("Message_Handler On_Workspace_Will_Delete_Files_Request");
return Response;
end On_Workspace_Will_Delete_Files_Request;
------------------------------------
-- On_DidDeleteFiles_Notification --
------------------------------------
overriding procedure On_DidDeleteFiles_Notification
(Self : access Message_Handler;
Value : LSP.Messages.DeleteFilesParams) is
begin
Self.Trace.Trace
("Message_Handler On_DidDeleteFiles_Notification");
-- Some project sources were deleted, so recompute its view
Self.Project_Tree.Recompute_View;
-- For each delete file of Value.files:
-- - find the contexts that contains it
-- - remove it from those contexts
-- - re-index it on those contexts so that an empty unit is reparsed
for File of Value.files loop
declare
Deleted_File : constant Virtual_File :=
Self.To_File (To_LSP_URI (File.uri));
function Has_File
(Context : LSP.Ada_Contexts.Context)
return Boolean
is (Context.Is_Part_Of_Project (Deleted_File));
-- Return True if Old_File is a source of the project held by
-- Context.
begin
if Self.Is_Ada_Source (Deleted_File) then
for Context of Self.Contexts.Each_Context
(Has_File'Unrestricted_Access)
loop
Context.Exclude_File (Deleted_File);
Context.Index_File (Deleted_File);
Self.Trace.Trace
("Excluded " & Deleted_File.Display_Base_Name
& " from context "
& VSS.Strings.Conversions.To_UTF_8_String (Context.Id));
end loop;
end if;
end;
end loop;
Self.Trace.Trace
("Finished Message_Handler On_DidDeleteFiles_Notification");
end On_DidDeleteFiles_Notification;
----------------------------------
-- On_Workspace_Symbols_Request --
----------------------------------
overriding function On_Workspace_Symbols_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Workspace_Symbols_Request)
return LSP.Messages.Server_Responses.Symbol_Response
is
use type LSP.Messages.Search_Kind;
use type VSS.Strings.Character_Count;
use type Ada.Containers.Count_Type;
procedure On_Inaccessible_Name
(File : GNATCOLL.VFS.Virtual_File;
Name : Libadalang.Analysis.Defining_Name;
Stop : in out Boolean);
Names : LSP.Ada_Completions.Completion_Maps.Map;
package Canceled is new LSP.Generic_Cancel_Check (Request'Access, 127);
procedure Write_Symbols is
new LSP.Ada_Completions.Generic_Write_Symbols
(Canceled.Has_Been_Canceled);
--------------------------
-- On_Inaccessible_Name --
--------------------------
procedure On_Inaccessible_Name
(File : GNATCOLL.VFS.Virtual_File;
Name : Libadalang.Analysis.Defining_Name;
Stop : in out Boolean) is
begin
-- Skip all names in open documents, because they could have
-- stale references. Then skip already provided results.
if not Self.Open_Documents.Contains (File)
and then not Names.Contains (Name)
then
Names.Insert
(Name,
(Is_Dot_Call => False,
Is_Visible => False,
Use_Snippets => False,
Pos => <>,
Weight => <>));
end if;
Stop := Canceled.Has_Been_Canceled;
end On_Inaccessible_Name;
Pattern : constant Search_Pattern'Class := Build
(Pattern => Request.params.query,
Case_Sensitive => Request.params.case_sensitive = LSP.Types.True,
Whole_Word => Request.params.whole_word = LSP.Types.True,
Negate => Request.params.negate = LSP.Types.True,
Kind =>
(if Request.params.kind.Is_Set
then Request.params.kind.Value
else LSP.Messages.Start_Word_Text));
Response : LSP.Messages.Server_Responses.Symbol_Response
(Is_Error => False);
Partial_Response_Sended : Boolean := False;
-- Send_Partial_Response --
procedure Send_Partial_Response;
procedure Send_Partial_Response
is
P : LSP.Messages.Progress_SymbolInformation_Vector;
V : LSP.Messages.Symbol_Vector;
begin
if Canceled.Has_Been_Canceled then
return;
end if;
Write_Symbols (Names, V);
Names.Clear;
P.token := Request.params.partialResultToken.Value;
P.value := V.Vector;
Self.Server.On_Progress_SymbolInformation_Vector (P);
Partial_Response_Sended := True;
end Send_Partial_Response;
begin
if Pattern.Get_Kind /= LSP.Messages.Start_Word_Text
and then Pattern.Get_Canonical_Pattern.Character_Length < 2
then
-- Do not process too small pattern because
-- this produces a huge response that is useless
-- and costs a while.
return Response;
end if;
for Context of Self.Contexts.Each_Context loop
Context.Get_Any_Symbol
(Pattern => Pattern,
Only_Public => False,
Callback => On_Inaccessible_Name'Access);
if Canceled.Has_Been_Canceled then
return Response;
elsif Request.params.partialResultToken.Is_Set
and then Names.Length > 100
then
Send_Partial_Response;
end if;
end loop;
for Doc of Self.Open_Documents loop
declare
Context : constant Context_Access :=
Self.Contexts.Get_Best_Context (Doc.URI);
begin
Doc.Get_Any_Symbol
(Context.all,
Pattern,
Ada.Containers.Count_Type'Last,
False,
Canceled.Has_Been_Canceled'Access,
Names);
end;
if Canceled.Has_Been_Canceled then
return Response;
elsif Request.params.partialResultToken.Is_Set
and then Names.Length > 100
then
Send_Partial_Response;
end if;
end loop;
if Partial_Response_Sended then
Send_Partial_Response;
else
Write_Symbols (Names, Response.result);
end if;
return Response;
end On_Workspace_Symbols_Request;
---------------------------
-- On_Completion_Request --
---------------------------
overriding function On_Completion_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Completion_Request)
return LSP.Messages.Server_Responses.Completion_Response
is
-- We're completing only based on one context, ie one project
-- tree: this seems reasonable. One further refinement could
-- be to return only results that are available for all
-- project contexts.
Value : LSP.Messages.TextDocumentPositionParams renames
Request.params;
Context : constant Context_Access :=
Self.Contexts.Get_Best_Context (Value.textDocument.uri);
Document : constant LSP.Ada_Documents.Document_Access :=
Get_Open_Document (Self, Value.textDocument.uri);
Names : LSP.Ada_Completions.Completion_Maps.Map;
-- If lazy computation for the 'detail' and 'documentation' fields is
-- supported by the client, set the Compute_Doc_And_Details flag to
-- False.
Compute_Doc_And_Details : constant Boolean :=
not
(Self.Completion_Resolve_Properties.Contains
(VSS.Strings.Conversions.To_Virtual_String ("detail"))
and then
Self.Completion_Resolve_Properties.Contains
(VSS.Strings.Conversions.To_Virtual_String ("documentation")));
P1 : aliased LSP.Ada_Completions.Aspects.Aspect_Completion_Provider;
P2 : aliased LSP.Ada_Completions.Pragmas.Pragma_Completion_Provider;
P3 : aliased LSP.Ada_Completions.Keywords.Keyword_Completion_Provider;
P4 : aliased
LSP.Ada_Completions.Attributes.Attributes_Completion_Provider;
P5 : aliased LSP.Ada_Completions.Names.Name_Completion_Provider
(Self.Use_Completion_Snippets);
P6 : aliased LSP.Ada_Handlers.Invisibles.Invisible_Completion_Provider
(Self, Context);
P7 : aliased
LSP.Ada_Completions.Parameters.Parameter_Completion_Provider
(Context => Context,
Document => Document,
Compute_Doc_And_Details => Compute_Doc_And_Details,
Named_Notation_Threshold => Self.Named_Notation_Threshold);
P8 : aliased LSP.Ada_Completions.End_Names.End_Name_Completion_Provider;
Providers : constant LSP.Ada_Completions.Completion_Provider_List :=
[P1'Unchecked_Access,
P2'Unchecked_Access,
P3'Unchecked_Access,
P4'Unchecked_Access,
P5'Unchecked_Access,
P6'Unchecked_Access,
P7'Unchecked_Access,
P8'Unchecked_Access];
Response : LSP.Messages.Server_Responses.Completion_Response
(Is_Error => False);
Sloc : Langkit_Support.Slocs.Source_Location;
Token : Libadalang.Common.Token_Reference;
Node : Libadalang.Analysis.Ada_Node;
begin
Document.Get_Completion_Node
(Context => Context.all,
Position => Value.position,
Sloc => Sloc,
Token => Token,
Node => Node);
Document.Get_Completions_At
(Context => Context.all,
Providers => Providers,
Sloc => Sloc,
Token => Token,
Node => Node,
Names => Names,
Result => Response.result);
LSP.Ada_Completions.Write_Completions
(Context => Context.all,
Document => Document.all,
Sloc => Sloc,
Node => Node,
Names => Names,
Named_Notation_Threshold => Self.Named_Notation_Threshold,
Compute_Doc_And_Details => Compute_Doc_And_Details,
Result => Response.result.items);
return Response;
end On_Completion_Request;
--------------------------------------
-- On_CompletionItemResolve_Request --
--------------------------------------
overriding function On_CompletionItemResolve_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.CompletionItemResolve_Request)
return LSP.Messages.Server_Responses.CompletionItemResolve_Response
is
Item : LSP.Messages.CompletionItem :=
Request.params;
Response : LSP.Messages.Server_Responses.CompletionItemResolve_Response
(Is_Error => False);
C : Context_Access;
Node : Libadalang.Analysis.Ada_Node;
begin
-- Return immediately if we don't have data that allows us to compute
-- additional information for the given item.
-- This is the case when all the completion item's fields have already
-- been computed.
if not Item.data.Is_Set then
Response.result := Item;
return Response;
end if;
C := Self.Contexts.Get_Best_Context (Item.data.Value.uri);
Node := Get_Node_At
(Self => C.all,
Document => null,
Project_Only => False,
Position => LSP.Messages.TextDocumentPositionParams'
(textDocument => (uri => Item.data.Value.uri),
position => Item.data.Value.span.first));
-- Retrieve the Basic_Decl from the completion item's SLOC
while not Node.Is_Null
and then Node.Kind not in Libadalang.Common.Ada_Basic_Decl
loop
Node := Node.Parent;
end loop;
-- Compute the completion item's details
if not Node.Is_Null then
declare
BD : constant Libadalang.Analysis.Basic_Decl :=
Node.As_Basic_Decl;
begin
Item.detail := (True, Compute_Completion_Detail (BD));
-- Property_Errors can occur when calling
-- Get_Documentation on unsupported docstrings, so
-- add an exception handler to catch them and recover.
Item.documentation :=
(Is_Set => True,
Value => LSP.Messages.String_Or_MarkupContent'
(Is_String => True,
String => LSP.Lal_Utils.Compute_Completion_Doc (BD)));
exception
when E : Libadalang.Common.Property_Error =>
LSP.Common.Log (C.Trace, E);
Item.documentation := (others => <>);
end;
Response.result := Item;
end if;
return Response;
end On_CompletionItemResolve_Request;
---------------------------
-- On_Formatting_Request --
---------------------------
overriding function On_Formatting_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Formatting_Request)
return LSP.Messages.Server_Responses.Formatting_Response
is
Context : constant Context_Access :=
Self.Contexts.Get_Best_Context (Request.params.textDocument.uri);
Document : constant LSP.Ada_Documents.Document_Access :=
Get_Open_Document (Self, Request.params.textDocument.uri);
begin
if Document.Has_Diagnostics (Context.all) then
return Response : LSP.Messages.Server_Responses.Formatting_Response
(Is_Error => True)
do
Response.error :=
(True,
(code => LSP.Errors.InternalError,
message => "Incorrect code can't be formatted",
data => <>));
end return;
end if;
declare
use LSP.Messages;
Response : constant Server_Responses.Formatting_Response :=
Format
(Self => Context.all,
Document => Document,
Span => LSP.Messages.Empty_Span,
Options => Request.params.options,
Handler => Self);
begin
return Response;
end;
end On_Formatting_Request;
---------------------------------------
-- On_Prepare_Call_Hierarchy_Request --
---------------------------------------
overriding function On_Prepare_Call_Hierarchy_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Prepare_Call_Hierarchy_Request)
return LSP.Messages.Server_Responses.PrepareCallHierarchy_Response
is
Value : LSP.Messages.CallHierarchyPrepareParams renames
Request.params;
Response : LSP.Messages.Server_Responses.PrepareCallHierarchy_Response
(Is_Error => False);
Imprecise : Boolean := False;
C : constant Context_Access :=
Self.Contexts.Get_Best_Context (Value.textDocument.uri);
-- For the PrepareCallHierarchy request, we're only interested in the
-- "best" response value, not in the list of values for all contexts
Node : constant Libadalang.Analysis.Name :=
Laltools.Common.Get_Node_As_Name
(C.Get_Node_At
(Get_Open_Document (Self, Value.textDocument.uri), Value));
Name : constant Libadalang.Analysis.Defining_Name :=
Laltools.Common.Resolve_Name
(Node,
Self.Trace,
Imprecise);
Decl : Libadalang.Analysis.Basic_Decl;
Next_Part : Libadalang.Analysis.Basic_Decl;
begin
if Name.Is_Null then
return Response;
end if;
Decl := Name.P_Basic_Decl;
if Decl.Is_Null or else not Decl.P_Is_Subprogram then
return Response;
end if;
Next_Part :=
Laltools.Common.Find_Next_Part_For_Decl (Decl, Self.Trace);
if Next_Part.Is_Null then
Next_Part := Decl;
end if;
Response.result.Append
(To_Call_Hierarchy_Item (Next_Part.P_Defining_Name));
if Imprecise then
Self.Show_Imprecise_Reference_Warning ("prepareCallHierarchy");
end if;
return Response;
end On_Prepare_Call_Hierarchy_Request;
-------------------------------
-- On_Prepare_Rename_Request --
-------------------------------
overriding function On_Prepare_Rename_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Prepare_Rename_Request)
return LSP.Messages.Server_Responses.Prepare_Rename_Response
is
Value : LSP.Messages.TextDocumentPositionParams renames
Request.params;
Response : LSP.Messages.Server_Responses.Prepare_Rename_Response
(Is_Error => False);
Document : constant LSP.Ada_Documents.Document_Access :=
Get_Open_Document (Self, Value.textDocument.uri);
Context : constant Context_Access :=
Self.Contexts.Get_Best_Context (Value.textDocument.uri);
-- For the prepareRename request, we're only interested in the "best"
-- context to check that we are able to rename the name.
Name_Node : constant Libadalang.Analysis.Name :=
Laltools.Common.Get_Node_As_Name
(Context.Get_Node_At (Document, Value));
Imprecise : Boolean := False;
Defining_Name : constant Libadalang.Analysis.Defining_Name :=
Laltools.Common.Resolve_Name (Name_Node, Self.Trace, Imprecise);
begin
if not Name_Node.Is_Null
and then not Defining_Name.Is_Null
and then not Imprecise
then
-- Success only if the node is a name and can be resolved precisely
Response.result :=
(Is_Set => True,
Value => LSP.Lal_Utils.To_Span (Name_Node.Sloc_Range));
end if;
return Response;
end On_Prepare_Rename_Request;
-------------------------------
-- On_Incoming_Calls_Request --
-------------------------------
overriding function On_Incoming_Calls_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Incoming_Calls_Request)
return LSP.Messages.Server_Responses.IncomingCalls_Response
is
use Libadalang.Analysis;
procedure Process_Context (C : Context_Access);
-- Process the subprogram found in one context and append corresponding
-- calls to Response.results.
Item : LSP.Messages.CallHierarchyItem renames
Request.params.item;
Response : LSP.Messages.Server_Responses.IncomingCalls_Response
(Is_Error => False);
Imprecise : Boolean := False;
Position : constant LSP.Messages.TextDocumentPositionParams :=
(textDocument => (uri => Item.uri),
position => Item.selectionRange.first);
Filter : File_Span_Sets.Set;
procedure Add_Incoming_Call
(Filter : in out File_Span_Sets.Set;
Call : LSP.Messages.CallHierarchyIncomingCall);
-- Add an incoming call in results. Use Filter to prevent having
-- duplicates
-----------------------
-- Add_Incoming_Call --
-----------------------
procedure Add_Incoming_Call
(Filter : in out File_Span_Sets.Set;
Call : LSP.Messages.CallHierarchyIncomingCall)
is
Span : constant File_Span :=
(Self.To_File (Call.from.uri), Call.from.span);
begin
if not Filter.Contains (Span) then
Response.result.Append (Call);
Filter.Insert (Span);
end if;
end Add_Incoming_Call;
---------------------
-- Process_Context --
---------------------
procedure Process_Context (C : Context_Access) is
Definition : Defining_Name;
begin
Self.Imprecise_Resolve_Name (C, Position, Definition);
-- Attempt to resolve the name, return no results if we can't or if
-- the name does not resolve to a callable object, like a subprogram
-- or an entry.
if Definition = No_Defining_Name
or else not Definition.P_Basic_Decl.P_Is_Subprogram
or else Request.Canceled
then
return;
end if;
declare
use Laltools.Common;
This_Imprecise : Boolean;
Incoming_Calls : constant References_By_Subprogram.Map :=
LSP.Lal_Utils.Find_Incoming_Calls
(C.all, Definition, This_Imprecise);
C : References_By_Subprogram.Cursor :=
Incoming_Calls.First;
begin
Imprecise := Imprecise or This_Imprecise;
-- Iterate through all the results, converting them to protocol
-- objects.
while References_By_Subprogram.Has_Element (C) loop
declare
Node : constant Defining_Name :=
References_By_Subprogram.Key (C);
Refs : constant References_Sets.Set :=
References_By_Subprogram.Element (C);
New_Call : LSP.Messages.CallHierarchyIncomingCall;
begin
To_Call_Hierarchy_Result
(Node => Node,
Refs => Refs,
Item => New_Call.from,
Spans => New_Call.fromRanges,
Kinds => New_Call.kinds);
Add_Incoming_Call (Filter, New_Call);
References_By_Subprogram.Next (C);
end;
end loop;
end;
end Process_Context;
begin
-- Find the references in all contexts
for C of Self.Contexts_For_URI (Item.uri) loop
Process_Context (C);
exit when Request.Canceled;
end loop;
if Imprecise then
Self.Show_Imprecise_Reference_Warning ("incomingCalls");
end if;
return Response;
end On_Incoming_Calls_Request;
-------------------------------
-- On_Outgoing_Calls_Request --
-------------------------------
overriding function On_Outgoing_Calls_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Outgoing_Calls_Request)
return LSP.Messages.Server_Responses.OutgoingCalls_Response
is
use Libadalang.Analysis;
Item : LSP.Messages.CallHierarchyItem renames
Request.params.item;
Response : LSP.Messages.Server_Responses.OutgoingCalls_Response
(Is_Error => False);
Imprecise : Boolean := False;
Position : constant LSP.Messages.TextDocumentPositionParams :=
(textDocument => (uri => Item.uri),
position => Item.selectionRange.first);
Filter : File_Span_Sets.Set;
procedure Add_Outgoing_Call
(Filter : in out File_Span_Sets.Set;
Call : LSP.Messages.CallHierarchyOutgoingCall);
-- Add a subprogram in results. Use Filter to prevent having duplicates
procedure Process_Context (C : Context_Access);
-- Process the calls found in one context and append
-- them to Response.results.
-----------------------
-- Add_Outgoing_Call --
-----------------------
procedure Add_Outgoing_Call
(Filter : in out File_Span_Sets.Set;
Call : LSP.Messages.CallHierarchyOutgoingCall)
is
Span : constant File_Span :=
(Self.To_File (Call.to.uri), Call.to.span);
begin
if not Filter.Contains (Span) then
Response.result.Append (Call);
Filter.Insert (Span);
end if;
end Add_Outgoing_Call;
---------------------
-- Process_Context --
---------------------
procedure Process_Context (C : Context_Access) is
Definition : Defining_Name;
begin
Self.Imprecise_Resolve_Name (C, Position, Definition);
-- Attempt to resolve the name, return no results if we can't or if
-- the name does not resolve to a callable object, like a subprogram
-- or an entry.
if Definition = No_Defining_Name
or else not Definition.P_Basic_Decl.P_Is_Subprogram
or else Request.Canceled
then
return;
end if;
declare
use Laltools.Common;
This_Imprecise : Boolean;
Outgoing_Calls : constant References_By_Subprogram.Map :=
LSP.Lal_Utils.Find_Outgoing_Calls
(C.all, Definition, This_Imprecise);
C : References_By_Subprogram.Cursor :=
Outgoing_Calls.First;
begin
Imprecise := Imprecise or This_Imprecise;
-- Iterate through all the results, converting them to protocol
-- objects.
while References_By_Subprogram.Has_Element (C) loop
declare
Node : constant Defining_Name :=
References_By_Subprogram.Key (C);
Refs : constant References_Sets.Set :=
References_By_Subprogram.Element (C);
New_Call : LSP.Messages.CallHierarchyOutgoingCall;
begin
To_Call_Hierarchy_Result
(Node => Node,
Refs => Refs,
Item => New_Call.to,
Spans => New_Call.fromRanges,
Kinds => New_Call.kinds);
Add_Outgoing_Call (Filter, New_Call);
References_By_Subprogram.Next (C);
end;
end loop;
end;
end Process_Context;
begin
-- Find the references in all contexts
for C of Self.Contexts_For_URI (Item.uri) loop
Process_Context (C);
exit when Request.Canceled;
end loop;
if Imprecise then
Self.Show_Imprecise_Reference_Warning ("outgoingCalls");
end if;
return Response;
end On_Outgoing_Calls_Request;
---------------------------------
-- On_Range_Formatting_Request --
---------------------------------
overriding function On_Range_Formatting_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.Range_Formatting_Request)
return LSP.Messages.Server_Responses.Range_Formatting_Response
is
Context : constant Context_Access :=
Self.Contexts.Get_Best_Context (Request.params.textDocument.uri);
Document : constant LSP.Ada_Documents.Document_Access :=
Get_Open_Document (Self, Request.params.textDocument.uri);
begin
if Document.Has_Diagnostics (Context.all) then
return Response : LSP.Messages.Server_Responses.
Range_Formatting_Response (Is_Error => True)
do
Response.error :=
(True,
(code => LSP.Errors.InternalError,
message => "Syntactically incorrect code can't be formatted",
data => <>));
end return;
end if;
declare
use LSP.Messages;
Result : constant Server_Responses.Formatting_Response :=
(if Partial_GNATpp.Is_Active then
Range_Format
(Self => Context.all,
Document => Document,
Span => Request.params.span,
Options => Request.params.options)
else
Format
(Self => Context.all,
Document => Document,
Span => Request.params.span,
Options => Request.params.options,
Handler => Self));
Response : Server_Responses.Range_Formatting_Response
(Is_Error => Result.Is_Error);
begin
if not Result.Is_Error then
Response.result := Result.result;
else
Response.error := Result.error;
end if;
return Response;
end;
end On_Range_Formatting_Request;
------------------
-- Handle_Error --
------------------
overriding procedure Handle_Error
(Self : access Message_Handler) is
begin
-- Reload the contexts in case of unexpected errors.
Self.Contexts.Reload_All_Contexts;
end Handle_Error;
function Hash (Value : File_Span) return Ada.Containers.Hash_Type is
use type Ada.Containers.Hash_Type;
Prime : constant := 271;
Name : constant Ada.Containers.Hash_Type := Value.File.Full_Name_Hash;
From : constant Ada.Containers.Hash_Type :=
Prime * Ada.Containers.Hash_Type'Mod (Value.Span.first.line)
+ Ada.Containers.Hash_Type'Mod (Value.Span.first.character);
To : constant Ada.Containers.Hash_Type :=
Prime * Ada.Containers.Hash_Type'Mod (Value.Span.last.line)
+ Ada.Containers.Hash_Type'Mod (Value.Span.last.character);
begin
return Name + From + To;
end Hash;
-------------------------
-- Publish_Diagnostics --
-------------------------
procedure Publish_Diagnostics
(Self : access Message_Handler'Class;
Document : not null LSP.Ada_Documents.Document_Access)
is
Ok : Boolean;
Diag : LSP.Messages.PublishDiagnosticsParams;
begin
if Self.Diagnostics_Enabled then
Document.Get_Errors
(Self.Contexts.Get_Best_Context (Document.URI).all,
Ok,
Diag.diagnostics);
if Ok then
Diag.uri := Document.URI;
Self.Server.On_Publish_Diagnostics (Diag);
end if;
end if;
end Publish_Diagnostics;
----------
-- Free --
----------
procedure Free (Self : in out Internal_Document_Access) is
procedure Unchecked_Free is new Ada.Unchecked_Deallocation
(LSP.Ada_Documents.Document, Internal_Document_Access);
begin
Self.Cleanup;
Unchecked_Free (Self);
end Free;
------------------
-- Show_Message --
------------------
procedure Show_Message
(Self : access Message_Handler;
Text : VSS.Strings.Virtual_String;
Mode : LSP.Messages.MessageType := LSP.Messages.Error) is
begin
Self.Server.On_Show_Message ((Mode, Text));
end Show_Message;
--------------------------------------
-- Show_Imprecise_Reference_Warning --
--------------------------------------
procedure Show_Imprecise_Reference_Warning
(Self : access Message_Handler;
Operation : String) is
begin
if Notifications_For_Imprecise.Is_Active then
Self.Server.On_Show_Message
((LSP.Messages.Warning,
VSS.Strings.Conversions.To_Virtual_String
("The result of '" & Operation & "' is approximate.")));
end if;
end Show_Imprecise_Reference_Warning;
-----------------
-- Before_Work --
-----------------
overriding procedure Before_Work
(Self : access Message_Handler;
Message : LSP.Messages.Message'Class) is null;
----------------
-- After_Work --
----------------
overriding procedure After_Work
(Self : access Message_Handler;
Message : LSP.Messages.Message'Class)
is
pragma Unreferenced (Message);
begin
-- We have finished processing a request or notification:
-- if it happens that indexing is required, do it now.
if not Self.Files_To_Index.Is_Empty then
Self.Index_Files;
end if;
end After_Work;
---------------
-- From_File --
---------------
function From_File
(Self : Message_Handler'Class;
File : Virtual_File) return LSP.Messages.DocumentUri is
(LSP.Types.To_LSP_URI
(VSS.Strings.Conversions.To_Virtual_String
(URIs.Conversions.From_File (File.Display_Full_Name))));
-------------
-- To_File --
-------------
function To_File
(Self : Message_Handler'Class;
URI : LSP.Types.LSP_URI) return GNATCOLL.VFS.Virtual_File
is
To : constant URIs.URI_String := LSP.Types.To_UTF_8_String (URI);
Result : constant String := URIs.Conversions.To_File
(To, Normalize => Self.Follow_Symlinks);
begin
return GNATCOLL.VFS.Create_From_UTF8 (Result);
end To_File;
-----------------
-- URI_To_File --
-----------------
function URI_To_File
(Self : Message_Handler'Class;
URI : VSS.Strings.Virtual_String) return VSS.Strings.Virtual_String
is
To : constant URIs.URI_String :=
VSS.Strings.Conversions.To_UTF_8_String (URI);
Result : constant String := URIs.Conversions.To_File
(To, Normalize => Self.Follow_Symlinks);
begin
return VSS.Strings.Conversions.To_Virtual_String (Result);
end URI_To_File;
---------------------------------
-- On_ALS_Check_Syntax_Request --
---------------------------------
overriding function On_ALS_Check_Syntax_Request
(Self : access Message_Handler;
Request : LSP.Messages.Server_Requests.ALS_Check_Syntax_Request)
return LSP.Messages.Server_Responses.ALS_Check_Syntax_Response
is
use Laltools.Common;
use LSP.Messages.Server_Responses;
use VSS.Strings;
function "+"
(Item : Virtual_String'Class)
return Ada.Strings.UTF_Encoding.UTF_8_String
renames VSS.Strings.Conversions.To_UTF_8_String;
function "+"
(Item : Virtual_String'Class)
return Unbounded_String
renames VSS.Strings.Conversions.To_Unbounded_UTF_8_String;
Invalid_Rule_Error_Message : constant Virtual_String :=
"Error parsing the grammar rules for the syntax check";
Input : constant Unbounded_String := +Request.params.Input;
Rules : Grammar_Rule_Vector;
Valid : Boolean := False;
begin
if Request.params.Rules.Length = 0 then
-- We need at least one rule in order to validate the input
raise Constraint_Error;
end if;
for Rule_Image of Request.params.Rules loop
-- A Constraint_Error can be raised here is an invalid rule is
-- received in the request parameters.
Rules.Append (Grammar_Rule'Value (+Rule_Image));
end loop;
-- The input cannot be empty and only needs to be valid against one of
-- the rules.
if Input /= "" then
Valid := Validate_Syntax (Input, Rules);
end if;
if Valid then
return Response : ALS_Check_Syntax_Response (Is_Error => False) do
Response.result := (Is_Set => False);
end return;
else
return Response : ALS_Check_Syntax_Response (Is_Error => False) do
Response.result := (Is_Set => True, Value => "Invalid Syntax");
end return;
end if;
exception
when Constraint_Error =>
return Response : ALS_Check_Syntax_Response (Is_Error => True) do
Response.error :=
(Is_Set => True,
Value => (code => LSP.Errors.InvalidRequest,
message => Invalid_Rule_Error_Message,
data => <>));
end return;
end On_ALS_Check_Syntax_Request;
-----------
-- Parse --
-----------
function Parse
(Value : LSP.Types.Optional_LSP_Any)
return Experimental_Client_Capabilities is
begin
return Result : Experimental_Client_Capabilities :=
(Advanced_Refactorings => [others => False])
do
if Value.Is_Set then
if Value.Value.
Has_Field ("advanced_refactorings")
and then Value.Value.Get ("advanced_refactorings").Kind in
GNATCOLL.JSON.JSON_Array_Type
then
declare
Advanced_Refactorings : constant GNATCOLL.JSON.JSON_Array :=
Value.Value.Get ("advanced_refactorings");
Advanced_Refactoring :
LSP.Ada_Handlers.Advanced_Refactorings;
begin
for Refactoring of Advanced_Refactorings loop
if Refactoring.Kind in GNATCOLL.JSON.JSON_String_Type then
begin
Advanced_Refactoring :=
LSP.Ada_Handlers.Advanced_Refactorings'Value
(GNATCOLL.JSON.Get (Refactoring));
Result.Advanced_Refactorings
(Advanced_Refactoring) := True;
exception
when others =>
null;
end;
end if;
end loop;
end;
end if;
end if;
end return;
end Parse;
end LSP.Ada_Handlers;
|