shape-lsp 0.3.2

Language Server Protocol implementation for Shape
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
//! Inlay hints provider for Shape
//!
//! Provides inline type hints for variables and parameter name hints for function calls.
//! Uses the Visitor trait for exhaustive AST traversal.

use std::collections::HashMap;

use crate::type_inference::simplify_result_type;
use crate::util::offset_to_position;
use shape_ast::ast::expr_helpers::ComptimeForExpr;
use shape_ast::ast::{
    Expr, FunctionDef, Item, Program, Span, Spanned, Statement, TypeAnnotation, VariableDecl,
};
use shape_ast::parser::parse_program;
use shape_runtime::visitor::{Visitor, walk_program};
use tower_lsp_server::ls_types::{InlayHint, InlayHintKind, InlayHintLabel, Position, Range};

use crate::type_inference::{
    FunctionTypeInfo, ParamReferenceMode, infer_expr_type, infer_expr_type_via_engine,
    infer_expr_type_with_env_public, infer_function_signatures, infer_program_types,
    infer_program_types_with_context, infer_variable_type_for_display, unified_metadata,
};

/// Configuration for inlay hints
#[derive(Debug, Clone)]
pub struct InlayHintConfig {
    pub show_type_hints: bool,
    pub show_parameter_hints: bool,
    /// Show `: type` hints after variable names in let/var/const without explicit annotations
    pub show_variable_type_hints: bool,
    /// Show `-> type` hints after function parameter lists without explicit return annotations
    pub show_return_type_hints: bool,
    /// W2.4 / 1.27: render the inferred type after every intermediate `.method()`
    /// call in a method chain (e.g. `xs.map(f).filter(g).sum()` → hint after
    /// `.map(f)` and `.filter(g)`).
    pub show_chain_hints: bool,
    /// W2.4 / 1.25 + LSP-I (R8 W11): render an approximate
    /// `BindingStorageClass` label after `let`/`var` bindings. The five
    /// ADR-006 §2 categories — `[Direct]` / `[UniqueHeap]` / `[SharedCow]` /
    /// `[SharedAtomic]` / `[SharedAtomicMut]` — are rendered as best-effort
    /// labels from the LSP-side AST (the authoritative classifier lives in
    /// the bytecode compiler at `crates/shape-vm/src/type_tracking.rs:286`
    /// + the MIR borrow solver). Always surfaced with the `[… approx]`
    /// qualifier so the user knows it is not the compiler verdict.
    ///
    /// **Standing pattern (binding 2026-05-26):** Shape-unique inlay hints
    /// (chain hints, binding-storage-class hints, anything not Rust/TS
    /// idiomatic) ship **opt-in default-OFF** under the `shape.inlayHints.*`
    /// namespace. The canonical LSP key for this toggle is
    /// `shape.inlayHints.bindingStorageClass.enable: boolean` (Decision 2
    /// ratify). The legacy `bindingKindHints` key (W2.4 / 1.25 vintage) is
    /// accepted as an alias for backward compatibility; future inlay-hint
    /// sub-clusters should follow the same opt-in default-OFF shape.
    pub show_binding_kind_hints: bool,
}

impl Default for InlayHintConfig {
    fn default() -> Self {
        Self {
            show_type_hints: true,
            show_parameter_hints: true,
            show_variable_type_hints: true,
            show_return_type_hints: true,
            show_chain_hints: true,
            show_binding_kind_hints: false,
        }
    }
}

impl InlayHintConfig {
    /// W2.4 / 1.70 + LSP-I (R8 W11): parse an `InlayHintConfig` from a
    /// `workspace/configuration` JSON value. Honors keys such as
    /// `shape.inlayHints.enable`, `shape.inlayHints.typeHints`,
    /// `shape.inlayHints.parameterHints`, `shape.inlayHints.variableTypeHints`,
    /// `shape.inlayHints.returnTypeHints`, `shape.inlayHints.chainHints`,
    /// `shape.inlayHints.bindingStorageClass.enable` (canonical Decision 2 key
    /// for binding-storage-class hints), and `shape.inlayHints.bindingKindHints`
    /// (legacy W2.4 / 1.25 alias, retained for backward compatibility).
    ///
    /// snake_case aliases (e.g. `chain_hints`, `binding_storage_class`) are also
    /// accepted. Unknown keys are ignored. Returns `Default::default()` when
    /// the input is `None` or contains no recognized keys.
    pub fn from_lsp_settings(value: Option<&serde_json::Value>) -> Self {
        let mut cfg = Self::default();
        let Some(root) = value else {
            return cfg;
        };

        // Accept the nested `shape.inlayHints` shape, or a top-level
        // `inlayHints` shape, or top-level direct keys.
        let mut sources: Vec<&serde_json::Value> = Vec::new();
        if let Some(shape) = root.get("shape") {
            if let Some(ih) = shape.get("inlayHints").or_else(|| shape.get("inlay_hints")) {
                sources.push(ih);
            }
        }
        if let Some(ih) = root.get("inlayHints").or_else(|| root.get("inlay_hints")) {
            sources.push(ih);
        }
        sources.push(root);

        let mut master = None;
        for src in &sources {
            if let Some(v) = src.get("enable").and_then(serde_json::Value::as_bool) {
                master = Some(v);
                break;
            }
        }

        let read_bool = |keys: &[&str]| -> Option<bool> {
            for src in &sources {
                for k in keys {
                    if let Some(v) = src.get(*k).and_then(serde_json::Value::as_bool) {
                        return Some(v);
                    }
                }
            }
            None
        };

        if let Some(v) = read_bool(&["typeHints", "type_hints"]) {
            cfg.show_type_hints = v;
        }
        if let Some(v) = read_bool(&["parameterHints", "parameter_hints"]) {
            cfg.show_parameter_hints = v;
        }
        if let Some(v) = read_bool(&["variableTypeHints", "variable_type_hints"]) {
            cfg.show_variable_type_hints = v;
        }
        if let Some(v) = read_bool(&["returnTypeHints", "return_type_hints"]) {
            cfg.show_return_type_hints = v;
        }
        if let Some(v) = read_bool(&["chainHints", "chain_hints"]) {
            cfg.show_chain_hints = v;
        }
        if let Some(v) = read_bool(&["bindingKindHints", "binding_kind_hints"]) {
            cfg.show_binding_kind_hints = v;
        }

        // LSP-I (R8 W11) Decision 2 canonical key:
        // `shape.inlayHints.bindingStorageClass.enable: boolean`.
        // Accepts either the nested-object shape
        //   { "bindingStorageClass": { "enable": true } }
        // (camelCase or snake_case "binding_storage_class"), or a flat boolean
        //   { "bindingStorageClass": true }
        // for client convenience. The legacy `bindingKindHints` parse above
        // remains the backward-compatible alias.
        for src in &sources {
            let nested = src
                .get("bindingStorageClass")
                .or_else(|| src.get("binding_storage_class"));
            if let Some(node) = nested {
                if let Some(v) = node.as_bool() {
                    cfg.show_binding_kind_hints = v;
                    break;
                }
                if let Some(v) = node.get("enable").and_then(serde_json::Value::as_bool) {
                    cfg.show_binding_kind_hints = v;
                    break;
                }
            }
        }

        // Master enable: when explicitly set to false, suppress everything.
        if master == Some(false) {
            cfg.show_type_hints = false;
            cfg.show_parameter_hints = false;
            cfg.show_variable_type_hints = false;
            cfg.show_return_type_hints = false;
            cfg.show_chain_hints = false;
            cfg.show_binding_kind_hints = false;
        }

        cfg
    }
}

/// Context for collecting inlay hints.
/// Implements the Visitor trait for exhaustive AST traversal.
struct HintContext<'a> {
    text: &'a str,
    program: &'a Program,
    range: Range,
    config: &'a InlayHintConfig,
    hints: Vec<InlayHint>,
    /// Program-level type map from TypeInferenceEngine (primary) + heuristic (fallback)
    type_map: HashMap<String, String>,
    /// Per-function inferred parameter and return types from TypeInferenceEngine
    function_types: HashMap<String, FunctionTypeInfo>,
    /// Offsets at which a chain hint has already been emitted, used to dedupe
    /// when the Visitor revisits inner MethodCall nodes of the chain spine
    /// (W2.4 / 1.27).
    chain_hint_offsets: std::collections::HashSet<usize>,
}

impl<'a> HintContext<'a> {
    fn is_primitive_value_type_name(name: &str) -> bool {
        let normalized = name.trim().trim_end_matches('?');
        matches!(
            normalized,
            "int"
                | "integer"
                | "i64"
                | "number"
                | "float"
                | "f64"
                | "decimal"
                | "bool"
                | "boolean"
                | "()"
                | "void"
                | "unit"
                | "none"
                | "null"
                | "undefined"
                | "never"
        )
    }

    fn split_top_level_union(type_str: &str) -> Vec<String> {
        let mut parts = Vec::new();
        let mut start = 0usize;
        let mut paren_depth = 0usize;
        let mut bracket_depth = 0usize;
        let mut brace_depth = 0usize;
        let mut angle_depth = 0usize;

        for (idx, ch) in type_str.char_indices() {
            match ch {
                '(' => paren_depth += 1,
                ')' => paren_depth = paren_depth.saturating_sub(1),
                '[' => bracket_depth += 1,
                ']' => bracket_depth = bracket_depth.saturating_sub(1),
                '{' => brace_depth += 1,
                '}' => brace_depth = brace_depth.saturating_sub(1),
                '<' => angle_depth += 1,
                '>' => angle_depth = angle_depth.saturating_sub(1),
                _ => {}
            }
            if ch == '|'
                && paren_depth == 0
                && bracket_depth == 0
                && brace_depth == 0
                && angle_depth == 0
            {
                parts.push(type_str[start..idx].trim().to_string());
                start = idx + ch.len_utf8();
            }
        }

        parts.push(type_str[start..].trim().to_string());
        parts.into_iter().filter(|part| !part.is_empty()).collect()
    }

    fn apply_ref_prefix(type_str: &str, mode: &ParamReferenceMode) -> String {
        let trimmed = type_str.trim();
        if trimmed.starts_with('&') {
            trimmed.to_string()
        } else {
            format!("{}{}", mode.prefix(), trimmed)
        }
    }

    fn format_reference_aware_type(type_str: &str, mode: Option<&ParamReferenceMode>) -> String {
        let Some(mode) = mode else {
            return type_str.to_string();
        };

        let union_parts = Self::split_top_level_union(type_str);
        if union_parts.len() <= 1 {
            return Self::apply_ref_prefix(type_str, mode);
        }

        union_parts
            .into_iter()
            .map(|part| {
                if Self::is_primitive_value_type_name(&part) {
                    part
                } else {
                    Self::apply_ref_prefix(&part, mode)
                }
            })
            .collect::<Vec<_>>()
            .join(" | ")
    }

    fn new(
        text: &'a str,
        program: &'a Program,
        range: Range,
        config: &'a InlayHintConfig,
        type_map: HashMap<String, String>,
        function_types: HashMap<String, FunctionTypeInfo>,
    ) -> Self {
        Self {
            text,
            program,
            range,
            config,
            hints: Vec::new(),
            type_map,
            function_types,
            chain_hint_offsets: std::collections::HashSet::new(),
        }
    }

    /// Collect type hint for a variable declaration without explicit type annotation.
    /// Uses the program-level type_map (from TypeInferenceEngine) first,
    /// falls back to heuristic infer_expr_type for unresolved variables.
    fn collect_variable_type_hint(&mut self, decl: &VariableDecl) {
        if !self.config.show_type_hints {
            return;
        }

        let want_type_hint =
            self.config.show_variable_type_hints && decl.type_annotation.is_none();
        let want_binding_hint = self.config.show_binding_kind_hints;

        if !want_type_hint && !want_binding_hint {
            return;
        }

        // W2.4 / 1.04: when the RHS is a closure (`FunctionExpr`), prefer
        // the LSP's `render_closure_signature` over the engine's
        // `(unknown) -> _` format — the engine erases param types when
        // unannotated; our renderer at least preserves source-annotated
        // params and surfaces inferred return types.
        let closure_signature: Option<String> = decl.value.as_ref().and_then(|v| {
            if let Expr::FunctionExpr {
                params,
                return_type,
                body,
                ..
            } = v
            {
                Some(crate::type_inference::render_closure_signature(
                    params,
                    return_type.as_ref(),
                    body,
                    &std::collections::HashMap::new(),
                ))
            } else {
                None
            }
        });

        // Try engine-inferred type from type_map first, fall back to heuristic
        let var_name = decl.pattern.as_identifier();
        let inferred_type = closure_signature.or_else(|| {
            var_name
                .and_then(|name| {
                    decl.pattern
                        .as_identifier_span()
                        .and_then(|span| {
                            if span.is_dummy() {
                                None
                            } else {
                                infer_variable_type_for_display(self.program, name, span.end)
                            }
                        })
                        .or_else(|| self.type_map.get(name).cloned())
                })
                .or_else(|| {
                    // LSP-H: program-level type_map flows in as env so the
                    // syntactic fallback can resolve identifier receivers in
                    // method-chain RHS (`xs.map(...)` learns `xs: int[]`).
                    decl.value
                        .as_ref()
                        .and_then(infer_expr_type_via_engine)
                        .or_else(|| {
                            decl.value
                                .as_ref()
                                .and_then(|v| infer_expr_type_with_env_public(v, &self.type_map))
                        })
                        .or_else(|| decl.value.as_ref().and_then(infer_expr_type))
                })
        });

        let Some(span) = decl.pattern.as_identifier_span() else {
            return;
        };
        if span.is_dummy() {
            return;
        }
        let position = offset_to_position(self.text, span.end);
        if !is_in_range(position, self.range) {
            return;
        }

        // 1.21 type hint (existing behavior, behind want_type_hint).
        if want_type_hint {
            if let Some(inferred_type) = inferred_type.as_ref() {
                // LSP-B: if the variable's initializer is a `&expr` / `&mut
                // expr` reference expression, surface the reference mode in
                // the inlay hint. The TypeInferenceEngine erases reference
                // mode on `Expr::Reference` (infers the inner expr's type
                // only) — without this prefix the hint would silently drop
                // `&` and the rendered type would diverge from what the
                // user could write as an annotation.
                let label_type = match decl.value.as_ref() {
                    Some(Expr::Reference { is_mutable, .. })
                        if !inferred_type.starts_with('&') =>
                    {
                        let prefix = if *is_mutable { "&mut " } else { "&" };
                        format!("{}{}", prefix, inferred_type)
                    }
                    _ => inferred_type.clone(),
                };
                self.hints.push(InlayHint {
                    position,
                    label: InlayHintLabel::String(format!(": {}", label_type)),
                    kind: Some(InlayHintKind::TYPE),
                    text_edits: None,
                    tooltip: None,
                    padding_left: Some(false),
                    padding_right: Some(true),
                    data: None,
                });
            }
        }

        // 1.25 binding-kind hint (LSP-side heuristic) — flagged on
        // `show_binding_kind_hints`. The compiler's `BindingStorageClass`
        // (`crates/shape-vm/src/type_tracking.rs:286`) is the authoritative
        // classifier; this LSP heuristic uses the declared/inferred type +
        // `is_mut` to render a plausible label without paying full bytecode
        // compilation cost on every keystroke.
        if want_binding_hint {
            let label_type = decl
                .type_annotation
                .as_ref()
                .and_then(crate::type_inference::type_annotation_to_string)
                .or(inferred_type.clone());
            let label = binding_kind_label_for(decl, label_type.as_deref());
            self.hints.push(InlayHint {
                position,
                label: InlayHintLabel::String(label),
                kind: Some(InlayHintKind::TYPE),
                text_edits: None,
                tooltip: Some(tower_lsp_server::ls_types::InlayHintTooltip::String(
                    "LSP-side approximation of BindingStorageClass (ADR-006 §2). The compiler's bytecode pass at crates/shape-vm/src/type_tracking.rs:286 is authoritative.".to_string(),
                )),
                padding_left: Some(true),
                padding_right: Some(true),
                data: Some(serde_json::json!({
                    "kind": "binding-kind",
                    "name": decl.pattern.as_identifier().unwrap_or_default(),
                })),
            });
        }
    }

    /// W2.4 / 1.27: emit a `: type` hint after an intermediate `.method()`
    /// call in a method chain. Skips the chain's final call (its type is
    /// already covered by `let x = chain` hints or by hover) and skips chains
    /// whose receiver is not itself a method-call / property-access (single
    /// `obj.method()` carries no chain).
    fn collect_chain_hint(&mut self, expr: &Expr) {
        if !self.config.show_type_hints || !self.config.show_chain_hints {
            return;
        }

        let Expr::MethodCall { receiver, .. } = expr else {
            return;
        };

        // Only emit hints for *intermediate* nodes — when this MethodCall is
        // itself the receiver of an outer MethodCall, we handle it from the
        // outer node so the chain renders once, in source order, top-down.
        // To detect chain depth, walk down the receiver spine and emit hints
        // for each intermediate node we find. Use a guard so we only handle
        // the outermost call.
        let outer_span = expr.span();
        if outer_span.is_dummy() {
            return;
        }

        // Walk receiver spine collecting intermediate method-call nodes whose
        // result has an inferable type.
        let mut spine: Vec<&Expr> = Vec::new();
        let mut cur: &Expr = receiver.as_ref();
        loop {
            match cur {
                Expr::MethodCall {
                    receiver: inner, ..
                } => {
                    spine.push(cur);
                    cur = inner.as_ref();
                }
                _ => break,
            }
        }

        if spine.is_empty() {
            return;
        }

        for node in spine {
            let span = node.span();
            if span.is_dummy() {
                continue;
            }
            if !self.chain_hint_offsets.insert(span.end) {
                continue;
            }
            let position = offset_to_position(self.text, span.end);
            if !is_in_range(position, self.range) {
                continue;
            }
            // Use the program-level type_map as env so an identifier receiver
            // like `xs.filter(...)` can resolve `xs`'s type from the engine.
            let inferred = infer_expr_type_via_engine(node)
                .or_else(|| crate::type_inference::infer_expr_type_with_env_public(node, &self.type_map))
                .or_else(|| infer_expr_type(node));
            let Some(inferred) = inferred else {
                continue;
            };
            self.hints.push(InlayHint {
                position,
                label: InlayHintLabel::String(format!(": {}", inferred)),
                kind: Some(InlayHintKind::TYPE),
                text_edits: None,
                tooltip: None,
                padding_left: Some(false),
                padding_right: Some(false),
                data: Some(serde_json::json!({
                    "kind": "chain",
                })),
            });
        }
    }

    /// Collect type hints for function parameters and return type.
    /// Uses types inferred by the TypeInferenceEngine — no manual AST walking.
    fn collect_function_type_hints(&mut self, func_def: &FunctionDef) {
        if !self.config.show_type_hints {
            return;
        }

        let info = match self.function_types.get(&func_def.name) {
            Some(info) => info.clone(),
            None => return,
        };

        // Parameter type hints: show `: type` after each unannotated parameter name
        for (param_name, type_str) in &info.param_types {
            // Find the matching AST parameter to get its span
            if let Some(ast_param) = func_def
                .params
                .iter()
                .find(|p| p.simple_name() == Some(param_name.as_str()))
            {
                let span = ast_param.span();
                if !span.is_dummy() {
                    let display_type = Self::format_reference_aware_type(
                        type_str,
                        info.param_ref_modes.get(param_name),
                    );
                    let position = offset_to_position(self.text, span.end);
                    if is_in_range(position, self.range) {
                        self.hints.push(InlayHint {
                            position,
                            label: InlayHintLabel::String(format!(": {}", display_type)),
                            kind: Some(InlayHintKind::TYPE),
                            text_edits: None,
                            tooltip: None,
                            padding_left: Some(false),
                            padding_right: Some(true),
                            data: None,
                        });
                    }
                }
            }
        }

        // Return type hint: show `-> type` after the closing `)` of the parameter list
        if let Some(return_type) = &info.return_type {
            if !self.config.show_return_type_hints {
                return;
            }
            if let Some(hint_offset) = self.return_hint_offset(func_def) {
                let position = offset_to_position(self.text, hint_offset);
                if is_in_range(position, self.range) {
                    let display_type = simplify_result_type(return_type);
                    self.hints.push(InlayHint {
                        position,
                        label: InlayHintLabel::String(format!("-> {}", display_type)),
                        kind: Some(InlayHintKind::TYPE),
                        text_edits: None,
                        tooltip: None,
                        padding_left: Some(true),
                        padding_right: Some(true),
                        data: None,
                    });
                }
            }
        }
    }

    /// Compute an AST-driven offset for function return inlay hints.
    ///
    /// We anchor after the closing `)` of the parameter list when possible.
    /// Fallback to the end of the last parameter span if the header cannot be
    /// recovered from source text.
    fn return_hint_offset(&self, func_def: &FunctionDef) -> Option<usize> {
        let text_len = self.text.len();
        let header_start = func_def.name_span.end.min(text_len);
        let header_tail = &self.text[header_start..];
        if let Some(open_brace_rel) = header_tail.find('{') {
            let header = &header_tail[..open_brace_rel];
            if let Some(close_paren_rel) = header.rfind(')') {
                return Some(header_start + close_paren_rel + 1);
            }
        }

        let last_param_end = func_def
            .params
            .iter()
            .filter_map(|param| {
                let span = param.span();
                if span.is_dummy() {
                    None
                } else {
                    Some(span.end)
                }
            })
            .max();

        if let Some(end) = last_param_end {
            return Some(end);
        }

        if !func_def.name_span.is_dummy() {
            return Some(func_def.name_span.end);
        }

        None
    }

    /// Collect parameter name hints for a function call
    /// Show an inlay hint for `comptime for` indicating unrolled iteration count.
    ///
    /// When the iterable is `target.fields` and we can resolve the struct type,
    /// shows the number of fields that will be unrolled. Otherwise shows a generic
    /// "comptime unrolled" indicator.
    fn collect_comptime_for_hint(&mut self, comptime_for: &ComptimeForExpr, span: &Span) {
        if span.is_dummy() {
            return;
        }

        // Try to resolve iteration count from iterable
        let hint_label =
            if let Expr::PropertyAccess { property, .. } = comptime_for.iterable.as_ref() {
                if property == "fields" {
                    // The iterable is `something.fields` — we can try to count struct fields
                    // In practice, this requires knowing what `target` refers to, which needs
                    // annotation context. For now, show a generic hint.
                    "comptime unrolled".to_string()
                } else {
                    "comptime unrolled".to_string()
                }
            } else {
                "comptime unrolled".to_string()
            };

        let position = offset_to_position(self.text, span.end);
        if is_in_range(position, self.range) {
            self.hints.push(InlayHint {
                position,
                label: InlayHintLabel::String(hint_label),
                kind: Some(InlayHintKind::TYPE),
                text_edits: None,
                tooltip: Some(tower_lsp_server::ls_types::InlayHintTooltip::String(
                    "This loop is unrolled at compile time by the comptime system.".to_string(),
                )),
                padding_left: Some(true),
                padding_right: Some(false),
                data: None,
            });
        }
    }

    /// Collect parameter-style hints for table row literals.
    /// Shows struct field names before each positional element in `[a, b, c], [d, e, f]`
    /// when the variable has a `Table<T>` type annotation.
    fn collect_table_row_hints(&mut self, decl: &VariableDecl) {
        if !self.config.show_parameter_hints {
            return;
        }

        // Check if the init expression is TableRows
        let rows = match &decl.value {
            Some(Expr::TableRows(rows, _)) => rows,
            _ => return,
        };

        // Extract inner type name from Table<T> annotation
        let inner_type = match &decl.type_annotation {
            Some(TypeAnnotation::Generic { name, args }) if name == "Table" => args
                .first()
                .and_then(|a| a.as_simple_name())
                .map(String::from),
            _ => None,
        };
        let inner_type = match inner_type {
            Some(t) => t,
            None => return,
        };

        // Find struct field names from the program
        let field_names: Vec<String> = self
            .program
            .items
            .iter()
            .find_map(|item| {
                if let Item::StructType(struct_def, _) = item {
                    if struct_def.name == inner_type {
                        Some(
                            struct_def
                                .fields
                                .iter()
                                .filter(|f| !f.is_comptime)
                                .map(|f| f.name.clone())
                                .collect(),
                        )
                    } else {
                        None
                    }
                } else {
                    None
                }
            })
            .unwrap_or_default();

        if field_names.is_empty() {
            return;
        }

        // Emit parameter hints for each element in each row
        for row in rows {
            for (i, elem) in row.iter().enumerate() {
                if let Some(field_name) = field_names.get(i) {
                    let elem_span = elem.span();
                    if !elem_span.is_dummy() {
                        let position = offset_to_position(self.text, elem_span.start);
                        if is_in_range(position, self.range) {
                            self.hints.push(InlayHint {
                                position,
                                label: InlayHintLabel::String(format!("{}:", field_name)),
                                kind: Some(InlayHintKind::PARAMETER),
                                text_edits: None,
                                tooltip: None,
                                padding_left: Some(false),
                                padding_right: Some(true),
                                data: None,
                            });
                        }
                    }
                }
            }
        }
    }

    fn collect_parameter_hints(&mut self, args: &[Expr], func_name: &str) {
        if func_name == "print" {
            return;
        }

        let func_info = unified_metadata().get_function(func_name);

        if let Some(func) = func_info {
            for (i, arg) in args.iter().enumerate() {
                if let Some(param) = func.parameters.get(i) {
                    // Don't show hints for single-letter parameter names
                    if param.name.len() > 1 {
                        // Use the argument's span to get the position before it
                        let arg_span = arg.span();
                        if !arg_span.is_dummy() {
                            let position = offset_to_position(self.text, arg_span.start);
                            if is_in_range(position, self.range) {
                                self.hints.push(InlayHint {
                                    position,
                                    label: InlayHintLabel::String(format!("{}:", param.name)),
                                    kind: Some(InlayHintKind::PARAMETER),
                                    text_edits: None,
                                    tooltip: Some(
                                        tower_lsp_server::ls_types::InlayHintTooltip::String(
                                            param.description.clone(),
                                        ),
                                    ),
                                    padding_left: Some(false),
                                    padding_right: Some(true),
                                    data: None,
                                });
                            }
                        }
                    }
                }
            }
        }
    }
}

impl<'a> Visitor for HintContext<'a> {
    fn visit_item(&mut self, item: &Item) -> bool {
        match item {
            Item::VariableDecl(decl, _) => {
                self.collect_variable_type_hint(decl);
                self.collect_table_row_hints(decl);
            }
            Item::Function(func_def, _) => self.collect_function_type_hints(func_def),
            _ => {}
        }
        true // Continue visiting children
    }

    fn visit_stmt(&mut self, stmt: &Statement) -> bool {
        // Handle variable declarations at the statement level
        if let Statement::VariableDecl(decl, _) = stmt {
            self.collect_variable_type_hint(decl);
            self.collect_table_row_hints(decl);
        }
        true // Continue visiting children
    }

    fn visit_expr(&mut self, expr: &Expr) -> bool {
        // Handle function calls for parameter hints
        if let Expr::FunctionCall { name, args, .. } = expr {
            if self.config.show_parameter_hints {
                self.collect_parameter_hints(args, name);
            }
        }

        // Handle method-chain intermediate hints (W2.4 / 1.27)
        if matches!(expr, Expr::MethodCall { .. }) {
            self.collect_chain_hint(expr);
        }

        // Handle comptime for — show unroll hint
        if let Expr::ComptimeFor(comptime_for, span) = expr {
            if self.config.show_type_hints {
                self.collect_comptime_for_hint(comptime_for, span);
            }
        }

        true // Continue visiting children
    }
}

/// Get inlay hints for a document within a range.
///
/// Hint positions must always be derived from the current text buffer.
/// On parse errors we use resilient parsing of the current text and return no
/// hints only if nothing can be recovered.
pub fn get_inlay_hints(
    text: &str,
    range: Range,
    config: &InlayHintConfig,
    _cached_program: Option<&Program>,
) -> Vec<InlayHint> {
    get_inlay_hints_with_context(text, range, config, _cached_program, None, None)
}

/// Get inlay hints with optional file/workspace context for extension-aware inference.
pub fn get_inlay_hints_with_context(
    text: &str,
    range: Range,
    config: &InlayHintConfig,
    _cached_program: Option<&Program>,
    current_file: Option<&std::path::Path>,
    workspace_root: Option<&std::path::Path>,
) -> Vec<InlayHint> {
    // Parse the current document; never use cached AST spans for hint placement.
    let program = match parse_program(text) {
        Ok(p) => p,
        Err(_) => {
            let partial = shape_ast::parse_program_resilient(text);
            if partial.items.is_empty() {
                return Vec::new();
            }
            partial.into_program()
        }
    };

    // Run type inference once for the whole program
    let type_map = if current_file.is_none() && workspace_root.is_none() {
        infer_program_types(&program)
    } else {
        infer_program_types_with_context(&program, current_file, workspace_root, Some(text))
    };
    let function_types = infer_function_signatures(&program);

    let mut ctx = HintContext::new(text, &program, range, config, type_map, function_types);

    // Use the Visitor trait for exhaustive AST traversal
    walk_program(&mut ctx, &program);

    // Collect comptime value hints for type aliases
    if config.show_type_hints {
        collect_comptime_alias_hints(text, &program, range, &mut ctx.hints);
    }

    ctx.hints
}

/// Collect inlay hints showing resolved comptime values on type alias definitions.
///
/// For `type EUR = Currency { symbol: "EUR" }`, shows the full resolved comptime values
/// as an inlay hint after the alias name, including inherited defaults.
fn collect_comptime_alias_hints(
    text: &str,
    program: &shape_ast::ast::Program,
    range: Range,
    hints: &mut Vec<InlayHint>,
) {
    use std::collections::HashMap;

    // First pass: collect struct definitions with comptime fields
    let mut struct_comptime: HashMap<String, Vec<(String, Option<String>)>> = HashMap::new();
    for item in &program.items {
        if let Item::StructType(struct_def, _) = item {
            let comptime_fields: Vec<(String, Option<String>)> = struct_def
                .fields
                .iter()
                .filter(|f| f.is_comptime)
                .map(|f| {
                    let default = f.default_value.as_ref().map(format_comptime_value);
                    (f.name.clone(), default)
                })
                .collect();
            if !comptime_fields.is_empty() {
                struct_comptime.insert(struct_def.name.clone(), comptime_fields);
            }
        }
    }

    // Second pass: for each type alias with overrides, show resolved values
    for item in &program.items {
        if let Item::TypeAlias(alias_def, span) = item {
            let base_type = match &alias_def.type_annotation {
                shape_ast::ast::TypeAnnotation::Basic(name) => name.clone(),
                _ => continue,
            };

            let comptime_fields = match struct_comptime.get(&base_type) {
                Some(fields) => fields,
                None => continue,
            };

            // Build the resolved values: override > default
            let resolved: Vec<String> = comptime_fields
                .iter()
                .filter_map(|(name, default)| {
                    let value = alias_def
                        .meta_param_overrides
                        .as_ref()
                        .and_then(|o| o.get(name))
                        .map(format_comptime_value)
                        .or_else(|| default.clone());
                    value.map(|v| format!("{} = {}", name, v))
                })
                .collect();

            if resolved.is_empty() {
                continue;
            }

            let hint_offset = span.end;
            let position = offset_to_position(text, hint_offset);
            if is_in_range(position, range) {
                hints.push(InlayHint {
                    position,
                    label: InlayHintLabel::String(format!(" [{}]", resolved.join(", "))),
                    kind: Some(InlayHintKind::TYPE),
                    text_edits: None,
                    tooltip: Some(tower_lsp_server::ls_types::InlayHintTooltip::String(
                        format!("Resolved comptime values from {}", base_type),
                    )),
                    padding_left: Some(false),
                    padding_right: Some(true),
                    data: None,
                });
            }
        }
    }
}

/// Format a comptime expression value for display
fn format_comptime_value(expr: &Expr) -> String {
    match expr {
        Expr::Literal(lit, _) => match lit {
            shape_ast::ast::Literal::String(s) => format!("\"{}\"", s),
            shape_ast::ast::Literal::Number(n) => format!("{}", n),
            shape_ast::ast::Literal::Int(n) => format!("{}", n),
            shape_ast::ast::Literal::Decimal(d) => format!("{}D", d),
            shape_ast::ast::Literal::Bool(b) => format!("{}", b),
            shape_ast::ast::Literal::None => "None".to_string(),
            _ => "...".to_string(),
        },
        _ => "...".to_string(),
    }
}

/// W2.4 / 1.25 + LSP-I (R8 W11): heuristic label approximating
/// `BindingStorageClass` (ADR-006 §2) for a `let`/`var` binding. This is
/// intentionally a best-effort LSP-side heuristic — the authoritative
/// classification requires the MIR borrow solver + storage planner. The
/// output uses the ADR-006 §2 vocabulary — `Direct`, `UniqueHeap`,
/// `SharedCow`, `SharedAtomic`, `SharedAtomicMut` — with an `[… approx]`
/// qualifier so the user knows it is not the compiler verdict.
///
/// **Mapping rules (LSP-side approximation):**
/// - RHS calls `Channel(...)`/`Channel.new(...)`/`Mutex(...)`/`Mutex.new(...)`,
///   declared type starts with `Channel`/`Mutex`, or the initializer is an
///   `async let` / `spawn { ... }` shape → `SharedAtomicMut` when the binding
///   is mutable, `SharedAtomic` otherwise (covers ADR-006 §2 line 119 / 143).
/// - RHS calls `Atomic(...)`/`Atomic.new(...)` or declared type starts with
///   `Atomic` → `SharedAtomic` (cross-thread read-shared, ADR-006 §2 line 118).
/// - Initializer is itself a closure `FunctionExpr` (the var IS a closure),
///   or the declared/inferred type contains `closure` / `Fn(`-like shape →
///   `SharedCow` (closures escape their defining scope; ADR-006 §2 line 117).
/// - Primitive value type (`int`, `number`, `bool`, ...) → `Direct`.
/// - Any other heap-resident type → `UniqueHeap` (ADR-006 §2 default).
/// - Reference initializer (`&expr` / `&mut expr`) → `Direct` (the binding
///   itself is a stack-resident typed pointer; ADR-006 §2 line 50).
fn binding_kind_label_for(decl: &VariableDecl, label_type: Option<&str>) -> String {
    let class = classify_binding_storage(decl, label_type);
    let mut_suffix = if decl.is_mut { " mut" } else { "" };
    format!("[{}{} approx]", class, mut_suffix)
}

/// Return the ADR-006 §2 `BindingStorageClass` name as best the LSP-side
/// heuristic can determine. Names match the canonical ADR-006 §2 vocabulary
/// (`Direct`, `UniqueHeap`, `SharedCow`, `SharedAtomic`, `SharedAtomicMut`).
fn classify_binding_storage(decl: &VariableDecl, label_type: Option<&str>) -> &'static str {
    // Reference initializer: typed pointer carrier sits on the stack — Direct.
    if let Some(Expr::Reference { .. }) = decl.value.as_ref() {
        return "Direct";
    }

    // Initializer-shape probes (RHS-driven). These dominate over type-driven
    // fallback when the user wrote an explicit concurrency-primitive construction.
    if let Some(value) = decl.value.as_ref() {
        if is_async_or_spawn_shape(value) {
            return if decl.is_mut { "SharedAtomicMut" } else { "SharedAtomic" };
        }
        if let Some(class) = concurrency_constructor_class(value, decl.is_mut) {
            return class;
        }
        if matches!(value, Expr::FunctionExpr { .. }) {
            // The variable IS a closure — closures escape their defining scope
            // by definition (ADR-006 §2 line 117).
            return "SharedCow";
        }
    }

    // Type-driven fallback.
    if let Some(ty) = label_type {
        let t = ty.trim();
        let bare = t.trim_start_matches('&').trim_start_matches("mut ").trim();
        if is_primitive_value_type(bare) {
            return "Direct";
        }
        if bare.starts_with("Mutex") || bare.starts_with("Channel") {
            return "SharedAtomicMut";
        }
        if bare.starts_with("Atomic") {
            return "SharedAtomic";
        }
        if bare.starts_with("Arc<") {
            // Bare Arc<T> is read-shared cross-thread — SharedAtomic. Arc<Mutex<T>>
            // would be SharedAtomicMut but we'd need to peek inside.
            if bare.contains("Mutex<") {
                return "SharedAtomicMut";
            }
            return "SharedAtomic";
        }
        // Closure-typed binding (e.g. `(int) -> int`) — escapes when captured.
        if bare.contains("->") && (bare.starts_with('(') || bare.starts_with("Fn")) {
            return "SharedCow";
        }
        // Heap-resident default per ADR-006 §2 line 92.
        return "UniqueHeap";
    }

    // No type info at all — pessimistic UniqueHeap default for heap-shaped
    // initializers, Direct otherwise.
    match decl.value.as_ref() {
        Some(Expr::Literal(lit, _)) => match lit {
            shape_ast::ast::Literal::Int(_)
            | shape_ast::ast::Literal::Number(_)
            | shape_ast::ast::Literal::Bool(_)
            | shape_ast::ast::Literal::None => "Direct",
            _ => "UniqueHeap",
        },
        _ => "UniqueHeap",
    }
}

/// Detect RHS shapes that imply cross-thread/task escape (ADR-006 §2 line 143).
fn is_async_or_spawn_shape(expr: &Expr) -> bool {
    matches!(
        expr,
        Expr::AsyncLet(..) | Expr::AsyncScope(..) | Expr::Await(..) | Expr::Join(..)
    )
}

/// Detect `Channel`/`Mutex`/`Atomic` constructor calls. Returns the appropriate
/// `BindingStorageClass` name when matched.
fn concurrency_constructor_class(expr: &Expr, is_mut: bool) -> Option<&'static str> {
    let head_name = match expr {
        Expr::FunctionCall { name, .. } => name.as_str(),
        Expr::QualifiedFunctionCall { function, .. } => function.as_str(),
        Expr::MethodCall { receiver, method, .. } => {
            // Pattern: `Channel.new(...)` / `Mutex.new(...)` etc. — the receiver
            // is the type-name `Identifier`, the method is `new`.
            if method == "new" || method == "open" || method == "with_capacity" {
                if let Expr::Identifier(name, _) = receiver.as_ref() {
                    name.as_str()
                } else {
                    return None;
                }
            } else {
                return None;
            }
        }
        _ => return None,
    };

    // `Channel`/`Mutex` both imply interior mutability (ADR-006 §2.7.20:
    // Channel's `Mutex<ChannelInner>` shape; ADR-006 §2 line 119 for Mutex)
    // — surface as `SharedAtomicMut` regardless of the outer binding's
    // `let mut` flag, since the *mutation capability* is what the storage
    // class records.
    let _ = is_mut;
    match head_name {
        "Channel" | "Mutex" => Some("SharedAtomicMut"),
        "Atomic" => Some("SharedAtomic"),
        _ => None,
    }
}

/// Match the same primitive vocabulary `HintContext::is_primitive_value_type_name`
/// uses but free-standing so the binding-kind label can share it. Keep the
/// two sets aligned.
fn is_primitive_value_type(name: &str) -> bool {
    let normalized = name.trim().trim_end_matches('?');
    matches!(
        normalized,
        "int"
            | "integer"
            | "i8"
            | "i16"
            | "i32"
            | "i64"
            | "u8"
            | "u16"
            | "u32"
            | "u64"
            | "number"
            | "float"
            | "f32"
            | "f64"
            | "bool"
            | "boolean"
            | "()"
            | "void"
            | "unit"
            | "none"
            | "null"
            | "undefined"
            | "never"
    )
}

/// Check if a position is within a range
fn is_in_range(pos: Position, range: Range) -> bool {
    if pos.line < range.start.line || pos.line > range.end.line {
        return false;
    }
    if pos.line == range.start.line && pos.character < range.start.character {
        return false;
    }
    if pos.line == range.end.line && pos.character > range.end.character {
        return false;
    }
    true
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::type_inference::infer_literal_type;
    use shape_ast::ast::Literal;

    #[test]
    fn test_infer_literal_type() {
        assert_eq!(infer_literal_type(&Literal::Number(42.0)), "number");
        assert_eq!(
            infer_literal_type(&Literal::String("hello".to_string())),
            "string"
        );
        assert_eq!(infer_literal_type(&Literal::Bool(true)), "bool");
        assert_eq!(infer_literal_type(&Literal::None), "Option");
    }

    #[test]
    fn test_infer_literal_type_int() {
        assert_eq!(infer_literal_type(&Literal::Int(42)), "int");
    }

    #[test]
    fn test_infer_literal_type_decimal() {
        use rust_decimal::Decimal;
        assert_eq!(
            infer_literal_type(&Literal::Decimal(Decimal::new(1050, 2))),
            "decimal"
        );
    }

    #[test]
    fn test_numeric_type_hints_int() {
        let config = InlayHintConfig::default();
        let range = Range {
            start: Position {
                line: 0,
                character: 0,
            },
            end: Position {
                line: 10,
                character: 100,
            },
        };

        let hints = get_inlay_hints("let i = 10", range, &config, None);
        assert!(!hints.is_empty(), "Expected at least one hint for integer");
        let label = match &hints[0].label {
            InlayHintLabel::String(s) => s.clone(),
            _ => panic!("Expected string label"),
        };
        assert!(
            label.contains("int"),
            "Expected 'int' in hint, got: {}",
            label
        );
    }

    #[test]
    fn test_numeric_type_hints_decimal() {
        let config = InlayHintConfig::default();
        let range = Range {
            start: Position {
                line: 0,
                character: 0,
            },
            end: Position {
                line: 10,
                character: 100,
            },
        };

        let hints = get_inlay_hints("let d = 10D", range, &config, None);
        assert!(!hints.is_empty(), "Expected at least one hint for decimal");
        let label = match &hints[0].label {
            InlayHintLabel::String(s) => s.clone(),
            _ => panic!("Expected string label"),
        };
        assert!(
            label.contains("decimal"),
            "Expected 'decimal' in hint, got: {}",
            label
        );
    }

    #[test]
    fn test_numeric_type_hints_number() {
        let config = InlayHintConfig::default();
        let range = Range {
            start: Position {
                line: 0,
                character: 0,
            },
            end: Position {
                line: 10,
                character: 100,
            },
        };

        let hints = get_inlay_hints("let f = 10.0", range, &config, None);
        assert!(!hints.is_empty(), "Expected at least one hint for float");
        let label = match &hints[0].label {
            InlayHintLabel::String(s) => s.clone(),
            _ => panic!("Expected string label"),
        };
        assert!(
            label.contains("number"),
            "Expected 'number' in hint, got: {}",
            label
        );
    }

    #[test]
    fn test_offset_to_position() {
        let text = "let x = 42;\nlet y = 10;";
        let pos = offset_to_position(text, 0);
        assert_eq!(pos.line, 0);
        assert_eq!(pos.character, 0);

        let pos = offset_to_position(text, 12);
        assert_eq!(pos.line, 1);
        assert_eq!(pos.character, 0);
    }

    #[test]
    fn test_match_expression_type_hint() {
        let config = InlayHintConfig::default();
        let range = Range {
            start: Position {
                line: 0,
                character: 0,
            },
            end: Position {
                line: 10,
                character: 100,
            },
        };

        let code = "let test = match 2 {\n  0 => true,\n  _ => false,\n}";
        let hints = get_inlay_hints(code, range, &config, None);
        eprintln!(
            "Hints for match: {:?}",
            hints
                .iter()
                .map(|h| match &h.label {
                    InlayHintLabel::String(s) => s.clone(),
                    _ => "non-string".to_string(),
                })
                .collect::<Vec<_>>()
        );
        let type_hints: Vec<_> = hints
            .iter()
            .filter(|h| h.kind == Some(InlayHintKind::TYPE))
            .collect();
        assert!(
            !type_hints.is_empty(),
            "Expected a type hint for 'let test = match ...'"
        );
        let label = match &type_hints[0].label {
            InlayHintLabel::String(s) => s.clone(),
            _ => panic!("Expected string label"),
        };
        assert!(
            label.contains("bool"),
            "Expected 'bool' in hint, got: {}",
            label
        );
    }

    // LSP-H regression: `let d = distance(p, q)` for a user-defined function
    // must propagate `-> number` (not `: any` / `: unknown`). Before LSP-H the
    // syntactic fallback was used with an empty env so identifier receivers
    // couldn't resolve through `.map(...)` chains; we now thread the
    // program-level type_map as env.
    #[test]
    fn lsp_h_type_hint_propagates_through_user_fn_call() {
        let code = "\
type Point { x: number, y: number }
fn distance(a: Point, b: Point) -> number { 0.0 }
let p = Point { x: 0.0, y: 0.0 }
let q = Point { x: 1.0, y: 1.0 }
let d = distance(p, q)
";
        let cfg = InlayHintConfig::default();
        let hints = get_inlay_hints(code, full_range(), &cfg, None);
        let labels = type_hint_labels(&hints);
        assert!(
            labels.iter().any(|l| l == ": number"),
            "expected `: number` for `let d = distance(...)`, got {:?}",
            labels
        );
    }

    // LSP-H regression: `.map` chain element type recovered from the closure
    // body (was bare `Array` pre-LSP-H, leaking element type).
    #[test]
    fn lsp_h_map_chain_preserves_element_type() {
        let code = "\
let xs = [1, 2, 3]
let doubled = xs.map(|x| x * 2)
";
        let cfg = InlayHintConfig::default();
        let hints = get_inlay_hints(code, full_range(), &cfg, None);
        let labels = type_hint_labels(&hints);
        assert!(
            labels.iter().any(|l| l == ": Array<int>"),
            "expected `: Array<int>` for `let doubled = xs.map(...)`, got {:?}",
            labels
        );
        // Regression guard: bare `: Array` would indicate the leak returned.
        assert!(
            !labels.iter().any(|l| l == ": Array"),
            "regression: bare `: Array` leak returned, labels = {:?}",
            labels
        );
    }

    // LSP-H new feature: chain hints after intermediate `.method()` calls
    // (`xs.map(...).sum()` shows `: Array<int>` after `.map` and `: number`
    // for the binding). Default-on per the LSP-H brief.
    #[test]
    fn lsp_h_chain_hint_emitted_for_intermediate_method() {
        let code = "\
let xs = [1, 2, 3]
let total = xs.map(|x| x * 2).sum()
";
        let cfg = InlayHintConfig::default();
        let hints = get_inlay_hints(code, full_range(), &cfg, None);
        let chain_hints: Vec<_> = hints
            .iter()
            .filter(|h| {
                h.data
                    .as_ref()
                    .and_then(|d| d.get("kind"))
                    .and_then(|k| k.as_str())
                    == Some("chain")
            })
            .collect();
        assert!(
            !chain_hints.is_empty(),
            "expected at least one chain hint on multi-`.` method chain, got hints = {:?}",
            hints
                .iter()
                .map(|h| match &h.label {
                    InlayHintLabel::String(s) => s.clone(),
                    _ => "non-string".to_string(),
                })
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_infer_try_operator_type() {
        use shape_ast::ast::Span;

        let expr = Expr::TryOperator(
            Box::new(Expr::FunctionCall {
                name: "some_func".to_string(),
                args: vec![],
                named_args: vec![],
                span: Span::DUMMY,
            }),
            Span::DUMMY,
        );
        let _ = infer_expr_type(&expr);
    }

    fn full_range() -> Range {
        Range {
            start: Position {
                line: 0,
                character: 0,
            },
            end: Position {
                line: 100,
                character: 100,
            },
        }
    }

    fn type_hint_labels(hints: &[InlayHint]) -> Vec<String> {
        hints
            .iter()
            .filter(|h| h.kind == Some(InlayHintKind::TYPE))
            .map(|h| match &h.label {
                InlayHintLabel::String(s) => s.clone(),
                _ => "non-string".to_string(),
            })
            .collect()
    }

    #[test]
    fn test_function_return_type_hint() {
        let code = "fn add(a: int, b: int) {\n  return a + b\n}";
        let config = InlayHintConfig::default();
        let hints = get_inlay_hints(code, full_range(), &config, None);
        let labels = type_hint_labels(&hints);
        eprintln!("Return type hints: {:?}", labels);
        // Engine should infer a return type from the body
        let has_return_hint = labels.iter().any(|l| l.starts_with("->"));
        assert!(
            has_return_hint,
            "Expected a return type hint for fn without return annotation, got: {:?}",
            labels
        );
    }

    #[test]
    fn test_function_return_hint_for_empty_params_anchors_after_close_paren() {
        let code = "fn test() {\n}\n";
        let config = InlayHintConfig::default();
        let hints = get_inlay_hints(code, full_range(), &config, None);

        let return_hint = hints
            .iter()
            .find(|hint| match &hint.label {
                InlayHintLabel::String(label) => label.starts_with("->"),
                _ => false,
            })
            .expect("expected return type hint");

        let expected_col = code
            .lines()
            .next()
            .and_then(|line| line.find(')'))
            .map(|idx| idx as u32 + 1)
            .expect("header should contain ')'");

        assert_eq!(
            return_hint.position,
            Position {
                line: 0,
                character: expected_col
            }
        );
        match &return_hint.label {
            InlayHintLabel::String(label) => assert_eq!(label, "-> ()"),
            _ => panic!("expected string inlay label"),
        }
    }

    #[test]
    fn test_print_parameter_hints_are_suppressed() {
        let code = "print(\"hello\")\n";
        let hints = get_inlay_hints(code, full_range(), &InlayHintConfig::default(), None);
        let has_parameter_hints = hints
            .iter()
            .any(|h| h.kind == Some(InlayHintKind::PARAMETER));
        assert!(
            !has_parameter_hints,
            "print() should not emit parameter hints, got: {:?}",
            hints
        );
    }

    #[test]
    fn test_function_param_type_hint_not_shown_when_annotated() {
        let code = "fn greet(name: string) {\n  return name\n}";
        let config = InlayHintConfig::default();
        let hints = get_inlay_hints(code, full_range(), &config, None);
        let labels = type_hint_labels(&hints);
        // Parameter already has type annotation — should NOT show a hint for it
        let has_param_hint = labels
            .iter()
            .any(|l| l.contains("string") && l.starts_with(":"));
        assert!(
            !has_param_hint,
            "Should not show param type hint when annotation exists, got: {:?}",
            labels
        );
    }

    #[test]
    fn test_function_no_hint_when_return_annotated() {
        let code = "fn double(x: int) -> int {\n  return x * 2\n}";
        let config = InlayHintConfig::default();
        let hints = get_inlay_hints(code, full_range(), &config, None);
        let labels = type_hint_labels(&hints);
        // Both param and return are annotated — no type hints expected
        let has_return_hint = labels.iter().any(|l| l.starts_with("->"));
        assert!(
            !has_return_hint,
            "Should not show return type hint when annotation exists, got: {:?}",
            labels
        );
    }

    #[test]
    fn test_function_param_hint_shows_inferred_shared_reference() {
        let code = r#"
fn read_only(a) {
  return a.len()
}
let s = "abc"
read_only(s)
"#;
        let hints = get_inlay_hints(code, full_range(), &InlayHintConfig::default(), None);
        let labels = type_hint_labels(&hints);
        assert!(
            labels.iter().any(|l| l == ": &string"),
            "Expected inferred shared reference hint ': &string', got: {:?}",
            labels
        );
    }

    #[test]
    fn test_function_param_hint_shows_inferred_exclusive_reference() {
        let code = r#"
fn write_ref(a) {
  a = a + "!"
  return a
}
let s = "abc"
write_ref(s)
"#;
        let hints = get_inlay_hints(code, full_range(), &InlayHintConfig::default(), None);
        let labels = type_hint_labels(&hints);
        assert!(
            labels.iter().any(|l| l == ": &mut string"),
            "Expected inferred exclusive reference hint ': &mut string', got: {:?}",
            labels
        );
    }

    #[test]
    fn test_function_param_hint_union_is_memberwise_reference_aware() {
        let code = r#"
fn foo(a) { return a }
let i = foo(1)
let s = foo("hi")
"#;
        let hints = get_inlay_hints(code, full_range(), &InlayHintConfig::default(), None);
        let labels = type_hint_labels(&hints);
        let union_hint = labels
            .iter()
            .find(|l| l.starts_with(":") && l.contains("int") && l.contains("string"))
            .cloned()
            .unwrap_or_default();
        assert!(
            union_hint.contains("&string"),
            "Expected union hint to show reference-aware heap member, got: {:?}",
            labels
        );
        assert!(
            union_hint.contains("int"),
            "Expected union hint to keep primitive member by value, got: {:?}",
            labels
        );
    }

    #[test]
    fn test_variable_type_hint_disabled() {
        let config = InlayHintConfig {
            show_variable_type_hints: false,
            ..InlayHintConfig::default()
        };
        let hints = get_inlay_hints("let x = 42", full_range(), &config, None);
        let type_labels = type_hint_labels(&hints);
        assert!(
            type_labels.is_empty(),
            "Should not show variable type hints when disabled, got: {:?}",
            type_labels
        );
    }

    #[test]
    fn test_return_type_hint_disabled() {
        let config = InlayHintConfig {
            show_return_type_hints: false,
            ..InlayHintConfig::default()
        };
        let code = "fn add(a: int, b: int) {\n  return a + b\n}";
        let hints = get_inlay_hints(code, full_range(), &config, None);
        let labels = type_hint_labels(&hints);
        let has_return_hint = labels.iter().any(|l| l.starts_with("->"));
        assert!(
            !has_return_hint,
            "Should not show return type hints when disabled, got: {:?}",
            labels
        );
    }

    #[test]
    fn test_variable_inside_function_gets_hint() {
        let config = InlayHintConfig::default();
        let code = "fn foo() {\n  let x = 42\n  return x\n}";
        let hints = get_inlay_hints(code, full_range(), &config, None);
        let type_labels = type_hint_labels(&hints);
        let has_int_hint = type_labels.iter().any(|l| l.contains("int"));
        assert!(
            has_int_hint,
            "Should show type hint for variable inside function body, got: {:?}",
            type_labels
        );
    }

    #[test]
    fn test_string_variable_hint() {
        let config = InlayHintConfig::default();
        let hints = get_inlay_hints("let name = \"hello\"", full_range(), &config, None);
        let labels = type_hint_labels(&hints);
        let has_string = labels.iter().any(|l| l.contains("string"));
        assert!(
            has_string,
            "Should show 'string' hint for string literal, got: {:?}",
            labels
        );
    }

    #[test]
    fn test_bool_variable_hint() {
        let config = InlayHintConfig::default();
        let hints = get_inlay_hints("let flag = true", full_range(), &config, None);
        let labels = type_hint_labels(&hints);
        let has_bool = labels.iter().any(|l| l.contains("bool"));
        assert!(
            has_bool,
            "Should show 'bool' hint for bool literal, got: {:?}",
            labels
        );
    }

    #[test]
    fn test_no_hint_when_type_annotated() {
        let config = InlayHintConfig::default();
        let hints = get_inlay_hints("let x: int = 42", full_range(), &config, None);
        let type_labels = type_hint_labels(&hints);
        // Should not produce a type hint since the variable already has an annotation
        let has_int = type_labels.iter().any(|l| l.contains("int"));
        assert!(
            !has_int,
            "Should not show type hint when annotation exists, got: {:?}",
            type_labels
        );
    }

    #[test]
    fn test_table_row_literal_field_hints() {
        let code = r#"type FinRecord {
  month: int,
  revenue: number,
  profit: number,
  note: string
}
let t: Table<FinRecord> = [1, 100.0, 60.0, "jan"], [2, 120.0, 70.0, "feb"]
"#;
        let config = InlayHintConfig::default();
        let hints = get_inlay_hints(code, full_range(), &config, None);
        let param_hints: Vec<String> = hints
            .iter()
            .filter(|h| h.kind == Some(InlayHintKind::PARAMETER))
            .map(|h| match &h.label {
                InlayHintLabel::String(s) => s.clone(),
                _ => "non-string".to_string(),
            })
            .collect();
        // Should have 8 parameter hints (4 fields x 2 rows)
        assert_eq!(
            param_hints.len(),
            8,
            "Expected 8 parameter hints for 2 rows x 4 fields, got: {:?}",
            param_hints
        );
        assert_eq!(param_hints[0], "month:");
        assert_eq!(param_hints[1], "revenue:");
        assert_eq!(param_hints[2], "profit:");
        assert_eq!(param_hints[3], "note:");
        // Second row repeats
        assert_eq!(param_hints[4], "month:");
        assert_eq!(param_hints[7], "note:");
    }

    // ---------- W2.4 / 1.04: closure type rendering ----------

    #[test]
    fn test_closure_type_hint_renders_signature() {
        // A `let f = |y| y + 1` should render `fn(_) -> int` (or similar)
        // rather than the bare "Function".
        let code = "let f = |y| y + 1\n";
        let hints = get_inlay_hints(code, full_range(), &InlayHintConfig::default(), None);
        let labels = type_hint_labels(&hints);
        let has_fn_sig = labels
            .iter()
            .any(|l| l.starts_with(": fn(") && l.contains("->"));
        assert!(
            has_fn_sig,
            "Expected closure type hint like ': fn(_) -> int', got: {:?}",
            labels
        );
    }

    #[test]
    fn test_closure_type_hint_no_param_annotation_still_renders_signature() {
        let code = "let f = |x| 42\n";
        let hints = get_inlay_hints(code, full_range(), &InlayHintConfig::default(), None);
        let labels = type_hint_labels(&hints);
        let has_fn_sig = labels.iter().any(|l| l.starts_with(": fn(") && l.contains("->"));
        assert!(
            has_fn_sig,
            "Expected closure type hint with `_` for unannotated param, got: {:?}",
            labels
        );
    }

    // ---------- W2.4 / 1.27: chain hints ----------

    #[test]
    fn test_chain_hints_emit_for_intermediate_method_calls() {
        // `xs.filter(...).reverse().sort()` should produce hints at each
        // intermediate `.method()` call site (chain spine length == 3).
        let code = r#"
let xs = [1, 2, 3]
let r = xs.filter(|x| x > 0).reverse().sort()
"#;
        let hints = get_inlay_hints(code, full_range(), &InlayHintConfig::default(), None);
        let chain_hints: Vec<_> = hints
            .iter()
            .filter(|h| {
                h.data
                    .as_ref()
                    .and_then(|d| d.get("kind"))
                    .and_then(|v| v.as_str())
                    == Some("chain")
            })
            .collect();
        assert!(
            !chain_hints.is_empty(),
            "Expected at least one chain hint, got hints: {:?}",
            hints.iter().map(|h| &h.label).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_chain_hints_disabled_emits_none() {
        let code = r#"
let xs = [1, 2, 3]
let r = xs.filter(|x| x > 0).reverse().sort()
"#;
        let cfg = InlayHintConfig {
            show_chain_hints: false,
            ..InlayHintConfig::default()
        };
        let hints = get_inlay_hints(code, full_range(), &cfg, None);
        let any_chain = hints.iter().any(|h| {
            h.data
                .as_ref()
                .and_then(|d| d.get("kind"))
                .and_then(|v| v.as_str())
                == Some("chain")
        });
        assert!(
            !any_chain,
            "Expected no chain hints when disabled, got: {:?}",
            hints.iter().map(|h| &h.label).collect::<Vec<_>>()
        );
    }

    // ---------- W2.4 / 1.25: binding-kind hints ----------

    #[test]
    fn test_binding_kind_hint_emits_for_primitive_let() {
        let code = "let x = 42\n";
        let cfg = InlayHintConfig {
            show_binding_kind_hints: true,
            ..InlayHintConfig::default()
        };
        let hints = get_inlay_hints(code, full_range(), &cfg, None);
        let any_kind = hints.iter().any(|h| {
            h.data
                .as_ref()
                .and_then(|d| d.get("kind"))
                .and_then(|v| v.as_str())
                == Some("binding-kind")
        });
        assert!(
            any_kind,
            "Expected a binding-kind hint, got: {:?}",
            hints
                .iter()
                .map(|h| (h.label.clone(), h.data.clone()))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_binding_kind_label_covers_five_adr006_categories() {
        // LSP-I (R8 W11): every ADR-006 §2 BindingStorageClass main category
        // (Direct / UniqueHeap / SharedCow / SharedAtomic / SharedAtomicMut)
        // must have a label-rendering path through the LSP-side heuristic.
        let cfg = InlayHintConfig {
            show_binding_kind_hints: true,
            ..InlayHintConfig::default()
        };

        let cases: &[(&str, &str)] = &[
            ("let x = 42\n", "[Direct approx]"),
            ("let s = \"hello\"\n", "[UniqueHeap approx]"),
            ("let f = |x| x + 1\n", "[SharedCow approx]"),
            ("let a = Atomic.new(0)\n", "[SharedAtomic approx]"),
            ("let mut q = Channel.new()\n", "[SharedAtomicMut mut approx]"),
        ];

        for (code, expected) in cases {
            let hints = get_inlay_hints(code, full_range(), &cfg, None);
            let labels: Vec<String> = hints
                .iter()
                .filter_map(|h| match &h.label {
                    InlayHintLabel::String(s) => Some(s.clone()),
                    _ => None,
                })
                .collect();
            assert!(
                labels.iter().any(|l| l == expected),
                "code {:?} expected label {:?}, got labels {:?}",
                code,
                expected,
                labels
            );
        }
    }

    #[test]
    fn test_binding_kind_hint_off_by_default() {
        let code = "let x = 42\n";
        let hints = get_inlay_hints(code, full_range(), &InlayHintConfig::default(), None);
        let any_kind = hints.iter().any(|h| {
            h.data
                .as_ref()
                .and_then(|d| d.get("kind"))
                .and_then(|v| v.as_str())
                == Some("binding-kind")
        });
        assert!(
            !any_kind,
            "Binding-kind hints should be opt-in (default off); got: {:?}",
            hints.iter().map(|h| h.label.clone()).collect::<Vec<_>>()
        );
    }

    // ---------- W2.4 / 1.70: client-respecting config ----------

    #[test]
    fn test_from_lsp_settings_master_disable() {
        let json = serde_json::json!({
            "shape": {
                "inlayHints": {
                    "enable": false
                }
            }
        });
        let cfg = InlayHintConfig::from_lsp_settings(Some(&json));
        assert!(!cfg.show_type_hints);
        assert!(!cfg.show_parameter_hints);
        assert!(!cfg.show_variable_type_hints);
        assert!(!cfg.show_return_type_hints);
        assert!(!cfg.show_chain_hints);
        assert!(!cfg.show_binding_kind_hints);
    }

    #[test]
    fn test_from_lsp_settings_individual_toggles() {
        let json = serde_json::json!({
            "shape": {
                "inlayHints": {
                    "parameterHints": false,
                    "chainHints": false,
                    "bindingKindHints": true
                }
            }
        });
        let cfg = InlayHintConfig::from_lsp_settings(Some(&json));
        assert!(cfg.show_type_hints);
        assert!(!cfg.show_parameter_hints);
        assert!(!cfg.show_chain_hints);
        assert!(cfg.show_binding_kind_hints);
    }

    #[test]
    fn test_from_lsp_settings_snake_case_alias_accepted() {
        let json = serde_json::json!({
            "inlay_hints": {
                "binding_kind_hints": true,
                "chain_hints": false
            }
        });
        let cfg = InlayHintConfig::from_lsp_settings(Some(&json));
        assert!(cfg.show_binding_kind_hints);
        assert!(!cfg.show_chain_hints);
    }

    // ---------- LSP-I (R8 W11): bindingStorageClass.enable canonical key ----------

    #[test]
    fn test_from_lsp_settings_binding_storage_class_nested_enable_on() {
        let json = serde_json::json!({
            "shape": {
                "inlayHints": {
                    "bindingStorageClass": { "enable": true }
                }
            }
        });
        let cfg = InlayHintConfig::from_lsp_settings(Some(&json));
        assert!(
            cfg.show_binding_kind_hints,
            "Decision 2 canonical key bindingStorageClass.enable=true must opt the user in"
        );
    }

    #[test]
    fn test_from_lsp_settings_binding_storage_class_default_off() {
        // Decision 2 mandate: default is OFF when the user has not set the key.
        let json = serde_json::json!({
            "shape": { "inlayHints": {} }
        });
        let cfg = InlayHintConfig::from_lsp_settings(Some(&json));
        assert!(
            !cfg.show_binding_kind_hints,
            "Decision 2 default OFF — no opt-in implies hint stays off"
        );
    }

    #[test]
    fn test_from_lsp_settings_binding_storage_class_snake_case_alias() {
        let json = serde_json::json!({
            "shape": {
                "inlayHints": {
                    "binding_storage_class": { "enable": true }
                }
            }
        });
        let cfg = InlayHintConfig::from_lsp_settings(Some(&json));
        assert!(cfg.show_binding_kind_hints);
    }

    #[test]
    fn test_from_lsp_settings_binding_storage_class_flat_bool() {
        let json = serde_json::json!({
            "shape": {
                "inlayHints": {
                    "bindingStorageClass": true
                }
            }
        });
        let cfg = InlayHintConfig::from_lsp_settings(Some(&json));
        assert!(cfg.show_binding_kind_hints);
    }

    #[test]
    fn test_from_lsp_settings_legacy_binding_kind_hints_still_honored() {
        // Backward compat: the older W2.4 / 1.25 `bindingKindHints` key still
        // toggles the same field so existing clients don't break.
        let json = serde_json::json!({
            "shape": {
                "inlayHints": {
                    "bindingKindHints": true
                }
            }
        });
        let cfg = InlayHintConfig::from_lsp_settings(Some(&json));
        assert!(cfg.show_binding_kind_hints);
    }

    #[test]
    fn test_default_inlay_hint_config_keeps_binding_storage_class_off() {
        let cfg = InlayHintConfig::default();
        assert!(
            !cfg.show_binding_kind_hints,
            "Default InlayHintConfig must keep binding-storage-class hint OFF \
             (Decision 2: Shape-unique inlay hints are opt-in default-OFF)."
        );
    }

    #[test]
    fn test_from_lsp_settings_none_returns_defaults() {
        let cfg = InlayHintConfig::from_lsp_settings(None);
        let default_cfg = InlayHintConfig::default();
        assert_eq!(cfg.show_type_hints, default_cfg.show_type_hints);
        assert_eq!(cfg.show_chain_hints, default_cfg.show_chain_hints);
        assert_eq!(
            cfg.show_binding_kind_hints,
            default_cfg.show_binding_kind_hints
        );
    }

    #[test]
    fn test_parse_error_with_no_recoverable_items_emits_no_hints() {
        let code = r#"
from std.core.snapshot import { Snapshot }

let x = {x: 1}
x.y = 1
let i = 10D
"#;
        let hints = get_inlay_hints(code, full_range(), &InlayHintConfig::default(), None);

        assert!(
            hints.is_empty(),
            "invalid parse with no recoverable AST should not emit hints"
        );
    }

    // W14.2-B1: per-line coverage additions
    #[test]
    fn test_is_primitive_value_type_inlay() {
        assert!(is_primitive_value_type("int"));
        assert!(is_primitive_value_type("number"));
        assert!(is_primitive_value_type("bool"));
        assert!(is_primitive_value_type("i32"));
        assert!(is_primitive_value_type("f64"));
        assert!(is_primitive_value_type("int?"));
        assert!(is_primitive_value_type("null"));
        assert!(is_primitive_value_type("void"));
        // string is NOT a value primitive here (it's a heap-allocated ref type)
        assert!(!is_primitive_value_type("string"));
        assert!(!is_primitive_value_type(""));
        assert!(!is_primitive_value_type("MyType"));
        assert!(!is_primitive_value_type("Array<int>"));
    }

    #[test]
    fn test_is_in_range_inside() {
        let range = Range {
            start: Position {
                line: 0,
                character: 0,
            },
            end: Position {
                line: 10,
                character: 50,
            },
        };
        assert!(is_in_range(
            Position {
                line: 5,
                character: 25,
            },
            range
        ));
    }

    #[test]
    fn test_is_in_range_outside() {
        let range = Range {
            start: Position {
                line: 0,
                character: 0,
            },
            end: Position {
                line: 5,
                character: 0,
            },
        };
        // Past the end line
        assert!(!is_in_range(
            Position {
                line: 10,
                character: 0,
            },
            range
        ));
    }

    #[test]
    fn test_format_comptime_value_number() {
        let expr = Expr::Literal(Literal::Int(42), Span::DUMMY);
        let formatted = format_comptime_value(&expr);
        assert!(
            formatted.contains("42"),
            "expected '42' in formatted output, got {formatted:?}"
        );
    }

    #[test]
    fn test_format_comptime_value_string() {
        let expr = Expr::Literal(Literal::String("hi".to_string()), Span::DUMMY);
        let formatted = format_comptime_value(&expr);
        assert!(
            formatted.contains("hi") || formatted.contains("\""),
            "expected string-ish in formatted output, got {formatted:?}"
        );
    }

    #[test]
    fn test_get_inlay_hints_empty_source() {
        let hints = get_inlay_hints("", full_range(), &InlayHintConfig::default(), None);
        assert!(hints.is_empty(), "expected no hints for empty source");
    }

    #[test]
    fn test_get_inlay_hints_respects_range_filter() {
        let code = "let x = 1\nlet y = 2\nlet z = 3\n";
        let limited_range = Range {
            start: Position {
                line: 0,
                character: 0,
            },
            end: Position {
                line: 0,
                character: 100,
            },
        };
        let hints = get_inlay_hints(code, limited_range, &InlayHintConfig::default(), None);
        // Only hints for line 0 should be present
        for h in &hints {
            assert_eq!(
                h.position.line, 0,
                "expected only line 0 hints when range is limited to line 0"
            );
        }
    }

    #[test]
    fn test_inlay_hints_config_show_type_hints_default() {
        let cfg = InlayHintConfig::default();
        assert!(cfg.show_type_hints, "show_type_hints should default to true");
    }

    #[test]
    fn test_inlay_hints_with_disabled_type_hints() {
        let cfg = InlayHintConfig {
            show_type_hints: false,
            ..InlayHintConfig::default()
        };
        let hints = get_inlay_hints("let x = 1\n", full_range(), &cfg, None);
        // With type hints disabled, no TYPE hints should appear.
        assert!(
            hints.iter().all(|h| h.kind != Some(InlayHintKind::TYPE)),
            "expected no TYPE hints when show_type_hints=false"
        );
    }

    #[test]
    fn test_get_inlay_hints_function_definition() {
        let code = "fn add(a, b) { return a + b }\n";
        let hints = get_inlay_hints(code, full_range(), &InlayHintConfig::default(), None);
        // Should produce parameter type hints (Variable kind).
        let _ = hints; // just-don't-crash check on the inferred-param flow
    }

    #[test]
    fn test_format_comptime_value_bool() {
        let expr = Expr::Literal(Literal::Bool(true), Span::DUMMY);
        let formatted = format_comptime_value(&expr);
        assert!(
            formatted.contains("true") || !formatted.is_empty(),
            "expected non-empty formatted output for bool, got {formatted:?}"
        );
    }
}