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
//! Code actions provider for Shape
//!
//! Provides quick fixes, refactoring actions, and source actions.

use crate::doc_actions::generate_doc_comment_action;
use crate::module_cache::ModuleCache;
use crate::util::{get_word_at_position, span_to_range};
use shape_ast::ast::{ImportItems, Item};
use shape_ast::parser::parse_program;
use std::collections::{HashMap, HashSet};
use tower_lsp_server::ls_types::{
    CodeAction, CodeActionKind, CodeActionOrCommand, Diagnostic, NumberOrString, Position, Range,
    TextEdit, Uri, WorkspaceEdit,
};

/// W2.3 / 1.40 — extract the canonical error code string from a diagnostic.
///
/// Returns `None` for diagnostics without a code (e.g. frontmatter
/// diagnostics that intentionally omit codes). The string form is the
/// canonical Shape error code (e.g. `"E0100"`, `"W0102"`, `"B0001"`).
fn diagnostic_code(diagnostic: &Diagnostic) -> Option<&str> {
    match &diagnostic.code {
        Some(NumberOrString::String(s)) => Some(s.as_str()),
        _ => None,
    }
}

/// Get code actions for a document at a given range
pub fn get_code_actions(
    text: &str,
    uri: &Uri,
    range: Range,
    diagnostics: &[Diagnostic],
    module_cache: Option<&ModuleCache>,
    requested_kinds: Option<&[CodeActionKind]>,
) -> Vec<CodeActionOrCommand> {
    let mut actions = Vec::new();

    if is_kind_requested(requested_kinds, CodeActionKind::QUICKFIX.as_str()) {
        // Add quick fixes for diagnostics at/near the requested range.
        for diagnostic in diagnostics {
            if ranges_overlap(range, diagnostic.range) {
                if let Some(fix_actions) = get_quick_fixes(text, uri, diagnostic, module_cache) {
                    actions.extend(fix_actions);
                }
            }
        }

        // Also offer symbol-based auto-import when the cursor is on an unresolved
        // type-like identifier, even if diagnostics are stale/misaligned.
        if let Some(cache) = module_cache {
            actions.extend(get_symbol_auto_import_actions(text, uri, range, cache));
        }
    }

    // Add refactoring actions based on selection
    if is_group_requested(requested_kinds, CodeActionKind::REFACTOR.as_str()) {
        if let Some(doc_action) = generate_doc_comment_action(text, uri, range) {
            actions.push(doc_action);
        }
        if let Some(refactor_actions) = get_refactor_actions(text, uri, range) {
            actions.extend(refactor_actions);
        }
    }

    // Add source actions (organize imports, etc.)
    if is_group_requested(requested_kinds, CodeActionKind::SOURCE.as_str()) {
        if let Some(source_actions) =
            get_source_actions(text, uri, range, diagnostics, module_cache, requested_kinds)
        {
            actions.extend(source_actions);
        }
    }

    dedupe_actions(actions)
}

/// Get quick fixes for a diagnostic.
///
/// W2.3 / 1.40 — fixes are dispatched primarily off `diagnostic.code`
/// (e.g. `E0101` undefined, `E0001` unexpected-token, `W0102` unused
/// import) with `diagnostic.message` substring matching retained as a
/// fallback for diagnostics that don't carry a code (e.g. some
/// frontmatter / foreign-LSP diagnostics) or that originated from
/// renamings that haven't been wired through the code table yet. The
/// code-keyed path is the canonical trigger; message matching is the
/// fallback for the un-coded subset.
fn get_quick_fixes(
    text: &str,
    uri: &Uri,
    diagnostic: &Diagnostic,
    module_cache: Option<&ModuleCache>,
) -> Option<Vec<CodeActionOrCommand>> {
    let mut fixes = Vec::new();
    let message = &diagnostic.message;
    let code = diagnostic_code(diagnostic);

    // W2.3 / 1.40 — code-keyed dispatch.
    //
    // Undefined identifier (E0101) — declare variable.
    let is_undefined = matches!(code, Some("E0101"))
        || (code.is_none() && (message.contains("undefined") || message.contains("not defined")));
    if is_undefined {
        if let Some(var_name) = extract_undefined_name(message) {
            fixes.push(create_quick_fix(
                format!("Declare variable '{}'", var_name),
                uri.clone(),
                vec![TextEdit {
                    range: Range {
                        start: Position {
                            line: diagnostic.range.start.line,
                            character: 0,
                        },
                        end: Position {
                            line: diagnostic.range.start.line,
                            character: 0,
                        },
                    },
                    new_text: format!("let {} = undefined;\n", var_name),
                }],
                diagnostic.clone(),
            ));
        }
    }

    // E0004 = missing-semicolon (matches `determine_error_code` in
    // crates/shape-ast/src/error/pest_converter.rs). Message fallback
    // covers other paths that synthesize the same diagnostic shape.
    let is_missing_semi = matches!(code, Some("E0004"))
        || message.contains("expected ';'")
        || message.contains("missing semicolon");
    if is_missing_semi {
        fixes.push(create_quick_fix(
            "Add missing semicolon".to_string(),
            uri.clone(),
            vec![TextEdit {
                range: Range {
                    start: diagnostic.range.end,
                    end: diagnostic.range.end,
                },
                new_text: ";".to_string(),
            }],
            diagnostic.clone(),
        ));
    }

    // E0005 = unbalanced delimiter (unclosed brace). E0001 / E0002 are
    // close cousins for unterminated structures; message fallback
    // remains the trigger for diagnostics that don't reach the
    // structured-error path.
    let is_unclosed = matches!(code, Some("E0005") | Some("E0002"))
        || message.contains("expected '}'")
        || message.contains("unclosed");
    if is_unclosed {
        fixes.push(create_quick_fix(
            "Add missing closing brace".to_string(),
            uri.clone(),
            vec![TextEdit {
                range: Range {
                    start: diagnostic.range.end,
                    end: diagnostic.range.end,
                },
                new_text: "\n}".to_string(),
            }],
            diagnostic.clone(),
        ));
    }

    // Prefer-let lint — no current canonical code; keep message-keyed
    // until the lint's emitter is wired through the structured-error
    // path. Tracked as a follow-up under shape-lsp-quality-residuals.
    // R8 W10 LSP-G — W0104 reserved for the prefer-let lint when wiring
    // through the structured-error path; matched here defensively so
    // future code-emitters fire the same fix without an LSP redeploy.
    let is_prefer_let = matches!(code, Some("W0104"))
        || message.contains("prefer 'let'")
        || message.contains("use 'let' instead of 'var'");
    if is_prefer_let {
        let line = get_line(text, diagnostic.range.start.line as usize);
        if let Some(line_text) = line {
            if let Some(var_pos) = line_text.find("var ") {
                fixes.push(create_quick_fix(
                    "Change 'var' to 'let'".to_string(),
                    uri.clone(),
                    vec![TextEdit {
                        range: Range {
                            start: Position {
                                line: diagnostic.range.start.line,
                                character: var_pos as u32,
                            },
                            end: Position {
                                line: diagnostic.range.start.line,
                                character: (var_pos + 3) as u32,
                            },
                        },
                        new_text: "let".to_string(),
                    }],
                    diagnostic.clone(),
                ));
            }
        }
    }

    // Auto-import for unknown enum/type — code-keyed dispatch off
    // E0102 / E0105 when the structured-error path emits them; message
    // fallback covers the SemanticError-bucket emissions in
    // `compiler/expressions/collections.rs` + `compiler/patterns/checking.rs`
    // that haven't been routed through the code table yet.
    let is_unknown_enum = matches!(code, Some("E0102") | Some("E0105"))
        || message.contains("Unknown enum type")
        || message.contains("Unknown variant");
    if is_unknown_enum {
        if let Some(cache) = module_cache {
            if let Some(name) = extract_quoted_name(message) {
                let symbols = if let Some(current_file) = uri.to_file_path() {
                    cache.find_exported_symbol_with_context(&name, current_file.as_ref(), None)
                } else {
                    cache.find_exported_symbol(&name)
                };
                for (import_path, _export) in symbols {
                    fixes.push(create_quick_fix(
                        format!("Import '{}' from {}", name, import_path),
                        uri.clone(),
                        vec![TextEdit {
                            range: Range {
                                start: Position {
                                    line: 0,
                                    character: 0,
                                },
                                end: Position {
                                    line: 0,
                                    character: 0,
                                },
                            },
                            new_text: format!("from {} use {{ {} }}\n", import_path, name),
                        }],
                        diagnostic.clone(),
                    ));
                }
            }
        }
    }

    // Empty-match arm — code-keyed off E0103 (invalid arguments family
    // — closest existing bucket for "expression requires arms" /
    // exhaustiveness) when the resilient parser path is upgraded;
    // message fallback today catches the `ParseErrorKind::EmptyMatch`
    // shape that flows through `server.rs` without a diagnostic code.
    let is_empty_match = matches!(code, Some("E0103"))
        || message.contains("match expression requires at least one arm");
    if is_empty_match {
        if let Some((insert_pos, indent)) = find_match_arm_insert_position(text, diagnostic.range) {
            let arm_indent = format!("{indent}  ");
            fixes.push(create_quick_fix(
                "Add wildcard match arm".to_string(),
                uri.clone(),
                vec![TextEdit {
                    range: Range {
                        start: insert_pos,
                        end: insert_pos,
                    },
                    new_text: format!("{arm_indent}_ => {{\n{arm_indent}}},\n"),
                }],
                diagnostic.clone(),
            ));
        }
    }

    // Non-exhaustive match — E0103 (invalid arguments / exhaustiveness
    // family) preferred when present; the variant list itself comes
    // from `parse_non_exhaustive_match(message)` which inherently has
    // to read the message text (structured payload not threaded
    // through the diagnostic shape). Code guard is defensive: a future
    // compiler emitter with a different message format but the right
    // code still benefits from the fallback.
    let is_non_exhaustive = matches!(code, Some("E0103"))
        || message.contains("Non-exhaustive match");
    if is_non_exhaustive
        && let Some((enum_name, missing_variants)) = parse_non_exhaustive_match(message)
    {
        if let Some((insert_pos, indent)) = find_match_arm_insert_position(text, diagnostic.range) {
            let arm_indent = format!("{indent}  ");
            let mut new_text = String::new();
            for variant in missing_variants {
                new_text.push_str(&format!(
                    "{arm_indent}{enum_name}::{variant} => {{\n{arm_indent}}},\n"
                ));
            }
            fixes.push(create_quick_fix(
                format!("Add missing match arms for {}", enum_name),
                uri.clone(),
                vec![TextEdit {
                    range: Range {
                        start: insert_pos,
                        end: insert_pos,
                    },
                    new_text,
                }],
                diagnostic.clone(),
            ));
        }
    }

    // Fix for missing required trait method — suggest adding the method
    // stub. E0401 emitted by `validate_trait_bounds` in `diagnostics.rs`
    // is the canonical code; message fallback catches any compiler-side
    // emitters that haven't been routed through the code table yet.
    let is_missing_method = matches!(code, Some("E0401"))
        || message.contains("Missing required method");
    if is_missing_method {
        if let Some(method_name) = extract_quoted_name(message) {
            // Find the closing brace of the impl block on the diagnostic line
            let impl_end_line = diagnostic.range.end.line;
            // Insert just before the closing brace
            fixes.push(create_quick_fix(
                format!("Implement method '{}'", method_name),
                uri.clone(),
                vec![TextEdit {
                    range: Range {
                        start: Position {
                            line: impl_end_line,
                            character: 0,
                        },
                        end: Position {
                            line: impl_end_line,
                            character: 0,
                        },
                    },
                    new_text: format!(
                        "    method {}() {{\n        // TODO: implement\n    }}\n",
                        method_name
                    ),
                }],
                diagnostic.clone(),
            ));
        }
    }

    // W0102 = unused-import lint (W2.3 / 1.19). W0103 reserved for
    // unused-variable. Both trigger the underscore-prefix fix; message
    // fallback covers any future compiler-emitted "unused" diagnostics.
    let is_unused =
        matches!(code, Some("W0102") | Some("W0103")) || message.contains("unused");
    if is_unused {
        if let Some(var_name) = extract_unused_name(message) {
            if !var_name.starts_with('_') {
                let line = get_line(text, diagnostic.range.start.line as usize);
                if let Some(line_text) = line {
                    if let Some(name_pos) = line_text.find(&var_name) {
                        fixes.push(create_quick_fix(
                            format!("Prefix with underscore: _{}", var_name),
                            uri.clone(),
                            vec![TextEdit {
                                range: Range {
                                    start: Position {
                                        line: diagnostic.range.start.line,
                                        character: name_pos as u32,
                                    },
                                    end: Position {
                                        line: diagnostic.range.start.line,
                                        character: (name_pos + var_name.len()) as u32,
                                    },
                                },
                                new_text: format!("_{}", var_name),
                            }],
                            diagnostic.clone(),
                        ));
                    }
                }
            }
        }
    }

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

/// Get refactoring actions for a selection
fn get_refactor_actions(text: &str, uri: &Uri, range: Range) -> Option<Vec<CodeActionOrCommand>> {
    let mut actions = Vec::new();

    // Get the selected text
    let selected = get_text_in_range(text, range);
    if selected.is_empty() {
        return None;
    }

    // Extract to variable
    if is_expression(&selected) {
        actions.push(CodeActionOrCommand::CodeAction(CodeAction {
            title: "Extract to variable".to_string(),
            kind: Some(CodeActionKind::REFACTOR_EXTRACT),
            diagnostics: None,
            edit: Some(WorkspaceEdit {
                changes: Some({
                    let mut changes = HashMap::new();
                    changes.insert(
                        uri.clone(),
                        vec![
                            TextEdit {
                                range: Range {
                                    start: Position {
                                        line: range.start.line,
                                        character: 0,
                                    },
                                    end: Position {
                                        line: range.start.line,
                                        character: 0,
                                    },
                                },
                                new_text: format!("let extracted = {};\n", selected),
                            },
                            TextEdit {
                                range,
                                new_text: "extracted".to_string(),
                            },
                        ],
                    );
                    changes
                }),
                document_changes: None,
                change_annotations: None,
            }),
            command: None,
            is_preferred: None,
            disabled: None,
            data: None,
        }));
    }

    // Extract to function (for multi-line selections or complex expressions)
    if selected.contains('\n') || selected.len() > 50 {
        actions.push(CodeActionOrCommand::CodeAction(CodeAction {
            title: "Extract to function".to_string(),
            kind: Some(CodeActionKind::REFACTOR_EXTRACT),
            diagnostics: None,
            edit: Some(WorkspaceEdit {
                changes: Some({
                    let mut changes = HashMap::new();
                    changes.insert(
                        uri.clone(),
                        vec![
                            TextEdit {
                                range: Range {
                                    start: Position {
                                        line: 0,
                                        character: 0,
                                    },
                                    end: Position {
                                        line: 0,
                                        character: 0,
                                    },
                                },
                                new_text: format!(
                                    "fn extractedFunction() {{\n    {}\n}}\n\n",
                                    selected.replace('\n', "\n    ")
                                ),
                            },
                            TextEdit {
                                range,
                                new_text: "extractedFunction()".to_string(),
                            },
                        ],
                    );
                    changes
                }),
                document_changes: None,
                change_annotations: None,
            }),
            command: None,
            is_preferred: None,
            disabled: None,
            data: None,
        }));
    }

    // Convert string concatenation to template string
    if selected.contains(" + ") && selected.contains('"') {
        // This is a simplification - real implementation would need proper parsing
        actions.push(CodeActionOrCommand::CodeAction(CodeAction {
            title: "Convert to template string".to_string(),
            kind: Some(CodeActionKind::REFACTOR_REWRITE),
            diagnostics: None,
            edit: None, // Would need proper implementation
            command: None,
            is_preferred: None,
            disabled: Some(tower_lsp_server::ls_types::CodeActionDisabled {
                reason: "Complex conversion - manual edit recommended".to_string(),
            }),
            data: None,
        }));
    }

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

/// Get source actions for the document
fn get_source_actions(
    text: &str,
    uri: &Uri,
    range: Range,
    diagnostics: &[Diagnostic],
    module_cache: Option<&ModuleCache>,
    requested_kinds: Option<&[CodeActionKind]>,
) -> Option<Vec<CodeActionOrCommand>> {
    let mut actions = Vec::new();

    let import_ranges = import_statement_ranges(text);
    let on_import_stmt = import_ranges.iter().any(|r| ranges_overlap(*r, range));
    let organize_requested = is_kind_explicitly_requested(
        requested_kinds,
        CodeActionKind::SOURCE_ORGANIZE_IMPORTS.as_str(),
    );

    // Show organize-imports only when explicitly requested or when cursor is
    // currently inside import declarations.
    if !import_ranges.is_empty() && (organize_requested || on_import_stmt) {
        actions.push(CodeActionOrCommand::CodeAction(CodeAction {
            title: "Organize imports".to_string(),
            kind: Some(CodeActionKind::SOURCE_ORGANIZE_IMPORTS),
            diagnostics: None,
            edit: None, // Would need proper implementation
            command: None,
            is_preferred: None,
            disabled: None,
            data: None,
        }));
    }

    // Add "Fix all" only when requested explicitly or when there are fixable
    // diagnostics on the current range.
    let fix_all_requested =
        is_kind_explicitly_requested(requested_kinds, CodeActionKind::SOURCE_FIX_ALL.as_str());
    let has_fixable_here = diagnostics
        .iter()
        .filter(|d| ranges_overlap(d.range, range))
        .any(|d| get_quick_fixes(text, uri, d, module_cache).is_some());
    if fix_all_requested || has_fixable_here {
        actions.push(CodeActionOrCommand::CodeAction(CodeAction {
            title: "Fix all auto-fixable problems".to_string(),
            kind: Some(CodeActionKind::SOURCE_FIX_ALL),
            diagnostics: None,
            edit: None, // Would need to collect all quick fixes
            command: None,
            is_preferred: None,
            disabled: None,
            data: None,
        }));
    }

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

/// Create a quick fix code action
fn create_quick_fix(
    title: String,
    uri: Uri,
    edits: Vec<TextEdit>,
    diagnostic: Diagnostic,
) -> CodeActionOrCommand {
    let mut changes = HashMap::new();
    changes.insert(uri, edits);

    CodeActionOrCommand::CodeAction(CodeAction {
        title,
        kind: Some(CodeActionKind::QUICKFIX),
        diagnostics: Some(vec![diagnostic]),
        edit: Some(WorkspaceEdit {
            changes: Some(changes),
            document_changes: None,
            change_annotations: None,
        }),
        command: None,
        is_preferred: Some(true),
        disabled: None,
        data: None,
    })
}

/// Extract a single-quoted name from an error message
fn extract_quoted_name(message: &str) -> Option<String> {
    let start = message.find('\'')?;
    let end = message[start + 1..].find('\'')?;
    Some(message[start + 1..start + 1 + end].to_string())
}

/// Extract the undefined variable name from an error message
fn extract_undefined_name(message: &str) -> Option<String> {
    // Pattern: "undefined variable 'name'" or "'name' is not defined"
    if let Some(start) = message.find('\'') {
        if let Some(end) = message[start + 1..].find('\'') {
            return Some(message[start + 1..start + 1 + end].to_string());
        }
    }
    None
}

/// Extract the unused variable name from an error message
fn extract_unused_name(message: &str) -> Option<String> {
    // Pattern: "unused variable 'name'" or "'name' is unused"
    if let Some(start) = message.find('\'') {
        if let Some(end) = message[start + 1..].find('\'') {
            return Some(message[start + 1..start + 1 + end].to_string());
        }
    }
    None
}

fn parse_non_exhaustive_match(message: &str) -> Option<(String, Vec<String>)> {
    const PREFIX: &str = "Non-exhaustive match on '";
    const MARKER: &str = "': missing variants ";
    let after_prefix = message.strip_prefix(PREFIX)?;
    let marker_pos = after_prefix.find(MARKER)?;
    let enum_name = after_prefix[..marker_pos].trim().to_string();
    if enum_name.is_empty() {
        return None;
    }
    let variants_part = &after_prefix[marker_pos + MARKER.len()..];
    let variants = variants_part
        .split(',')
        .map(|v| v.trim())
        .filter(|v| !v.is_empty())
        .map(|v| v.to_string())
        .collect::<Vec<_>>();
    if variants.is_empty() {
        None
    } else {
        Some((enum_name, variants))
    }
}

fn find_match_arm_insert_position(text: &str, range: Range) -> Option<(Position, String)> {
    let lines: Vec<&str> = text.lines().collect();
    if lines.is_empty() {
        return None;
    }
    let start_line = range.start.line as usize;
    let mut line_index = start_line.min(lines.len().saturating_sub(1));
    while line_index < lines.len() {
        let line = lines[line_index];
        let trimmed = line.trim_start();
        if trimmed.starts_with('}') {
            let indent_len = line.len().saturating_sub(trimmed.len());
            let indent = " ".repeat(indent_len);
            return Some((
                Position {
                    line: line_index as u32,
                    character: 0,
                },
                indent,
            ));
        }
        line_index += 1;
    }
    None
}

/// Check if two ranges overlap
fn ranges_overlap(a: Range, b: Range) -> bool {
    !(a.end.line < b.start.line
        || (a.end.line == b.start.line && a.end.character < b.start.character)
        || b.end.line < a.start.line
        || (b.end.line == a.start.line && b.end.character < a.start.character))
}

/// Get a line from text by line number
fn get_line(text: &str, line: usize) -> Option<&str> {
    text.lines().nth(line)
}

/// Get text within a range
fn get_text_in_range(text: &str, range: Range) -> String {
    let lines: Vec<&str> = text.lines().collect();

    if range.start.line == range.end.line {
        // Single line selection
        if let Some(line) = lines.get(range.start.line as usize) {
            let start = range.start.character as usize;
            let end = range.end.character as usize;
            if start < line.len() && end <= line.len() {
                return line[start..end].to_string();
            }
        }
    } else {
        // Multi-line selection
        let mut result = String::new();

        for (i, line) in lines.iter().enumerate() {
            let line_num = i as u32;

            if line_num < range.start.line {
                continue;
            }
            if line_num > range.end.line {
                break;
            }

            if line_num == range.start.line {
                let start = range.start.character as usize;
                if start < line.len() {
                    result.push_str(&line[start..]);
                }
            } else if line_num == range.end.line {
                let end = range.end.character as usize;
                if end <= line.len() {
                    result.push_str(&line[..end]);
                }
            } else {
                result.push_str(line);
            }

            if line_num != range.end.line {
                result.push('\n');
            }
        }

        return result;
    }

    String::new()
}

/// Check if a string looks like an expression
fn is_expression(text: &str) -> bool {
    let trimmed = text.trim();

    // Empty or whitespace-only is not an expression
    if trimmed.is_empty() {
        return false;
    }

    // Statements are not expressions (simplified check)
    if trimmed.starts_with("let ")
        || trimmed.starts_with("var ")
        || trimmed.starts_with("const ")
        || trimmed.starts_with("fn ")
        || trimmed.starts_with("function ")
        || trimmed.starts_with("if ")
        || trimmed.starts_with("for ")
        || trimmed.starts_with("while ")
        || trimmed.starts_with("return ")
    {
        return false;
    }

    // Try to parse as expression
    let test_code = format!("let _test = {};", trimmed);
    parse_program(&test_code).is_ok()
}

/// True when `requested_kinds` allows the exact `target` kind.
/// If a broad parent kind is requested (e.g. `source`), sub-kinds are allowed.
fn is_kind_requested(requested_kinds: Option<&[CodeActionKind]>, target: &str) -> bool {
    match requested_kinds {
        None => true,
        Some(kinds) if kinds.is_empty() => true,
        Some(kinds) => kinds.iter().any(|k| {
            let requested = k.as_str();
            requested == target || target.starts_with(&format!("{requested}."))
        }),
    }
}

/// True when `requested_kinds` allows a kind group (`quickfix`, `source`, `refactor`).
fn is_group_requested(requested_kinds: Option<&[CodeActionKind]>, group: &str) -> bool {
    match requested_kinds {
        None => true,
        Some(kinds) if kinds.is_empty() => true,
        Some(kinds) => kinds.iter().any(|k| {
            let requested = k.as_str();
            requested == group || requested.starts_with(&format!("{group}."))
        }),
    }
}

/// True only when a request explicitly provided `only` kinds including `target`
/// (or a parent kind such as `source` for `source.organizeImports`).
fn is_kind_explicitly_requested(requested_kinds: Option<&[CodeActionKind]>, target: &str) -> bool {
    let Some(kinds) = requested_kinds else {
        return false;
    };
    if kinds.is_empty() {
        return false;
    }
    kinds.iter().any(|k| {
        let requested = k.as_str();
        requested == target || target.starts_with(&format!("{requested}."))
    })
}

/// Deduplicate actions by `(kind, title)`.
fn dedupe_actions(actions: Vec<CodeActionOrCommand>) -> Vec<CodeActionOrCommand> {
    let mut seen = HashSet::new();
    let mut deduped = Vec::new();

    for action in actions {
        let key = match &action {
            CodeActionOrCommand::CodeAction(ca) => format!(
                "{}::{}",
                ca.kind.as_ref().map(|k| k.as_str()).unwrap_or(""),
                ca.title
            ),
            CodeActionOrCommand::Command(cmd) => format!("command::{}", cmd.title),
        };

        if seen.insert(key) {
            deduped.push(action);
        }
    }

    deduped
}

/// Collect LSP ranges for parsed import statements.
fn import_statement_ranges(text: &str) -> Vec<Range> {
    if let Ok(program) = parse_program(text) {
        let mut ranges = Vec::new();
        for item in &program.items {
            if let Item::Import(_, span) = item {
                ranges.push(span_to_range(text, span));
            }
        }
        return ranges;
    }

    // Parse fallback: use line-based detection for unfinished import lines.
    text.lines()
        .enumerate()
        .filter_map(|(line, raw)| {
            let trimmed = raw.trim_start();
            if trimmed.starts_with("from ") || trimmed.starts_with("use ") {
                Some(Range {
                    start: Position {
                        line: line as u32,
                        character: 0,
                    },
                    end: Position {
                        line: line as u32,
                        character: raw.len() as u32,
                    },
                })
            } else {
                None
            }
        })
        .collect()
}

/// Return local names currently imported into scope.
fn collect_imported_local_names(text: &str) -> HashSet<String> {
    let Ok(program) = parse_program(text) else {
        return HashSet::new();
    };

    let mut imported = HashSet::new();
    for item in &program.items {
        let Item::Import(import_stmt, _) = item else {
            continue;
        };
        match &import_stmt.items {
            ImportItems::Named(specs) => {
                for spec in specs {
                    imported.insert(spec.alias.clone().unwrap_or_else(|| spec.name.clone()));
                }
            }
            ImportItems::Namespace { name, alias } => {
                imported.insert(alias.clone().unwrap_or_else(|| name.clone()));
            }
        }
    }

    imported
}

fn import_insert_position(text: &str) -> Position {
    let import_ranges = import_statement_ranges(text);
    if let Some(last_line) = import_ranges.iter().map(|r| r.end.line).max() {
        Position {
            line: last_line + 1,
            character: 0,
        }
    } else {
        Position {
            line: 0,
            character: 0,
        }
    }
}

fn get_symbol_auto_import_actions(
    text: &str,
    uri: &Uri,
    range: Range,
    cache: &ModuleCache,
) -> Vec<CodeActionOrCommand> {
    let Some(symbol) = symbol_at_or_in_range(text, range) else {
        return Vec::new();
    };
    if !is_import_candidate_symbol(&symbol) {
        return Vec::new();
    }

    let imported_names = collect_imported_local_names(text);
    if imported_names.contains(&symbol) {
        return Vec::new();
    }

    let matches = if let Some(current_file) = uri.to_file_path() {
        cache.find_exported_symbol_with_context(&symbol, current_file.as_ref(), None)
    } else {
        cache.find_exported_symbol(&symbol)
    };
    if matches.is_empty() {
        return Vec::new();
    }

    let mut out = Vec::new();
    let insert_at = import_insert_position(text);
    for (import_path, _export) in matches {
        out.push(CodeActionOrCommand::CodeAction(CodeAction {
            title: format!("Import '{}' from {}", symbol, import_path),
            kind: Some(CodeActionKind::QUICKFIX),
            diagnostics: None,
            edit: Some(WorkspaceEdit {
                changes: Some({
                    let mut changes = HashMap::new();
                    changes.insert(
                        uri.clone(),
                        vec![TextEdit {
                            range: Range {
                                start: insert_at,
                                end: insert_at,
                            },
                            new_text: format!("from {} use {{ {} }}\n", import_path, symbol),
                        }],
                    );
                    changes
                }),
                document_changes: None,
                change_annotations: None,
            }),
            command: None,
            is_preferred: Some(true),
            disabled: None,
            data: None,
        }));
    }

    out
}

fn symbol_at_or_in_range(text: &str, range: Range) -> Option<String> {
    let selected = get_text_in_range(text, range);
    let selected = selected.trim();
    if !selected.is_empty() && is_identifier(selected) {
        return Some(selected.to_string());
    }
    get_word_at_position(text, range.start)
}

fn is_identifier(name: &str) -> bool {
    let mut chars = name.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    if !(first.is_ascii_alphabetic() || first == '_') {
        return false;
    }
    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}

fn is_import_candidate_symbol(name: &str) -> bool {
    is_identifier(name) && name.chars().next().is_some_and(|c| c.is_ascii_uppercase())
}

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

    #[test]
    fn test_extract_undefined_name() {
        assert_eq!(
            extract_undefined_name("undefined variable 'foo'"),
            Some("foo".to_string())
        );
        assert_eq!(
            extract_undefined_name("'bar' is not defined"),
            Some("bar".to_string())
        );
        assert_eq!(extract_undefined_name("some other message"), None);
    }

    #[test]
    fn test_ranges_overlap() {
        let r1 = Range {
            start: Position {
                line: 1,
                character: 0,
            },
            end: Position {
                line: 1,
                character: 10,
            },
        };
        let r2 = Range {
            start: Position {
                line: 1,
                character: 5,
            },
            end: Position {
                line: 1,
                character: 15,
            },
        };
        let r3 = Range {
            start: Position {
                line: 2,
                character: 0,
            },
            end: Position {
                line: 2,
                character: 10,
            },
        };

        assert!(ranges_overlap(r1, r2));
        assert!(!ranges_overlap(r1, r3));
    }

    #[test]
    fn test_get_text_in_range() {
        let text = "let x = 42;\nlet y = 10;";

        let range = Range {
            start: Position {
                line: 0,
                character: 4,
            },
            end: Position {
                line: 0,
                character: 5,
            },
        };
        assert_eq!(get_text_in_range(text, range), "x");

        let range = Range {
            start: Position {
                line: 0,
                character: 8,
            },
            end: Position {
                line: 0,
                character: 10,
            },
        };
        assert_eq!(get_text_in_range(text, range), "42");
    }

    #[test]
    fn test_is_expression() {
        assert!(is_expression("42"));
        assert!(is_expression("x + y"));
        assert!(is_expression("foo()"));
        assert!(!is_expression("let x = 42"));
        assert!(!is_expression("function foo() {}"));
    }

    #[test]
    fn test_extract_quoted_name_from_compiler_errors() {
        // Matches actual compiler error message format from checking.rs
        assert_eq!(
            extract_quoted_name(
                "Unknown enum type 'Snapshot'. Make sure it is imported or defined."
            ),
            Some("Snapshot".to_string())
        );
        assert_eq!(
            extract_quoted_name("Unknown variant 'BadVariant' for enum 'Color'"),
            Some("BadVariant".to_string())
        );
        assert_eq!(extract_quoted_name("no quotes here"), None);
    }

    #[test]
    fn test_missing_trait_method_quick_fix() {
        let text = "trait Q {\n    filter(p): any;\n    select(c): any\n}\nimpl Q for T {\n    method filter(p) { self }\n}\n";
        let uri = Uri::from_file_path("/tmp/test.shape").unwrap();
        let diagnostic = Diagnostic {
            range: Range {
                start: Position {
                    line: 4,
                    character: 0,
                },
                end: Position {
                    line: 6,
                    character: 1,
                },
            },
            severity: Some(tower_lsp_server::ls_types::DiagnosticSeverity::ERROR),
            code: Some(tower_lsp_server::ls_types::NumberOrString::String(
                "E0401".to_string(),
            )),
            message: "Missing required method 'select' in impl Q for T.".to_string(),
            ..Default::default()
        };
        let actions = get_code_actions(text, &uri, diagnostic.range, &[diagnostic], None, None);
        assert!(
            actions.iter().any(|a| {
                if let CodeActionOrCommand::CodeAction(action) = a {
                    action.title.contains("Implement method 'select'")
                } else {
                    false
                }
            }),
            "Should have quick fix to implement missing method. Got: {:?}",
            actions
                .iter()
                .map(|a| match a {
                    CodeActionOrCommand::CodeAction(action) => action.title.clone(),
                    CodeActionOrCommand::Command(cmd) => cmd.title.clone(),
                })
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_auto_import_generates_valid_syntax() {
        // Verify the generated import text matches Shape grammar
        let name = "Snapshot";
        let import_path = "std::core::snapshot";
        let import_text = format!("from {} use {{ {} }}\n", import_path, name);
        assert_eq!(import_text, "from std::core::snapshot use { Snapshot }\n");
        // Verify it parses as valid Shape
        let full_code = format!("{}let x = 1\n", import_text);
        assert!(
            shape_ast::parser::parse_program(&full_code).is_ok(),
            "Generated import should be valid Shape syntax: {}",
            full_code
        );
    }

    #[test]
    fn test_source_actions_organize_imports_only_on_import_lines() {
        let text = "from std::core::math use { abs }\nlet x = abs(1)\n";
        let uri = Uri::from_file_path("/tmp/test.shape").unwrap();

        let import_range = Range {
            start: Position {
                line: 0,
                character: 5,
            },
            end: Position {
                line: 0,
                character: 5,
            },
        };
        let non_import_range = Range {
            start: Position {
                line: 1,
                character: 4,
            },
            end: Position {
                line: 1,
                character: 4,
            },
        };

        let on_import = get_code_actions(text, &uri, import_range, &[], None, None);
        let away_from_import = get_code_actions(text, &uri, non_import_range, &[], None, None);

        let has_organize = |actions: &[CodeActionOrCommand]| {
            actions.iter().any(|a| {
                matches!(
                    a,
                    CodeActionOrCommand::CodeAction(CodeAction {
                        kind: Some(kind),
                        ..
                    }) if kind == &CodeActionKind::SOURCE_ORGANIZE_IMPORTS
                )
            })
        };

        assert!(has_organize(&on_import));
        assert!(!has_organize(&away_from_import));
    }

    #[test]
    fn test_symbol_auto_import_action_from_cursor() {
        let text = "match snapshot() {\n  Snapshot::Resumed => { }\n}\n";
        let uri = Uri::from_file_path("/tmp/test.shape").unwrap();
        let range = Range {
            start: Position {
                line: 1,
                character: 3,
            },
            end: Position {
                line: 1,
                character: 11,
            },
        };

        let cache = ModuleCache::new();
        let actions = get_code_actions(text, &uri, range, &[], Some(&cache), None);
        assert!(
            actions.iter().any(|a| {
                matches!(
                    a,
                    CodeActionOrCommand::CodeAction(CodeAction { title, .. })
                        if title.contains("Import 'Snapshot' from std::core::snapshot")
                )
            }),
            "Expected auto-import action for Snapshot. Got: {:?}",
            actions
                .iter()
                .map(|a| match a {
                    CodeActionOrCommand::CodeAction(action) => action.title.clone(),
                    CodeActionOrCommand::Command(cmd) => cmd.title.clone(),
                })
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_empty_match_quick_fix_adds_wildcard_arm() {
        let text = "fn afunc(c) {\n  match c {\n\n  }\n}\n";
        let uri = Uri::from_file_path("/tmp/test.shape").unwrap();
        let diagnostic = Diagnostic {
            range: Range {
                start: Position {
                    line: 1,
                    character: 2,
                },
                end: Position {
                    line: 3,
                    character: 3,
                },
            },
            severity: None,
            code: None,
            code_description: None,
            source: Some("shape".to_string()),
            message: "match expression requires at least one arm".to_string(),
            related_information: None,
            tags: None,
            data: None,
        };
        let range = Range {
            start: Position {
                line: 2,
                character: 2,
            },
            end: Position {
                line: 2,
                character: 2,
            },
        };

        let actions = get_code_actions(text, &uri, range, &[diagnostic], None, None);
        assert!(
            actions.iter().any(|a| matches!(
                a,
                CodeActionOrCommand::CodeAction(CodeAction { title, .. })
                    if title == "Add wildcard match arm"
            )),
            "Expected wildcard match-arm quick fix. Got: {:?}",
            actions
                .iter()
                .map(|a| match a {
                    CodeActionOrCommand::CodeAction(action) => action.title.clone(),
                    CodeActionOrCommand::Command(cmd) => cmd.title.clone(),
                })
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_non_exhaustive_match_quick_fix_adds_missing_arms() {
        let text = "match snapshot() {\n  Snapshot::Resumed => { }\n}\n";
        let uri = Uri::from_file_path("/tmp/test.shape").unwrap();
        let diagnostic = Diagnostic {
            range: Range {
                start: Position {
                    line: 0,
                    character: 0,
                },
                end: Position {
                    line: 2,
                    character: 1,
                },
            },
            severity: None,
            code: None,
            code_description: None,
            source: Some("shape".to_string()),
            message: "Non-exhaustive match on 'Snapshot': missing variants Hash".to_string(),
            related_information: None,
            tags: None,
            data: None,
        };
        let range = Range {
            start: Position {
                line: 1,
                character: 5,
            },
            end: Position {
                line: 1,
                character: 5,
            },
        };

        let actions = get_code_actions(text, &uri, range, &[diagnostic], None, None);
        assert!(
            actions.iter().any(|a| matches!(
                a,
                CodeActionOrCommand::CodeAction(CodeAction { title, .. })
                    if title == "Add missing match arms for Snapshot"
            )),
            "Expected missing-arms quick fix. Got: {:?}",
            actions
                .iter()
                .map(|a| match a {
                    CodeActionOrCommand::CodeAction(action) => action.title.clone(),
                    CodeActionOrCommand::Command(cmd) => cmd.title.clone(),
                })
                .collect::<Vec<_>>()
        );
    }

    // W14.2-B1: per-line coverage additions
    #[test]
    fn test_extract_quoted_name_no_quote_returns_none() {
        assert_eq!(extract_quoted_name("no quotes here"), None);
    }

    #[test]
    fn test_extract_unused_name() {
        assert_eq!(
            extract_unused_name("'baz' is unused"),
            Some("baz".to_string())
        );
        assert_eq!(extract_unused_name("nothing here"), None);
    }

    #[test]
    fn test_parse_non_exhaustive_match_basic() {
        let parsed =
            parse_non_exhaustive_match("Non-exhaustive match on 'Color': missing variants Red, Green, Blue");
        assert!(parsed.is_some());
        let (name, variants) = parsed.unwrap();
        assert_eq!(name, "Color");
        assert_eq!(variants, vec!["Red", "Green", "Blue"]);
    }

    #[test]
    fn test_parse_non_exhaustive_match_no_prefix() {
        let parsed = parse_non_exhaustive_match("Some other message");
        assert!(parsed.is_none());
    }

    #[test]
    fn test_parse_non_exhaustive_match_no_variants() {
        let parsed =
            parse_non_exhaustive_match("Non-exhaustive match on 'Foo': missing variants ");
        assert!(parsed.is_none());
    }

    #[test]
    fn test_find_match_arm_insert_position_simple() {
        let text = "fn f() {\n  match x {\n    A => 1,\n  }\n}\n";
        let range = Range {
            start: Position {
                line: 2,
                character: 0,
            },
            end: Position {
                line: 2,
                character: 10,
            },
        };
        let result = find_match_arm_insert_position(text, range);
        assert!(result.is_some(), "expected to find a closing brace position");
        let (pos, indent) = result.unwrap();
        // Should point to line 3 (the closing brace)
        assert_eq!(pos.line, 3);
        // Indent should be 2 spaces (matching the closing brace's indent)
        assert_eq!(indent, "  ");
    }

    #[test]
    fn test_find_match_arm_insert_position_no_closing_brace() {
        let text = "abc\ndef\n";
        let range = Range {
            start: Position {
                line: 0,
                character: 0,
            },
            end: Position {
                line: 0,
                character: 3,
            },
        };
        let result = find_match_arm_insert_position(text, range);
        assert!(result.is_none(), "expected None when no closing brace exists");
    }

    #[test]
    fn test_get_line_returns_line_content() {
        let text = "first\nsecond\nthird";
        assert_eq!(get_line(text, 0), Some("first"));
        assert_eq!(get_line(text, 1), Some("second"));
        assert_eq!(get_line(text, 2), Some("third"));
        assert_eq!(get_line(text, 3), None);
    }

    #[test]
    fn test_get_text_in_range_multiline() {
        let text = "abc\ndef\nghi";
        let range = Range {
            start: Position {
                line: 0,
                character: 1,
            },
            end: Position {
                line: 2,
                character: 2,
            },
        };
        let result = get_text_in_range(text, range);
        assert!(
            result.contains("bc") && result.contains("def") && result.contains("gh"),
            "expected multi-line text in {result:?}"
        );
    }

    #[test]
    fn test_is_expression_handles_statements() {
        // Statement-shaped should be rejected
        assert!(!is_expression("let x = 1"));
        assert!(!is_expression("var y = 2"));
        assert!(!is_expression("const z = 3"));
        assert!(!is_expression("if x { 1 }"));
        assert!(!is_expression("for i in 0..10 { }"));
        assert!(!is_expression("while x { }"));
        assert!(!is_expression("return x"));
        assert!(!is_expression("fn foo() { }"));
        assert!(!is_expression(""));
        assert!(!is_expression("   "));
    }

    #[test]
    fn test_is_kind_requested_none_allows_all() {
        assert!(is_kind_requested(None, "quickfix"));
        assert!(is_kind_requested(None, "refactor.extract"));
    }

    #[test]
    fn test_is_kind_requested_empty_allows_all() {
        let empty: &[CodeActionKind] = &[];
        assert!(is_kind_requested(Some(empty), "quickfix"));
    }

    #[test]
    fn test_is_kind_requested_exact_match() {
        let kinds = &[CodeActionKind::QUICKFIX];
        assert!(is_kind_requested(Some(kinds), "quickfix"));
        assert!(!is_kind_requested(Some(kinds), "refactor"));
    }

    #[test]
    fn test_is_group_requested_with_parent_kind() {
        let kinds = &[CodeActionKind::SOURCE];
        assert!(is_group_requested(Some(kinds), "source"));
        // Sub-kinds should also be permitted under group "source"
        assert!(is_kind_requested(
            Some(kinds),
            "source.organizeImports"
        ));
    }

    #[test]
    fn test_dedupe_actions_removes_same_title() {
        let action1 = CodeActionOrCommand::CodeAction(CodeAction {
            title: "dup".to_string(),
            kind: Some(CodeActionKind::QUICKFIX),
            ..Default::default()
        });
        let action2 = CodeActionOrCommand::CodeAction(CodeAction {
            title: "dup".to_string(),
            kind: Some(CodeActionKind::QUICKFIX),
            ..Default::default()
        });
        let action3 = CodeActionOrCommand::CodeAction(CodeAction {
            title: "unique".to_string(),
            kind: Some(CodeActionKind::QUICKFIX),
            ..Default::default()
        });
        let deduped = dedupe_actions(vec![action1, action2, action3]);
        assert_eq!(deduped.len(), 2, "expected dedupe to collapse same-title actions");
    }

    #[test]
    fn test_dedupe_actions_preserves_different_kinds() {
        let action1 = CodeActionOrCommand::CodeAction(CodeAction {
            title: "do x".to_string(),
            kind: Some(CodeActionKind::QUICKFIX),
            ..Default::default()
        });
        let action2 = CodeActionOrCommand::CodeAction(CodeAction {
            title: "do x".to_string(),
            kind: Some(CodeActionKind::REFACTOR),
            ..Default::default()
        });
        let deduped = dedupe_actions(vec![action1, action2]);
        assert_eq!(deduped.len(), 2, "different kinds + same title preserved");
    }

    #[test]
    fn test_is_identifier() {
        assert!(is_identifier("foo"));
        assert!(is_identifier("_bar"));
        assert!(is_identifier("baz123"));
        assert!(!is_identifier(""));
        assert!(!is_identifier("123abc"));
        assert!(!is_identifier("foo bar"));
        assert!(!is_identifier("foo.bar"));
    }

    #[test]
    fn test_is_import_candidate_symbol_requires_uppercase() {
        // Import candidate must be valid identifier AND start with uppercase
        assert!(is_import_candidate_symbol("Foo"));
        assert!(is_import_candidate_symbol("Snapshot"));
        assert!(!is_import_candidate_symbol("foo"));
        assert!(!is_import_candidate_symbol("foo_bar"));
        assert!(!is_import_candidate_symbol(""));
        assert!(!is_import_candidate_symbol("123Foo"));
    }

    #[test]
    fn test_import_statement_ranges_finds_from_use() {
        let text = "from std::core::math use { abs }\nlet x = 1\n";
        let ranges = import_statement_ranges(text);
        assert_eq!(ranges.len(), 1, "expected one import range");
        assert_eq!(ranges[0].start.line, 0);
    }

    #[test]
    fn test_import_statement_ranges_handles_parse_failure() {
        // Use a fallback path with text-based detection for unfinished imports.
        let text = "from std::core::math\n";
        let ranges = import_statement_ranges(text);
        // Either parsed range or fallback range
        assert!(
            !ranges.is_empty(),
            "expected to find import range via parse or fallback"
        );
    }

    #[test]
    fn test_collect_imported_local_names_named() {
        let text = "from std::core::math use { abs, max }\nlet x = abs(1)\n";
        let names = collect_imported_local_names(text);
        assert!(names.contains("abs"));
        assert!(names.contains("max"));
    }

    #[test]
    fn test_collect_imported_local_names_empty() {
        let text = "let x = 1\n";
        let names = collect_imported_local_names(text);
        assert!(names.is_empty());
    }

    #[test]
    fn test_import_insert_position_after_existing_imports() {
        let text = "from std::core::math use { abs }\nlet x = 1\n";
        let pos = import_insert_position(text);
        // Should insert after the existing import (at least line 1).
        assert!(
            pos.line >= 1,
            "expected insert position after import line, got {}",
            pos.line
        );
        assert_eq!(pos.character, 0);
    }

    #[test]
    fn test_import_insert_position_no_imports() {
        let text = "let x = 1\n";
        let pos = import_insert_position(text);
        assert_eq!(pos.line, 0);
        assert_eq!(pos.character, 0);
    }

    #[test]
    fn test_diagnostic_code_returns_string_form() {
        let d = Diagnostic {
            code: Some(NumberOrString::String("E0001".to_string())),
            ..Default::default()
        };
        assert_eq!(diagnostic_code(&d), Some("E0001"));

        let d2 = Diagnostic {
            code: Some(NumberOrString::Number(42)),
            ..Default::default()
        };
        // Numeric codes return None per the canonical-string contract.
        assert_eq!(diagnostic_code(&d2), None);

        let d3 = Diagnostic {
            code: None,
            ..Default::default()
        };
        assert_eq!(diagnostic_code(&d3), None);
    }

    /// R8 W10 LSP-G — verify code-keyed dispatch fires the
    /// declare-variable quickfix when the diagnostic carries E0101 but
    /// the message text does NOT contain "undefined" / "not defined".
    /// This guards the migration from message-substring keying off the
    /// SemanticError text shape onto the canonical numbered code.
    #[test]
    fn test_quickfix_keys_off_e0101_code_without_message_substring() {
        let uri = Uri::from_file_path("/tmp/test.shape").unwrap();
        let diagnostic = Diagnostic {
            range: Range {
                start: Position {
                    line: 0,
                    character: 8,
                },
                end: Position {
                    line: 0,
                    character: 21,
                },
            },
            severity: Some(tower_lsp_server::ls_types::DiagnosticSeverity::ERROR),
            // E0101 set; message has NO "undefined" / "not defined" substring.
            code: Some(NumberOrString::String("E0101".to_string())),
            message: "Identifier 'zzz_xyz' is not in scope".to_string(),
            ..Default::default()
        };
        let text = "let x = zzz_xyz + 1\n";
        let actions = get_code_actions(text, &uri, diagnostic.range, &[diagnostic], None, None);
        assert!(
            actions.iter().any(|a| matches!(
                a,
                CodeActionOrCommand::CodeAction(CodeAction { title, .. })
                    if title.contains("Declare variable 'zzz_xyz'")
            )),
            "expected declare-variable quickfix from E0101 code-keyed dispatch; got: {:?}",
            actions
                .iter()
                .map(|a| match a {
                    CodeActionOrCommand::CodeAction(action) => action.title.clone(),
                    CodeActionOrCommand::Command(cmd) => cmd.title.clone(),
                })
                .collect::<Vec<_>>()
        );
    }

    /// R8 W10 LSP-G — verify code-keyed dispatch fires the
    /// implement-method quickfix when the diagnostic carries E0401 but
    /// the message text does NOT contain "Missing required method".
    #[test]
    fn test_quickfix_keys_off_e0401_code_without_message_substring() {
        let uri = Uri::from_file_path("/tmp/test.shape").unwrap();
        let diagnostic = Diagnostic {
            range: Range {
                start: Position {
                    line: 0,
                    character: 0,
                },
                end: Position {
                    line: 1,
                    character: 1,
                },
            },
            severity: Some(tower_lsp_server::ls_types::DiagnosticSeverity::ERROR),
            code: Some(NumberOrString::String("E0401".to_string())),
            // Note: no "Missing required method" substring; quoted name still extracted.
            message: "impl block omits trait method 'select'".to_string(),
            ..Default::default()
        };
        let text = "impl Q for T {\n}\n";
        let actions = get_code_actions(text, &uri, diagnostic.range, &[diagnostic], None, None);
        assert!(
            actions.iter().any(|a| matches!(
                a,
                CodeActionOrCommand::CodeAction(CodeAction { title, .. })
                    if title.contains("Implement method 'select'")
            )),
            "expected implement-method quickfix from E0401 code-keyed dispatch; got: {:?}",
            actions
                .iter()
                .map(|a| match a {
                    CodeActionOrCommand::CodeAction(action) => action.title.clone(),
                    CodeActionOrCommand::Command(cmd) => cmd.title.clone(),
                })
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_get_code_actions_filters_to_requested_kind() {
        let text = "let x = 1";
        let uri = Uri::from_file_path("/tmp/test.shape").unwrap();
        // Request ONLY refactor kind; quickfix should be excluded.
        let actions = get_code_actions(
            text,
            &uri,
            Range {
                start: Position {
                    line: 0,
                    character: 0,
                },
                end: Position {
                    line: 0,
                    character: 5,
                },
            },
            &[],
            None,
            Some(&[CodeActionKind::REFACTOR]),
        );
        for action in &actions {
            if let CodeActionOrCommand::CodeAction(ca) = action {
                if let Some(kind) = &ca.kind {
                    assert!(
                        kind.as_str().starts_with("refactor"),
                        "expected refactor-only action, got {}",
                        kind.as_str()
                    );
                }
            }
        }
    }
}