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
//! Go-to-definition and find references provider
//!
//! Enables navigation to symbol definitions and finding all references.

use crate::annotation_discovery::AnnotationDiscovery;
use crate::document::DocumentManager;
use crate::module_cache::ModuleCache;
use crate::type_inference::infer_variable_type;
use crate::util::{get_word_at_position, offset_to_line_col, position_to_offset};
use shape_ast::ast::{
    ImportItems, Item, Program, Span, Statement, TraitMember, TraitMemberSignature, TypeName,
};
use shape_ast::parser::parse_program;
use std::path::{Path, PathBuf};
use tower_lsp_server::ls_types::{
    DocumentHighlight, DocumentHighlightKind, GotoDefinitionResponse, Location, Position, Range,
    Uri,
};

/// Find the definition of a symbol at the given position.
///
/// When `cached_program` is provided, it is used as a fallback AST when
/// the current source text fails to parse.
pub fn get_definition(
    text: &str,
    position: Position,
    uri: &Uri,
    module_cache: Option<&ModuleCache>,
    annotation_discovery: Option<&AnnotationDiscovery>,
    cached_program: Option<&Program>,
) -> Option<GotoDefinitionResponse> {
    // Get the word at cursor
    let word = get_word_at_position(text, position)?;

    // Parse the current file, falling back to cached program or resilient parser
    let program = match parse_program(text) {
        Ok(p) => p,
        Err(_) => {
            if let Some(cached) = cached_program {
                cached.clone()
            } else {
                // Fall back to resilient parser — always succeeds with partial results
                let partial = shape_ast::parser::resilient::parse_program_resilient(text);
                if partial.items.is_empty() {
                    return None;
                }
                partial.into_program()
            }
        }
    };

    // First, try to find definition in the current file
    if let Some(location) = find_definition_location(&program, &word, uri, text) {
        return Some(GotoDefinitionResponse::Scalar(location));
    }

    // If not found locally, check if it's an imported symbol
    if let Some(cache) = module_cache {
        if let Some(location) = find_imported_definition(&program, &word, uri, cache) {
            return Some(GotoDefinitionResponse::Scalar(location));
        }
    }

    // Check if it's an annotation
    if let Some(discovery) = annotation_discovery {
        if let Some(location) = find_annotation_definition(&word, discovery, uri) {
            return Some(GotoDefinitionResponse::Scalar(location));
        }
    }

    None
}

/// Find all references to a symbol at the given position.
///
/// Uses scope-aware resolution via `ScopeTree` to correctly handle
/// variable shadowing and lexical scoping.
pub fn get_references(text: &str, position: Position, uri: &Uri) -> Option<Vec<Location>> {
    get_references_with_fallback(text, position, uri, None)
}

/// W2.6 — Find all references to a symbol at the given position, including
/// cross-file references from open documents and workspace `.shape` files.
///
/// Algorithm:
///  1. Resolve the symbol locally via `ScopeTree::references_of` (same as
///     `get_references_with_fallback`).
///  2. If the local binding is module-scope-visible (top-level item — fn /
///     type / trait / enum / pub var), enumerate other files (open docs +
///     workspace `.shape` files via `ModuleCache::enumerate_workspace_shape_files`)
///     and scan each one's `ScopeTree` for **module-scope** references to the
///     same name. Lexical scoping within each file is preserved by
///     `ScopeTree::references_of` — only top-level usages cross.
///  3. Locally-scoped bindings (loop vars, closure params, block lets) do not
///     produce cross-file results.
///
/// Returns `None` if no references are found anywhere.
pub fn get_references_cross_file(
    text: &str,
    position: Position,
    uri: &Uri,
    cached_program: Option<&Program>,
    documents: Option<&DocumentManager>,
    module_cache: Option<&ModuleCache>,
    workspace_root: Option<&Path>,
) -> Option<Vec<Location>> {
    // Local file references via ScopeTree (and text-search fallback).
    let mut locations = get_references_with_fallback(text, position, uri, cached_program)
        .unwrap_or_default();

    // Determine the symbol name + whether it's module-scope-visible.
    let Some(word) = get_word_at_position(text, position) else {
        return if locations.is_empty() {
            None
        } else {
            Some(locations)
        };
    };

    // Parse to inspect the binding kind. If parse fails, skip cross-file.
    let program = match parse_program(text) {
        Ok(p) => p,
        Err(_) => match cached_program {
            Some(p) => p.clone(),
            None => {
                return if locations.is_empty() {
                    None
                } else {
                    Some(locations)
                };
            }
        },
    };

    if !is_module_scope_symbol(&program, &word) {
        // Local-scope binding (loop var, closure param, block let) — no
        // cross-file lookup. Return whatever local refs we found.
        return if locations.is_empty() {
            None
        } else {
            Some(locations)
        };
    }

    // Cross-file scan: open documents (other than current uri) + workspace
    // .shape files (de-duplicated).
    let mut visited: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
    if let Some(current_path) = uri.to_file_path() {
        visited.insert(current_path.into_owned());
    }

    if let Some(docs) = documents {
        for other_uri in docs.all_uris() {
            if &other_uri == uri {
                continue;
            }
            let Some(other_path_cow) = other_uri.to_file_path() else {
                continue;
            };
            let other_path = other_path_cow.into_owned();
            if !visited.insert(other_path.clone()) {
                continue;
            }
            let Some(other_doc) = docs.get(&other_uri) else {
                continue;
            };
            let other_text = other_doc.text();
            collect_module_scope_refs_in_file(
                &other_text,
                &other_uri,
                &word,
                &mut locations,
            );
        }
    }

    if let (Some(cache), Some(root)) = (module_cache, workspace_root) {
        let _ = cache; // Reserved for future symbol-identity refinement.
        for path in cache.enumerate_workspace_shape_files(root) {
            if !visited.insert(path.clone()) {
                continue;
            }
            let Some(other_uri) = Uri::from_file_path(&path) else {
                continue;
            };
            // Skip files already visited via open documents.
            let Ok(other_text) = std::fs::read_to_string(&path) else {
                continue;
            };
            collect_module_scope_refs_in_file(
                &other_text,
                &other_uri,
                &word,
                &mut locations,
            );
        }
    }

    if locations.is_empty() {
        None
    } else {
        Some(locations)
    }
}

/// Return true when `name` is bound at module (top-level) scope in
/// `program` — i.e. it is a candidate for cross-file references because
/// other files could import or refer to it.
///
/// W2.6 conservative heuristic: top-level fn / type / trait / enum /
/// struct / foreign-fn / module-level variable declarations are
/// module-scope-visible. Statement-nested `let`, loop vars, closure
/// params are not.
fn is_module_scope_symbol(program: &Program, name: &str) -> bool {
    for item in &program.items {
        match item {
            Item::Function(func, _) if func.name == name => return true,
            Item::ForeignFunction(func, _) if func.name == name => return true,
            Item::Trait(t, _) if t.name == name => return true,
            Item::Enum(e, _) if e.name == name => return true,
            Item::TypeAlias(ta, _) if ta.name == name => return true,
            Item::StructType(s, _) if s.name == name => return true,
            Item::VariableDecl(decl, _) => {
                for (n, _) in crate::symbols::get_pattern_names(&decl.pattern) {
                    if n == name {
                        return true;
                    }
                }
            }
            Item::Statement(Statement::VariableDecl(decl, _), _) => {
                for (n, _) in crate::symbols::get_pattern_names(&decl.pattern) {
                    if n == name {
                        return true;
                    }
                }
            }
            Item::Import(import_stmt, _) => match &import_stmt.items {
                ImportItems::Named(specs) => {
                    for spec in specs {
                        let local = spec.alias.as_ref().unwrap_or(&spec.name);
                        if local == name {
                            return true;
                        }
                    }
                }
                ImportItems::Namespace { name: ns_name, alias } => {
                    let local = alias.as_ref().unwrap_or(ns_name);
                    if local == name {
                        return true;
                    }
                }
            },
            _ => {}
        }
    }
    false
}

/// Collect ScopeTree references to a top-level `name` in `text`, appending
/// `Location`s into `out`. Only the module-scope binding (and its
/// references) is considered — locally-shadowing inner bindings are
/// excluded by `ScopeTree::references_of` semantics.
fn collect_module_scope_refs_in_file(
    text: &str,
    uri: &Uri,
    name: &str,
    out: &mut Vec<Location>,
) {
    let program = match parse_program(text) {
        Ok(p) => p,
        Err(_) => {
            let partial = shape_ast::parse_program_resilient(text);
            if partial.items.is_empty() {
                return;
            }
            partial.into_program()
        }
    };

    if !is_module_scope_symbol(&program, name) {
        return;
    }

    let tree = crate::scope::ScopeTree::build(&program, text);
    // Find any module-scope binding with this name. ScopeTree's first
    // scope is the module (root) scope; its bindings are the top-level
    // names.
    let Some(root) = tree.scopes.first() else {
        return;
    };
    for binding in &root.bindings {
        if binding.name != name {
            continue;
        }
        let push = |span: (usize, usize), out: &mut Vec<Location>| {
            let (sl, sc) = offset_to_line_col(text, span.0);
            let (el, ec) = offset_to_line_col(text, span.1);
            out.push(Location {
                uri: uri.clone(),
                range: Range {
                    start: Position {
                        line: sl,
                        character: sc,
                    },
                    end: Position {
                        line: el,
                        character: ec,
                    },
                },
            });
        };
        push(binding.def_span, out);
        for span in &binding.references {
            push(*span, out);
        }
    }
}

/// Find all references to a symbol at the given position, with cached program fallback.
pub fn get_references_with_fallback(
    text: &str,
    position: Position,
    uri: &Uri,
    cached_program: Option<&Program>,
) -> Option<Vec<Location>> {
    // Get the byte offset of the cursor
    let offset = position_to_offset(text, position)?;

    // Parse, falling back to cached program or resilient parser
    let program = match parse_program(text) {
        Ok(p) => p,
        Err(_) => {
            if let Some(cached) = cached_program {
                cached.clone()
            } else {
                let partial = shape_ast::parse_program_resilient(text);
                if partial.items.is_empty() {
                    return None;
                }
                partial.into_program()
            }
        }
    };
    let tree = crate::scope::ScopeTree::build(&program, text);

    // Find all references (def + uses) via scope-aware resolution
    let spans = tree.references_of(offset)?;

    let locations: Vec<Location> = spans
        .into_iter()
        .map(|(start, end)| {
            let (start_line, start_col) = offset_to_line_col(text, start);
            let (end_line, end_col) = offset_to_line_col(text, end);
            Location {
                uri: uri.clone(),
                range: Range {
                    start: Position {
                        line: start_line,
                        character: start_col,
                    },
                    end: Position {
                        line: end_line,
                        character: end_col,
                    },
                },
            }
        })
        .collect();

    if locations.is_empty() {
        // Fallback to text-based search if scope tree didn't find anything
        let word = get_word_at_position(text, position)?;
        let fallback = find_all_references(&program, &word, uri, text);
        if fallback.is_empty() {
            None
        } else {
            Some(fallback)
        }
    } else {
        Some(locations)
    }
}

/// Find the definition site of the *type* of the symbol at the cursor.
///
/// W2.5 feature 1.33 (`textDocument/typeDefinition`): given an expression
/// (typically a variable identifier), look up its inferred type name and
/// then navigate to that type's declaration site.
///
/// Strategy:
/// 1. Extract the word at the cursor.
/// 2. Use `infer_variable_type` to determine the variable's type as a string.
/// 3. Strip generic wrappers (e.g. `Array<T>` → `T`, `Option<T>` → `T`,
///    `HashMap<K,V>` → `K` falls back to `V`) and dereference / postfix `?`
///    decorations to recover a base type name.
/// 4. Re-use `find_definition_location` to look up that type name in the
///    current file, then fall back to imported definitions.
///
/// Returns `None` when no type can be inferred or when the inferred type is
/// a primitive (`int`, `number`, `bool`, `string`, etc.) for which no
/// user-visible definition site exists.
pub fn get_type_definition(
    text: &str,
    position: Position,
    uri: &Uri,
    module_cache: Option<&ModuleCache>,
    cached_program: Option<&Program>,
) -> Option<GotoDefinitionResponse> {
    let word = get_word_at_position(text, position)?;

    let program = match parse_program(text) {
        Ok(p) => p,
        Err(_) => {
            if let Some(cached) = cached_program {
                cached.clone()
            } else {
                let partial = shape_ast::parser::resilient::parse_program_resilient(text);
                if partial.items.is_empty() {
                    return None;
                }
                partial.into_program()
            }
        }
    };

    let inferred = infer_variable_type(&program, &word)?;
    let base = extract_base_type_name(&inferred)?;
    if is_builtin_primitive(&base) {
        return None;
    }

    if let Some(location) = find_definition_location(&program, &base, uri, text) {
        return Some(GotoDefinitionResponse::Scalar(location));
    }

    if let Some(cache) = module_cache {
        if let Some(location) = find_imported_definition(&program, &base, uri, cache) {
            return Some(GotoDefinitionResponse::Scalar(location));
        }
    }

    None
}

/// Find all `impl Trait for Type` blocks for the symbol at the cursor.
///
/// W2.5 feature 1.34 (`textDocument/implementation`): when the cursor is on
/// a trait name, return every impl block in the current file that targets
/// that trait. When the cursor is on a type name, return every impl block
/// (and extend block) whose target type matches.
///
/// LSP-K (audit §D regression flow): when the cursor is on a trait-method
/// name (inside the trait body, either `Required` signature or `Default`
/// method), return every matching impl-method body location across all
/// impl blocks in the current file that target the enclosing trait. This
/// is the trait-method → impl-method jump the audit §A.1 surfaced as
/// returning null.
///
/// This is a current-file-only enumeration; cross-workspace impl discovery
/// is part of the broader workspace-symbol indexing work tracked in W2.6/W2.7.
pub fn get_implementations(
    text: &str,
    position: Position,
    uri: &Uri,
    cached_program: Option<&Program>,
) -> Option<Vec<Location>> {
    let word = get_word_at_position(text, position)?;

    let program = match parse_program(text) {
        Ok(p) => p,
        Err(_) => {
            if let Some(cached) = cached_program {
                cached.clone()
            } else {
                let partial = shape_ast::parser::resilient::parse_program_resilient(text);
                if partial.items.is_empty() {
                    return None;
                }
                partial.into_program()
            }
        }
    };

    // LSP-K: trait-method → impl-method path. If the cursor sits on a
    // trait-method name (`Required` signature or `Default` method) inside
    // a trait body, surface every impl-method body that overrides it.
    if let Some(cursor_offset) = position_to_offset(text, position) {
        if let Some((trait_name, method_name)) =
            find_trait_method_at_offset(&program, cursor_offset, &word)
        {
            let impl_method_locations =
                collect_impl_method_locations(&program, trait_name, method_name, uri, text);
            if !impl_method_locations.is_empty() {
                return Some(impl_method_locations);
            }
        }
    }

    let mut locations: Vec<Location> = Vec::new();

    for item in &program.items {
        match item {
            Item::Impl(impl_block, item_span) => {
                let trait_str = type_name_str(&impl_block.trait_name);
                let target_str = type_name_str(&impl_block.target_type);
                if trait_str == word || target_str == word {
                    locations.push(create_location_from_span(uri, *item_span, text));
                }
            }
            Item::Extend(extend_stmt, item_span) => {
                let target_str = type_name_str(&extend_stmt.type_name);
                if target_str == word {
                    locations.push(create_location_from_span(uri, *item_span, text));
                }
            }
            _ => {}
        }
    }

    if locations.is_empty() {
        None
    } else {
        Some(locations)
    }
}

/// LSP-K helper: detect whether the cursor sits on a trait-method name
/// (in a `Required` signature or `Default` method) inside the body of a
/// `trait` item in the parsed program.
///
/// Returns `Some((trait_name, method_name))` when the offset falls inside
/// a trait-member span AND the cursor word matches the method's name.
/// The word match prevents drilling into impl-methods when the cursor is
/// on a method body keyword/identifier that happens to share a name with
/// another trait-method.
fn find_trait_method_at_offset<'p>(
    program: &'p Program,
    offset: usize,
    word: &str,
) -> Option<(&'p str, &'p str)> {
    for item in &program.items {
        if let Item::Trait(trait_def, _trait_span) = item {
            for member in &trait_def.members {
                match member {
                    TraitMember::Required(TraitMemberSignature::Method { name, span, .. }) => {
                        if offset >= span.start && offset <= span.end && name == word {
                            return Some((trait_def.name.as_str(), name.as_str()));
                        }
                    }
                    TraitMember::Default(method) => {
                        let span = method.span;
                        if offset >= span.start && offset <= span.end && method.name == word {
                            return Some((trait_def.name.as_str(), method.name.as_str()));
                        }
                    }
                    _ => {}
                }
            }
        }
    }
    None
}

/// LSP-K helper: collect impl-method body `Location`s for every
/// `impl <trait_name> for X` block whose method list contains a method
/// named `method_name`.
fn collect_impl_method_locations(
    program: &Program,
    trait_name: &str,
    method_name: &str,
    uri: &Uri,
    text: &str,
) -> Vec<Location> {
    let mut locations: Vec<Location> = Vec::new();
    for item in &program.items {
        if let Item::Impl(impl_block, _) = item {
            if type_name_str(&impl_block.trait_name) != trait_name {
                continue;
            }
            for method in &impl_block.methods {
                if method.name == method_name {
                    locations.push(create_location_from_span(uri, method.span, text));
                }
            }
        }
    }
    locations
}

/// Find the declaration site of a symbol at the cursor.
///
/// W2.5 feature 1.35 (`textDocument/declaration`): in languages with a
/// declaration/definition split (C++, etc.) this jumps to the declaration
/// (e.g. header file). Shape has no such split — every binding is its own
/// declaration — so this aliases to `get_definition` for VS-Code-style
/// `Ctrl+Click → Go to Declaration` interop.
pub fn get_declaration(
    text: &str,
    position: Position,
    uri: &Uri,
    module_cache: Option<&ModuleCache>,
    annotation_discovery: Option<&AnnotationDiscovery>,
    cached_program: Option<&Program>,
) -> Option<GotoDefinitionResponse> {
    get_definition(
        text,
        position,
        uri,
        module_cache,
        annotation_discovery,
        cached_program,
    )
}

/// Find all occurrences of the symbol at the cursor within the current file.
///
/// W2.5 feature 1.60 (`textDocument/documentHighlight`): editors use these
/// to highlight every usage of the cursor's symbol in the active file
/// (e.g. background-tint every `myVar` when the cursor is on one of them).
///
/// Reuses the scope-aware `ScopeTree::references_of` infrastructure that
/// powers in-file rename (`rename.rs`) so highlights respect lexical scope
/// and variable shadowing — falling back to text search only when the scope
/// tree cannot bind the position.
pub fn get_document_highlights(
    text: &str,
    position: Position,
    cached_program: Option<&Program>,
) -> Option<Vec<DocumentHighlight>> {
    let offset = position_to_offset(text, position)?;

    let program = match parse_program(text) {
        Ok(p) => p,
        Err(_) => {
            if let Some(cached) = cached_program {
                cached.clone()
            } else {
                let partial = shape_ast::parse_program_resilient(text);
                if partial.items.is_empty() {
                    return None;
                }
                partial.into_program()
            }
        }
    };

    let tree = crate::scope::ScopeTree::build(&program, text);

    let spans = tree.references_of(offset);

    let highlights: Vec<DocumentHighlight> = match spans {
        Some(spans) => spans
            .into_iter()
            .map(|(start, end)| span_to_highlight(text, start, end))
            .collect(),
        None => {
            // Fall back to text-based search to match the find-references behaviour.
            let word = get_word_at_position(text, position)?;
            text_search_highlights(text, &word)
        }
    };

    if highlights.is_empty() {
        None
    } else {
        Some(highlights)
    }
}

/// Word-boundary text-search variant of `find_all_references`, returning
/// `DocumentHighlight` ranges (no URI required — highlights are always
/// scoped to the active file per LSP spec).
fn text_search_highlights(text: &str, symbol_name: &str) -> Vec<DocumentHighlight> {
    let mut highlights = Vec::new();
    let lines: Vec<&str> = text.lines().collect();
    for (line_idx, line) in lines.iter().enumerate() {
        let mut char_pos = 0;
        while let Some(pos) = line[char_pos..].find(symbol_name) {
            let absolute_pos = char_pos + pos;
            let is_start_boundary = absolute_pos == 0
                || !line
                    .chars()
                    .nth(absolute_pos - 1)
                    .map(|c| c.is_alphanumeric() || c == '_')
                    .unwrap_or(false);
            let is_end_boundary = absolute_pos + symbol_name.len() >= line.len()
                || !line
                    .chars()
                    .nth(absolute_pos + symbol_name.len())
                    .map(|c| c.is_alphanumeric() || c == '_')
                    .unwrap_or(false);

            if is_start_boundary && is_end_boundary {
                highlights.push(DocumentHighlight {
                    range: Range {
                        start: Position {
                            line: line_idx as u32,
                            character: absolute_pos as u32,
                        },
                        end: Position {
                            line: line_idx as u32,
                            character: (absolute_pos + symbol_name.len()) as u32,
                        },
                    },
                    kind: Some(DocumentHighlightKind::TEXT),
                });
            }
            char_pos = absolute_pos + symbol_name.len();
        }
    }
    highlights
}

fn span_to_highlight(text: &str, start: usize, end: usize) -> DocumentHighlight {
    let (start_line, start_col) = offset_to_line_col(text, start);
    let (end_line, end_col) = offset_to_line_col(text, end);
    DocumentHighlight {
        range: Range {
            start: Position {
                line: start_line,
                character: start_col,
            },
            end: Position {
                line: end_line,
                character: end_col,
            },
        },
        kind: Some(DocumentHighlightKind::TEXT),
    }
}

/// Render a `TypeName` AST node as its bare leading identifier.
fn type_name_str(type_name: &TypeName) -> &str {
    match type_name {
        TypeName::Simple(n) => n.as_str(),
        TypeName::Generic { name, .. } => name.as_str(),
    }
}

/// Extract the user-visible base identifier from a rendered type string.
///
/// Inputs are produced by `type_inference::infer_variable_type`, which renders
/// strings like `"Array<Point>"`, `"Option<Point>"`, `"Point"`, `"Point?"`,
/// `"&Point"`. This function peels generic wrappers / decorations and returns
/// the inner-most identifier suitable for a `find_definition_location` lookup.
///
/// Returns `None` for empty / whitespace-only / object-shape strings (`"{...}"`)
/// where no nameable type exists.
fn extract_base_type_name(rendered: &str) -> Option<String> {
    let mut current: String = rendered.trim().to_string();
    if current.is_empty() || current.starts_with('{') {
        return None;
    }

    // Strip leading reference markers.
    loop {
        let trimmed = current.trim_start();
        if let Some(rest) = trimmed.strip_prefix("&mut ") {
            current = rest.trim_start().to_string();
        } else if let Some(rest) = trimmed.strip_prefix('&') {
            current = rest.trim_start().to_string();
        } else {
            break;
        }
    }

    // Strip trailing `?` (Option sugar) until none remain.
    while let Some(rest) = current.strip_suffix('?') {
        current = rest.trim_end().to_string();
    }

    // Unwrap one level of common generic carriers — repeated to handle
    // `Array<Option<Point>>`-style nesting.
    loop {
        let unwrapped: Option<String> = if let Some(inner) = strip_generic_wrapper(&current, "Array")
        {
            Some(inner.to_string())
        } else if let Some(inner) = strip_generic_wrapper(&current, "Option") {
            Some(inner.to_string())
        } else if let Some(inner) = strip_generic_wrapper(&current, "Result") {
            // Result<T, E> — first generic arg is the success type.
            Some(first_generic_arg(inner).to_string())
        } else if let Some(inner) = strip_generic_wrapper(&current, "HashMap") {
            // HashMap<K, V> — first arg keeps it deterministic.
            Some(first_generic_arg(inner).to_string())
        } else {
            None
        };
        match unwrapped {
            Some(inner) => {
                let inner_trim = inner.trim().to_string();
                if inner_trim == current {
                    break;
                }
                current = inner_trim;
            }
            None => break,
        }
    }

    // Final shape: must be a single identifier (no `<`, no whitespace, no `,`).
    let base = current
        .split(|c: char| c == '<' || c == ',' || c.is_whitespace())
        .next()?;
    let base = base.trim();
    if base.is_empty() {
        None
    } else {
        Some(base.to_string())
    }
}

/// If `s` matches `Name<...>`, return the `...` portion. Else `None`.
fn strip_generic_wrapper<'a>(s: &'a str, name: &str) -> Option<&'a str> {
    let s = s.strip_prefix(name)?.trim_start();
    let s = s.strip_prefix('<')?;
    let s = s.strip_suffix('>')?;
    Some(s)
}

fn first_generic_arg(args: &str) -> &str {
    args.split(',').next().unwrap_or(args).trim()
}

/// Primitive type names that have no user-visible definition site.
fn is_builtin_primitive(name: &str) -> bool {
    matches!(
        name,
        "int"
            | "number"
            | "bool"
            | "string"
            | "decimal"
            | "bigint"
            | "unit"
            | "null"
            | "DateTime"
            | "unknown"
            | "any"
    )
}

/// Find the location where a symbol is defined
fn find_definition_location(
    program: &Program,
    symbol_name: &str,
    uri: &Uri,
    text: &str,
) -> Option<Location> {
    for item in &program.items {
        match item {
            Item::Function(func, _) if func.name == symbol_name => {
                return Some(create_location_from_span(uri, func.name_span, text));
            }
            Item::VariableDecl(var_decl, item_span) => {
                for (name, name_span) in crate::symbols::get_pattern_names(&var_decl.pattern) {
                    if name == symbol_name {
                        let span = if name_span.is_dummy() {
                            *item_span
                        } else {
                            name_span
                        };
                        return Some(create_location_from_span(uri, span, text));
                    }
                }
            }
            Item::Statement(Statement::VariableDecl(var_decl, stmt_span), _) => {
                for (name, name_span) in crate::symbols::get_pattern_names(&var_decl.pattern) {
                    if name == symbol_name {
                        let span = if name_span.is_dummy() {
                            *stmt_span
                        } else {
                            name_span
                        };
                        return Some(create_location_from_span(uri, span, text));
                    }
                }
            }
            Item::TypeAlias(type_alias, item_span) if type_alias.name == symbol_name => {
                return Some(create_location_from_span(uri, *item_span, text));
            }
            Item::Enum(enum_def, item_span) if enum_def.name == symbol_name => {
                return Some(create_location_from_span(uri, *item_span, text));
            }
            Item::Trait(trait_def, item_span) if trait_def.name == symbol_name => {
                return Some(create_location_from_span(uri, *item_span, text));
            }
            Item::Impl(impl_block, _) => {
                // Navigate from impl method name to trait definition
                let trait_name_str = match &impl_block.trait_name {
                    shape_ast::ast::TypeName::Simple(n) => n.as_str(),
                    shape_ast::ast::TypeName::Generic { name, .. } => name.as_str(),
                };
                // If clicking on the trait name in `impl TraitName for Type`,
                // navigate to the trait definition
                if trait_name_str == symbol_name {
                    // Find the trait definition elsewhere in the program
                    for other_item in &program.items {
                        if let Item::Trait(td, ts) = other_item {
                            if td.name == symbol_name {
                                return Some(create_location_from_span(uri, *ts, text));
                            }
                        }
                    }
                }
                // If clicking on a method name inside the impl block,
                // navigate to the trait's method signature
                for method in &impl_block.methods {
                    if method.name == symbol_name {
                        // Find the trait definition and navigate to the method member
                        for other_item in &program.items {
                            if let Item::Trait(td, ts) = other_item {
                                if td.name == trait_name_str {
                                    // Return trait span (method-level spans not yet available)
                                    return Some(create_location_from_span(uri, *ts, text));
                                }
                            }
                        }
                    }
                }
            }
            Item::Extend(extend_stmt, item_span) => {
                // Navigate from method name usage to method definition in extend block
                for method in &extend_stmt.methods {
                    if method.name == symbol_name {
                        return Some(create_location_from_span(uri, *item_span, text));
                    }
                }
            }
            Item::StructType(struct_def, item_span) if struct_def.name == symbol_name => {
                return Some(create_location_from_span(uri, *item_span, text));
            }
            _ => {}
        }
    }

    // Sprint 4L: If the symbol is "format" and it's a method call on a typed object,
    // try to navigate to the Display trait impl for that type.
    if symbol_name == "format" || symbol_name == "toString" {
        // Find impl Display for ... blocks
        for item in &program.items {
            if let Item::Impl(impl_block, item_span) = item {
                let trait_name_str = match &impl_block.trait_name {
                    shape_ast::ast::TypeName::Simple(n) => n.as_str(),
                    shape_ast::ast::TypeName::Generic { name, .. } => name.as_str(),
                };
                if trait_name_str == "Display" {
                    // Check if the impl block has a method matching our symbol
                    for method in &impl_block.methods {
                        if method.name == symbol_name {
                            return Some(create_location_from_span(uri, *item_span, text));
                        }
                    }
                    // Even if method not found, navigate to impl block
                    return Some(create_location_from_span(uri, *item_span, text));
                }
            }
        }
    }

    None
}

/// Find all references to a symbol in the program
fn find_all_references(
    _program: &Program,
    symbol_name: &str,
    uri: &Uri,
    text: &str,
) -> Vec<Location> {
    let mut locations = Vec::new();
    let lines: Vec<&str> = text.lines().collect();

    // Simple approach: find all occurrences of the symbol name in the text
    // A more sophisticated approach would parse the AST and find identifier references
    for (line_idx, line) in lines.iter().enumerate() {
        let mut char_pos = 0;
        while let Some(pos) = line[char_pos..].find(symbol_name) {
            let absolute_pos = char_pos + pos;

            // Check if it's a word boundary (not part of another identifier)
            let is_start_boundary = absolute_pos == 0
                || !line
                    .chars()
                    .nth(absolute_pos - 1)
                    .map(|c| c.is_alphanumeric() || c == '_')
                    .unwrap_or(false);

            let is_end_boundary = absolute_pos + symbol_name.len() >= line.len()
                || !line
                    .chars()
                    .nth(absolute_pos + symbol_name.len())
                    .map(|c| c.is_alphanumeric() || c == '_')
                    .unwrap_or(false);

            if is_start_boundary && is_end_boundary {
                locations.push(Location {
                    uri: uri.clone(),
                    range: Range {
                        start: Position {
                            line: line_idx as u32,
                            character: absolute_pos as u32,
                        },
                        end: Position {
                            line: line_idx as u32,
                            character: (absolute_pos + symbol_name.len()) as u32,
                        },
                    },
                });
            }

            char_pos = absolute_pos + symbol_name.len();
        }
    }

    locations
}

/// Create a location from a span
fn create_location_from_span(uri: &Uri, span: Span, text: &str) -> Location {
    let (start_line, start_col) = offset_to_line_col(text, span.start);
    let (end_line, end_col) = offset_to_line_col(text, span.end);

    Location {
        uri: uri.clone(),
        range: Range {
            start: Position {
                line: start_line,
                character: start_col,
            },
            end: Position {
                line: end_line,
                character: end_col,
            },
        },
    }
}

/// Find the definition of a symbol in imported modules
fn find_imported_definition(
    program: &Program,
    symbol_name: &str,
    current_uri: &Uri,
    module_cache: &ModuleCache,
) -> Option<Location> {
    // Get current file path from URI
    let current_path = current_uri.to_file_path()?.into_owned();

    // Look through import statements to find where the symbol comes from
    for item in &program.items {
        if let Item::Import(import_stmt, _span) = item {
            // Check if this import includes the symbol we're looking for
            let imports_symbol = match &import_stmt.items {
                ImportItems::Named(specs) => specs.iter().any(|spec| {
                    let imported_name = spec.alias.as_ref().unwrap_or(&spec.name);
                    imported_name == symbol_name
                }),
                ImportItems::Namespace { name, alias } => {
                    let local_name = alias.as_ref().unwrap_or(name);
                    local_name == symbol_name
                }
            };

            if !imports_symbol {
                continue;
            }

            // Resolve the import path
            // Note: module resolution uses dot-separated paths.
            // std. imports resolve via stdlib path.
            let resolved_path =
                module_cache.resolve_import(&import_stmt.from, &current_path, None)?;

            // Load the module
            let module_info =
                module_cache.load_module_with_context(&resolved_path, &current_path, None)?;

            // Find the symbol in the module's exports
            for export in &module_info.exports {
                if export.exported_name() == symbol_name {
                    // Find the actual definition in the module's program
                    let target_uri = Uri::from_file_path(&module_info.path)?;
                    let source = std::fs::read_to_string(&module_info.path).ok()?;

                    // Look up the definition in the target module
                    let location = find_definition_location(
                        &module_info.program,
                        &export.name,
                        &target_uri,
                        &source,
                    )?;

                    return Some(location);
                }
            }
        }
    }

    None
}

/// Find the definition of an annotation
fn find_annotation_definition(
    annotation_name: &str,
    annotation_discovery: &AnnotationDiscovery,
    current_uri: &Uri,
) -> Option<Location> {
    // Get annotation info
    let info = annotation_discovery.get(annotation_name)?;

    // If the annotation has a valid location (not a built-in), create a location
    if info.location != Span::default() {
        // Determine which file the annotation is defined in
        let target_uri = if let Some(ref source_path) = info.source_file {
            // Imported annotation — navigate to the source file
            Uri::from_file_path(source_path)?
        } else {
            // Local annotation — same file
            current_uri.clone()
        };

        // Read source to convert byte offset to line/col
        let source = if let Some(ref source_path) = info.source_file {
            std::fs::read_to_string(source_path).ok()?
        } else {
            // For local annotations, we'd need the current file text
            // but we don't have it here. Return a reasonable position.
            return Some(Location {
                uri: target_uri,
                range: Range {
                    start: Position {
                        line: 0,
                        character: 0,
                    },
                    end: Position {
                        line: 0,
                        character: 0,
                    },
                },
            });
        };

        let (line, col) = offset_to_line_col(&source, info.location.start);
        Some(Location {
            uri: target_uri,
            range: Range {
                start: Position {
                    line,
                    character: col,
                },
                end: Position {
                    line,
                    character: col + annotation_name.len() as u32,
                },
            },
        })
    } else {
        None
    }
}

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

    #[test]
    fn test_get_word_at_position() {
        let text = "let myVar = 5;";
        let word = get_word_at_position(
            text,
            Position {
                line: 0,
                character: 5,
            },
        );
        assert_eq!(word, Some("myVar".to_string()));
    }

    #[test]
    fn test_find_function_definition() {
        let code = r#"function myFunc(x, y) {
    return x + y;
}

let result = myFunc(1, 2);
"#;
        let program = parse_program(code).unwrap();
        let uri = Uri::from_file_path("/test.shape").unwrap();

        let location = find_definition_location(&program, "myFunc", &uri, code);
        assert!(location.is_some());

        let loc = location.unwrap();
        assert_eq!(loc.range.start.line, 0);
        // Should point to the function name "myFunc"
        assert_eq!(loc.range.start.character, 9); // "function " is 9 chars
    }

    #[test]
    fn test_find_variable_definition() {
        let code = r#"let myVar = 42;
let x = myVar + 5;
"#;
        let program = parse_program(code).unwrap();
        let uri = Uri::from_file_path("/test.shape").unwrap();

        let location = find_definition_location(&program, "myVar", &uri, code);
        assert!(location.is_some());
    }

    #[test]
    fn test_find_references() {
        let code = r#"let myVar = 42;
let x = myVar + 5;
let y = myVar * 2;
"#;
        let program = parse_program(code).unwrap();
        let uri = Uri::from_file_path("/test.shape").unwrap();

        let refs = find_all_references(&program, "myVar", &uri, code);
        assert_eq!(refs.len(), 3); // Definition + 2 usages
    }

    #[test]
    fn test_get_definition_with_module_cache() {
        let code = r#"function localFunc() {
    return 42;
}
"#;
        let uri = Uri::from_file_path("/test.shape").unwrap();
        let cache = ModuleCache::new();

        let definition = get_definition(
            code,
            Position {
                line: 0,
                character: 10,
            },
            &uri,
            Some(&cache),
            None,
            None,
        );
        assert!(definition.is_some());
    }

    #[test]
    fn test_find_imported_definition_not_found() {
        let code = r#"from utils use { foo };

let x = foo();
"#;
        let program = parse_program(code).unwrap();
        let uri = Uri::from_file_path("/test.shape").unwrap();
        let cache = ModuleCache::new();

        // This will return None because the module doesn't exist
        let location = find_imported_definition(&program, "foo", &uri, &cache);
        assert!(location.is_none());
    }

    // --- W2.5: definition family extras (typeDefinition / implementation /
    //          declaration / documentHighlight) tests ---

    #[test]
    fn test_extract_base_type_name_plain() {
        assert_eq!(extract_base_type_name("Point"), Some("Point".to_string()));
    }

    #[test]
    fn test_extract_base_type_name_array_wrapper() {
        assert_eq!(
            extract_base_type_name("Array<Point>"),
            Some("Point".to_string())
        );
    }

    #[test]
    fn test_extract_base_type_name_option_question_mark() {
        assert_eq!(extract_base_type_name("Point?"), Some("Point".to_string()));
    }

    #[test]
    fn test_extract_base_type_name_option_wrapper() {
        assert_eq!(
            extract_base_type_name("Option<Point>"),
            Some("Point".to_string())
        );
    }

    #[test]
    fn test_extract_base_type_name_reference() {
        assert_eq!(
            extract_base_type_name("&mut Point"),
            Some("Point".to_string())
        );
        assert_eq!(extract_base_type_name("&Point"), Some("Point".to_string()));
    }

    #[test]
    fn test_extract_base_type_name_nested() {
        assert_eq!(
            extract_base_type_name("Array<Option<Point>>"),
            Some("Point".to_string())
        );
    }

    #[test]
    fn test_extract_base_type_name_result() {
        assert_eq!(
            extract_base_type_name("Result<Point, Error>"),
            Some("Point".to_string())
        );
    }

    #[test]
    fn test_extract_base_type_name_object_shape_skipped() {
        // Object-literal shape strings have no nameable type to navigate to.
        assert_eq!(extract_base_type_name("{ x: int, y: int }"), None);
    }

    #[test]
    fn test_is_builtin_primitive_filters_int() {
        assert!(is_builtin_primitive("int"));
        assert!(is_builtin_primitive("string"));
        assert!(!is_builtin_primitive("Point"));
    }

    #[test]
    fn test_get_implementations_finds_impl_block() {
        let code = r#"trait Greet {
    method greet() -> string
}

type Cat { name: string }

impl Greet for Cat {
    method greet() { return "meow" }
}
"#;
        // Sanity-check parse — surface any imprecision in test fixture syntax.
        let program = parse_program(code).expect("test fixture must parse");
        let impl_count = program
            .items
            .iter()
            .filter(|i| matches!(i, Item::Impl(_, _)))
            .count();
        assert!(impl_count >= 1, "Expected at least 1 Item::Impl in parsed program");

        let uri = Uri::from_file_path("/test.shape").unwrap();
        // Cursor on "Greet" trait name in the impl line (line 6, after "impl ").
        let impls = get_implementations(
            code,
            Position {
                line: 6,
                character: 6,
            },
            &uri,
            None,
        );
        assert!(impls.is_some(), "Should find impl block for trait Greet");
        let locations = impls.unwrap();
        assert_eq!(locations.len(), 1);
    }

    #[test]
    fn test_get_implementations_by_target_type() {
        // Cursor on the *target* type (Cat) should also surface the impl.
        let code = r#"trait Greet {
    method greet() -> string
}

type Cat { name: string }

impl Greet for Cat {
    method greet() { return "meow" }
}
"#;
        let program = parse_program(code).expect("test fixture must parse");
        assert!(program.items.iter().any(|i| matches!(i, Item::Impl(_, _))));

        let uri = Uri::from_file_path("/test.shape").unwrap();
        // Cursor on "Cat" target — line 6, char 16 ("impl Greet for Cat" — 'C' of Cat).
        let impls = get_implementations(
            code,
            Position {
                line: 6,
                character: 16,
            },
            &uri,
            None,
        );
        assert!(
            impls.is_some(),
            "Should find impl block when cursor is on target type Cat"
        );
    }

    #[test]
    fn test_get_declaration_aliases_definition() {
        let code = r#"let myVar = 42;
let x = myVar + 5;
"#;
        let uri = Uri::from_file_path("/test.shape").unwrap();
        // Cursor on `myVar` use on line 1.
        let decl = get_declaration(
            code,
            Position {
                line: 1,
                character: 9,
            },
            &uri,
            None,
            None,
            None,
        );
        let def = get_definition(
            code,
            Position {
                line: 1,
                character: 9,
            },
            &uri,
            None,
            None,
            None,
        );
        assert_eq!(decl.is_some(), def.is_some());
    }

    #[test]
    fn test_get_document_highlights_finds_variable_uses() {
        let code = r#"let myVar = 42;
let x = myVar + 5;
let y = myVar * 2;
"#;
        // Cursor on the definition site of `myVar`.
        let highlights = get_document_highlights(
            code,
            Position {
                line: 0,
                character: 6,
            },
            None,
        );
        assert!(highlights.is_some(), "Should find highlights for myVar");
        let hs = highlights.unwrap();
        assert!(
            hs.len() >= 3,
            "Expected at least 3 highlights (def + 2 uses), got {}",
            hs.len()
        );
        for h in &hs {
            assert_eq!(h.kind, Some(DocumentHighlightKind::TEXT));
        }
    }

    #[test]
    fn test_get_document_highlights_returns_none_off_symbol() {
        let code = "let myVar = 42;\n";
        // Cursor on whitespace before `let`.
        let highlights = get_document_highlights(
            code,
            Position {
                line: 0,
                character: 0,
            },
            None,
        );
        // ScopeTree won't bind at offset 0, fallback path needs a word — none here.
        // Result depends on the surrounding text; ensure the call doesn't panic.
        let _ = highlights;
    }

    #[test]
    fn test_is_module_scope_symbol_top_level_fn() {
        let code = "fn foo() { return 1 }\nlet x = foo()";
        let program = parse_program(code).unwrap();
        assert!(is_module_scope_symbol(&program, "foo"));
        assert!(is_module_scope_symbol(&program, "x"));
        // Inner locals are not module-scope-visible.
        assert!(!is_module_scope_symbol(&program, "nope"));
    }

    #[test]
    fn test_collect_module_scope_refs_finds_call_site() {
        let text = "fn helper() { return 1 }\nlet x = helper() + helper()";
        let uri = Uri::from_file_path("/other.shape").unwrap();
        let mut out = Vec::new();
        collect_module_scope_refs_in_file(text, &uri, "helper", &mut out);
        // def + 2 references = 3 locations
        assert!(
            out.len() >= 3,
            "expected def + at least 2 refs to `helper`, got {}",
            out.len()
        );
    }

    #[test]
    fn test_get_references_cross_file_module_scope() {
        // Simulate two open documents that both reference `shared`.
        use crate::document::DocumentManager;
        let docs = DocumentManager::new();
        let main_text = "fn shared() { return 1 }\nlet a = shared()".to_string();
        let other_text = "fn shared() { return 2 }\nlet b = shared() + shared()".to_string();
        let main_uri = Uri::from_file_path("/main.shape").unwrap();
        let other_uri = Uri::from_file_path("/other.shape").unwrap();
        docs.open(main_uri.clone(), 1, main_text.clone());
        docs.open(other_uri.clone(), 1, other_text);

        // Click on `shared` in main.shape (col 3 of `fn shared()`)
        let pos = Position {
            line: 0,
            character: 3,
        };
        let refs = get_references_cross_file(
            &main_text,
            pos,
            &main_uri,
            None,
            Some(&docs),
            None,
            None,
        )
        .expect("should find cross-file references");
        // Local def + local 1 use + other def + other 2 uses = 5
        assert!(
            refs.len() >= 4,
            "expected cross-file refs, got {}: {:?}",
            refs.len(),
            refs
        );
        assert!(
            refs.iter().any(|loc| &loc.uri == &other_uri),
            "expected at least one reference from /other.shape"
        );
    }

    #[test]
    fn test_get_references_cross_file_local_binding_no_crossover() {
        // Local `let` inside a function — should NOT cascade to other files.
        use crate::document::DocumentManager;
        let docs = DocumentManager::new();
        let main_text =
            "fn outer() {\n  let local = 1\n  return local + local\n}".to_string();
        let other_text =
            "fn other() {\n  let local = 5\n  return local\n}".to_string();
        let main_uri = Uri::from_file_path("/main.shape").unwrap();
        let other_uri = Uri::from_file_path("/other.shape").unwrap();
        docs.open(main_uri.clone(), 1, main_text.clone());
        docs.open(other_uri.clone(), 1, other_text);

        // Click on `local` in main.shape at its definition site
        let local_offset = main_text.find("local").unwrap();
        let (line, col) = offset_to_line_col(&main_text, local_offset);
        let pos = Position {
            line,
            character: col,
        };
        let refs = get_references_cross_file(
            &main_text,
            pos,
            &main_uri,
            None,
            Some(&docs),
            None,
            None,
        );
        // Expect refs only in main.shape (local-scope binding)
        if let Some(refs) = refs {
            assert!(
                refs.iter().all(|loc| &loc.uri == &main_uri),
                "local-scope `local` should NOT cascade to other files, got: {:?}",
                refs
            );
        }
    }

    #[test]
    fn test_references_with_broken_code() {
        // Code with a syntax error after a valid function
        let code =
            "fn greet(name) {\n  return name\n}\nlet x = greet(\"hi\")\n??broken syntax here";
        let uri = Uri::from_file_path("/test.shape").unwrap();

        // Position on "greet" in the function definition (line 0, char 3)
        let refs = get_references_with_fallback(
            code,
            Position {
                line: 0,
                character: 3,
            },
            &uri,
            None, // no cached program, relies on resilient parser
        );

        // With resilient parsing, we should find at least the definition of "greet"
        assert!(
            refs.is_some(),
            "Should find references even with broken code via resilient parsing"
        );
    }

    // W14.2-B1: per-line coverage additions
    #[test]
    fn test_get_definition_returns_none_for_non_identifier_position() {
        let code = "let x = 5\n";
        let uri = Uri::from_file_path("/test.shape").unwrap();
        // Position on `=` (non-identifier)
        let result = get_definition(
            code,
            Position {
                line: 0,
                character: 6,
            },
            &uri,
            None,
            None,
            None,
        );
        assert!(result.is_none(), "expected None at non-identifier position");
    }

    #[test]
    fn test_get_definition_finds_function_at_call_site() {
        let code = "fn myFunc() { return 1 }\nlet x = myFunc()\n";
        let uri = Uri::from_file_path("/test.shape").unwrap();
        // Position on `myFunc` at call site
        let result = get_definition(
            code,
            Position {
                line: 1,
                character: 9,
            },
            &uri,
            None,
            None,
            None,
        );
        assert!(result.is_some(), "expected definition at call site");
    }

    #[test]
    fn test_get_definition_unknown_symbol_returns_none() {
        let code = "let x = neverDefined\n";
        let uri = Uri::from_file_path("/test.shape").unwrap();
        // Position on `neverDefined`
        let result = get_definition(
            code,
            Position {
                line: 0,
                character: 8,
            },
            &uri,
            None,
            None,
            None,
        );
        assert!(result.is_none(), "expected None for unknown symbol");
    }

    #[test]
    fn test_get_type_definition_returns_none_for_unknown_symbol() {
        let code = "let x = 5\n";
        let uri = Uri::from_file_path("/test.shape").unwrap();
        let result = get_type_definition(
            code,
            Position {
                line: 0,
                character: 4,
            },
            &uri,
            None,
            None,
        );
        // int is a primitive — type definition returns None.
        assert!(result.is_none(), "expected None for primitive type");
    }

    #[test]
    fn test_get_implementations_returns_none_for_no_impls() {
        let code = "let x = 5\n";
        let uri = Uri::from_file_path("/test.shape").unwrap();
        let result = get_implementations(
            code,
            Position {
                line: 0,
                character: 4,
            },
            &uri,
            None,
        );
        assert!(result.is_none(), "expected None when no impls exist");
    }

    #[test]
    fn test_get_implementations_finds_impl_by_trait_name() {
        let code = "trait Q { fn q(self) -> int; }\ntype T { x: int }\nimpl Q for T { fn q(self) -> int { 1 } }\n";
        let uri = Uri::from_file_path("/test.shape").unwrap();
        // Position on "Q" in the trait header at line 2 (0-indexed)
        let result = get_implementations(
            code,
            Position {
                line: 2,
                character: 5,
            },
            &uri,
            None,
        );
        assert!(result.is_some(), "expected impl-block location for Q");
        let locs = result.unwrap();
        assert!(!locs.is_empty());
    }

    // == LSP-K: trait-method → impl-method body jump ============================

    #[test]
    fn test_get_implementations_jumps_from_trait_method_to_impl_method() {
        // LSP-K: cursor on the trait-method name `q` (line 0 char 13, the 'q'
        // inside `fn q(self)` of the trait body) must surface the impl-method
        // body, not the impl block as a whole.
        let code = "trait Q { fn q(self) -> int; }\ntype T { x: int }\nimpl Q for T { fn q(self) -> int { 1 } }\n";
        let uri = Uri::from_file_path("/test.shape").unwrap();
        let result = get_implementations(
            code,
            Position {
                line: 0,
                character: 13,
            },
            &uri,
            None,
        );
        assert!(
            result.is_some(),
            "expected impl-method location for trait-method 'q'"
        );
        let locs = result.unwrap();
        assert_eq!(locs.len(), 1, "expected exactly one impl-method match");
        // The returned range must fall inside the impl block on line 2 — that
        // is, NOT the trait declaration itself on line 0.
        assert_eq!(locs[0].range.start.line, 2);
    }

    #[test]
    fn test_get_implementations_trait_method_multi_impls() {
        // Multiple impls of the same trait — all impl-method bodies must
        // appear in the result.
        let code = "trait Greet {\n    fn hello(self) -> string;\n}\ntype Cat { name: string }\ntype Dog { name: string }\nimpl Greet for Cat {\n    fn hello(self) -> string { return \"meow\" }\n}\nimpl Greet for Dog {\n    fn hello(self) -> string { return \"woof\" }\n}\n";
        let uri = Uri::from_file_path("/test.shape").unwrap();
        // Cursor on the trait-method name `hello` (line 1).
        let result = get_implementations(
            code,
            Position {
                line: 1,
                character: 7,
            },
            &uri,
            None,
        );
        assert!(
            result.is_some(),
            "expected impl-method locations for trait-method 'hello'"
        );
        let locs = result.unwrap();
        assert_eq!(locs.len(), 2, "expected two impl-method matches");
    }

    #[test]
    fn test_get_implementations_default_trait_method_still_finds_impls() {
        // Cursor on a default-method name in a trait body — impls that
        // override it must still surface.
        let code = "trait Greet {\n    fn hello(self) -> string { return \"hi\" }\n}\ntype Cat { name: string }\nimpl Greet for Cat {\n    fn hello(self) -> string { return \"meow\" }\n}\n";
        let uri = Uri::from_file_path("/test.shape").unwrap();
        // Cursor on `hello` in the default-method body's signature line.
        let result = get_implementations(
            code,
            Position {
                line: 1,
                character: 7,
            },
            &uri,
            None,
        );
        assert!(
            result.is_some(),
            "expected impl-method location for default trait-method 'hello'"
        );
        let locs = result.unwrap();
        // Default-method body is itself in the trait — the impl override is
        // the only "implementation" target.
        assert_eq!(locs.len(), 1);
    }

    #[test]
    fn test_get_implementations_trait_name_still_returns_impl_block() {
        // Regression guard for the existing trait-name → impl-block path
        // (LSP-D's existing behavior must not be broken by LSP-K).
        let code = "trait Q { fn q(self) -> int; }\ntype T { x: int }\nimpl Q for T { fn q(self) -> int { 1 } }\n";
        let uri = Uri::from_file_path("/test.shape").unwrap();
        // Cursor on the trait name `Q` in the impl header.
        let result = get_implementations(
            code,
            Position {
                line: 2,
                character: 5,
            },
            &uri,
            None,
        );
        assert!(result.is_some(), "trait-name path must still resolve");
        let locs = result.unwrap();
        assert_eq!(locs.len(), 1);
        // The trait-name path returns the impl BLOCK range, which begins on
        // line 2 (start of `impl Q for T { ... }`).
        assert_eq!(locs[0].range.start.line, 2);
    }

    #[test]
    fn test_get_implementations_trait_method_no_matching_impl() {
        // Trait-method exists, but no impl provides it — return None
        // (the impl-method path must not fall back to the impl-block path
        // here, since the cursor is on a trait-method, not a trait-name).
        let code = "trait Q { fn q(self) -> int; }\n";
        let uri = Uri::from_file_path("/test.shape").unwrap();
        let result = get_implementations(
            code,
            Position {
                line: 0,
                character: 13,
            },
            &uri,
            None,
        );
        // No impls at all → None is correct (current-file enumeration).
        assert!(result.is_none());
    }

    #[test]
    fn test_get_document_highlights_returns_none_off_word() {
        let code = "let x = 5\n";
        let result = get_document_highlights(
            code,
            Position {
                line: 0,
                character: 6, // on `=`
            },
            None,
        );
        // Off any identifier — should still be Some or None gracefully.
        // The function should not panic; success is just-don't-crash.
        let _ = result;
    }

    #[test]
    fn test_get_references_cross_file_no_documents_or_cache() {
        let code = "fn foo() { return 1 }\nlet x = foo()\n";
        let uri = Uri::from_file_path("/test.shape").unwrap();
        let result = get_references_cross_file(
            code,
            Position {
                line: 0,
                character: 3,
            },
            &uri,
            None, // cached_program
            None, // documents
            None, // module_cache
            None, // workspace_root
        );
        // Should still find local references via get_references.
        assert!(result.is_some(), "expected local references when no cross-file context");
    }

    #[test]
    fn test_get_declaration_aliases_get_definition() {
        let code = "fn foo() { return 1 }\nlet x = foo()\n";
        let uri = Uri::from_file_path("/test.shape").unwrap();
        let pos = Position {
            line: 1,
            character: 9,
        };
        let decl = get_declaration(code, pos, &uri, None, None, None);
        let def = get_definition(code, pos, &uri, None, None, None);
        // Should produce equivalent results (both Some or both None)
        assert_eq!(decl.is_some(), def.is_some());
    }
}