harn-lint 0.7.7

Linter for the Harn programming language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
use super::*;
use harn_lexer::Lexer;
use harn_parser::Parser;

fn lint_source(source: &str) -> Vec<LintDiagnostic> {
    let mut lexer = Lexer::new(source);
    let tokens = lexer.tokenize().unwrap();
    let mut parser = Parser::new(tokens);
    let program = parser.parse().unwrap();
    lint_with_source(&program, source)
}

fn has_rule(diagnostics: &[LintDiagnostic], rule: &str) -> bool {
    diagnostics.iter().any(|d| d.rule == rule)
}

fn count_rule(diagnostics: &[LintDiagnostic], rule: &str) -> usize {
    diagnostics.iter().filter(|d| d.rule == rule).count()
}

#[test]
fn test_clean_code() {
    let diags = lint_source(
        r#"
pipeline default(task) {
let x = 1
log(x)
}
"#,
    );
    // x is used, task is a pipeline param -- should be clean.
    assert!(
        !has_rule(&diags, "unused-variable"),
        "expected no unused-variable, got: {diags:?}"
    );
}

#[test]
fn test_public_function_requires_harndoc() {
    let diags = lint_source(
        r#"
pub fn exposed() -> string {
  return "x"
}
"#,
    );
    assert!(has_rule(&diags, "missing-harndoc"));
}

#[test]
fn test_assert_outside_test_pipeline_warns() {
    let diags = lint_source(
        r#"
pipeline default(task) {
assert(true)
}
"#,
    );
    assert!(
        has_rule(&diags, "assert-outside-test"),
        "expected assert-outside-test warning, got: {diags:?}"
    );
}

#[test]
fn test_assert_inside_test_pipeline_is_allowed() {
    let diags = lint_source(
        r#"
pipeline test(task) {
assert_eq(1 + 1, 2)
}
"#,
    );
    assert!(
        !has_rule(&diags, "assert-outside-test"),
        "asserts inside test pipelines should be allowed: {diags:?}"
    );
}

#[test]
fn test_require_inside_test_pipeline_warns() {
    let diags = lint_source(
        r#"
pipeline test_example(task) {
require 1 + 1 == 2, "math still works"
}
"#,
    );
    assert!(
        has_rule(&diags, "require-in-test"),
        "expected require-in-test warning, got: {diags:?}"
    );
}

#[test]
fn test_require_outside_test_pipeline_is_allowed() {
    let diags = lint_source(
        r#"
pipeline default(task) {
require task != nil, "task is required"
}
"#,
    );
    assert!(
        !has_rule(&diags, "require-in-test"),
        "require outside tests should be allowed: {diags:?}"
    );
}

#[test]
fn test_public_function_with_harndoc_is_clean() {
    let diags = lint_source(
        r#"
/** Explain the public API. */
pub fn exposed() -> string {
  return "x"
}
"#,
    );
    assert!(!has_rule(&diags, "missing-harndoc"));
}

#[test]
fn test_public_function_with_multiline_harndoc_is_clean() {
    let diags = lint_source(
        r#"
/**
 * Explain the public API.
 * Across multiple lines.
 */
pub fn exposed() -> string {
  return "x"
}
"#,
    );
    assert!(!has_rule(&diags, "missing-harndoc"));
}

#[test]
fn test_legacy_triple_slash_above_pub_fn_fires() {
    let diags = lint_source(
        r#"
/// Old-style doc.
pub fn exposed() -> string {
  return "x"
}
"#,
    );
    assert!(
        has_rule(&diags, "legacy-doc-comment"),
        "expected legacy-doc-comment, got: {diags:?}"
    );
    // And the autofix should produce a canonical /** */ block.
    let fix = diags
        .iter()
        .find(|d| d.rule == "legacy-doc-comment")
        .and_then(|d| d.fix.as_ref())
        .expect("legacy-doc-comment must carry an autofix");
    assert_eq!(fix.len(), 1);
    assert!(
        fix[0].replacement.contains("/**") && fix[0].replacement.contains("*/"),
        "replacement should be a canonical /** */ block: {:?}",
        fix[0].replacement
    );
}

#[test]
fn test_plain_double_slash_adjacent_to_pub_fn_fires() {
    let diags = lint_source(
        r#"
// Doc-by-adjacency.
pub fn exposed() -> string {
  return "x"
}
"#,
    );
    assert!(
        has_rule(&diags, "legacy-doc-comment"),
        "expected legacy-doc-comment for // adjacent to def, got: {diags:?}"
    );
}

#[test]
fn test_plain_double_slash_with_blank_line_does_not_fire() {
    let diags = lint_source(
        r#"
// unrelated comment

pub fn exposed() -> string {
  return "x"
}
"#,
    );
    assert!(
        !has_rule(&diags, "legacy-doc-comment"),
        "// with blank-line gap should not be treated as doc: {diags:?}"
    );
}

#[test]
fn test_existing_block_doc_does_not_fire_legacy() {
    let diags = lint_source(
        r#"
/** Already canonical. */
pub fn exposed() -> string {
  return "x"
}
"#,
    );
    assert!(
        !has_rule(&diags, "legacy-doc-comment"),
        "/** */ block should not trigger legacy rule: {diags:?}"
    );
    assert!(
        !has_rule(&diags, "missing-harndoc"),
        "/** */ block should satisfy missing-harndoc: {diags:?}"
    );
}

#[test]
fn test_plain_comment_does_not_satisfy_harndoc() {
    let diags = lint_source(
        r#"
// Not HarnDoc.
pub fn exposed() -> string {
  return "x"
}
"#,
    );
    assert!(has_rule(&diags, "missing-harndoc"));
}

#[test]
fn test_private_function_does_not_require_harndoc() {
    let diags = lint_source(
        r#"
fn helper() -> string {
  return "x"
}
"#,
    );
    assert!(!has_rule(&diags, "missing-harndoc"));
}

#[test]
fn test_unused_variable() {
    let diags = lint_source(
        r#"
pipeline default(task) {
let unused = 42
log("hello")
}
"#,
    );
    assert!(
        has_rule(&diags, "unused-variable"),
        "expected unused-variable warning, got: {diags:?}"
    );
}

#[test]
fn test_unused_underscore_ignored() {
    let diags = lint_source(
        r#"
pipeline default(task) {
let _ = 42
log("hello")
}
"#,
    );
    assert!(
        !has_rule(&diags, "unused-variable"),
        "underscore variables should not trigger unused-variable: {diags:?}"
    );
}

#[test]
fn test_unreachable_code() {
    let diags = lint_source(
        r#"
pipeline default(task) {
return 1
log("never reached")
}
"#,
    );
    assert!(
        has_rule(&diags, "unreachable-code"),
        "expected unreachable-code warning, got: {diags:?}"
    );
}

#[test]
fn test_no_unreachable_when_return_is_last() {
    let diags = lint_source(
        r#"
pipeline default(task) {
log("hello")
return 1
}
"#,
    );
    assert!(
        !has_rule(&diags, "unreachable-code"),
        "return at end should not trigger unreachable-code: {diags:?}"
    );
}

#[test]
fn test_mutable_never_reassigned() {
    let diags = lint_source(
        r#"
pipeline default(task) {
var x = 1
log(x)
}
"#,
    );
    assert!(
        has_rule(&diags, "mutable-never-reassigned"),
        "expected mutable-never-reassigned warning, got: {diags:?}"
    );
}

#[test]
fn test_mutable_reassigned_ok() {
    let diags = lint_source(
        r#"
pipeline default(task) {
var x = 1
x = 2
log(x)
}
"#,
    );
    assert!(
        !has_rule(&diags, "mutable-never-reassigned"),
        "reassigned var should not trigger mutable-never-reassigned: {diags:?}"
    );
}

#[test]
fn test_empty_block_if() {
    let diags = lint_source(
        r#"
pipeline default(task) {
if true {
}
}
"#,
    );
    assert!(
        has_rule(&diags, "empty-block"),
        "expected empty-block warning for if, got: {diags:?}"
    );
}

#[test]
fn test_shadow_variable() {
    let diags = lint_source(
        r#"
pipeline default(task) {
let x = 1
if true {
    let x = 2
    log(x)
}
log(x)
}
"#,
    );
    assert!(
        has_rule(&diags, "shadow-variable"),
        "expected shadow-variable warning, got: {diags:?}"
    );
}

#[test]
fn test_no_shadow_same_scope() {
    // Re-declaration in the same scope is not shadowing (it may be a
    // parser error, but the linter only checks outer-scope shadows).
    let diags = lint_source(
        r#"
pipeline default(task) {
let x = 1
log(x)
}
"#,
    );
    assert!(
        !has_rule(&diags, "shadow-variable"),
        "same-scope should not trigger shadow-variable: {diags:?}"
    );
}

#[test]
fn test_unreachable_after_throw() {
    let diags = lint_source("pipeline t(task) { throw \"err\"\nlog(\"unreachable\") }");
    assert!(
        diags.iter().any(|d| d.rule == "unreachable-code"),
        "expected unreachable-code after throw, got: {diags:?}"
    );
}

#[test]
fn test_unused_fn_param() {
    let diags = lint_source(
        r#"
pipeline default(task) {
fn greet(name, unused) {
    log(name)
}
greet("hi", "there")
}
"#,
    );
    assert!(
        has_rule(&diags, "unused-parameter"),
        "expected unused-parameter for unused fn param, got: {diags:?}"
    );
    // Should NOT trigger unused-variable (parameters are tracked separately).
    assert!(
        !has_rule(&diags, "unused-variable"),
        "unused fn param should not trigger unused-variable: {diags:?}"
    );
}

#[test]
fn test_unused_closure_param() {
    let diags = lint_source(
        r#"
pipeline default(task) {
let f = { x, y -> log(x) }
f(1, 2)
}
"#,
    );
    assert!(
        has_rule(&diags, "unused-parameter"),
        "expected unused-parameter for unused closure param, got: {diags:?}"
    );
}

#[test]
fn test_unused_param_underscore_prefix_ignored() {
    let diags = lint_source(
        r#"
pipeline default(task) {
fn greet(name, _unused) {
    log(name)
}
greet("hi", "there")
}
"#,
    );
    assert!(
        !has_rule(&diags, "unused-parameter"),
        "underscore-prefixed params should not trigger unused-parameter: {diags:?}"
    );
}

#[test]
fn test_used_fn_param_ok() {
    let diags = lint_source(
        r#"
pipeline default(task) {
fn add(a, b) {
    return a + b
}
log(add(1, 2))
}
"#,
    );
    assert!(
        !has_rule(&diags, "unused-parameter"),
        "used params should not trigger unused-parameter: {diags:?}"
    );
}

#[test]
fn test_multiple_rules() {
    let diags = lint_source(
        r#"
pipeline default(task) {
var unused = 1
return 0
log("dead")
}
"#,
    );
    assert!(has_rule(&diags, "unused-variable"));
    assert!(has_rule(&diags, "mutable-never-reassigned"));
    assert!(has_rule(&diags, "unreachable-code"));
    assert_eq!(count_rule(&diags, "unreachable-code"), 1);
}

#[test]
fn test_comparison_to_bool_true() {
    let diags = lint_source(
        r#"
pipeline default(task) {
let x = true
if x == true { log("yes") }
}
"#,
    );
    assert!(
        has_rule(&diags, "comparison-to-bool"),
        "expected comparison-to-bool, got: {diags:?}"
    );
}

#[test]
fn test_comparison_to_bool_false() {
    let diags = lint_source(
        r#"
pipeline default(task) {
let x = true
if x == false { log("no") }
}
"#,
    );
    assert!(
        has_rule(&diags, "comparison-to-bool"),
        "expected comparison-to-bool, got: {diags:?}"
    );
}

#[test]
fn test_no_comparison_to_bool_for_normal() {
    let diags = lint_source(
        r#"
pipeline default(task) {
let x = 1
if x == 1 { log("one") }
}
"#,
    );
    assert!(
        !has_rule(&diags, "comparison-to-bool"),
        "should not trigger for non-bool comparison: {diags:?}"
    );
}

#[test]
fn test_unnecessary_else_return() {
    let diags = lint_source(
        r#"
pipeline default(task) {
let x = 1
if x == 1 {
    return "one"
} else {
    return "other"
}
}
"#,
    );
    assert!(
        has_rule(&diags, "unnecessary-else-return"),
        "expected unnecessary-else-return, got: {diags:?}"
    );
}

#[test]
fn test_no_unnecessary_else_return_when_no_return() {
    let diags = lint_source(
        r#"
pipeline default(task) {
let x = 1
if x == 1 {
    log("one")
} else {
    log("other")
}
}
"#,
    );
    assert!(
        !has_rule(&diags, "unnecessary-else-return"),
        "should not trigger when branches don't return: {diags:?}"
    );
}

#[test]
fn test_duplicate_match_arm() {
    let diags = lint_source(
        r#"
pipeline default(task) {
let x = 1
match x {
    1 -> { log("one") }
    1 -> { log("also one") }
    _ -> { log("other") }
}
}
"#,
    );
    assert!(
        has_rule(&diags, "duplicate-match-arm"),
        "expected duplicate-match-arm, got: {diags:?}"
    );
}

#[test]
fn test_break_outside_loop() {
    let diags = lint_source(
        r#"
pipeline default(task) {
break
}
"#,
    );
    assert!(
        has_rule(&diags, "break-outside-loop"),
        "expected break-outside-loop, got: {diags:?}"
    );
}

#[test]
fn test_break_inside_loop_ok() {
    let diags = lint_source(
        r#"
pipeline default(task) {
while true {
    break
}
}
"#,
    );
    assert!(
        !has_rule(&diags, "break-outside-loop"),
        "break inside loop should be fine: {diags:?}"
    );
}

#[test]
fn test_unreachable_after_break() {
    let diags = lint_source(
        r#"
pipeline default(task) {
while true {
    break
    log("unreachable")
}
}
"#,
    );
    assert!(
        has_rule(&diags, "unreachable-code"),
        "expected unreachable-code after break, got: {diags:?}"
    );
}

#[test]
fn test_unreachable_after_composite_exit() {
    let diags = lint_source(
        r#"
pipeline default(task) {
fn foo(x: bool) {
    if x { return 1 } else { throw "err" }
    log("unreachable")
}
foo(true)
}
"#,
    );
    assert!(
        has_rule(&diags, "unreachable-code"),
        "expected unreachable-code after composite exit, got: {diags:?}"
    );
}

#[test]
fn test_no_unreachable_without_both_branches_exiting() {
    let diags = lint_source(
        r#"
pipeline default(task) {
fn foo(x: bool) {
    if x { return 1 }
    log("reachable")
}
foo(true)
}
"#,
    );
    assert!(
        !has_rule(&diags, "unreachable-code"),
        "should not flag reachable code: {diags:?}"
    );
}

#[test]
fn test_unused_function_basic() {
    let diags = lint_source(
        r#"
pipeline default(task) {
fn helper() {
    return 42
}
log("hello")
}
"#,
    );
    assert!(
        has_rule(&diags, "unused-function"),
        "expected unused-function warning, got: {diags:?}"
    );
}

#[test]
fn test_used_function_no_warning() {
    let diags = lint_source(
        r#"
pipeline default(task) {
fn helper() {
    return 42
}
log(helper())
}
"#,
    );
    assert!(
        !has_rule(&diags, "unused-function"),
        "used function should not trigger unused-function: {diags:?}"
    );
}

#[test]
fn test_pub_function_exempt() {
    let diags = lint_source(
        r#"
/// Documented public function.
pub fn api_endpoint() {
return "ok"
}
"#,
    );
    assert!(
        !has_rule(&diags, "unused-function"),
        "pub functions should be exempt: {diags:?}"
    );
}

#[test]
fn test_function_passed_as_value() {
    let diags = lint_source(
        r#"
pipeline default(task) {
fn transformer(x) {
    return x * 2
}
let f = transformer
log(f(5))
}
"#,
    );
    assert!(
        !has_rule(&diags, "unused-function"),
        "function referenced as value should not trigger: {diags:?}"
    );
}

#[test]
fn test_function_called_from_another_function() {
    let diags = lint_source(
        r#"
pipeline default(task) {
fn inner() {
    return 42
}
fn outer() {
    return inner()
}
log(outer())
}
"#,
    );
    assert!(
        !has_rule(&diags, "unused-function"),
        "function called from another function should not trigger: {diags:?}"
    );
}

#[test]
fn test_pipeline_not_flagged_as_unused() {
    let diags = lint_source(
        r#"
pipeline default(task) {
log("hello")
}
"#,
    );
    assert!(
        !has_rule(&diags, "unused-function"),
        "pipelines should never trigger unused-function: {diags:?}"
    );
}

#[test]
fn test_impl_methods_exempt() {
    let diags = lint_source(
        r#"
pipeline default(task) {
struct Point {
    x: int
    y: int
}
impl Point {
    fn distance(self) {
        return self.x + self.y
    }
}
let p = Point({x: 3, y: 4})
log(p)
}
"#,
    );
    assert!(
        !has_rule(&diags, "unused-function"),
        "impl methods should be exempt: {diags:?}"
    );
}

#[test]
fn test_recursive_function_called_externally() {
    let diags = lint_source(
        r#"
pipeline default(task) {
fn factorial(n) {
    if n <= 1 {
        return 1
    }
    return n * factorial(n - 1)
}
log(factorial(5))
}
"#,
    );
    assert!(
        !has_rule(&diags, "unused-function"),
        "recursive function called externally should not trigger: {diags:?}"
    );
}

#[test]
fn test_mutually_recursive_functions_one_called() {
    let diags = lint_source(
        r#"
pipeline default(task) {
fn is_even(n) {
    if n == 0 { return true }
    return is_odd(n - 1)
}
fn is_odd(n) {
    if n == 0 { return false }
    return is_even(n - 1)
}
log(is_even(4))
}
"#,
    );
    assert!(
        !has_rule(&diags, "unused-function"),
        "mutually recursive functions where one is called should not trigger: {diags:?}"
    );
}

#[test]
fn test_underscore_prefixed_function_exempt() {
    let diags = lint_source(
        r#"
pipeline default(task) {
fn _unused_helper() {
    return 42
}
log("hello")
}
"#,
    );
    assert!(
        !has_rule(&diags, "unused-function"),
        "underscore-prefixed functions should be exempt: {diags:?}"
    );
}

#[test]
fn test_unused_function_suggestion_message() {
    let diags = lint_source(
        r#"
pipeline default(task) {
fn helper() {
    return 42
}
log("hello")
}
"#,
    );
    let unused = diags
        .iter()
        .find(|d| d.rule == "unused-function")
        .expect("expected unused-function diagnostic");
    assert!(unused.message.contains("helper"));
    assert!(unused.suggestion.as_ref().unwrap().contains("_helper"));
}

#[test]
fn test_multiple_unused_functions() {
    let diags = lint_source(
        r#"
pipeline default(task) {
fn helper1() { return 1 }
fn helper2() { return 2 }
fn used() { return 3 }
log(used())
}
"#,
    );
    assert_eq!(
        count_rule(&diags, "unused-function"),
        2,
        "expected 2 unused-function warnings, got: {diags:?}"
    );
}

#[test]
fn test_top_level_unused_function() {
    let diags = lint_source(
        r#"
fn orphan() {
return 42
}
pipeline default(task) {
log("hello")
}
"#,
    );
    assert!(
        has_rule(&diags, "unused-function"),
        "top-level unused function should trigger: {diags:?}"
    );
}

#[test]
fn test_unused_function_with_wildcard_import() {
    // Wildcard imports shouldn't suppress unused-function checks —
    // external code can't call local non-pub functions.
    let diags = lint_source(
        r#"
import "some_module"
pipeline default(task) {
fn helper() { return 1 }
log("hello")
}
"#,
    );
    assert!(
        has_rule(&diags, "unused-function"),
        "unused-function should still fire with wildcard imports: {diags:?}"
    );
}

#[test]
fn test_unused_function_suppressed_by_cross_file_imports() {
    // When another file imports a function by name, it should not be
    // flagged as unused even if it has no local references.
    let source = r###"
fn done_sentinel() { return "##DONE##" }
fn truly_unused() { return 1 }
"###;
    let mut lexer = Lexer::new(source);
    let tokens = lexer.tokenize().unwrap();
    let mut parser = Parser::new(tokens);
    let program = parser.parse().unwrap();

    // Without cross-file info: both flagged
    let diags = lint_with_config_and_source(&program, &[], Some(source));
    assert_eq!(
        count_rule(&diags, "unused-function"),
        2,
        "both functions should be flagged without cross-file info: {diags:?}"
    );

    // With cross-file info: only truly_unused flagged
    let mut imported = HashSet::new();
    imported.insert("done_sentinel".to_string());
    let diags = lint_with_cross_file_imports(&program, &[], Some(source), &imported);
    assert_eq!(
        count_rule(&diags, "unused-function"),
        1,
        "only truly_unused should be flagged: {diags:?}"
    );
    assert!(
        diags
            .iter()
            .any(|d| d.rule == "unused-function" && d.message.contains("truly_unused")),
        "the remaining warning should be for truly_unused: {diags:?}"
    );
}

#[test]
fn test_invalid_binary_op_literal_bool() {
    let diags = lint_source(
        r#"
pipeline default(task) {
let x = true + 1
log(x)
}
"#,
    );
    assert!(
        has_rule(&diags, "invalid-binary-op-literal"),
        "expected invalid-binary-op-literal for bool in arithmetic: {diags:?}"
    );
}

#[test]
fn test_invalid_binary_op_literal_nil() {
    let diags = lint_source(
        r#"
pipeline default(task) {
let x = nil - 5
log(x)
}
"#,
    );
    assert!(
        has_rule(&diags, "invalid-binary-op-literal"),
        "expected invalid-binary-op-literal for nil in arithmetic: {diags:?}"
    );
}

#[test]
fn test_no_invalid_binary_op_for_valid_types() {
    let diags = lint_source(
        r#"
pipeline default(task) {
let x = 1 + 2
let y = "a" + "b"
log(x)
log(y)
}
"#,
    );
    assert!(
        !has_rule(&diags, "invalid-binary-op-literal"),
        "should not fire for valid operand types: {diags:?}"
    );
}

#[test]
fn test_collect_selective_import_names() {
    let source = r#"
import { foo, bar } from "module_a"
import { baz } from "module_b"
import "wildcard_module"
fn local() { return foo() + bar() + baz() }
"#;
    let mut lexer = Lexer::new(source);
    let tokens = lexer.tokenize().unwrap();
    let mut parser = Parser::new(tokens);
    let program = parser.parse().unwrap();

    let names = collect_selective_import_names(&program);
    assert!(names.contains("foo"), "should contain foo");
    assert!(names.contains("bar"), "should contain bar");
    assert!(names.contains("baz"), "should contain baz");
    assert_eq!(names.len(), 3, "should have exactly 3 names: {names:?}");
}

/// Get the first fix for a given rule, or None.
fn get_fix(diagnostics: &[LintDiagnostic], rule: &str) -> Option<Vec<FixEdit>> {
    diagnostics
        .iter()
        .find(|d| d.rule == rule)
        .and_then(|d| d.fix.clone())
}

/// Apply all non-overlapping fixes to the source (reverse order).
fn apply_fixes(source: &str, diagnostics: &[LintDiagnostic]) -> String {
    let mut edits: Vec<&FixEdit> = diagnostics
        .iter()
        .filter_map(|d| d.fix.as_ref())
        .flatten()
        .collect();
    edits.sort_by(|a, b| b.span.start.cmp(&a.span.start));
    let mut accepted: Vec<&FixEdit> = Vec::new();
    for edit in &edits {
        let overlaps = accepted
            .iter()
            .any(|prev| edit.span.start < prev.span.end && edit.span.end > prev.span.start);
        if !overlaps {
            accepted.push(edit);
        }
    }
    let mut result = source.to_string();
    for edit in &accepted {
        let before = &result[..edit.span.start];
        let after = &result[edit.span.end..];
        result = format!("{before}{}{after}", edit.replacement);
    }
    result
}

#[test]
fn test_fix_mutable_never_reassigned() {
    let source = "pipeline default(task) {\n  var x = 10\n  log(x)\n}";
    let diags = lint_source(source);
    let fix = get_fix(&diags, "mutable-never-reassigned");
    assert!(fix.is_some(), "expected fix for mutable-never-reassigned");
    let result = apply_fixes(source, &diags);
    assert!(
        result.contains("let x = 10"),
        "expected var→let, got: {result}"
    );
    assert!(
        !result.contains("var x"),
        "var should be replaced, got: {result}"
    );
}

#[test]
fn test_fix_comparison_to_bool_true() {
    let source = "pipeline default(task) {\n  let x = true\n  let y = x == true\n  log(y)\n}";
    let diags = lint_source(source);
    let fix = get_fix(&diags, "comparison-to-bool");
    assert!(fix.is_some(), "expected fix for comparison-to-bool");
    let result = apply_fixes(source, &diags);
    assert!(
        result.contains("let y = x"),
        "expected simplified comparison, got: {result}"
    );
    assert!(
        !result.contains("== true"),
        "should remove == true, got: {result}"
    );
}

#[test]
fn test_fix_comparison_to_bool_false() {
    let source = "pipeline default(task) {\n  let x = true\n  let y = x == false\n  log(y)\n}";
    let diags = lint_source(source);
    let fix = get_fix(&diags, "comparison-to-bool");
    assert!(fix.is_some(), "expected fix for comparison-to-bool");
    let result = apply_fixes(source, &diags);
    assert!(
        result.contains("let y = !x"),
        "expected negated, got: {result}"
    );
}

#[test]
fn test_fix_comparison_to_bool_ne_true() {
    let source = "pipeline default(task) {\n  let x = true\n  let y = x != true\n  log(y)\n}";
    let diags = lint_source(source);
    let fix = get_fix(&diags, "comparison-to-bool");
    assert!(fix.is_some(), "expected fix for comparison-to-bool");
    let result = apply_fixes(source, &diags);
    assert!(
        result.contains("let y = !x"),
        "!= true should become !x, got: {result}"
    );
}

#[test]
fn test_fix_unused_import_all_unused() {
    let source = "import { foo, bar } from \"mod\"\npipeline default(task) {\n  log(task)\n}";
    let diags = lint_source(source);
    assert!(
        count_rule(&diags, "unused-import") >= 1,
        "expected unused-import warnings"
    );
    // When all names are unused, the fix should remove the entire import line
    let fix = get_fix(&diags, "unused-import");
    assert!(fix.is_some(), "expected fix for unused-import");
    let edits = fix.unwrap();
    assert_eq!(edits.len(), 1);
    assert!(
        edits[0].replacement.is_empty(),
        "expected deletion, got: {:?}",
        edits[0].replacement
    );
}

#[test]
fn test_fix_unused_import_partial() {
    let source = "import { foo, bar } from \"mod\"\npipeline default(task) {\n  log(foo)\n}";
    let diags = lint_source(source);
    // bar is unused, foo is used
    assert_eq!(
        count_rule(&diags, "unused-import"),
        1,
        "expected 1 unused-import warning"
    );
    let fix = get_fix(&diags, "unused-import");
    assert!(fix.is_some(), "expected fix for unused-import");
    let result = apply_fixes(source, &diags);
    assert!(
        result.contains("{ foo }") || result.contains("{foo}"),
        "expected bar removed from import, got: {result}"
    );
    assert!(
        !result.contains("bar"),
        "bar should be removed, got: {result}"
    );
}

#[test]
fn test_fix_invalid_binop_string_plus_bool() {
    let source = "pipeline default(task) {\n  let x = \"hello\" + true\n  log(x)\n}";
    let diags = lint_source(source);
    let fix = get_fix(&diags, "invalid-binary-op-literal");
    assert!(
        fix.is_some(),
        "expected interpolation fix for string + bool"
    );
    let result = apply_fixes(source, &diags);
    assert!(
        result.contains("\"hello${true}\""),
        "expected interpolation, got: {result}"
    );
}

#[test]
fn test_fix_invalid_binop_no_fix_for_non_string() {
    let source = "pipeline default(task) {\n  let x = true + 1\n  log(x)\n}";
    let diags = lint_source(source);
    let fix = get_fix(&diags, "invalid-binary-op-literal");
    assert!(
        fix.is_none(),
        "should not offer fix for non-string binop, got: {fix:?}"
    );
}

#[test]
fn test_fix_multiple_fixes_applied() {
    let source = "pipeline default(task) {\n  var x = 10\n  let y = x == true\n  log(y)\n}";
    let diags = lint_source(source);
    let result = apply_fixes(source, &diags);
    assert!(
        result.contains("let x = 10"),
        "var should be fixed to let, got: {result}"
    );
    assert!(
        result.contains("let y = x"),
        "comparison should be simplified, got: {result}"
    );
}

#[test]
fn test_naming_convention_flags_non_snake_case_function() {
    let diags = lint_source(
        r#"
fn BadName() {
  return nil
}
"#,
    );
    assert!(
        has_rule(&diags, "naming-convention"),
        "expected naming-convention warning, got: {diags:?}"
    );
}

#[test]
fn test_naming_convention_flags_non_pascal_case_type() {
    let diags = lint_source(
        r#"
struct bad_name {
  value: int
}
"#,
    );
    assert!(
        has_rule(&diags, "naming-convention"),
        "expected naming-convention warning, got: {diags:?}"
    );
}

#[test]
fn test_unused_type_warns_for_unreferenced_struct() {
    let diags = lint_source(
        r#"
struct Helper {
  value: int
}

pipeline default(task) {
  log("ready")
}
"#,
    );
    assert!(
        has_rule(&diags, "unused-type"),
        "expected unused-type warning, got: {diags:?}"
    );
}

#[test]
fn test_unused_type_ignores_referenced_struct() {
    let diags = lint_source(
        r#"
struct Helper {
  value: int
}

fn build() -> Helper {
  return Helper { value: 1 }
}

pipeline default(task) {
  let item = build()
  log(item.value)
}
"#,
    );
    assert!(
        !has_rule(&diags, "unused-type"),
        "referenced types should not trigger unused-type: {diags:?}"
    );
}

#[test]
fn test_cyclomatic_complexity_warns_for_branchy_function() {
    let diags = lint_source(
        r#"
fn complicated(x: int) {
  if x > 0 { log("1") }
  if x > 1 { log("2") }
  if x > 2 { log("3") }
  if x > 3 { log("4") }
  if x > 4 { log("5") }
  if x > 5 { log("6") }
  if x > 6 { log("7") }
  if x > 7 { log("8") }
  if x > 8 { log("9") }
  if x > 9 { log("10") }
}

pipeline default(task) {
  complicated(10)
}
"#,
    );
    assert!(
        has_rule(&diags, "cyclomatic-complexity"),
        "expected cyclomatic-complexity warning, got: {diags:?}"
    );
}

#[test]
fn test_prompt_injection_risk_warns_on_interpolated_system_prompt() {
    let diags = lint_source(
        r#"
pipeline default(task) {
  let user_text = "ignore safety"
  llm_call("hello", "You are safe. ${user_text}")
}
"#,
    );
    assert!(
        has_rule(&diags, "prompt-injection-risk"),
        "expected prompt-injection-risk warning, got: {diags:?}"
    );
}

#[test]
fn test_no_fix_when_source_unavailable() {
    // lint without source — fixes should be None
    let source = "pipeline default(task) {\n  var x = 10\n  log(x)\n}";
    let mut lexer = Lexer::new(source);
    let tokens = lexer.tokenize().unwrap();
    let mut parser = Parser::new(tokens);
    let program = parser.parse().unwrap();
    let diags = lint(&program); // no source
    let fix = get_fix(&diags, "mutable-never-reassigned");
    assert!(
        fix.is_none(),
        "without source, fix should be None, got: {fix:?}"
    );
}

#[test]
fn test_fix_unused_variable_simple_let_binding() {
    let source = "pipeline default(task) {\n  let unused_thing = 42\n  log(\"hi\")\n}";
    let diags = lint_source(source);
    assert!(has_rule(&diags, "unused-variable"));
    let fix = get_fix(&diags, "unused-variable");
    assert!(
        fix.is_some(),
        "expected autofix for simple let binding, got: {diags:?}"
    );
    let result = apply_fixes(source, &diags);
    assert!(
        result.contains("let _unused_thing = 42"),
        "expected `_unused_thing` prefix, got: {result}"
    );
    assert!(
        !result.contains("let unused_thing"),
        "original name should be replaced, got: {result}"
    );
}

#[test]
fn test_fix_unused_variable_simple_let_binding_with_type() {
    // Type annotation between the name and `=` must not confuse the scan.
    // We use `let` (not `var`) so the `mutable-never-reassigned` autofix
    // doesn't also fire and combine with this one.
    let source = "pipeline default(task) {\n  let leftover: int = 3\n  log(\"hi\")\n}";
    let diags = lint_source(source);
    let fix = get_fix(&diags, "unused-variable").expect("expected autofix");
    assert_eq!(fix.len(), 1, "expected single-edit fix");
    let edit = &fix[0];
    let renamed = {
        let before = &source[..edit.span.start];
        let after = &source[edit.span.end..];
        format!("{before}{}{after}", edit.replacement)
    };
    assert!(
        renamed.contains("let _leftover: int = 3"),
        "expected `_leftover: int` prefix, got: {renamed}"
    );
    assert!(
        !renamed.contains("let leftover:"),
        "original name should be replaced, got: {renamed}"
    );
}

#[test]
fn test_no_fix_for_unused_variable_in_dict_destructuring() {
    // Destructuring patterns are intentionally not autofixed today — the
    // rename would need a per-field span we do not currently track. The
    // diagnostic must still fire with a suggestion so the user can fix
    // manually.
    let source = "pipeline default(task) {\n  let { a, b } = { a: 1, b: 2 }\n  log(a)\n}";
    let diags = lint_source(source);
    let unused: Vec<_> = diags
        .iter()
        .filter(|d| d.rule == "unused-variable")
        .collect();
    assert!(
        unused.iter().any(|d| d.message.contains("`b`")),
        "expected unused-variable for `b`, got: {diags:?}"
    );
    for diag in &unused {
        if diag.message.contains("`b`") {
            assert!(
                diag.fix.is_none(),
                "destructuring unused-variable must not autofix, got: {:?}",
                diag.fix
            );
            assert!(
                diag.suggestion.is_some(),
                "destructuring unused-variable must keep its suggestion"
            );
        }
    }
}

#[test]
fn test_fix_empty_if_with_pure_condition() {
    let source = "pipeline default(task) {\n  let x = 3\n  if x > 0 { }\n  log(\"done\")\n}";
    let diags = lint_source(source);
    let fix = get_fix(&diags, "empty-block");
    assert!(
        fix.is_some(),
        "expected autofix for empty if with pure condition, got: {diags:?}"
    );
    let result = apply_fixes(source, &diags);
    assert!(
        !result.contains("if x > 0"),
        "empty if should be removed, got: {result}"
    );
    assert!(
        result.contains("log(\"done\")"),
        "sibling statement must survive, got: {result}"
    );
    // Re-parse so we know the rewrite produced valid source.
    let mut lexer = Lexer::new(&result);
    let tokens = lexer.tokenize().expect("relex after fix");
    let mut parser = Parser::new(tokens);
    parser.parse().expect("reparse after fix");
}

#[test]
fn test_no_fix_for_empty_if_with_side_effecting_condition() {
    // side_effect() is a function call — removing the whole if would
    // drop the call, which could be observable. The diagnostic must
    // still fire but must not produce an autofix.
    let source = r#"
pipeline default(task) {
  if side_effect() { }
  log("hi")
}
"#;
    let diags = lint_source(source);
    let empty: Vec<_> = diags.iter().filter(|d| d.rule == "empty-block").collect();
    assert!(
        empty.iter().any(|d| d.message.contains("if")),
        "expected empty-block for if, got: {diags:?}"
    );
    assert!(
        empty.iter().all(|d| d.fix.is_none()),
        "side-effecting condition must not get an autofix"
    );
}

#[test]
fn test_no_fix_for_empty_if_with_else_branch() {
    // If both branches are empty we still warn, but autofixing the if
    // would silently drop the else body when someone fills it in later.
    // Conservative: no fix when else_body is present.
    let source = r#"
pipeline default(task) {
  let y = 1
  if y > 0 { } else { log("y") }
  log("end")
}
"#;
    let diags = lint_source(source);
    let empty: Vec<_> = diags
        .iter()
        .filter(|d| d.rule == "empty-block" && d.message.contains("if"))
        .collect();
    assert!(
        !empty.is_empty(),
        "expected empty-block for if, got: {diags:?}"
    );
    assert!(
        empty.iter().all(|d| d.fix.is_none()),
        "autofix must be suppressed when else branch exists"
    );
}

#[test]
fn test_fix_empty_for_with_pure_iterable() {
    let source = "pipeline default(task) {\n  let items = [1, 2, 3]\n  for item in items { }\n  log(\"done\")\n}";
    let diags = lint_source(source);
    let fix = get_fix(&diags, "empty-block");
    assert!(
        fix.is_some(),
        "expected autofix for empty for with pure iterable, got: {diags:?}"
    );
    let result = apply_fixes(source, &diags);
    assert!(
        !result.contains("for item in items"),
        "empty for should be removed, got: {result}"
    );
    let mut lexer = Lexer::new(&result);
    let tokens = lexer.tokenize().expect("relex after fix");
    let mut parser = Parser::new(tokens);
    parser.parse().expect("reparse after fix");
}

#[test]
fn test_no_fix_for_empty_for_with_side_effecting_iterable() {
    let source = r#"
pipeline default(task) {
  for item in fetch_items() { }
  log("hi")
}
"#;
    let diags = lint_source(source);
    let empty: Vec<_> = diags
        .iter()
        .filter(|d| d.rule == "empty-block" && d.message.contains("for"))
        .collect();
    assert!(
        !empty.is_empty(),
        "expected empty-block for for-loop, got: {diags:?}"
    );
    assert!(
        empty.iter().all(|d| d.fix.is_none()),
        "side-effecting iterable must not get an autofix"
    );
}

#[test]
fn test_fix_redundant_nil_ternary_eq_pattern() {
    let source = r#"
pipeline default(task) {
  let x = 5
  let y = x == nil ? 0 : x
  log(y)
}
"#;
    let diags = lint_source(source);
    let fix = get_fix(&diags, "redundant-nil-ternary");
    assert!(
        fix.is_some(),
        "expected autofix for `x == nil ? 0 : x`, got: {diags:?}"
    );
    let result = apply_fixes(source, &diags);
    assert!(
        result.contains("let y = x ?? 0"),
        "expected `x ?? 0`, got: {result}"
    );
    let mut lexer = Lexer::new(&result);
    let tokens = lexer.tokenize().expect("relex after fix");
    let mut parser = Parser::new(tokens);
    parser.parse().expect("reparse after fix");
}

#[test]
fn test_fix_redundant_nil_ternary_ne_pattern() {
    let source = r#"
pipeline default(task) {
  let x = 5
  let y = x != nil ? x : 0
  log(y)
}
"#;
    let diags = lint_source(source);
    let fix = get_fix(&diags, "redundant-nil-ternary");
    assert!(
        fix.is_some(),
        "expected autofix for `x != nil ? x : 0`, got: {diags:?}"
    );
    let result = apply_fixes(source, &diags);
    assert!(
        result.contains("let y = x ?? 0"),
        "expected `x ?? 0`, got: {result}"
    );
}

#[test]
fn test_no_warn_for_unrelated_ternary() {
    let source = r#"
pipeline default(task) {
  let a = 1
  let b = 2
  let c = a > b ? a : b
  log(c)
}
"#;
    let diags = lint_source(source);
    assert!(
        !has_rule(&diags, "redundant-nil-ternary"),
        "unrelated ternary should not trigger redundant-nil-ternary, got: {diags:?}"
    );
}

#[test]
fn test_no_warn_when_non_nil_arm_differs_from_checked_var() {
    // `x != nil ? y : z` — the non-nil arm is NOT `x`, so the rewrite
    // would change semantics. Lint must stay silent.
    let source = r#"
pipeline default(task) {
  let x = 1
  let y = 2
  let z = 3
  let w = x != nil ? y : z
  log(w)
}
"#;
    let diags = lint_source(source);
    assert!(
        !has_rule(&diags, "redundant-nil-ternary"),
        "rewrite would change semantics, lint must be silent, got: {diags:?}"
    );
}

#[test]
fn test_fix_unused_variable_is_word_boundary_safe() {
    // The variable name also appears in the RHS expression. The autofix
    // must only rewrite the binding occurrence, not the reference inside
    // the initializer, so the resulting source still parses.
    let source =
        "pipeline default(task) {\n  let threshold_ms = threshold_ms_default()\n  log(\"hi\")\n}";
    let diags = lint_source(source);
    let fix = get_fix(&diags, "unused-variable");
    assert!(fix.is_some(), "expected autofix, got: {diags:?}");
    let result = apply_fixes(source, &diags);
    assert!(
        result.contains("let _threshold_ms = threshold_ms_default()"),
        "expected only the LHS binding renamed, got: {result}"
    );
}

#[test]
fn test_untyped_dict_access_json_parse_property() {
    let diags = lint_source(
        r#"
pipeline default(task) {
    let x = json_parse(task).name
    log(x)
}
"#,
    );
    assert!(
        has_rule(&diags, "untyped-dict-access"),
        "expected untyped-dict-access, got: {diags:?}"
    );
}

#[test]
fn test_untyped_dict_access_yaml_parse_subscript() {
    let diags = lint_source(
        r#"
pipeline default(task) {
    let x = yaml_parse(task)["key"]
    log(x)
}
"#,
    );
    assert!(
        has_rule(&diags, "untyped-dict-access"),
        "expected untyped-dict-access for yaml_parse subscript, got: {diags:?}"
    );
}

#[test]
fn test_untyped_dict_access_not_flagged_on_dict_literal() {
    let diags = lint_source(
        r#"
pipeline default(task) {
    let x = {"name": "test"}
    log(x.name)
}
"#,
    );
    assert!(
        !has_rule(&diags, "untyped-dict-access"),
        "dict literal access should not trigger rule, got: {diags:?}"
    );
}

#[test]
fn test_untyped_dict_access_not_flagged_on_normal_function() {
    let diags = lint_source(
        r#"
pipeline default(task) {
    fn get_data() -> dict {
        return {"name": "test"}
    }
    log(get_data().name)
}
"#,
    );
    assert!(
        !has_rule(&diags, "untyped-dict-access"),
        "non-boundary function should not trigger rule, got: {diags:?}"
    );
}

#[test]
fn test_untyped_dict_access_llm_call() {
    let diags = lint_source(
        r#"
pipeline default(task) {
    let x = llm_call("p", "s").data
    log(x)
}
"#,
    );
    assert!(
        has_rule(&diags, "untyped-dict-access"),
        "llm_call direct access should trigger rule, got: {diags:?}"
    );
}

#[test]
fn test_blank_line_between_items_fires_for_two_adjacent_fns() {
    let source = "fn a() -> int {\n  return 1\n}\nfn b() -> int {\n  return 2\n}\n";
    let diags = lint_source(source);
    assert!(
        has_rule(&diags, "blank-line-between-items"),
        "expected blank-line-between-items, got: {diags:?}"
    );
}

#[test]
fn test_blank_line_between_items_ok_when_blank_present() {
    let source = "fn a() -> int {\n  return 1\n}\n\nfn b() -> int {\n  return 2\n}\n";
    let diags = lint_source(source);
    assert!(
        !has_rule(&diags, "blank-line-between-items"),
        "should not fire with blank line present, got: {diags:?}"
    );
}

#[test]
fn test_blank_line_between_items_ok_with_doc_block_and_blank_above() {
    // Blank line above the doc block — doc block is glued to fn b.
    let source =
        "fn a() -> int {\n  return 1\n}\n\n/** Describes b. */\nfn b() -> int {\n  return 2\n}\n";
    let diags = lint_source(source);
    assert!(
        !has_rule(&diags, "blank-line-between-items"),
        "blank line above doc block should satisfy the rule, got: {diags:?}"
    );
}

#[test]
fn test_eager_collection_conversion_let_list() {
    let source = r#"pipeline default(task) {
  let xs: list<int> = iter([1, 2, 3]).map(fn(x) { return x + 1 })
  log(xs)
}
"#;
    let diags = lint_source(source);
    assert_eq!(
        count_rule(&diags, "eager-collection-conversion"),
        1,
        "expected exactly one eager-collection-conversion diagnostic, got: {diags:?}"
    );
    let fixed = apply_fixes(source, &diags);
    assert!(
        fixed.contains(".to_list()"),
        "expected autofix to append .to_list(), got: {fixed}"
    );
}

#[test]
fn test_eager_collection_conversion_no_flag_when_already_to_list() {
    let source = r#"pipeline default(task) {
  let xs: list<int> = iter([1, 2, 3]).map(fn(x) { return x + 1 }).to_list()
  log(xs)
}
"#;
    let diags = lint_source(source);
    assert_eq!(
        count_rule(&diags, "eager-collection-conversion"),
        0,
        "should not flag already-materialized chains, got: {diags:?}"
    );
}

#[test]
fn test_eager_collection_conversion_return_stmt() {
    let source = r#"fn build() -> list<int> {
  return iter([1, 2, 3]).filter(fn(x) { return x > 0 })
}
"#;
    let diags = lint_source(source);
    assert_eq!(
        count_rule(&diags, "eager-collection-conversion"),
        1,
        "expected eager-collection-conversion on return, got: {diags:?}"
    );
    let fixed = apply_fixes(source, &diags);
    assert!(
        fixed.contains(".to_list()"),
        "expected autofix to append .to_list(), got: {fixed}"
    );
}

#[test]
fn test_blank_line_between_items_fires_when_doc_has_no_blank_above() {
    // No blank line above the doc block — the rule fires.
    let source =
        "fn a() -> int {\n  return 1\n}\n/** Describes b. */\nfn b() -> int {\n  return 2\n}\n";
    let diags = lint_source(source);
    let hit = diags
        .iter()
        .find(|d| d.rule == "blank-line-between-items")
        .expect("expected blank-line-between-items to fire");
    // Autofix should insert a newline at the start of the doc comment's
    // line (line 4) — the "\n" replacement lives above the doc block.
    let fix = hit.fix.as_ref().expect("autofix expected");
    assert_eq!(fix.len(), 1);
    assert_eq!(fix[0].replacement, "\n");
}

#[test]
fn test_blank_line_between_items_does_not_fire_between_imports() {
    let source = "import \"std/strings\"\nimport \"std/io\"\n\nfn a() -> int { return 1 }\n";
    let diags = lint_source(source);
    assert!(
        !has_rule(&diags, "blank-line-between-items"),
        "consecutive imports are intentionally tight, got: {diags:?}"
    );
}

#[test]
fn test_trailing_comma_fires_on_multiline_list() {
    let source =
        "pipeline default(task) {\n  let xs = [\n    1,\n    2,\n    3\n  ]\n  log(xs[0])\n}\n";
    let diags = lint_source(source);
    assert!(
        has_rule(&diags, "trailing-comma"),
        "expected trailing-comma on multiline list, got: {diags:?}"
    );
}

#[test]
fn test_trailing_comma_ok_when_present() {
    let source =
        "pipeline default(task) {\n  let xs = [\n    1,\n    2,\n    3,\n  ]\n  log(xs[0])\n}\n";
    let diags = lint_source(source);
    assert!(
        !has_rule(&diags, "trailing-comma"),
        "should not fire when comma already present, got: {diags:?}"
    );
}

#[test]
fn test_trailing_comma_ignores_single_line_list() {
    let source = "pipeline default(task) {\n  let xs = [1, 2, 3]\n  log(xs[0])\n}\n";
    let diags = lint_source(source);
    assert!(
        !has_rule(&diags, "trailing-comma"),
        "single-line list should not fire, got: {diags:?}"
    );
}

#[test]
fn test_trailing_comma_ignores_fn_body_block() {
    // fn body is `{ ... }` but not a dict/struct — must not fire.
    let source = "fn x() -> int {\n  let y = 1\n  return y\n}\n";
    let diags = lint_source(source);
    assert!(
        !has_rule(&diags, "trailing-comma"),
        "fn body block should not fire, got: {diags:?}"
    );
}

#[test]
fn test_trailing_comma_fires_on_dict_literal() {
    let source =
        "pipeline default(task) {\n  let d = {\n    \"a\": 1,\n    \"b\": 2\n  }\n  log(d)\n}\n";
    let diags = lint_source(source);
    assert!(
        has_rule(&diags, "trailing-comma"),
        "expected trailing-comma on multiline dict, got: {diags:?}"
    );
}

#[test]
fn test_trailing_comma_fires_on_fn_call_args() {
    let source = "pipeline default(task) {\n  log(\n    \"first\",\n    \"second\"\n  )\n}\n";
    let diags = lint_source(source);
    assert!(
        has_rule(&diags, "trailing-comma"),
        "expected trailing-comma on multiline call args, got: {diags:?}"
    );
}

#[test]
fn test_import_order_fires_when_out_of_order() {
    let source = "import \"std/io\"\nimport \"std/fs\"\n\nfn a() -> int { return 1 }\n";
    let diags = lint_source(source);
    assert!(
        has_rule(&diags, "import-order"),
        "expected import-order when out of order, got: {diags:?}"
    );
}

#[test]
fn test_import_order_canonical_does_not_fire() {
    let source = "import \"std/fs\"\nimport \"std/io\"\n\nfn a() -> int { return 1 }\n";
    let diags = lint_source(source);
    assert!(
        !has_rule(&diags, "import-order"),
        "canonical order should not fire, got: {diags:?}"
    );
}

#[test]
fn test_import_order_single_import_does_not_fire() {
    let source = "import \"std/io\"\n\nfn a() -> int { return 1 }\n";
    let diags = lint_source(source);
    assert!(
        !has_rule(&diags, "import-order"),
        "single import should not fire, got: {diags:?}"
    );
}

#[test]
fn test_import_order_stdlib_before_third_party() {
    let source = "import \"mypkg/util\"\nimport \"std/io\"\n\nfn a() -> int { return 1 }\n";
    let diags = lint_source(source);
    assert!(
        has_rule(&diags, "import-order"),
        "stdlib should come before third-party, got: {diags:?}"
    );
}

fn lint_with_require_header(source: &str, path: Option<&std::path::Path>) -> Vec<LintDiagnostic> {
    let mut lexer = Lexer::new(source);
    let tokens = lexer.tokenize().unwrap();
    let mut parser = Parser::new(tokens);
    let program = parser.parse().unwrap();
    let options = LintOptions {
        file_path: path,
        require_file_header: true,
    };
    lint_with_options(
        &program,
        &[],
        Some(source),
        &std::collections::HashSet::new(),
        &options,
    )
}

#[test]
fn test_require_file_header_fires_when_missing() {
    let path = std::path::PathBuf::from("foo.harn");
    let source = "fn main() -> int {\n  return 0\n}\n";
    let diags = lint_with_require_header(source, Some(&path));
    let hit = diags
        .iter()
        .find(|d| d.rule == "require-file-header")
        .expect("expected require-file-header");
    let fix = hit.fix.as_ref().expect("autofix expected");
    assert_eq!(fix.len(), 1);
    assert!(
        fix[0].replacement.starts_with("/**\n * Foo."),
        "expected 'Foo.' title, got: {:?}",
        fix[0].replacement
    );
}

#[test]
fn test_require_file_header_ok_when_present() {
    let path = std::path::PathBuf::from("foo.harn");
    let source = "/**\n * Some header.\n */\nfn main() -> int {\n  return 0\n}\n";
    let diags = lint_with_require_header(source, Some(&path));
    assert!(
        !has_rule(&diags, "require-file-header"),
        "should not fire when header present, got: {diags:?}"
    );
}

#[test]
fn test_require_file_header_fires_when_only_line_comment() {
    let path = std::path::PathBuf::from("foo.harn");
    let source = "// not a header\nfn main() -> int {\n  return 0\n}\n";
    let diags = lint_with_require_header(source, Some(&path));
    assert!(
        has_rule(&diags, "require-file-header"),
        "// comment does not count as header, got: {diags:?}"
    );
}

#[test]
fn test_require_file_header_off_by_default() {
    // Without LintOptions { require_file_header: true }, the rule must
    // not fire — this protects the existing repo from sudden regressions.
    let diags = lint_source("fn main() -> int {\n  return 0\n}\n");
    assert!(
        !has_rule(&diags, "require-file-header"),
        "rule should be opt-in, got: {diags:?}"
    );
}

#[test]
fn test_derive_file_header_title_cases() {
    use std::path::PathBuf;
    let cases = [
        ("foo.harn", "Foo."),
        ("foo_bar.harn", "Foo bar."),
        ("foo-bar.harn", "Foo bar."),
        ("Foo.harn", "Foo."),
        ("data_pipeline.harn", "Data pipeline."),
        ("llm-cost.harn", "Llm cost."),
    ];
    for (name, expected) in cases {
        let path = PathBuf::from(name);
        let got = derive_file_header_title(Some(&path));
        assert_eq!(got, expected, "title for {name}");
    }
}

#[test]
fn test_derive_file_header_title_no_path_fallback() {
    let got = derive_file_header_title(None);
    assert_eq!(got, "Module.");
}

#[test]
fn test_eager_collection_conversion_ignores_iter_annotation() {
    let source = r#"pipeline default(task) {
  let xs: Iter<int> = iter([1, 2, 3]).map(fn(x) { return x + 1 })
  log(xs)
}
"#;
    let diags = lint_source(source);
    assert_eq!(
        count_rule(&diags, "eager-collection-conversion"),
        0,
        "Iter<T> annotation should not trigger rule, got: {diags:?}"
    );
}