mcpls-core 0.8.0

Core library for MCP to LSP protocol translation
Documentation
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
//! Public MCP-facing result/data-transfer types returned by the tool-call
//! handlers in the sibling domain modules.

use std::num::NonZeroU32;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use thiserror::Error;

use super::enclosing::{ContextualDiagnostic, ContextualLocation, EnrichmentSummary};
use super::kind_filter::{self, KindFilter};
use crate::bridge::notifications::ReportedSeverity;
use crate::config::text_newtype::impl_text_newtype;
use crate::config::{BoundedText, InvalidBoundedText};
use crate::error::spelled_enum;
use crate::redaction::{Redactions, ServerText};

/// Convert an LSP integer-valued enum (`SymbolKind`, `CompletionItemKind`,
/// `InlayHintKind`, ...) to its wire-format `u32`.
///
/// Infallible and needs no fallback value, unlike a `serde_json` roundtrip.
pub(super) fn lsp_kind_to_u32<T: Into<u32>>(kind: T) -> u32 {
    kind.into()
}

/// Position in a document (1-based for MCP).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Position2D {
    /// Line number (1-based).
    pub line: u32,
    /// Character offset (1-based).
    pub character: u32,
}

/// Largest line or character value a client may supply.
pub const MAX_POSITION_VALUE: u32 = 1_000_000;

/// Largest line span of a range given to a range-taking tool.
pub const MAX_RANGE_LINES: u32 = 10_000;

/// Why a client-supplied position was rejected.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum InvalidPosition {
    /// A line or character below 1; positions are 1-based.
    #[error("Line and character positions must be >= 1")]
    ZeroBased,
    /// A line or character above [`MAX_POSITION_VALUE`].
    #[error("Position values must be <= {MAX_POSITION_VALUE}")]
    TooLarge,
}

/// Longest accepted `rename_symbol` `new_name`, in bytes.
///
/// No real identifier approaches this length in any language mcpls targets.
pub const MAX_NEW_NAME_LENGTH: usize = 1_000;

spelled_enum! {
    /// The client-supplied text fields that are validated as bounded text, named
    /// as they are on the wire.
    TextField {
        /// `new_name` of `rename_symbol`.
        NewName => "new_name",
        /// `trigger` of `get_completions`.
        Trigger => "trigger",
        /// `symbol_name` of a name-addressed tool.
        SymbolName => "symbol_name",
        /// `container` of a name-addressed tool.
        Container => "container",
    }
}

/// Why a client-supplied text field was rejected, and which one.
///
/// # Examples
///
/// ```
/// use mcpls_core::bridge::{NewName, TextField};
/// use mcpls_core::config::InvalidBoundedText;
///
/// let error = NewName::new("  ").unwrap_err();
/// assert_eq!(error.field, TextField::NewName);
/// assert_eq!(error.reason, InvalidBoundedText::Blank);
/// assert_eq!(error.to_string(), "`new_name` cannot be empty");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[error("`{field}` {reason}")]
pub struct InvalidTextField {
    /// The field that was rejected.
    pub field: TextField,
    /// The rule it broke.
    pub reason: InvalidBoundedText,
}

impl InvalidTextField {
    /// Tags a rejection with the `field` it was raised for.
    pub(crate) fn of(field: TextField) -> impl Fn(InvalidBoundedText) -> Self {
        move |reason| Self { field, reason }
    }
}

/// The name a `rename_symbol` call renames to: non-blank and at most
/// [`MAX_NEW_NAME_LENGTH`] bytes, so an unusable name is rejected before any
/// language server is asked.
///
/// # Examples
///
/// ```
/// use mcpls_core::bridge::NewName;
/// use mcpls_core::config::InvalidBoundedText;
///
/// assert_eq!(NewName::new("renamed")?.as_str(), "renamed");
/// assert_eq!(NewName::new("  ").unwrap_err().reason, InvalidBoundedText::Blank);
/// # Ok::<(), mcpls_core::bridge::InvalidTextField>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(try_from = "String")]
pub struct NewName(BoundedText<MAX_NEW_NAME_LENGTH>);

impl NewName {
    /// Validates `raw` as given; surrounding whitespace is kept.
    ///
    /// # Errors
    ///
    /// [`InvalidTextField`] naming `new_name` when `raw` is blank or longer
    /// than [`MAX_NEW_NAME_LENGTH`].
    pub fn new(raw: impl Into<String>) -> Result<Self, InvalidTextField> {
        BoundedText::new(raw)
            .map(Self)
            .map_err(InvalidTextField::of(TextField::NewName))
    }

    /// The name text, owned.
    #[must_use]
    pub fn into_string(self) -> String {
        String::from(self)
    }
}

impl_text_newtype!(NewName, InvalidTextField);

/// Longest accepted `get_completions` `trigger`, in bytes.
///
/// LSP defines `triggerCharacter` as a single character; 8 bytes covers any
/// one Unicode codepoint (at most 4 bytes in UTF-8) and short multi-character
/// triggers such as `->`, while rejecting anything that is not plausibly a
/// trigger.
pub const MAX_TRIGGER_CHARACTER_BYTES: usize = 8;

/// The text that triggered a completion request: not empty and at most
/// [`MAX_TRIGGER_CHARACTER_BYTES`] bytes.
///
/// Whitespace is a valid trigger (a space triggers completion in some
/// languages), so only the empty string is refused, not a blank one. That is
/// why it is not a [`BoundedText`], which refuses blank text.
///
/// # Examples
///
/// ```
/// use mcpls_core::bridge::CompletionTrigger;
/// use mcpls_core::config::InvalidBoundedText;
///
/// assert_eq!(CompletionTrigger::new("->")?.as_str(), "->");
/// assert!(CompletionTrigger::new(" ").is_ok());
/// assert_eq!(CompletionTrigger::new("").unwrap_err().reason, InvalidBoundedText::Blank);
/// assert!(CompletionTrigger::new("123456789").is_err());
/// # Ok::<(), mcpls_core::bridge::InvalidTextField>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(try_from = "String")]
pub struct CompletionTrigger(String);

impl CompletionTrigger {
    /// Validates `raw`.
    ///
    /// # Errors
    ///
    /// [`InvalidTextField`] naming `trigger` when `raw` is empty or exceeds
    /// [`MAX_TRIGGER_CHARACTER_BYTES`].
    pub fn new(raw: impl Into<String>) -> Result<Self, InvalidTextField> {
        let raw = raw.into();
        let invalid = InvalidTextField::of(TextField::Trigger);
        if raw.is_empty() {
            return Err(invalid(InvalidBoundedText::Blank));
        }
        if raw.len() > MAX_TRIGGER_CHARACTER_BYTES {
            return Err(invalid(InvalidBoundedText::TooLong {
                len: raw.len(),
                max: MAX_TRIGGER_CHARACTER_BYTES,
            }));
        }
        Ok(Self(raw))
    }

    /// The trigger text, owned.
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }
}

impl_text_newtype!(CompletionTrigger, InvalidTextField);

/// Largest tab size a client may request for formatting.
pub const MAX_TAB_SIZE: u32 = 32;

/// Tab size used when a formatting request gives none.
const DEFAULT_TAB_SIZE: u32 = 4;

/// A tab size outside 1 to [`MAX_TAB_SIZE`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[error("tab_size must be between 1 and {MAX_TAB_SIZE}, got {0}")]
pub struct InvalidTabSize(pub u32);

/// The tab size a formatting request asks the server for: 1 to
/// [`MAX_TAB_SIZE`], 4 by default.
///
/// Deserializes from a JSON integer and rejects out-of-range values as
/// invalid params, so an unbounded `u32` never reaches a language server.
///
/// # Examples
///
/// ```
/// use mcpls_core::bridge::{InvalidTabSize, MAX_TAB_SIZE, TabSize};
///
/// assert_eq!(TabSize::default().get(), 4);
/// assert_eq!(TabSize::try_from(MAX_TAB_SIZE)?.get(), MAX_TAB_SIZE);
/// assert_eq!(TabSize::try_from(0), Err(InvalidTabSize(0)));
/// assert_eq!(TabSize::try_from(MAX_TAB_SIZE + 1), Err(InvalidTabSize(MAX_TAB_SIZE + 1)));
/// # Ok::<(), InvalidTabSize>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "u32", into = "u32")]
pub struct TabSize(NonZeroU32);

impl TabSize {
    /// The wrapped tab size, within 1 to [`MAX_TAB_SIZE`].
    #[must_use]
    pub const fn get(self) -> u32 {
        self.0.get()
    }
}

impl Default for TabSize {
    fn default() -> Self {
        const DEFAULT: TabSize = match NonZeroU32::new(DEFAULT_TAB_SIZE) {
            Some(size) => TabSize(size),
            None => panic!("the default tab size must be non-zero"),
        };
        DEFAULT
    }
}

impl TryFrom<u32> for TabSize {
    type Error = InvalidTabSize;

    fn try_from(value: u32) -> Result<Self, Self::Error> {
        match NonZeroU32::new(value) {
            Some(size) if value <= MAX_TAB_SIZE => Ok(Self(size)),
            _ => Err(InvalidTabSize(value)),
        }
    }
}

impl From<TabSize> for u32 {
    fn from(size: TabSize) -> Self {
        size.get()
    }
}

impl JsonSchema for TabSize {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "TabSize".into()
    }

    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({
            "type": "integer",
            "minimum": 1,
            "maximum": MAX_TAB_SIZE,
            "default": DEFAULT_TAB_SIZE,
        })
    }
}

/// Why a client-supplied range was rejected.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum InvalidRange {
    /// The start position is invalid.
    #[error("invalid range start: {0}")]
    Start(InvalidPosition),
    /// The end position is invalid.
    #[error("invalid range end: {0}")]
    End(InvalidPosition),
    /// The start lies after the end.
    #[error("Start position must be before or equal to end position")]
    Reversed,
    /// The range spans more than [`MAX_RANGE_LINES`] lines.
    #[error("Range size must be <= {MAX_RANGE_LINES} lines")]
    TooManyLines,
}

/// A 1-based MCP position taken as input by `Translator::handle_*` methods.
///
/// Kept distinct from [`Position2D`] (which carries an *output* position back
/// to the caller) and made of two [`NonZeroU32`]s, so a zero position cannot
/// exist and a call site that swaps `line` and `character` still names them
/// (#322). A position typed by a client goes through [`Self::from_client`],
/// the only fallible constructor; positions derived from server output
/// convert infallibly through `Position::from_server_output`.
///
/// # Examples
///
/// ```
/// use mcpls_core::bridge::{InvalidPosition, Position};
///
/// let position = Position::from_client(3, 5)?;
/// assert_eq!((position.line().get(), position.character().get()), (3, 5));
/// assert_eq!(Position::from_client(0, 1), Err(InvalidPosition::ZeroBased));
/// # Ok::<(), InvalidPosition>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Position {
    line: NonZeroU32,
    character: NonZeroU32,
}

impl Position {
    /// Builds a position from client-supplied 1-based numbers.
    ///
    /// # Errors
    ///
    /// Returns [`InvalidPosition::ZeroBased`] for a zero line or character
    /// and [`InvalidPosition::TooLarge`] above [`MAX_POSITION_VALUE`].
    pub const fn from_client(line: u32, character: u32) -> Result<Self, InvalidPosition> {
        let (Some(line), Some(character)) = (NonZeroU32::new(line), NonZeroU32::new(character))
        else {
            return Err(InvalidPosition::ZeroBased);
        };
        if line.get() > MAX_POSITION_VALUE || character.get() > MAX_POSITION_VALUE {
            return Err(InvalidPosition::TooLarge);
        }
        Ok(Self { line, character })
    }

    /// Line number (1-based).
    #[must_use]
    pub const fn line(self) -> NonZeroU32 {
        self.line
    }

    /// Character offset (1-based).
    #[must_use]
    pub const fn character(self) -> NonZeroU32 {
        self.character
    }

    /// Zero-based LSP line.
    #[must_use]
    pub const fn lsp_line(self) -> u32 {
        self.line.get().saturating_sub(1)
    }

    /// Zero-based character offset, still in UTF-16 units.
    #[must_use]
    pub const fn lsp_character(self) -> u32 {
        self.character.get().saturating_sub(1)
    }

    /// Reuses a position taken from server output, which is already 1-based
    /// MCP form, as a handler input position. Deliberately not a `From`
    /// impl: a position typed by a client must go through
    /// [`Self::from_client`]. A zero, which converted LSP output never
    /// carries, clamps to 1.
    pub(crate) fn from_server_output(position: &Position2D) -> Self {
        let clamp = |value: u32| NonZeroU32::new(value).unwrap_or(NonZeroU32::MIN);
        Self {
            line: clamp(position.line),
            character: clamp(position.character),
        }
    }

    /// Builds a fixture position, panicking on an invalid one.
    #[cfg(test)]
    pub(crate) fn at(line: u32, character: u32) -> Self {
        Self::from_client(line, character).expect("fixture position is valid")
    }
}

/// An ordered pair of positions, `start <= end`.
///
/// # Examples
///
/// ```
/// use mcpls_core::bridge::{InvalidRange, Position, PositionRange};
///
/// let start = Position::from_client(1, 1).unwrap();
/// let end = Position::from_client(2, 4).unwrap();
/// assert!(PositionRange::new(start, end).is_ok());
/// assert_eq!(PositionRange::new(end, start), Err(InvalidRange::Reversed));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PositionRange {
    start: Position,
    end: Position,
}

impl PositionRange {
    /// Builds an ordered range.
    ///
    /// # Errors
    ///
    /// Returns [`InvalidRange::Reversed`] when `start` lies after `end`.
    pub fn new(start: Position, end: Position) -> Result<Self, InvalidRange> {
        let ordered = (start.line, start.character) <= (end.line, end.character);
        ordered
            .ok_or(InvalidRange::Reversed)
            .map(|()| Self { start, end })
    }

    /// Builds a range from client-supplied 1-based numbers.
    ///
    /// # Errors
    ///
    /// Returns the invalid endpoint or [`InvalidRange::Reversed`].
    pub fn from_client(
        (start_line, start_character): (u32, u32),
        (end_line, end_character): (u32, u32),
    ) -> Result<Self, InvalidRange> {
        let start =
            Position::from_client(start_line, start_character).map_err(InvalidRange::Start)?;
        let end = Position::from_client(end_line, end_character).map_err(InvalidRange::End)?;
        Self::new(start, end)
    }

    /// First position of the range.
    #[must_use]
    pub const fn start(self) -> Position {
        self.start
    }

    /// Last position of the range.
    #[must_use]
    pub const fn end(self) -> Position {
        self.end
    }
}

/// A [`PositionRange`] spanning at most [`MAX_RANGE_LINES`] lines, taken by
/// the tools whose server-side cost grows with the range.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BoundedRange(PositionRange);

impl BoundedRange {
    /// The underlying ordered range.
    #[must_use]
    pub const fn range(self) -> PositionRange {
        self.0
    }
}

impl TryFrom<PositionRange> for BoundedRange {
    type Error = InvalidRange;

    fn try_from(range: PositionRange) -> Result<Self, Self::Error> {
        let span = range.end.line.get().saturating_sub(range.start.line.get());
        (span <= MAX_RANGE_LINES)
            .ok_or(InvalidRange::TooManyLines)
            .map(|()| Self(range))
    }
}

/// Range in a document (1-based for MCP).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Range {
    /// Start position.
    pub start: Position2D,
    /// End position.
    pub end: Position2D,
}

/// Location in a document.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Location {
    /// URI of the document.
    pub uri: String,
    /// Range within the document.
    pub range: Range,
    /// Whether this location is not provably inside a configured workspace root (stdlib, a dependency).
    ///
    /// Advisory only, not a security/safety guarantee: read-only navigation
    /// results are never filtered by workspace containment (a legitimate
    /// result routinely points into the standard library or a dependency),
    /// so callers that want to apply their own policy toward out-of-workspace
    /// locations can check this flag. The check is purely lexical -- it does
    /// not resolve symlinks. A root counts together with the spellings it
    /// was configured or launched under (for example a symlinked path or the
    /// shell's logical working directory), but a location reached through any
    /// other symlink (e.g. a package manager's symlinked dependency store)
    /// can read `true` even though it is genuinely inside the workspace. Also
    /// always `true` when no workspace roots are configured: without a
    /// configured root, nothing can be vouched for as inside the workspace.
    /// Omitted (defaults to `false`) when serialized.
    #[serde(default, skip_serializing_if = "is_false")]
    pub out_of_workspace: bool,
}

/// `skip_serializing_if` predicate for a `bool` field that should be omitted
/// from the serialized output when `false`.
///
/// Takes `&bool` rather than `bool` because serde's `skip_serializing_if`
/// always calls the predicate with a field reference.
#[expect(
    clippy::trivially_copy_pass_by_ref,
    reason = "serde's `skip_serializing_if` requires `fn(&T) -> bool`"
)]
const fn is_false(value: &bool) -> bool {
    !*value
}

/// How a non-UTF-16 server's `character` offsets became inexact in a result.
// Variant order matters: derived `Ord` makes `Request` > `Response`, so `Option::max` keeps the worse.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum PositionDegradation {
    /// Only offsets in the returned data may be inexact. The result still
    /// describes the symbol that was asked about; keep it and treat the
    /// returned `character` values as approximate.
    Response,
    /// The queried position was sent to the server unconverted, so the result
    /// may describe a different symbol. Do not trust it.
    Request,
}

/// Result of a hover request.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct HoverResult {
    /// Hover contents as markdown string.
    pub contents: String,
    /// Optional range the hover applies to.
    pub range: Option<Range>,
    /// Set only when some `character` offsets are inexact (non-UTF-16 servers); omitted otherwise.
    ///
    /// Tells whether the queried position or only the returned offsets are affected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub positions_degraded: Option<PositionDegradation>,
}

/// A single diagnostic.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Diagnostic {
    /// Range where the diagnostic applies.
    pub range: Range,
    /// Severity of the diagnostic.
    pub severity: ReportedSeverity,
    /// Diagnostic message.
    pub message: String,
    /// Optional diagnostic code.
    pub code: Option<String>,
}

/// Result of a diagnostics request.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DiagnosticsResult {
    /// List of diagnostics for the document.
    pub diagnostics: Vec<Diagnostic>,
    /// Set only when some `character` offsets are inexact (non-UTF-16 servers); omitted otherwise.
    ///
    /// Tells whether the queried position or only the returned offsets are affected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(with = "PositionDegradation")]
    pub positions_degraded: Option<PositionDegradation>,
}

/// Result of a `get_diagnostics` request: [`DiagnosticsResult`] plus the
/// opt-in enclosing-symbol context.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DocumentDiagnosticsResult {
    /// List of diagnostics for the document.
    pub diagnostics: Vec<ContextualDiagnostic>,
    /// Set only when some `character` offsets are inexact (non-UTF-16 servers); omitted otherwise.
    ///
    /// Tells whether the queried position or only the returned offsets are affected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(with = "PositionDegradation")]
    pub positions_degraded: Option<PositionDegradation>,
    /// Set only with `context: "enclosing_symbol"`: how many files were enriched or skipped.
    ///
    /// Set only when that context was requested and the file has diagnostics.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(with = "EnrichmentSummary")]
    pub enrichment: Option<EnrichmentSummary>,
}

/// A text edit operation.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct TextEdit {
    /// Range to replace.
    pub range: Range,
    /// New text.
    pub new_text: String,
}

/// Changes to a document.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DocumentChanges {
    /// URI of the document.
    pub uri: String,
    /// List of edits to apply.
    pub edits: Vec<TextEdit>,
}

/// Result of a rename request.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RenameResult {
    /// Changes to apply across documents.
    pub changes: Vec<DocumentChanges>,
    /// Entries withheld from `changes` -- see [`DroppedEdits`]. A non-empty
    /// value means the rename is incomplete even if `changes` is non-empty,
    /// and callers must not treat this result as the full rename otherwise.
    #[serde(default, skip_serializing_if = "DroppedEdits::is_empty")]
    pub dropped: DroppedEdits,
    /// Set only when some `character` offsets are inexact (non-UTF-16 servers); omitted otherwise.
    ///
    /// Tells whether the queried position or only the returned offsets are affected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub positions_degraded: Option<PositionDegradation>,
}

/// Counts of `WorkspaceEdit` entries withheld during conversion to MCP DTOs,
/// broken down by reason (#475).
///
/// `convert_workspace_edit` silently discarded such entries with only a
/// `tracing` log line, so a client applying a [`RenameResult`] or
/// `WorkspaceEditDescription` straight to disk could not tell "nothing to
/// rename" apart from "some of the rename was withheld" -- this makes that
/// distinction visible in the result itself.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DroppedEdits {
    /// Entries referencing a URI outside every configured workspace root.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub out_of_workspace: usize,
    /// `CreateFile`/`RenameFile`/`DeleteFile` document changes, which mcpls
    /// does not translate into MCP DTOs.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub unsupported_file_operation: usize,
    /// `SnippetTextEdit` entries, which mcpls does not translate since it
    /// advertises no `snippetEditSupport`.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub unsupported_snippet_edit: usize,
    /// Edits not admitted because the response exceeded
    /// `MAX_NORMALIZED_LOCATIONS` (#487), including whole files skipped once
    /// the budget was spent.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub exceeds_item_cap: usize,
    /// `documentChanges` text-document edits ignored because a non-empty
    /// `changes` map took precedence and did not already name their URI
    /// (#498).
    #[serde(default, skip_serializing_if = "is_zero")]
    pub shadowed_by_changes: usize,
}

impl DroppedEdits {
    /// Whether no entries were withheld.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        *self == Self::default()
    }
}

#[expect(
    clippy::trivially_copy_pass_by_ref,
    reason = "serde's `skip_serializing_if` requires `fn(&T) -> bool`"
)]
const fn is_zero(count: &usize) -> bool {
    *count == 0
}

/// A completion item.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Completion {
    /// Label of the completion.
    pub label: String,
    /// LSP numeric completion-item kind (e.g. 3 for Function).
    pub kind: Option<u32>,
    /// Detail information.
    pub detail: Option<String>,
    /// Documentation.
    pub documentation: Option<String>,
}

/// Result of a completions request.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CompletionsResult {
    /// List of completion items.
    pub items: Vec<Completion>,
    /// Set only when some `character` offsets are inexact (non-UTF-16 servers); omitted otherwise.
    ///
    /// Tells whether the queried position or only the returned offsets are affected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub positions_degraded: Option<PositionDegradation>,
}

/// A document symbol.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Symbol {
    /// Name of the symbol.
    pub name: String,
    /// LSP numeric symbol kind (e.g. 12 for Function).
    pub kind: u32,
    /// Range of the symbol.
    pub range: Range,
    /// Selection range (identifier location).
    pub selection_range: Range,
    /// Child symbols.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub children: Option<Vec<Self>>,
}

/// Result of a document symbols request.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DocumentSymbolsResult {
    /// List of symbols in the document.
    pub symbols: Vec<Symbol>,
    /// Set only when some `character` offsets are inexact (non-UTF-16 servers); omitted otherwise.
    ///
    /// Tells whether the queried position or only the returned offsets are affected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(with = "PositionDegradation")]
    pub positions_degraded: Option<PositionDegradation>,
}

/// Result of a format document request.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct FormatDocumentResult {
    /// List of edits to format the document.
    pub edits: Vec<TextEdit>,
    /// Set only when some `character` offsets are inexact (non-UTF-16 servers); omitted otherwise.
    ///
    /// Tells whether the queried position or only the returned offsets are affected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub positions_degraded: Option<PositionDegradation>,
}

/// A workspace symbol.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct WorkspaceSymbol {
    /// Name of the symbol.
    pub name: String,
    /// LSP numeric symbol kind (e.g. 12 for Function).
    pub kind: u32,
    /// Location of the symbol.
    pub location: Location,
    /// Optional container name (parent scope).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub container_name: Option<String>,
}

/// Result of workspace symbol search.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct WorkspaceSymbolResult {
    /// List of symbols found.
    pub symbols: Vec<WorkspaceSymbol>,
    /// Whether more symbols matched than `symbols` returns.
    ///
    /// Set whenever any are dropped, by the caller's own smaller `limit` or by the server-side
    /// maximum it is clamped to (see `MAX_NORMALIZED_LOCATIONS`, #474); this does not distinguish
    /// which of the two caused it. Omitted (defaults to `false`) when serialized.
    #[serde(default, skip_serializing_if = "is_false")]
    pub truncated: bool,
    /// Set only when some `character` offsets are inexact (non-UTF-16 servers); omitted otherwise.
    ///
    /// Tells whether the queried position or only the returned offsets are affected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub positions_degraded: Option<PositionDegradation>,
    /// Set only when the server itself answered with no symbols: what its answer covers.
    ///
    /// Omitted for a non-empty result.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(with = "IndexCoverage")]
    pub index_coverage: Option<IndexCoverage>,
}

/// A single code action.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CodeAction {
    /// Title of the code action.
    pub title: String,
    /// Kind of code action (quickfix, refactor, etc.).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    /// Diagnostics that this action resolves.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub diagnostics: Vec<Diagnostic>,
    /// Workspace edit to apply.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub edit: Option<WorkspaceEditDescription>,
    /// Command to execute.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub command: Option<CommandDescription>,
    /// Whether this is the preferred action.
    #[serde(default)]
    pub is_preferred: bool,
}

/// Description of a workspace edit.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct WorkspaceEditDescription {
    /// Changes to apply to documents.
    pub changes: Vec<DocumentChanges>,
    /// Entries withheld from `changes` -- see [`DroppedEdits`].
    #[serde(default, skip_serializing_if = "DroppedEdits::is_empty")]
    pub dropped: DroppedEdits,
}

/// Description of a command.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CommandDescription {
    /// Title of the command.
    pub title: String,
    /// Command identifier.
    pub command: String,
    /// Command arguments.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub arguments: Vec<serde_json::Value>,
}

/// Result of code actions request.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CodeActionsResult {
    /// Available code actions.
    pub actions: Vec<CodeAction>,
    /// Whether `actions`, their diagnostics or their edits were capped below the server's response.
    ///
    /// See `MAX_NORMALIZED_LOCATIONS`, #487. A per-action `dropped.exceeds_item_cap` pinpoints
    /// dropped edits. Omitted (defaults to `false`) when serialized.
    #[serde(default, skip_serializing_if = "is_false")]
    pub truncated: bool,
    /// Set only when some `character` offsets are inexact (non-UTF-16 servers); omitted otherwise.
    ///
    /// Tells whether the queried position or only the returned offsets are affected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub positions_degraded: Option<PositionDegradation>,
}

/// Result of call hierarchy prepare request.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CallHierarchyPrepareResult {
    /// List of callable items at the position.
    pub items: Vec<HierarchyItem>,
    /// Whether `items` was capped below the server's full response.
    ///
    /// See `MAX_NORMALIZED_LOCATIONS`, #516. Omitted (defaults to `false`) when serialized.
    #[serde(default, skip_serializing_if = "is_false")]
    pub truncated: bool,
    /// Set only when some `character` offsets are inexact (non-UTF-16 servers); omitted otherwise.
    ///
    /// Tells whether the queried position or only the returned offsets are affected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub positions_degraded: Option<PositionDegradation>,
}

/// An incoming call (caller of the current item).
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct IncomingCall {
    /// The item that calls the current item.
    pub from: HierarchyItem,
    /// Ranges where the call occurs.
    pub from_ranges: Vec<Range>,
}

/// Result of incoming calls request.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct IncomingCallsResult {
    /// List of incoming calls.
    pub calls: Vec<IncomingCall>,
    /// Whether `calls` (with their `from_ranges`) was capped below the server's full response.
    ///
    /// See `MAX_NORMALIZED_LOCATIONS`, #487. Omitted (defaults to `false`) when serialized.
    #[serde(default, skip_serializing_if = "is_false")]
    pub truncated: bool,
    /// Set only when some `character` offsets are inexact (non-UTF-16 servers); omitted otherwise.
    ///
    /// Tells whether the queried position or only the returned offsets are affected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub positions_degraded: Option<PositionDegradation>,
}

/// An outgoing call (callee from the current item).
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct OutgoingCall {
    /// The item being called.
    pub to: HierarchyItem,
    /// Ranges where the call occurs.
    pub from_ranges: Vec<Range>,
}

/// Result of outgoing calls request.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct OutgoingCallsResult {
    /// List of outgoing calls.
    pub calls: Vec<OutgoingCall>,
    /// Whether `calls` (with their `from_ranges`) was capped below the server's full response.
    ///
    /// See `MAX_NORMALIZED_LOCATIONS`, #487. Omitted (defaults to `false`) when serialized.
    #[serde(default, skip_serializing_if = "is_false")]
    pub truncated: bool,
    /// Set only when some `character` offsets are inexact (non-UTF-16 servers); omitted otherwise.
    ///
    /// Tells whether the queried position or only the returned offsets are affected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub positions_degraded: Option<PositionDegradation>,
}

/// Result of server logs request.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ServerLogsResult {
    /// List of log entries.
    pub logs: Vec<crate::bridge::notifications::LogEntry>,
}

/// Result of server messages request.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ServerMessagesResult {
    /// List of server messages.
    pub messages: Vec<crate::bridge::notifications::ServerMessage>,
}

/// A single parameter in a signature.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SignatureParameter {
    /// Label of the parameter; absent when the server gave an offset pair that does not resolve.
    ///
    /// An offset pair does not resolve when it does not name a substring of the signature label
    /// (out of range, inside a character, or reversed).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    /// Optional documentation for the parameter.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub documentation: Option<String>,
}

/// A single signature overload.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SignatureInfo {
    /// Full label of the signature.
    pub label: String,
    /// Optional documentation for the signature.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub documentation: Option<String>,
    /// Parameters of the signature.
    pub parameters: Vec<SignatureParameter>,
}

/// Result of a signature help request.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SignatureHelpResult {
    /// Available signatures.
    pub signatures: Vec<SignatureInfo>,
    /// Index of the active signature.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub active_signature: Option<u32>,
    /// Index of the active parameter within the active signature.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub active_parameter: Option<u32>,
    /// Set only when some `character` offsets are inexact (non-UTF-16 servers); omitted otherwise.
    ///
    /// Tells whether the queried position or only the returned offsets are affected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub positions_degraded: Option<PositionDegradation>,
}

/// Locations answering a definition, references, implementation,
/// type-definition or declaration request.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct LocationsResult {
    /// Locations found.
    pub locations: Vec<ContextualLocation>,
    /// Whether `locations` was capped below the server's full response.
    ///
    /// If `true`, more locations exist than are returned here (see `MAX_NORMALIZED_LOCATIONS`,
    /// #474). Omitted (defaults to `false`) when serialized.
    #[serde(default, skip_serializing_if = "is_false")]
    pub truncated: bool,
    /// Set only when some `character` offsets are inexact (non-UTF-16 servers); omitted otherwise.
    ///
    /// Tells whether the queried position or only the returned offsets are affected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(with = "PositionDegradation")]
    pub positions_degraded: Option<PositionDegradation>,
    /// Set only with `context: "enclosing_symbol"`: how many files were enriched or skipped.
    ///
    /// Set only when that context was requested and at least one item was looked up. It also says
    /// whether the file cap or time budget cut the lookup short.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(with = "EnrichmentSummary")]
    pub enrichment: Option<EnrichmentSummary>,
}

/// What an empty references or workspace-symbol answer covers.
///
/// A language server that indexes only documents sent with `didOpen` answers an empty list for
/// symbols in files this session never opened, so an empty answer is not proof of absence.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct IndexCoverage {
    /// Documents currently tracked as synced to the server process; LRU eviction lowers it.
    pub synced_documents: u32,
    /// Set only when the server was restarted or respawned; stays set for the rest of the session.
    #[serde(default, skip_serializing_if = "is_false")]
    pub server_restarted: bool,
}

/// Result of a references request: the locations plus an optional index-coverage note.
///
/// A separate type from [`LocationsResult`] so the note's schema is paid for by one tool only.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ReferencesResult {
    /// The locations found.
    #[serde(flatten)]
    pub result: LocationsResult,
    /// Set only when `locations` is empty: what the routed server's answer covers.
    ///
    /// Omitted for a non-empty result.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(with = "IndexCoverage")]
    pub index_coverage: Option<IndexCoverage>,
}

/// A single inlay hint entry.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct InlayHintEntry {
    /// Position of the hint (1-based MCP).
    pub position: Position2D,
    /// Label text for the hint.
    pub label: String,
    /// LSP numeric inlay-hint kind (1 = Type, 2 = Parameter, or a
    /// server-defined custom value).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<u32>,
    /// Whether to add a space before the hint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub padding_left: Option<bool>,
    /// Whether to add a space after the hint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub padding_right: Option<bool>,
    /// Tooltip text.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tooltip: Option<String>,
}

/// Result of an inlay hints request.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct InlayHintsResult {
    /// List of inlay hints.
    pub hints: Vec<InlayHintEntry>,
    /// Whether `hints` was capped below the server's full response.
    ///
    /// See `MAX_NORMALIZED_LOCATIONS`, #487. Omitted (defaults to `false`) when serialized.
    #[serde(default, skip_serializing_if = "is_false")]
    pub truncated: bool,
    /// Set only when some `character` offsets are inexact (non-UTF-16 servers); omitted otherwise.
    ///
    /// Tells whether the queried position or only the returned offsets are affected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub positions_degraded: Option<PositionDegradation>,
}

/// A call or type hierarchy item.
///
/// Returned by the hierarchy tools and accepted back as the typed `item`
/// input of the walking tools (`get_incoming_calls`, `get_outgoing_calls`,
/// `get_supertypes`, `get_subtypes`). LSP's call and type hierarchy items carry the same fields, so one shape
/// serves both. `data` is opaque to the caller and meaningful only to the
/// server that produced the item.
///
/// Lines and columns above [`MAX_POSITION_VALUE`] cannot be passed back, so
/// an item from a `prepare_*` tool whose range crosses that column (for
/// example on a minified line) is rejected by the walking tools.
///
/// # Examples
///
/// ```
/// use mcpls_core::bridge::HierarchyItem;
///
/// let item: HierarchyItem = serde_json::from_value(serde_json::json!({
///     "name": "Base", "kind": 5, "uri": "file:///a.cpp",
///     "range": {"start": {"line": 1, "character": 1}, "end": {"line": 2, "character": 1}},
///     "selectionRange": {"start": {"line": 1, "character": 7}, "end": {"line": 1, "character": 11}},
/// }))
/// .unwrap();
/// assert_eq!(item.name, "Base");
/// assert!(serde_json::from_value::<HierarchyItem>(serde_json::json!({})).is_err());
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct HierarchyItem {
    /// Name of the symbol.
    pub name: String,
    /// LSP numeric symbol kind (e.g. 12 for Function, 5 for Class).
    pub kind: u32,
    /// More detail for this item.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
    /// URI of the document.
    pub uri: String,
    /// Range of the symbol.
    pub range: Range,
    /// Selection range (identifier location).
    ///
    /// Serialized as `selectionRange` (camelCase) so that a returned item
    /// round-trips when the MCP client passes it back to a walking tool.
    #[serde(rename = "selectionRange")]
    pub selection_range: Range,
    /// Opaque data to pass back unchanged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,
    /// Whether this item is not provably inside any configured workspace
    /// root -- see [`Location::out_of_workspace`] for the exact semantics
    /// and caveats (advisory only, lexical, symlink-unaware). Ignored on
    /// input.
    #[serde(default, skip_serializing_if = "is_false")]
    pub out_of_workspace: bool,
}

/// Why a client-supplied [`HierarchyItem`] was rejected.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum InvalidHierarchyItem {
    /// The item's `range` is invalid.
    #[error("invalid hierarchy item range: {0}")]
    Range(InvalidRange),
    /// The item's `selectionRange` is invalid.
    #[error("invalid hierarchy item selectionRange: {0}")]
    SelectionRange(InvalidRange),
}

/// A [`HierarchyItem`] whose ranges passed client-input validation.
///
/// Taken by the walking handlers instead of the raw wire DTO, so a zero,
/// oversized or reversed range cannot reach the LSP conversion. Built only by
/// [`Self::from_client`].
///
/// # Examples
///
/// ```
/// use std::assert_matches;
///
/// use mcpls_core::bridge::{CheckedHierarchyItem, HierarchyItem, InvalidHierarchyItem};
///
/// let wire = |line: u32| -> HierarchyItem {
///     serde_json::from_value(serde_json::json!({
///         "name": "Base", "kind": 5, "uri": "file:///a.cpp",
///         "range": {"start": {"line": line, "character": 1}, "end": {"line": 2, "character": 1}},
///         "selectionRange": {"start": {"line": 1, "character": 7}, "end": {"line": 1, "character": 11}},
///     }))
///     .unwrap()
/// };
/// assert!(CheckedHierarchyItem::from_client(wire(1)).is_ok());
/// assert_matches!(
///     CheckedHierarchyItem::from_client(wire(0)),
///     Err(InvalidHierarchyItem::Range(_))
/// );
/// ```
#[derive(Debug, Clone)]
pub struct CheckedHierarchyItem {
    pub(super) name: String,
    pub(super) kind: u32,
    pub(super) detail: Option<String>,
    pub(super) uri: String,
    pub(super) range: PositionRange,
    pub(super) selection_range: PositionRange,
    pub(super) data: Option<serde_json::Value>,
}

impl CheckedHierarchyItem {
    /// Validates the ranges of a client-supplied item.
    ///
    /// # Errors
    ///
    /// Returns which range was zero-based, above [`MAX_POSITION_VALUE`] or
    /// reversed. Containment of `selectionRange` in `range` is not checked.
    pub fn from_client(item: HierarchyItem) -> Result<Self, InvalidHierarchyItem> {
        let range = checked_range(&item.range).map_err(InvalidHierarchyItem::Range)?;
        let selection_range =
            checked_range(&item.selection_range).map_err(InvalidHierarchyItem::SelectionRange)?;
        Ok(Self {
            name: item.name,
            kind: item.kind,
            detail: item.detail,
            uri: item.uri,
            range,
            selection_range,
            data: item.data,
        })
    }

    /// The item's document URI, as the client sent it.
    #[must_use]
    pub fn uri(&self) -> &str {
        &self.uri
    }
}

fn checked_range(range: &Range) -> Result<PositionRange, InvalidRange> {
    PositionRange::from_client(
        (range.start.line, range.start.character),
        (range.end.line, range.end.character),
    )
}

/// Result of a type hierarchy prepare, supertypes or subtypes request.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct TypeHierarchyResult {
    /// Type hierarchy items at the position, or the supertypes/subtypes of
    /// the queried item.
    pub items: Vec<HierarchyItem>,
    /// Whether `items` was capped below the server's full response.
    ///
    /// See `MAX_NORMALIZED_LOCATIONS`. Omitted (defaults to `false`) when serialized.
    #[serde(default, skip_serializing_if = "is_false")]
    pub truncated: bool,
    /// Set only when some `character` offsets are inexact (non-UTF-16 servers); omitted otherwise.
    ///
    /// Tells whether the queried position or only the returned offsets are affected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(with = "PositionDegradation")]
    pub positions_degraded: Option<PositionDegradation>,
}

/// Whether the symbol at a position can be renamed, as answered by
/// `textDocument/prepareRename`.
///
/// # Examples
///
/// ```
/// use mcpls_core::bridge::PrepareRenameOutcome;
///
/// let outcome = PrepareRenameOutcome::NotRenameable { server_message: None };
/// assert_eq!(
///     serde_json::to_value(&outcome).unwrap(),
///     serde_json::json!({"status": "not_renameable"})
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum PrepareRenameOutcome {
    /// The identifier can be renamed.
    Renameable {
        /// Range of the identifier that a rename would replace.
        range: Range,
        /// Current name of the identifier, when the server supplies it.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        placeholder: Option<String>,
    },
    /// The server accepts a rename here but leaves the identifier range to the client.
    ///
    /// The client applies its own word-selection rule; no range is invented.
    DefaultBehavior,
    /// The position cannot be renamed. Distinct from a transport failure and
    /// from a server that does not support rename preparation.
    NotRenameable {
        /// The server's own explanation, when it reported one as an error.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        server_message: Option<String>,
    },
}

/// Result of a prepare rename request.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PrepareRenameResult {
    /// The rename-preparation verdict.
    #[serde(flatten)]
    pub outcome: PrepareRenameOutcome,
    /// Set only when some `character` offsets are inexact (non-UTF-16 servers); omitted otherwise.
    ///
    /// Tells whether the queried position or only the returned offsets are affected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(with = "PositionDegradation")]
    pub positions_degraded: Option<PositionDegradation>,
}

/// How a document highlight occurrence uses its symbol.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum DocumentHighlightKind {
    /// A textual occurrence; also what a server that omits the kind means.
    Text,
    /// A read access, such as reading a variable.
    Read,
    /// A write access, such as assigning a variable.
    Write,
}

/// One occurrence of a symbol within a document.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DocumentHighlightEntry {
    /// Range of the occurrence.
    pub range: Range,
    /// How the occurrence uses the symbol.
    pub kind: DocumentHighlightKind,
}

/// Most ranges one selection chain returns; a longer chain is cut to its
/// innermost ranges.
pub const MAX_SELECTION_CHAIN: usize = 32;

/// Result of a selection range request: the ranges enclosing a position.
///
/// # Examples
///
/// ```
/// use mcpls_core::bridge::{MAX_SELECTION_CHAIN, SelectionRangesResult};
///
/// let result: SelectionRangesResult = serde_json::from_value(serde_json::json!({
///     "ranges": [],
/// }))?;
/// assert!(result.ranges.is_empty() && !result.truncated);
/// assert_eq!(MAX_SELECTION_CHAIN, 32);
/// # Ok::<(), serde_json::Error>(())
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SelectionRangesResult {
    /// Ranges enclosing the position, innermost first, as the server reported them.
    ///
    /// They are not merged, reordered or added to.
    pub ranges: Vec<Range>,
    /// Whether the chain was longer than `MAX_SELECTION_CHAIN` and the
    /// outermost ranges were dropped. Omitted when `false`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub truncated: bool,
    /// Set only when the queried position or some `character` offsets are inexact (non-UTF-16).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(with = "PositionDegradation")]
    pub positions_degraded: Option<PositionDegradation>,
}

/// Largest `collapsed_text` returned for a folding region, in bytes before the
/// truncation marker.
pub const MAX_COLLAPSED_TEXT_BYTES: usize = 256;

/// What a folding region covers, from the LSP's open-string kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FoldingKind {
    /// A comment block.
    Comment,
    /// An import group.
    Imports,
    /// A marked region.
    Region,
    /// No kind, or a server-defined one.
    Unspecified,
}

/// Which folding regions to return.
///
/// `Unspecified` regions are returned only by [`Self::All`]. Accepted in any
/// case, like every other kind filter.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum FoldingKindFilter {
    /// Every region.
    #[default]
    All,
    /// Comment blocks only.
    Comment,
    /// Import groups only.
    Imports,
    /// Marked regions only.
    Region,
}

/// Schema of the closed string sets, compact on the wire.
impl JsonSchema for FoldingKind {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "FoldingKind".into()
    }

    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({
            "type": "string",
            "enum": ["comment", "imports", "region", "unspecified"],
        })
    }
}

impl JsonSchema for FoldingKindFilter {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        Self::SCHEMA_NAME.into()
    }

    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        Self::schema()
    }
}

kind_filter::closed_kind_filter!(FoldingKindFilter, "FoldingKindFilter");

impl FoldingKindFilter {
    /// Every filter, in documentation order.
    pub const ALL: [Self; 4] = [Self::All, Self::Comment, Self::Imports, Self::Region];

    /// The lowercase spelling the schema documents.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::All => "all",
            Self::Comment => "comment",
            Self::Imports => "imports",
            Self::Region => "region",
        }
    }

    /// Whether a region of `kind` passes this filter.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcpls_core::bridge::{FoldingKind, FoldingKindFilter};
    ///
    /// assert!(FoldingKindFilter::All.admits(FoldingKind::Unspecified));
    /// assert!(FoldingKindFilter::Imports.admits(FoldingKind::Imports));
    /// assert!(!FoldingKindFilter::Imports.admits(FoldingKind::Unspecified));
    /// ```
    #[must_use]
    pub const fn admits(self, kind: FoldingKind) -> bool {
        matches!(
            (self, kind),
            (Self::All, _)
                | (Self::Comment, FoldingKind::Comment)
                | (Self::Imports, FoldingKind::Imports)
                | (Self::Region, FoldingKind::Region)
        )
    }
}

/// One foldable region of a file, 1-based.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct FoldingRegion {
    /// First line.
    pub start_line: u32,
    /// Last line.
    pub end_line: u32,
    /// Where the fold starts, when the server says; absent means line end.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub start_character: Option<u32>,
    /// Where the fold ends, when the server says; absent means line end.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end_character: Option<u32>,
    /// Region kind.
    pub kind: FoldingKind,
    /// Text shown in place of the fold, when the server gives it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub collapsed_text: Option<String>,
}

/// Result of a folding range request.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct FoldingRangesResult {
    /// The regions, by ascending start line then descending end line.
    pub regions: Vec<FoldingRegion>,
    /// Whether more matching regions exist than are returned. Omitted when
    /// `false`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub truncated: bool,
    /// Set only when some `character` offsets are inexact (non-UTF-16 servers); omitted otherwise.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(with = "PositionDegradation")]
    pub positions_degraded: Option<PositionDegradation>,
}

/// Result of a document highlights request.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DocumentHighlightsResult {
    /// Occurrences of the symbol at the position within the file.
    pub highlights: Vec<DocumentHighlightEntry>,
    /// Whether `highlights` was capped below the server's full response.
    ///
    /// See `MAX_NORMALIZED_LOCATIONS`. Omitted (defaults to `false`) when serialized.
    #[serde(default, skip_serializing_if = "is_false")]
    pub truncated: bool,
    /// Set only when some `character` offsets are inexact (non-UTF-16 servers); omitted otherwise.
    ///
    /// Tells whether the queried position or only the returned offsets are affected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(with = "PositionDegradation")]
    pub positions_degraded: Option<PositionDegradation>,
}

impl ServerText for Location {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            uri,
            range: _,
            out_of_workspace: _,
        } = self;
        redactions.note_payload(uri);
    }
}

impl ServerText for HoverResult {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            contents,
            range: _,
            positions_degraded: _,
        } = self;
        redactions.redact_in_place(contents);
    }
}

impl ServerText for LocationsResult {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            locations,
            truncated: _,
            positions_degraded: _,
            enrichment: _,
        } = self;
        locations.redact_server_text(redactions);
    }
}

impl ServerText for ReferencesResult {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            result,
            index_coverage: _,
        } = self;
        result.redact_server_text(redactions);
    }
}

impl ServerText for Diagnostic {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            range: _,
            severity: _,
            message,
            code,
        } = self;
        redactions.redact_in_place(message);
        if let Some(code) = code {
            redactions.redact_in_place(code);
        }
    }
}

// Document diagnostics are redacted where they enter the cache or the pull path.
impl ServerText for DiagnosticsResult {
    fn redact_server_text(&mut self, _redactions: &Redactions) {
        let Self {
            diagnostics: _,
            positions_degraded: _,
        } = self;
    }
}

impl ServerText for DocumentDiagnosticsResult {
    fn redact_server_text(&mut self, _redactions: &Redactions) {
        let Self {
            diagnostics: _,
            positions_degraded: _,
            enrichment: _,
        } = self;
    }
}

impl ServerText for TextEdit {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self { range: _, new_text } = self;
        redactions.note_payload(new_text);
    }
}

impl ServerText for DocumentChanges {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self { uri, edits } = self;
        redactions.note_payload(uri);
        edits.redact_server_text(redactions);
    }
}

impl ServerText for RenameResult {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            changes,
            dropped: _,
            positions_degraded: _,
        } = self;
        changes.redact_server_text(redactions);
    }
}

impl ServerText for Completion {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            label,
            kind: _,
            detail,
            documentation,
        } = self;
        redactions.note_payload(label);
        for prose in [detail, documentation].into_iter().flatten() {
            redactions.redact_in_place(prose);
        }
    }
}

impl ServerText for CompletionsResult {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            items,
            positions_degraded: _,
        } = self;
        items.redact_server_text(redactions);
    }
}

impl ServerText for Symbol {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            name,
            kind: _,
            range: _,
            selection_range: _,
            children,
        } = self;
        redactions.note_payload(name);
        if let Some(children) = children {
            children.redact_server_text(redactions);
        }
    }
}

impl ServerText for DocumentSymbolsResult {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            symbols,
            positions_degraded: _,
        } = self;
        symbols.redact_server_text(redactions);
    }
}

impl ServerText for FormatDocumentResult {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            edits,
            positions_degraded: _,
        } = self;
        edits.redact_server_text(redactions);
    }
}

impl ServerText for WorkspaceSymbol {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            name,
            kind: _,
            location,
            container_name,
        } = self;
        redactions.note_payload(name);
        if let Some(container) = container_name {
            redactions.note_payload(container);
        }
        location.redact_server_text(redactions);
    }
}

impl ServerText for WorkspaceSymbolResult {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            symbols,
            truncated: _,
            positions_degraded: _,
            index_coverage: _,
        } = self;
        symbols.redact_server_text(redactions);
    }
}

impl ServerText for CodeAction {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            title,
            kind: _,
            diagnostics,
            edit,
            command,
            is_preferred: _,
        } = self;
        redactions.redact_in_place(title);
        diagnostics.redact_server_text(redactions);
        edit.redact_server_text(redactions);
        command.redact_server_text(redactions);
    }
}

impl ServerText for WorkspaceEditDescription {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            changes,
            dropped: _,
        } = self;
        changes.redact_server_text(redactions);
    }
}

impl ServerText for CommandDescription {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            title,
            command,
            arguments,
        } = self;
        redactions.redact_in_place(title);
        redactions.note_payload(command);
        for argument in arguments {
            redactions.note_payload_json(argument);
        }
    }
}

impl ServerText for CodeActionsResult {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            actions,
            truncated: _,
            positions_degraded: _,
        } = self;
        actions.redact_server_text(redactions);
    }
}

impl ServerText for CallHierarchyPrepareResult {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            items,
            truncated: _,
            positions_degraded: _,
        } = self;
        items.redact_server_text(redactions);
    }
}

impl ServerText for IncomingCall {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            from,
            from_ranges: _,
        } = self;
        from.redact_server_text(redactions);
    }
}

impl ServerText for IncomingCallsResult {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            calls,
            truncated: _,
            positions_degraded: _,
        } = self;
        calls.redact_server_text(redactions);
    }
}

impl ServerText for OutgoingCall {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self { to, from_ranges: _ } = self;
        to.redact_server_text(redactions);
    }
}

impl ServerText for OutgoingCallsResult {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            calls,
            truncated: _,
            positions_degraded: _,
        } = self;
        calls.redact_server_text(redactions);
    }
}

// Logs and messages are redacted when the notification enters the cache.
impl ServerText for ServerLogsResult {
    fn redact_server_text(&mut self, _redactions: &Redactions) {
        let Self { logs: _ } = self;
    }
}

impl ServerText for ServerMessagesResult {
    fn redact_server_text(&mut self, _redactions: &Redactions) {
        let Self { messages: _ } = self;
    }
}

impl ServerText for SignatureParameter {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            label,
            documentation,
        } = self;
        for prose in [label, documentation].into_iter().flatten() {
            redactions.redact_in_place(prose);
        }
    }
}

impl ServerText for SignatureInfo {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            label,
            documentation,
            parameters,
        } = self;
        redactions.redact_in_place(label);
        if let Some(documentation) = documentation {
            redactions.redact_in_place(documentation);
        }
        parameters.redact_server_text(redactions);
    }
}

impl ServerText for SignatureHelpResult {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            signatures,
            active_signature: _,
            active_parameter: _,
            positions_degraded: _,
        } = self;
        signatures.redact_server_text(redactions);
    }
}

impl ServerText for InlayHintEntry {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            position: _,
            label,
            kind: _,
            padding_left: _,
            padding_right: _,
            tooltip,
        } = self;
        redactions.redact_in_place(label);
        if let Some(tooltip) = tooltip {
            redactions.redact_in_place(tooltip);
        }
    }
}

impl ServerText for InlayHintsResult {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            hints,
            truncated: _,
            positions_degraded: _,
        } = self;
        hints.redact_server_text(redactions);
    }
}

impl ServerText for HierarchyItem {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            name,
            kind: _,
            detail,
            uri,
            range: _,
            selection_range: _,
            data,
            out_of_workspace: _,
        } = self;
        redactions.note_payload(name);
        if let Some(detail) = detail {
            redactions.note_payload(detail);
        }
        redactions.note_payload(uri);
        if let Some(data) = data {
            redactions.note_payload_json(data);
        }
    }
}

impl ServerText for TypeHierarchyResult {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            items,
            truncated: _,
            positions_degraded: _,
        } = self;
        items.redact_server_text(redactions);
    }
}

impl ServerText for PrepareRenameOutcome {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        match self {
            Self::Renameable {
                range: _,
                placeholder,
            } => {
                if let Some(placeholder) = placeholder {
                    redactions.note_payload(placeholder);
                }
            }
            Self::DefaultBehavior => {}
            Self::NotRenameable { server_message } => {
                if let Some(message) = server_message {
                    redactions.redact_in_place(message);
                }
            }
        }
    }
}

impl ServerText for PrepareRenameResult {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            outcome,
            positions_degraded: _,
        } = self;
        outcome.redact_server_text(redactions);
    }
}

impl ServerText for DocumentHighlightsResult {
    fn redact_server_text(&mut self, _redactions: &Redactions) {
        let Self {
            highlights: _,
            truncated: _,
            positions_degraded: _,
        } = self;
    }
}

impl ServerText for FoldingRangesResult {
    fn redact_server_text(&mut self, redactions: &Redactions) {
        let Self {
            regions,
            truncated: _,
            positions_degraded: _,
        } = self;
        for region in regions {
            if let Some(text) = &mut region.collapsed_text {
                redactions.redact_in_place(text);
                *text =
                    crate::util::truncate_string(std::mem::take(text), MAX_COLLAPSED_TEXT_BYTES);
            }
        }
    }
}

impl ServerText for SelectionRangesResult {
    fn redact_server_text(&mut self, _redactions: &Redactions) {
        let Self {
            ranges: _,
            truncated: _,
            positions_degraded: _,
        } = self;
    }
}

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

    fn hierarchy_wire(range: [u32; 4], selection: [u32; 4]) -> HierarchyItem {
        let at = |line, character| serde_json::json!({"line": line, "character": character});
        serde_json::from_value(serde_json::json!({
            "name": "x", "kind": 5, "uri": "file:///a.rs",
            "range": {"start": at(range[0], range[1]), "end": at(range[2], range[3])},
            "selectionRange": {"start": at(selection[0], selection[1]), "end": at(selection[2], selection[3])},
        }))
        .unwrap()
    }

    #[test]
    fn checked_hierarchy_item_accepts_valid_ranges() {
        let item = CheckedHierarchyItem::from_client(hierarchy_wire([1, 1, 2, 1], [1, 7, 1, 9]));
        assert_eq!(item.unwrap().uri(), "file:///a.rs");
    }

    #[test]
    fn checked_hierarchy_item_rejects_bad_range_and_names_it() {
        for bad in [
            [0, 1, 1, 1],
            [1, 0, 1, 1],
            [1, 1, 1, 1_000_001],
            [1, 1, u32::MAX, 1],
            [2, 1, 1, 1],
        ] {
            let err =
                CheckedHierarchyItem::from_client(hierarchy_wire(bad, [1, 1, 1, 1])).unwrap_err();
            assert_matches!(err, InvalidHierarchyItem::Range(_), "{bad:?}");
            let err =
                CheckedHierarchyItem::from_client(hierarchy_wire([1, 1, 9, 1], bad)).unwrap_err();
            assert_matches!(err, InvalidHierarchyItem::SelectionRange(_), "{bad:?}");
        }
    }

    #[test]
    fn checked_hierarchy_item_rejects_selection_column_above_max() {
        let err = CheckedHierarchyItem::from_client(hierarchy_wire(
            [1, 1, 2, 1],
            [1, 1_000_001, 1, 1_000_001],
        ))
        .unwrap_err();
        assert_eq!(
            err,
            InvalidHierarchyItem::SelectionRange(InvalidRange::Start(InvalidPosition::TooLarge))
        );
    }

    use super::*;

    #[test]
    fn test_text_fields_report_the_field_and_the_rule() {
        let blank = NewName::new("  ").unwrap_err();
        assert_eq!(blank.to_string(), "`new_name` cannot be empty");

        let long = NewName::new("x".repeat(MAX_NEW_NAME_LENGTH + 1)).unwrap_err();
        assert_eq!(
            long.reason,
            InvalidBoundedText::TooLong {
                len: MAX_NEW_NAME_LENGTH + 1,
                max: MAX_NEW_NAME_LENGTH,
            }
        );
        assert_eq!(
            NewName::new(" keeps spaces ").unwrap().as_str(),
            " keeps spaces "
        );

        let empty = CompletionTrigger::new("").unwrap_err();
        assert_eq!(empty.field, TextField::Trigger);
        assert_eq!(empty.reason, InvalidBoundedText::Blank);
        assert_eq!(CompletionTrigger::new(" ").unwrap().as_str(), " ");
        assert!(CompletionTrigger::new("x".repeat(MAX_TRIGGER_CHARACTER_BYTES)).is_ok());
        assert_eq!(
            CompletionTrigger::new("x".repeat(MAX_TRIGGER_CHARACTER_BYTES + 1))
                .unwrap_err()
                .reason,
            InvalidBoundedText::TooLong {
                len: MAX_TRIGGER_CHARACTER_BYTES + 1,
                max: MAX_TRIGGER_CHARACTER_BYTES,
            }
        );
    }

    const SECRET: &str = "SuperSecretValue123";

    fn range() -> Range {
        Range {
            start: Position2D {
                line: 1,
                character: 1,
            },
            end: Position2D {
                line: 1,
                character: 2,
            },
        }
    }

    #[test]
    fn test_server_text_redacts_prose_and_leaves_edit_payload() {
        let set = Redactions::new([("API_TOKEN".to_owned(), SECRET.to_owned())]);
        let mut actions = vec![CodeAction {
            title: format!("fix {SECRET}"),
            kind: None,
            diagnostics: vec![Diagnostic {
                range: range(),
                severity: ReportedSeverity::Error,
                message: format!("bad {SECRET}"),
                code: Some(format!("E-{SECRET}")),
            }],
            edit: Some(WorkspaceEditDescription {
                changes: vec![DocumentChanges {
                    uri: format!("file:///{SECRET}.rs"),
                    edits: vec![TextEdit {
                        range: range(),
                        new_text: format!("let k = \"{SECRET}\";"),
                    }],
                }],
                dropped: DroppedEdits::default(),
            }),
            command: None,
            is_preferred: false,
        }];

        actions.redact_server_text(&set);

        let action = &actions[0];
        assert_eq!(action.title, "fix [redacted:API_TOKEN]");
        assert_eq!(action.diagnostics[0].message, "bad [redacted:API_TOKEN]");
        assert_eq!(
            action.diagnostics[0].code.as_deref(),
            Some("E-[redacted:API_TOKEN]")
        );
        let changes = &action.edit.as_ref().unwrap().changes[0];
        assert!(changes.uri.contains(SECRET));
        assert!(changes.edits[0].new_text.contains(SECRET));
    }

    #[test]
    fn test_server_text_completion_keeps_label_and_redacts_detail_and_documentation() {
        let set = Redactions::new([("API_TOKEN".to_owned(), SECRET.to_owned())]);
        let mut completion = Completion {
            label: format!("use_{SECRET}"),
            kind: Some(3),
            detail: Some(format!("fn {SECRET}()")),
            documentation: Some(format!("docs {SECRET}")),
        };

        completion.redact_server_text(&set);

        assert_eq!(completion.label, format!("use_{SECRET}"));
        assert_eq!(
            completion.detail.as_deref(),
            Some("fn [redacted:API_TOKEN]()")
        );
        assert_eq!(
            completion.documentation.as_deref(),
            Some("docs [redacted:API_TOKEN]")
        );
    }

    #[test]
    fn test_server_text_redacts_signature_label_documentation_and_parameters() {
        let set = Redactions::new([("API_TOKEN".to_owned(), SECRET.to_owned())]);
        let mut result = SignatureHelpResult {
            signatures: vec![SignatureInfo {
                label: format!("f({SECRET})"),
                documentation: Some(format!("doc {SECRET}")),
                parameters: vec![SignatureParameter {
                    label: Some(format!("p {SECRET}")),
                    documentation: Some(format!("pd {SECRET}")),
                }],
            }],
            active_signature: Some(0),
            active_parameter: Some(0),
            positions_degraded: None,
        };

        result.redact_server_text(&set);

        let json = serde_json::to_string(&result).unwrap();
        assert!(!json.contains(SECRET), "{json}");
        assert_eq!(json.matches("[redacted:API_TOKEN]").count(), 4, "{json}");
    }

    #[test]
    fn test_server_text_redacts_inlay_label_and_tooltip() {
        let set = Redactions::new([("API_TOKEN".to_owned(), SECRET.to_owned())]);
        let mut hint = InlayHintEntry {
            position: Position2D {
                line: 1,
                character: 1,
            },
            label: format!(": {SECRET}"),
            kind: None,
            padding_left: None,
            padding_right: None,
            tooltip: Some(format!("tip {SECRET}")),
        };

        hint.redact_server_text(&set);

        assert_eq!(hint.label, ": [redacted:API_TOKEN]");
        assert_eq!(hint.tooltip.as_deref(), Some("tip [redacted:API_TOKEN]"));
    }

    #[test]
    fn test_server_text_command_redacts_title_and_keeps_command_and_arguments() {
        let set = Redactions::new([("API_TOKEN".to_owned(), SECRET.to_owned())]);
        let mut command = CommandDescription {
            title: format!("run {SECRET}"),
            command: format!("cmd.{SECRET}"),
            arguments: vec![serde_json::json!({ "key": SECRET })],
        };

        command.redact_server_text(&set);

        assert_eq!(command.title, "run [redacted:API_TOKEN]");
        assert_eq!(command.command, format!("cmd.{SECRET}"));
        assert_eq!(
            command.arguments,
            vec![serde_json::json!({ "key": SECRET })]
        );
    }

    #[test]
    fn test_server_text_leaves_symbol_and_hierarchy_identifiers() {
        let set = Redactions::new([("API_TOKEN".to_owned(), SECRET.to_owned())]);
        let mut symbols = DocumentSymbolsResult {
            symbols: vec![Symbol {
                name: format!("sym_{SECRET}"),
                kind: 12,
                range: range(),
                selection_range: range(),
                children: Some(vec![Symbol {
                    name: format!("child_{SECRET}"),
                    kind: 12,
                    range: range(),
                    selection_range: range(),
                    children: None,
                }]),
            }],
            positions_degraded: None,
        };
        let mut item = HierarchyItem {
            name: format!("call_{SECRET}"),
            kind: 12,
            detail: Some(format!("detail {SECRET}")),
            uri: format!("file:///{SECRET}.rs"),
            range: range(),
            selection_range: range(),
            data: Some(serde_json::json!({ "id": SECRET })),
            out_of_workspace: false,
        };
        let mut type_item = HierarchyItem {
            name: format!("type_{SECRET}"),
            kind: 5,
            detail: None,
            uri: format!("file:///{SECRET}.rs"),
            range: range(),
            selection_range: range(),
            data: None,
            out_of_workspace: false,
        };
        let before = (
            serde_json::to_string(&symbols).unwrap(),
            serde_json::to_string(&item).unwrap(),
            serde_json::to_string(&type_item).unwrap(),
        );

        symbols.redact_server_text(&set);
        item.redact_server_text(&set);
        type_item.redact_server_text(&set);

        let after = (
            serde_json::to_string(&symbols).unwrap(),
            serde_json::to_string(&item).unwrap(),
            serde_json::to_string(&type_item).unwrap(),
        );
        assert_eq!(before, after);
    }

    #[test]
    fn test_server_text_with_no_secrets_rewrites_nothing() {
        let mut hover = HoverResult {
            contents: format!("doc {SECRET}"),
            range: None,
            positions_degraded: None,
        };

        hover.redact_server_text(&Redactions::default());

        assert_eq!(hover.contents, format!("doc {SECRET}"));
    }

    #[test]
    fn test_server_text_does_not_touch_already_redacted_diagnostics() {
        let set = Redactions::new([("API_TOKEN".to_owned(), SECRET.to_owned())]);
        let mut result = DocumentDiagnosticsResult {
            diagnostics: vec![ContextualDiagnostic::from(Diagnostic {
                range: range(),
                severity: ReportedSeverity::Error,
                message: format!("echo {SECRET}"),
                code: None,
            })],
            positions_degraded: None,
            enrichment: None,
        };

        result.redact_server_text(&set);

        assert_eq!(result.diagnostics[0].message, format!("echo {SECRET}"));
    }

    #[test]
    fn test_server_text_redacts_hover_and_prepare_rename_message() {
        let set = Redactions::new([("API_TOKEN".to_owned(), SECRET.to_owned())]);
        let mut hover = HoverResult {
            contents: format!("doc {SECRET}"),
            range: None,
            positions_degraded: None,
        };
        let mut outcome = PrepareRenameOutcome::NotRenameable {
            server_message: Some(format!("no {SECRET}")),
        };

        hover.redact_server_text(&set);
        outcome.redact_server_text(&set);

        assert_eq!(hover.contents, "doc [redacted:API_TOKEN]");
        assert_eq!(
            outcome,
            PrepareRenameOutcome::NotRenameable {
                server_message: Some("no [redacted:API_TOKEN]".to_owned())
            }
        );
    }

    #[test]
    fn test_position_degradation_request_outranks_response() {
        assert!(PositionDegradation::Request > PositionDegradation::Response);
        assert_eq!(
            Some(PositionDegradation::Response).max(Some(PositionDegradation::Request)),
            Some(PositionDegradation::Request)
        );
        assert_eq!(
            None.max(Some(PositionDegradation::Response)),
            Some(PositionDegradation::Response)
        );
    }

    #[test]
    fn test_position_degradation_serializes_as_snake_case_string() {
        assert_eq!(
            serde_json::to_value(PositionDegradation::Request).unwrap(),
            "request"
        );
        assert_eq!(
            serde_json::to_value(PositionDegradation::Response).unwrap(),
            "response"
        );
    }

    #[test]
    fn test_positions_degraded_key_omitted_when_none() {
        let result = super::DocumentSymbolsResult {
            symbols: Vec::new(),
            positions_degraded: None,
        };
        let value = serde_json::to_value(&result).unwrap();
        assert!(value.get("positions_degraded").is_none());

        let result = super::DocumentSymbolsResult {
            positions_degraded: Some(PositionDegradation::Response),
            ..result
        };
        let value = serde_json::to_value(&result).unwrap();
        assert_eq!(value["positions_degraded"], "response");
    }

    /// #467 regression: the old `Option<u8>` narrowing silently dropped any
    /// `InlayHintKind::Custom(n)` with `n > 255` to `None`, indistinguishable
    /// from "server sent no kind". `lsp_kind_to_u32` must preserve the full
    /// `u32` value losslessly.
    #[test]
    fn test_lsp_kind_to_u32_preserves_custom_values_above_u8_range() {
        let kind = lsp_types::InlayHintKind::Custom(300);
        assert_eq!(lsp_kind_to_u32(kind), 300u32);
    }

    #[test]
    fn test_position_from_client_bounds() {
        assert_eq!(Position::from_client(0, 1), Err(InvalidPosition::ZeroBased));
        assert_eq!(Position::from_client(1, 0), Err(InvalidPosition::ZeroBased));
        assert_eq!(
            Position::from_client(MAX_POSITION_VALUE + 1, 1),
            Err(InvalidPosition::TooLarge)
        );
        assert_eq!(
            Position::from_client(1, MAX_POSITION_VALUE + 1),
            Err(InvalidPosition::TooLarge)
        );
        let max = Position::from_client(MAX_POSITION_VALUE, MAX_POSITION_VALUE).unwrap();
        assert_eq!((max.lsp_line(), max.lsp_character()), (999_999, 999_999));
    }

    #[test]
    fn test_position_from_output_position_is_not_capped_and_clamps_zero() {
        let big = Position::from_server_output(&Position2D {
            line: MAX_POSITION_VALUE + 7,
            character: 2_000_000,
        });
        assert_eq!(big.line().get(), MAX_POSITION_VALUE + 7);
        let clamped = Position::from_server_output(&Position2D {
            line: 0,
            character: 0,
        });
        assert_eq!((clamped.line().get(), clamped.character().get()), (1, 1));
    }

    #[test]
    fn test_position_range_orders_and_bounds() {
        let at = Position::at;
        assert!(PositionRange::new(at(1, 5), at(1, 5)).is_ok());
        assert_eq!(
            PositionRange::new(at(2, 1), at(1, 9)),
            Err(InvalidRange::Reversed)
        );
        assert_eq!(
            PositionRange::new(at(1, 5), at(1, 4)),
            Err(InvalidRange::Reversed)
        );
        assert_eq!(
            PositionRange::from_client((0, 1), (1, 1)),
            Err(InvalidRange::Start(InvalidPosition::ZeroBased))
        );
        assert_eq!(
            PositionRange::from_client((1, 1), (1, 0)),
            Err(InvalidRange::End(InvalidPosition::ZeroBased))
        );

        let within = PositionRange::new(at(1, 1), at(1 + MAX_RANGE_LINES, 1)).unwrap();
        assert!(BoundedRange::try_from(within).is_ok());
        let beyond = PositionRange::new(at(1, 1), at(2 + MAX_RANGE_LINES, 1)).unwrap();
        assert_eq!(
            BoundedRange::try_from(beyond),
            Err(InvalidRange::TooManyLines)
        );
    }

    #[test]
    fn test_folding_kind_schema_lists_exactly_the_serde_names() {
        let kinds = |k: FoldingKind| match k {
            FoldingKind::Comment
            | FoldingKind::Imports
            | FoldingKind::Region
            | FoldingKind::Unspecified => k,
        };
        let variants = [
            FoldingKind::Comment,
            FoldingKind::Imports,
            FoldingKind::Region,
            FoldingKind::Unspecified,
        ]
        .map(kinds);
        let mut generator = schemars::SchemaGenerator::default();
        let schema = FoldingKind::json_schema(&mut generator);
        let listed: Vec<String> = schema
            .get("enum")
            .unwrap()
            .as_array()
            .unwrap()
            .iter()
            .map(|name| name.as_str().unwrap().to_owned())
            .collect();
        let serialized: Vec<String> = variants
            .iter()
            .map(|k| {
                serde_json::to_value(k)
                    .unwrap()
                    .as_str()
                    .unwrap()
                    .to_owned()
            })
            .collect();
        assert_eq!(listed, serialized);
    }

    #[test]
    fn test_folding_kind_filter_schema_lists_exactly_the_serde_names() {
        let filters = |f: FoldingKindFilter| match f {
            FoldingKindFilter::All
            | FoldingKindFilter::Comment
            | FoldingKindFilter::Imports
            | FoldingKindFilter::Region => f,
        };
        let variants = FoldingKindFilter::ALL.map(filters);
        let schema = FoldingKindFilter::schema();
        let listed: Vec<FoldingKindFilter> = schema
            .get("enum")
            .unwrap()
            .as_array()
            .unwrap()
            .iter()
            .map(|name| FoldingKindFilter::parse(name.as_str().unwrap()).unwrap())
            .collect();
        assert_eq!(listed, variants);
        assert_eq!(
            FoldingKindFilter::parse("IMPORTS"),
            Some(FoldingKindFilter::Imports)
        );
        assert_eq!(FoldingKindFilter::parse("unspecified"), None);
    }

    #[test]
    fn test_folding_collapsed_text_is_redacted_before_it_is_cut() {
        use crate::redaction::{Redactions, ServerText as _};

        let secret = "bravo-secret-222";
        let redactions = Redactions::new([("B_TOKEN".to_owned(), secret.to_owned())]);
        let straddling = format!("{}{secret}tail", "x".repeat(MAX_COLLAPSED_TEXT_BYTES - 8));
        let region = |text: String| FoldingRegion {
            start_line: 1,
            end_line: 2,
            start_character: None,
            end_character: None,
            kind: FoldingKind::Region,
            collapsed_text: Some(text),
        };
        let mut result = FoldingRangesResult {
            regions: vec![region(straddling), region("short".to_string())],
            truncated: false,
            positions_degraded: None,
        };

        result.redact_server_text(&redactions);

        let text = result.regions[0].collapsed_text.as_deref().unwrap();
        assert!(!text.contains("bravo"), "{text}");
        assert!(text.ends_with("... (truncated)"), "{text}");
        assert!(text.len() <= MAX_COLLAPSED_TEXT_BYTES + "... (truncated)".len());
        assert_eq!(result.regions[1].collapsed_text.as_deref(), Some("short"));
    }
}