piano 0.15.0

Automatic instrumentation-based profiler for Rust. Measures self-time, call counts, and heap allocations per function.
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
use std::path::{Path, PathBuf};

use ra_ap_syntax::ast::HasAttrs;
use ra_ap_syntax::ast::HasModuleItem;
use ra_ap_syntax::ast::HasName;
use ra_ap_syntax::{AstNode, AstToken, Edition, SyntaxKind, ast};

use crate::error::{Error, io_context};

/// What the user asked to instrument.
#[derive(Debug, Clone)]
pub enum TargetSpec {
    /// Match against function names (--fn). Substring by default, exact with --exact.
    Fn(String),
    /// All functions in a specific file (--file).
    File(PathBuf),
    /// All functions in a module directory (--mod).
    Mod(String),
}

/// A file and the functions within it that matched.
#[derive(Debug, Clone)]
pub struct ResolvedTarget {
    pub file: PathBuf,
    pub functions: Vec<crate::naming::QualifiedFunction>,
}

/// Why a function was excluded from instrumentation.
///
/// Only structurally uninstrumentable signatures belong here.
/// unsafe fn is NOT skipped -- it receives ctx and guard like any other function.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SkipReason {
    Const,
    ExternAbi,
}

impl std::fmt::Display for SkipReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SkipReason::Const => write!(f, "const"),
            SkipReason::ExternAbi => write!(f, "extern"),
        }
    }
}

/// Whether a function signature is safe to instrument.
///
/// Explicit enum with no implicit "everything else is fine" default.
/// Every code path through `classify()` returns a named variant.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Classification {
    /// Safe to instrument with standard guard or PianoFuture.
    Instrumentable,
    /// Must not be instrumented, with reason.
    Skip(SkipReason),
}

/// A function that was in the target set but excluded from instrumentation.
#[derive(Debug, Clone)]
pub struct SkippedFunction {
    pub name: String,
    pub reason: SkipReason,
    /// File path relative to the project root (e.g. "src/ffi.rs").
    pub path: PathBuf,
}

/// Result of target resolution: resolved targets plus any skipped functions.
#[derive(Debug)]
pub struct ResolveResult {
    /// Functions selected for measurement (matched by selectors, or all when no selectors).
    pub targets: Vec<ResolvedTarget>,
    /// Functions excluded from instrumentation (const fn, extern fn).
    pub skipped: Vec<SkippedFunction>,
    /// ALL instrumentable functions across the source tree, regardless of selectors.
    /// Used to build the pass-through set: functions that receive ctx but no guard.
    /// When selectors are empty, this equals the union of all targets.
    pub all_functions: Vec<ResolvedTarget>,
}

/// Resolve user-provided target specs against the source tree rooted at `src_dir`.
///
/// Returns one `ResolvedTarget` per file that contains at least one matching function.
/// When `specs` is empty, collects all functions from all files (instrument-everything mode).
/// When `specs` is non-empty, errors if no functions match any spec.
/// When `exact` is true, `Fn` patterns match bare or qualified names exactly
/// instead of by substring.
pub fn resolve_targets(
    src_dir: &Path,
    specs: &[TargetSpec],
    exact: bool,
) -> Result<ResolveResult, Error> {
    let rs_files = walk_rs_files(src_dir)?;

    // Compute a relative path like "src/main.rs" from an absolute file path.
    let project_root = src_dir.parent().unwrap_or(src_dir);
    let rel_path = |file: &Path| -> PathBuf {
        file.strip_prefix(project_root)
            .unwrap_or(file)
            .to_path_buf()
    };

    let mut results: Vec<ResolvedTarget> = Vec::new();
    let mut skipped: Vec<SkippedFunction> = Vec::new();
    // Collect all function names seen during resolution for suggestion hints,
    // avoiding a redundant re-parse in build_suggestion_hint.
    let mut all_seen_names: Vec<String> = Vec::new();

    // Always collect ALL instrumentable functions for pass-through support.
    // When selectors are active, non-selected functions become pass-through:
    // they receive ctx but no guard (zero profiling overhead for pass-through).
    let mut all_functions: Vec<ResolvedTarget> = Vec::new();
    let mut all_skipped: Vec<SkippedFunction> = Vec::new();
    for file in &rs_files {
        let source = std::fs::read_to_string(file).map_err(|source| Error::RunReadError {
            path: file.clone(),
            source,
        })?;
        let (all_fns, file_skipped) = extract_functions(&source, rel_path(file));
        if !all_fns.is_empty() {
            merge_into(&mut all_functions, file, all_fns);
        }
        all_skipped.extend(file_skipped);
    }

    if specs.is_empty() {
        // No specs = instrument all functions in all files.
        // Reuse the already-collected all_functions and all_skipped.
        results = all_functions.clone();
        skipped = all_skipped;
    } else {
        for spec in specs {
            match spec {
                TargetSpec::Fn(pattern) => {
                    for file in &rs_files {
                        let source = std::fs::read_to_string(file).map_err(|source| {
                            Error::RunReadError {
                                path: file.clone(),
                                source,
                            }
                        })?;
                        let (all_fns, file_skipped) = extract_functions(&source, rel_path(file));
                        all_seen_names.extend(all_fns.iter().map(|qf| qf.minimal.clone()));
                        let matched: Vec<crate::naming::QualifiedFunction> = all_fns
                            .into_iter()
                            .filter(|qf| {
                                let name = &qf.minimal;
                                // Match against the bare function name (after any Type:: prefix).
                                let bare = name.rsplit("::").next().unwrap_or(name);
                                if exact {
                                    bare == pattern.as_str() || name == pattern.as_str()
                                } else {
                                    bare.contains(pattern.as_str())
                                        || name.contains(pattern.as_str())
                                }
                            })
                            .collect();
                        if !matched.is_empty() {
                            merge_into(&mut results, file, matched);
                        }
                        let matched_skipped: Vec<SkippedFunction> = file_skipped
                            .into_iter()
                            .filter(|s| {
                                let bare = s.name.rsplit("::").next().unwrap_or(&s.name);
                                if exact {
                                    bare == pattern.as_str() || s.name == pattern.as_str()
                                } else {
                                    bare.contains(pattern.as_str())
                                        || s.name.contains(pattern.as_str())
                                }
                            })
                            .collect();
                        skipped.extend(matched_skipped);
                    }
                }
                TargetSpec::File(file_path) => {
                    // Find files whose path ends with the given relative path.
                    let matching_files: Vec<&PathBuf> =
                        rs_files.iter().filter(|f| f.ends_with(file_path)).collect();
                    for file in matching_files {
                        let source = std::fs::read_to_string(file).map_err(|source| {
                            Error::RunReadError {
                                path: file.clone(),
                                source,
                            }
                        })?;
                        let (all_fns, file_skipped) = extract_functions(&source, rel_path(file));
                        all_seen_names.extend(all_fns.iter().map(|qf| qf.minimal.clone()));
                        if !all_fns.is_empty() {
                            merge_into(&mut results, file, all_fns);
                        }
                        skipped.extend(file_skipped);
                    }
                }
                TargetSpec::Mod(module_name) => {
                    // Look for files under a directory named `module_name` (e.g. walker/mod.rs,
                    // walker/sub.rs) or a file named `module_name.rs`.
                    for file in &rs_files {
                        let is_mod_file = file
                            .parent()
                            .and_then(|p| p.file_name())
                            .is_some_and(|dir| dir == module_name.as_str());
                        let is_named_file = file
                            .file_stem()
                            .is_some_and(|stem| stem == module_name.as_str());

                        if !is_mod_file && !is_named_file {
                            continue;
                        }

                        let source = std::fs::read_to_string(file).map_err(|source| {
                            Error::RunReadError {
                                path: file.clone(),
                                source,
                            }
                        })?;
                        let (all_fns, file_skipped) = extract_functions(&source, rel_path(file));
                        all_seen_names.extend(all_fns.iter().map(|qf| qf.minimal.clone()));
                        if !all_fns.is_empty() {
                            merge_into(&mut results, file, all_fns);
                        }
                        skipped.extend(file_skipped);
                    }
                }
            }
        }

        if results.is_empty() {
            let desc = specs
                .iter()
                .map(|s| match s {
                    TargetSpec::Fn(p) => format!("--fn {p}"),
                    TargetSpec::File(p) => format!("--file {}", p.display()),
                    TargetSpec::Mod(m) => format!("--mod {m}"),
                })
                .collect::<Vec<_>>()
                .join(", ");

            let hint = if skipped.is_empty() {
                build_suggestion_hint(specs, &all_seen_names)
            } else {
                let reasons = skipped
                    .iter()
                    .map(|s| s.reason.to_string())
                    .collect::<std::collections::BTreeSet<_>>()
                    .into_iter()
                    .collect::<Vec<_>>()
                    .join(", ");
                format!(
                    ". All {} matched function(s) were skipped ({}) -- piano cannot instrument these",
                    skipped.len(),
                    reasons
                )
            };
            return Err(Error::NoTargetsFound { specs: desc, hint });
        }
    }

    // Sort by file path for deterministic output.
    results.sort_by(|a, b| a.file.cmp(&b.file));
    for r in &mut results {
        r.functions.sort_by(|a, b| a.full.cmp(&b.full));
        r.functions.dedup_by(|a, b| a.full == b.full);
    }

    skipped.sort_by(|a, b| a.name.cmp(&b.name));
    skipped.dedup_by(|a, b| a.name == b.name);

    // Sort all_functions the same way as results.
    all_functions.sort_by(|a, b| a.file.cmp(&b.file));
    for r in &mut all_functions {
        r.functions.sort_by(|a, b| a.full.cmp(&b.full));
        r.functions.dedup_by(|a, b| a.full == b.full);
    }

    Ok(ResolveResult {
        targets: results,
        skipped,
        all_functions,
    })
}

/// Merge matched functions into the results vec, coalescing by file path.
fn merge_into(
    results: &mut Vec<ResolvedTarget>,
    file: &Path,
    functions: Vec<crate::naming::QualifiedFunction>,
) {
    if let Some(existing) = results.iter_mut().find(|r| r.file == file) {
        existing.functions.extend(functions);
    } else {
        results.push(ResolvedTarget {
            file: file.to_path_buf(),
            functions,
        });
    }
}

/// Recursively find all `.rs` files under `dir`.
fn walk_rs_files(dir: &Path) -> Result<Vec<PathBuf>, Error> {
    let mut files = Vec::new();
    walk_rs_files_inner(dir, &mut files)?;
    files.sort();
    Ok(files)
}

fn walk_rs_files_inner(dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), Error> {
    let entries = std::fs::read_dir(dir).map_err(io_context("read directory", dir))?;
    for entry in entries {
        let entry = entry.map_err(io_context("read directory entry", dir))?;
        let path = entry.path();
        if path.is_dir() {
            walk_rs_files_inner(&path, out)?;
        } else if path.extension().is_some_and(|ext| ext == "rs") {
            out.push(path);
        }
    }
    Ok(())
}

/// Parse a Rust source file and extract all function names.
///
/// Top-level functions are returned as bare names.
/// Impl methods are returned as "Type::method".
/// Default trait methods are returned as "Trait::method".
///
/// Functions annotated with `#[test]` and items inside `#[cfg(test)]` modules
/// are excluded -- they are not useful instrumentation targets.
pub(crate) fn extract_functions(
    source: &str,
    rel_path: PathBuf,
) -> (Vec<crate::naming::QualifiedFunction>, Vec<SkippedFunction>) {
    let parse = ast::SourceFile::parse(source, Edition::Edition2024);

    // ra_ap_syntax does error recovery, so we always get a tree.
    // If there are errors, warn but continue (like syn did -- we just get
    // fewer functions from broken regions).
    if !parse.errors().is_empty() {
        eprintln!(
            "warning: parse errors in {} ({} errors, continuing with recovered tree)",
            rel_path.display(),
            parse.errors().len()
        );
    }

    let file = parse.tree();
    let mut collector = FnCollector {
        functions: Vec::new(),
        skipped: Vec::new(),
        path: rel_path,
        scope: crate::naming::ScopeState::new(),
    };
    collector.walk_source_file(&file);

    // Discover functions generated by macro_rules! invocations.
    // This replaces the old token-scan approach (visit_macro_rules) for
    // metavar-named functions. Uses ra_ap_mbe to expand each invocation
    // and parses the expansion to find fn items.
    let (expansions, _defs, calls) =
        crate::macro_expand::expand_fn_generating_macros(file.syntax());
    for exp in &expansions {
        let call = &calls[exp.call_idx];

        // Determine impl context from the macro call's position in the CST.
        // Inline parent-walk with fn-break guard: macro-expanded fns are parsed
        // from expanded text, so we can't call qualified_name_for_fn on them.
        let impl_prefix = {
            use ra_ap_syntax::TextSize;
            let offset = TextSize::from(call.byte_start as u32);
            file.syntax()
                .token_at_offset(offset)
                .right_biased()
                .and_then(|token| {
                    let mut node = token.parent();
                    while let Some(n) = node {
                        if let Some(imp) = ast::Impl::cast(n.clone()) {
                            let self_ty = imp.self_ty()?;
                            return Some(crate::naming::render_impl_name(
                                &self_ty,
                                imp.trait_().as_ref(),
                            ));
                        }
                        if ast::Fn::can_cast(n.kind()) {
                            break;
                        }
                        node = n.parent();
                    }
                    None
                })
        };

        for fn_name in &exp.fn_names {
            let qualified = if let Some(ref prefix) = impl_prefix {
                format!("{prefix}::{fn_name}")
            } else {
                fn_name.clone()
            };
            let minimal = collector.scope.render_minimal(&qualified);
            let medium = collector.scope.render_medium(&qualified);
            let full = collector.scope.render_full(&qualified);
            collector
                .functions
                .push(crate::naming::QualifiedFunction::new(
                    &minimal, &medium, &full,
                ));
        }
    }

    (collector.functions, collector.skipped)
}

/// Check whether a CST node's attributes contain a specific simple attribute (e.g. `#[test]`).
fn has_attr_cst(attrs: impl Iterator<Item = ast::Attr>, name: &str) -> bool {
    attrs.into_iter().any(|a| {
        // Simple path attribute: `#[test]` has a single path segment.
        a.path()
            .and_then(|p| p.segment())
            .and_then(|seg| seg.name_ref())
            .is_some_and(|n| n.text() == name)
    })
}

/// Check whether a CST node's attributes contain `#[cfg(test)]`.
fn has_cfg_test_cst(attrs: impl Iterator<Item = ast::Attr>) -> bool {
    attrs.into_iter().any(|a| {
        let path_is_cfg = a
            .path()
            .and_then(|p| p.segment())
            .and_then(|seg| seg.name_ref())
            .is_some_and(|n| n.text() == "cfg");
        if !path_is_cfg {
            return false;
        }
        // Check if the token tree content is just "test".
        // The token tree text is "(test)" -- strip parens and check.
        a.token_tree().is_some_and(|tt| {
            let text = tt.syntax().text().to_string();
            let inner = text.trim_start_matches('(').trim_end_matches(')').trim();
            inner == "test"
        })
    })
}

/// Extract the ABI string from a CST `ast::Fn`, stripping surrounding quotes.
///
/// Returns `None` when there is no `extern` keyword (default Rust ABI).
/// Returns `Some("")` for bare `extern fn` (no ABI string, defaults to C).
/// Returns `Some("C")`, `Some("Rust")`, etc. for explicit ABI strings.
fn extract_cst_abi(func: &ast::Fn) -> Option<String> {
    let abi = func.abi()?;
    match abi.abi_string() {
        Some(abi_str) => {
            // abi_string().text() returns the token including quotes, e.g. "\"Rust\"".
            let raw = abi_str.text();
            let unquoted = raw
                .strip_prefix('"')
                .and_then(|s| s.strip_suffix('"'))
                .unwrap_or(raw);
            Some(unquoted.to_string())
        }
        None => {
            // bare `extern fn` (no ABI string) defaults to "C"
            Some(String::new())
        }
    }
}

/// Classify whether a function is safe to instrument based on primitive properties.
///
/// Takes parser-agnostic bools and an optional ABI string so that both the
/// resolver and the rewriter call the same implementation. One function, one proof.
///
/// `abi` semantics: `None` means no explicit ABI (default Rust ABI, instrumentable).
/// `Some("Rust")` is also instrumentable. Any other value (including `Some("")`
/// for bare `extern fn`) causes a skip.
///
/// Defense against the "wrong function filtering" bug class:
/// - This function: signature modifiers via is_const, abi
/// - Return type: `returns_future()` in the strategy layer (rewrite/mod.rs)
/// - Attributes: caller-level checks (#[test]) + structural coverage
/// - Syntactic context: item walking (FnCollector/InjectionCollector)
///
/// unsafe fn is NOT skipped -- it receives ctx parameter and guard like any
/// other instrumentable function.
///
/// Built-in attribute audit (Rust 1.88, 26 attrs on functions):
///   Safe: cfg, cfg_attr, ignore, should_panic, allow, expect, warn, deny,
///     forbid, deprecated, must_use, inline, cold, track_caller,
///     instruction_set, no_mangle, export_name, link_section, doc
///   Policy skip: test (handled by caller)
///   Caught by signature: naked (extern), target_feature (safe to instrument)
///   Unreachable: proc_macro, proc_macro_derive, proc_macro_attribute,
///     panic_handler (no_std only)
pub(crate) fn classify(is_const: bool, abi: Option<&str>) -> Classification {
    if is_const {
        return Classification::Skip(SkipReason::Const);
    }
    if let Some(abi_str) = abi {
        if abi_str != "Rust" {
            return Classification::Skip(SkipReason::ExternAbi);
        }
    }
    Classification::Instrumentable
}

/// Classify a CST function node using primitive properties extracted from the CST.
fn classify_cst_fn(func: &ast::Fn) -> Classification {
    let cst_abi = extract_cst_abi(func);
    classify(func.const_token().is_some(), cst_abi.as_deref())
}

/// CST-based collector that walks module items to extract function names.
struct FnCollector {
    functions: Vec<crate::naming::QualifiedFunction>,
    skipped: Vec<SkippedFunction>,
    /// File path relative to the project root (e.g. "src/core.rs").
    path: PathBuf,
    /// Scope tracking (mod, fn, block).
    scope: crate::naming::ScopeState,
}

impl FnCollector {
    fn walk_source_file(&mut self, file: &ast::SourceFile) {
        for item in file.items() {
            self.walk_item(&item);
        }
    }

    fn walk_item(&mut self, item: &ast::Item) {
        match item {
            ast::Item::Module(module) => self.visit_module(module),
            ast::Item::Fn(func) => self.visit_top_level_fn(func),
            ast::Item::Impl(imp) => self.visit_impl(imp),
            ast::Item::Trait(tr) => self.visit_trait(tr),
            // MacroRules: fn discovery handled by macro_expand module
            // after the tree walk (see extract_functions).
            _ => {}
        }
    }

    fn walk_item_list(&mut self, item_list: &ast::ItemList) {
        for item in item_list.items() {
            self.walk_item(&item);
        }
    }

    fn visit_module(&mut self, module: &ast::Module) {
        if has_cfg_test_cst(module.attrs()) {
            return; // skip entire #[cfg(test)] module
        }
        let mod_name = module
            .name()
            .map(|n| n.text().to_string())
            .unwrap_or_else(|| "_".to_string());
        self.scope.push_mod(&mod_name);
        if let Some(item_list) = module.item_list() {
            self.walk_item_list(&item_list);
        }
        self.scope.pop();
    }

    fn visit_top_level_fn(&mut self, func: &ast::Fn) {
        if !has_attr_cst(func.attrs(), "test") {
            let name = func
                .name()
                .map(|n| n.text().to_string())
                .unwrap_or_default();
            self.record_function(func, &name);
        }
        // Push fn scope for nested items, then walk the body for nested fns.
        let fn_name = func
            .name()
            .map(|n| n.text().to_string())
            .unwrap_or_default();
        self.scope.push_fn(&fn_name);
        if let Some(body) = func.body() {
            self.walk_fn_body(&body);
        }
        self.scope.pop();
    }

    fn visit_impl(&mut self, imp: &ast::Impl) {
        if let Some(assoc_list) = imp.assoc_item_list() {
            for assoc in assoc_list.assoc_items() {
                if let ast::AssocItem::Fn(func) = assoc {
                    self.visit_impl_fn(&func);
                }
            }
        }
    }

    fn visit_impl_fn(&mut self, func: &ast::Fn) {
        if !has_attr_cst(func.attrs(), "test") {
            let qualified = crate::naming::qualified_name_for_fn(func);
            self.record_function(func, &qualified);
        }
        let fn_name = func
            .name()
            .map(|n| n.text().to_string())
            .unwrap_or_default();
        self.scope.push_fn(&fn_name);
        if let Some(body) = func.body() {
            self.walk_fn_body(&body);
        }
        self.scope.pop();
    }

    fn visit_trait(&mut self, tr: &ast::Trait) {
        if let Some(assoc_list) = tr.assoc_item_list() {
            for assoc in assoc_list.assoc_items() {
                if let ast::AssocItem::Fn(func) = assoc {
                    self.visit_trait_fn(&func);
                }
            }
        }
    }

    fn visit_trait_fn(&mut self, func: &ast::Fn) {
        if func.body().is_some() {
            let qualified = crate::naming::qualified_name_for_fn(func);
            self.record_function(func, &qualified);
            let fn_name = func
                .name()
                .map(|n| n.text().to_string())
                .unwrap_or_default();
            self.scope.push_fn(&fn_name);
            if let Some(body) = func.body() {
                self.walk_fn_body(&body);
            }
            self.scope.pop();
        }
    }

    /// Walk descendants of a function body to find nested items
    /// (inner fns, impls, traits, modules defined inside function bodies).
    fn walk_fn_body(&mut self, body: &ast::BlockExpr) {
        // Walk direct statement-level items in the block.
        // We need to handle nested items like:
        //   fn outer() {
        //     struct S;
        //     impl S { fn m() {} }
        //     fn inner() {}
        //   }
        // Use descendants to find nested items at any depth within the block.
        for node in body.syntax().descendants() {
            if node.kind() == SyntaxKind::FN {
                // Skip the function itself (body's parent fn is already handled).
                if node.text_range() == body.syntax().text_range() {
                    continue;
                }
                if let Some(inner_fn) = ast::Fn::cast(node.clone()) {
                    let qualified = crate::naming::qualified_name_for_fn(&inner_fn);
                    self.visit_nested_fn(&inner_fn, &qualified);
                }
            }
        }
    }

    /// Process a nested function found inside another function's body.
    fn visit_nested_fn(&mut self, func: &ast::Fn, qualified: &str) {
        if !has_attr_cst(func.attrs(), "test") {
            self.record_function(func, qualified);
        }
    }

    /// Classify a function and record it as instrumentable or skipped.
    /// Single site for classification -> push, so adding a Classification
    /// variant or SkippedFunction field can't silently break one of the callers.
    fn record_function(&mut self, func: &ast::Fn, qualified: &str) {
        let minimal = self.scope.render_minimal(qualified);
        match classify_cst_fn(func) {
            Classification::Skip(reason) => {
                self.skipped.push(SkippedFunction {
                    name: minimal,
                    reason,
                    path: self.path.clone(),
                });
            }
            Classification::Instrumentable => {
                let medium = self.scope.render_medium(qualified);
                let full = self.scope.render_full(qualified);
                self.functions.push(crate::naming::QualifiedFunction::new(
                    &minimal, &medium, &full,
                ));
            }
        }
    }
}

/// Levenshtein edit distance between two strings.
fn levenshtein(a: &str, b: &str) -> usize {
    let b_len = b.len();
    let mut row: Vec<usize> = (0..=b_len).collect();

    for (i, a_ch) in a.chars().enumerate() {
        let mut prev = i;
        row[0] = i + 1;
        for (j, b_ch) in b.chars().enumerate() {
            let cost = if a_ch == b_ch { prev } else { prev + 1 };
            prev = row[j + 1];
            row[j + 1] = cost.min(row[j] + 1).min(prev + 1);
        }
    }

    row[b_len]
}

/// Build a recovery hint for the NoTargetsFound error.
///
/// For `--fn` specs: computes Levenshtein suggestions against all function names.
/// Falls back to showing function count with guidance when no close matches exist.
/// Accepts pre-collected function names from the resolution pass to avoid re-parsing.
fn build_suggestion_hint(specs: &[TargetSpec], seen_names: &[String]) -> String {
    // Collect --fn patterns only; other spec types don't get suggestions.
    let fn_patterns: Vec<&str> = specs
        .iter()
        .filter_map(|s| match s {
            TargetSpec::Fn(p) => Some(p.as_str()),
            _ => None,
        })
        .collect();

    if fn_patterns.is_empty() {
        return String::new();
    }

    // Deduplicate the pre-collected names.
    let mut all_names: Vec<&String> = seen_names.iter().collect();
    all_names.sort();
    all_names.dedup();

    let total_count = all_names.len();

    // Find Levenshtein-close matches for each pattern.
    let mut suggestions: Vec<String> = Vec::new();
    for pattern in &fn_patterns {
        let threshold = pattern.len() / 3;
        let mut scored: Vec<(usize, &str)> = all_names
            .iter()
            .filter_map(|name| {
                let bare = name.rsplit("::").next().unwrap_or(name);
                let dist = levenshtein(pattern, bare).min(levenshtein(pattern, name));
                if dist <= threshold && dist > 0 {
                    Some((dist, name.as_str()))
                } else {
                    None
                }
            })
            .collect();
        scored.sort_by_key(|(d, _)| *d);
        suggestions.extend(scored.iter().take(5).map(|(_, name)| (*name).to_owned()));
    }
    suggestions.sort();
    suggestions.dedup();

    if !suggestions.is_empty() {
        format!(". Did you mean: {}?", suggestions.join(", "))
    } else {
        format!(". Found {total_count} functions, none matched. Run without --fn to instrument all")
    }
}

/// Derive a Rust module path prefix from a file path relative to `src/`.
///
/// - `main.rs` / `lib.rs` -> `""` (crate root)
/// - `mod.rs` -> parent directory components (e.g., `db/mod.rs` -> `"db"`)
/// - other -> parent components + file stem (e.g., `db/query.rs` -> `"db::query"`)
pub fn module_prefix(relative: &Path) -> String {
    let stem = relative.file_stem().and_then(|s| s.to_str()).unwrap_or("_");

    let parent_components: Vec<&str> = relative
        .parent()
        .map(|p| {
            p.components()
                .map(|c| c.as_os_str().to_str().unwrap_or("_"))
                .collect()
        })
        .unwrap_or_default();

    if stem == "main" || stem == "lib" || stem == "mod" {
        parent_components.join("::")
    } else {
        let mut parts = parent_components;
        parts.push(stem);
        parts.join("::")
    }
}

/// Qualify a function name with a module prefix. Returns the name unchanged
/// if the prefix is empty.
pub fn qualify(prefix: &str, name: &str) -> String {
    if prefix.is_empty() {
        name.to_string()
    } else {
        format!("{prefix}::{name}")
    }
}

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

    use tempfile::TempDir;

    use super::*;

    /// Build the synthetic test project inside `dir/src/`.
    fn create_test_project(dir: &Path) {
        let src = dir.join("src");
        fs::create_dir_all(src.join("walker")).unwrap();

        fs::write(src.join("main.rs"), "fn main() { walk(); }\nfn walk() {}\n").unwrap();

        fs::write(
            src.join("resolver.rs"),
            "\
struct Resolver;
impl Resolver {
    pub fn resolve(&self) -> bool { true }
    fn internal_resolve(&self) {}
}
fn helper() {}
",
        )
        .unwrap();

        fs::write(
            src.join("walker").join("mod.rs"),
            "pub fn walk_dir() {}\nfn scan() {}\n",
        )
        .unwrap();

        fs::write(
            src.join("special_fns.rs"),
            "\
const fn fixed_size() -> usize { 42 }
unsafe fn dangerous() -> i32 { 0 }
extern \"C\" fn ffi_callback() {}
fn normal_fn() {}

struct Widget;
impl Widget {
    const fn none() -> Option<Self> { None }
    unsafe fn raw_ptr(&self) -> *const u8 { std::ptr::null() }
    fn valid_method(&self) {}
}

trait Processor {
    fn process(&self);
    fn default_method(&self) { }
    unsafe fn unsafe_default(&self) { }
    fn required_method(&self);
}
",
        )
        .unwrap();

        fs::write(
            src.join("with_tests.rs"),
            "\
fn production_fn() {}

#[test]
fn test_something() {}

#[cfg(test)]
mod tests {
    fn test_helper() {}

    #[test]
    fn it_works() {}
}
",
        )
        .unwrap();
    }

    #[test]
    fn resolve_fn_by_substring() {
        let tmp = TempDir::new().unwrap();
        create_test_project(tmp.path());

        let specs = [TargetSpec::Fn("walk".into())];
        let result = resolve_targets(&tmp.path().join("src"), &specs, false).unwrap();

        let all_fns: Vec<&str> = result
            .targets
            .iter()
            .flat_map(|r| r.functions.iter().map(|qf| qf.minimal.as_str()))
            .collect();

        assert!(all_fns.contains(&"walk"), "should match exact 'walk'");
        assert!(
            all_fns.contains(&"walk_dir"),
            "should match 'walk_dir' (substring)"
        );
        assert!(!all_fns.contains(&"helper"), "should not match 'helper'");
        assert!(!all_fns.contains(&"scan"), "should not match 'scan'");
    }

    #[test]
    fn resolve_fn_finds_impl_methods() {
        let tmp = TempDir::new().unwrap();
        create_test_project(tmp.path());

        let specs = [TargetSpec::Fn("resolve".into())];
        let result = resolve_targets(&tmp.path().join("src"), &specs, false).unwrap();

        let all_fns: Vec<&str> = result
            .targets
            .iter()
            .flat_map(|r| r.functions.iter().map(|qf| qf.minimal.as_str()))
            .collect();

        assert!(
            all_fns.contains(&"Resolver::resolve"),
            "should match impl method 'resolve'"
        );
        assert!(
            all_fns.contains(&"Resolver::internal_resolve"),
            "should match impl method 'internal_resolve'"
        );
    }

    #[test]
    fn resolve_file_gets_all_functions() {
        let tmp = TempDir::new().unwrap();
        create_test_project(tmp.path());

        let specs = [TargetSpec::File("resolver.rs".into())];
        let result = resolve_targets(&tmp.path().join("src"), &specs, false).unwrap();

        assert_eq!(result.targets.len(), 1);
        let fns: Vec<&str> = result.targets[0]
            .functions
            .iter()
            .map(|qf| qf.minimal.as_str())
            .collect();
        assert!(fns.contains(&"helper"));
        assert!(fns.contains(&"Resolver::internal_resolve"));
        assert!(fns.contains(&"Resolver::resolve"));
    }

    #[test]
    fn resolve_mod_gets_directory_module() {
        let tmp = TempDir::new().unwrap();
        create_test_project(tmp.path());

        let specs = [TargetSpec::Mod("walker".into())];
        let result = resolve_targets(&tmp.path().join("src"), &specs, false).unwrap();

        assert_eq!(result.targets.len(), 1);
        let fns: Vec<&str> = result.targets[0]
            .functions
            .iter()
            .map(|qf| qf.minimal.as_str())
            .collect();
        assert!(fns.contains(&"walk_dir"));
        assert!(fns.contains(&"scan"));
    }

    #[test]
    fn no_match_returns_error() {
        let tmp = TempDir::new().unwrap();
        create_test_project(tmp.path());

        let specs = [TargetSpec::Fn("nonexistent_xyz".into())];
        let result = resolve_targets(&tmp.path().join("src"), &specs, false);

        assert!(result.is_err(), "should error when no functions match");
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("nonexistent_xyz"),
            "error should mention the pattern: {err}"
        );
        assert!(
            err.contains("Found 14 functions"),
            "error should show function count: {err}"
        );
        assert!(
            err.contains("Run without --fn"),
            "error should suggest running without --fn: {err}"
        );
    }

    #[test]
    fn resolve_skips_test_functions_and_cfg_test_modules() {
        let tmp = TempDir::new().unwrap();
        create_test_project(tmp.path());

        let specs = [TargetSpec::File("with_tests.rs".into())];
        let result = resolve_targets(&tmp.path().join("src"), &specs, false).unwrap();

        let all_fns: Vec<&str> = result
            .targets
            .iter()
            .flat_map(|r| r.functions.iter().map(|qf| qf.minimal.as_str()))
            .collect();

        assert!(
            all_fns.contains(&"production_fn"),
            "should include production function"
        );
        assert!(
            !all_fns.contains(&"test_something"),
            "should skip #[test] function"
        );
        assert!(
            !all_fns.contains(&"test_helper"),
            "should skip function inside #[cfg(test)] module"
        );
        assert!(
            !all_fns.contains(&"it_works"),
            "should skip #[test] inside #[cfg(test)] module"
        );
    }

    #[test]
    fn resolve_skips_unparseable_files() {
        let tmp = TempDir::new().unwrap();
        create_test_project(tmp.path());

        // Add a file that looks like .rs but isn't valid Rust (e.g. a Tera template).
        let src = tmp.path().join("src");
        fs::write(
            src.join("template.tera.rs"),
            "{% for variant in variants %}\nfn {{ variant }}() {}\n{% endfor %}\n",
        )
        .unwrap();

        // Should succeed despite the unparseable file.
        let specs = [TargetSpec::Fn("walk".into())];
        let result = resolve_targets(&src, &specs, false).unwrap();

        let all_fns: Vec<&str> = result
            .targets
            .iter()
            .flat_map(|r| r.functions.iter().map(|qf| qf.minimal.as_str()))
            .collect();

        assert!(
            all_fns.contains(&"walk"),
            "should still find valid functions"
        );
        assert!(
            all_fns.contains(&"walk_dir"),
            "should still find valid functions"
        );
    }

    #[test]
    fn resolve_empty_specs_returns_all_functions() {
        let tmp = TempDir::new().unwrap();
        create_test_project(tmp.path());

        let specs: Vec<TargetSpec> = vec![];
        let result = resolve_targets(&tmp.path().join("src"), &specs, false).unwrap();

        let all_fns: Vec<&str> = result
            .targets
            .iter()
            .flat_map(|r| r.functions.iter().map(|qf| qf.minimal.as_str()))
            .collect();

        // Should find functions from all files: main.rs, resolver.rs, walker/mod.rs, with_tests.rs
        assert!(all_fns.contains(&"main"), "should include main");
        assert!(
            all_fns.contains(&"walk"),
            "should include walk from main.rs"
        );
        assert!(
            all_fns.contains(&"helper"),
            "should include helper from resolver.rs"
        );
        assert!(
            all_fns.contains(&"Resolver::resolve"),
            "should include impl methods"
        );
        assert!(
            all_fns.contains(&"walk_dir"),
            "should include walk_dir from walker"
        );
        assert!(all_fns.contains(&"scan"), "should include scan from walker");
        assert!(
            all_fns.contains(&"production_fn"),
            "should include production_fn"
        );

        // Should still skip test functions
        assert!(!all_fns.contains(&"test_something"), "should skip #[test]");
        assert!(
            !all_fns.contains(&"it_works"),
            "should skip test in cfg(test)"
        );
    }

    #[test]
    fn resolve_skips_const_and_extern_functions() {
        let tmp = TempDir::new().unwrap();
        create_test_project(tmp.path());

        let specs = [TargetSpec::File("special_fns.rs".into())];
        let result = resolve_targets(&tmp.path().join("src"), &specs, false).unwrap();

        let all_fns: Vec<&str> = result
            .targets
            .iter()
            .flat_map(|r| r.functions.iter().map(|qf| qf.minimal.as_str()))
            .collect();

        // Should include normal functions
        assert!(all_fns.contains(&"normal_fn"), "should include normal_fn");
        assert!(
            all_fns.contains(&"Widget::valid_method"),
            "should include Widget::valid_method"
        );

        // unsafe fn IS instrumentable -- guard is pure safe code
        assert!(all_fns.contains(&"dangerous"), "should include unsafe fn");
        assert!(
            all_fns.contains(&"Widget::raw_ptr"),
            "should include unsafe impl method"
        );

        // Should skip const/extern
        assert!(!all_fns.contains(&"fixed_size"), "should skip const fn");
        assert!(!all_fns.contains(&"ffi_callback"), "should skip extern fn");
        assert!(
            !all_fns.contains(&"Widget::none"),
            "should skip const impl method"
        );
    }

    #[test]
    fn resolve_instruments_unsafe_trait_default_methods() {
        let tmp = TempDir::new().unwrap();
        create_test_project(tmp.path());

        let specs = [TargetSpec::File("special_fns.rs".into())];
        let result = resolve_targets(&tmp.path().join("src"), &specs, false).unwrap();

        let all_fns: Vec<&str> = result
            .targets
            .iter()
            .flat_map(|r| r.functions.iter().map(|qf| qf.minimal.as_str()))
            .collect();

        // Trait default methods should be included
        assert!(
            all_fns.contains(&"Processor::default_method"),
            "should include safe trait default method"
        );

        // unsafe trait default methods ARE instrumentable -- guard is pure safe code
        assert!(
            all_fns.contains(&"Processor::unsafe_default"),
            "should include unsafe trait default method"
        );

        // Trait methods without default bodies should not appear at all
        assert!(
            !all_fns.contains(&"Processor::process"),
            "should not include trait method without default body"
        );
        assert!(
            !all_fns.contains(&"Processor::required_method"),
            "should not include trait method without default body"
        );

        // unsafe_default should NOT be in the skipped list
        let skipped_names: Vec<&str> = result.skipped.iter().map(|s| s.name.as_str()).collect();
        assert!(
            !skipped_names.contains(&"Processor::unsafe_default"),
            "unsafe trait default method should not be skipped"
        );
    }

    #[test]
    fn no_match_error_includes_suggestions_for_typo() {
        let tmp = TempDir::new().unwrap();
        create_test_project(tmp.path());

        // "heper" is close to "helper" (distance 1, threshold = 5/3 = 1, so distance <= 1 passes).
        let specs = [TargetSpec::Fn("heper".into())];
        let result = resolve_targets(&tmp.path().join("src"), &specs, false);

        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("helper"),
            "error should suggest 'helper' for typo 'heper': {err}"
        );
        assert!(
            err.contains("Did you mean"),
            "error should include 'Did you mean' phrasing: {err}"
        );
    }

    #[test]
    fn levenshtein_basic_cases() {
        assert_eq!(levenshtein("", ""), 0);
        assert_eq!(levenshtein("abc", "abc"), 0);
        assert_eq!(levenshtein("abc", ""), 3);
        assert_eq!(levenshtein("", "abc"), 3);
        assert_eq!(levenshtein("kitten", "sitting"), 3);
        assert_eq!(levenshtein("parse", "prase"), 2); // swap = 2 edits
        assert_eq!(levenshtein("walk", "wlak"), 2);
        assert_eq!(levenshtein("a", "b"), 1);
    }

    #[test]
    fn no_match_error_shows_count_for_large_project() {
        let tmp = TempDir::new().unwrap();
        let src = tmp.path().join("src");
        fs::create_dir_all(&src).unwrap();

        // Create a file with 20 functions to verify the count fallback path.
        let mut code = String::new();
        for i in 0..20 {
            code.push_str(&format!("fn func_{i}() {{}}\n"));
        }
        fs::write(src.join("many.rs"), &code).unwrap();

        let specs = [TargetSpec::Fn("nonexistent".into())];
        let result = resolve_targets(&src, &specs, false);

        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("Found 20 functions"),
            "error should show function count: {err}"
        );
        assert!(
            err.contains("Run without --fn"),
            "error should suggest running without --fn: {err}"
        );
    }

    #[test]
    fn no_match_error_shows_clean_patterns() {
        let tmp = TempDir::new().unwrap();
        create_test_project(tmp.path());

        let specs = [TargetSpec::Fn("zzz_nonexistent".into())];
        let result = resolve_targets(&tmp.path().join("src"), &specs, false);
        let err = result.unwrap_err().to_string();
        assert!(
            err.starts_with("no functions matched"),
            "error should start with 'no functions matched': {err}"
        );
        assert!(
            err.contains("--fn zzz_nonexistent"),
            "error should include the spec: {err}"
        );
    }

    #[test]
    fn resolve_fn_substring_matches_qualified_name() {
        let tmp = TempDir::new().unwrap();
        create_test_project(tmp.path());

        // "Resolver" appears in the qualified name "Resolver::resolve" but not in the bare
        // name "resolve". Substring matching should check both.
        let specs = [TargetSpec::Fn("Resolver".into())];
        let result = resolve_targets(&tmp.path().join("src"), &specs, false).unwrap();

        let all_fns: Vec<&str> = result
            .targets
            .iter()
            .flat_map(|r| r.functions.iter().map(|qf| qf.minimal.as_str()))
            .collect();

        assert!(
            all_fns.contains(&"Resolver::resolve"),
            "should match 'Resolver::resolve' via qualified name substring"
        );
        assert!(
            all_fns.contains(&"Resolver::internal_resolve"),
            "should match 'Resolver::internal_resolve' via qualified name substring"
        );
        assert!(
            !all_fns.contains(&"helper"),
            "should not match unrelated 'helper'"
        );
    }

    #[test]
    fn resolve_fn_exact_match() {
        let tmp = TempDir::new().unwrap();
        create_test_project(tmp.path());

        // "walk" with exact=true should match only "walk", not "walk_dir".
        let specs = [TargetSpec::Fn("walk".into())];
        let result = resolve_targets(&tmp.path().join("src"), &specs, true).unwrap();

        let all_fns: Vec<&str> = result
            .targets
            .iter()
            .flat_map(|r| r.functions.iter().map(|qf| qf.minimal.as_str()))
            .collect();

        assert!(all_fns.contains(&"walk"), "should match exact 'walk'");
        assert!(
            !all_fns.contains(&"walk_dir"),
            "should NOT match 'walk_dir' in exact mode"
        );
    }

    #[test]
    fn resolve_fn_exact_match_qualified() {
        let tmp = TempDir::new().unwrap();
        create_test_project(tmp.path());

        // Exact match should also work with qualified names like "Resolver::resolve".
        let specs = [TargetSpec::Fn("Resolver::resolve".into())];
        let result = resolve_targets(&tmp.path().join("src"), &specs, true).unwrap();

        let all_fns: Vec<&str> = result
            .targets
            .iter()
            .flat_map(|r| r.functions.iter().map(|qf| qf.minimal.as_str()))
            .collect();

        assert!(
            all_fns.contains(&"Resolver::resolve"),
            "should match qualified 'Resolver::resolve'"
        );
        assert!(
            !all_fns.contains(&"Resolver::internal_resolve"),
            "should NOT match 'Resolver::internal_resolve' in exact mode"
        );
    }

    #[test]
    fn resolve_fn_exact_no_match_shows_error() {
        let tmp = TempDir::new().unwrap();
        create_test_project(tmp.path());

        // "wal" is a substring of "walk" but not an exact match.
        let specs = [TargetSpec::Fn("wal".into())];
        let result = resolve_targets(&tmp.path().join("src"), &specs, true);

        assert!(result.is_err(), "partial match should fail in exact mode");
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("no functions matched"),
            "error should say no functions matched: {err}"
        );
    }

    #[test]
    fn resolve_finds_unsafe_fn_by_pattern() {
        let tmp = TempDir::new().unwrap();
        create_test_project(tmp.path());

        // "dangerous" matches the unsafe fn "dangerous" -- unsafe fn is instrumentable.
        let specs = [TargetSpec::Fn("dangerous".into())];
        let result = resolve_targets(&tmp.path().join("src"), &specs, false).unwrap();

        let all_fns: Vec<&str> = result
            .targets
            .iter()
            .flat_map(|r| r.functions.iter().map(|qf| qf.minimal.as_str()))
            .collect();
        assert!(
            all_fns.contains(&"dangerous"),
            "should find and instrument unsafe fn 'dangerous': {all_fns:?}"
        );
    }

    #[test]
    fn resolve_reports_skipped_functions_with_reasons() {
        let tmp = TempDir::new().unwrap();
        create_test_project(tmp.path());

        let specs = [TargetSpec::File("special_fns.rs".into())];
        let result = resolve_targets(&tmp.path().join("src"), &specs, false).unwrap();

        let skipped_names: Vec<(&str, &SkipReason)> = result
            .skipped
            .iter()
            .map(|s| (s.name.as_str(), &s.reason))
            .collect();

        assert!(
            skipped_names.contains(&("fixed_size", &SkipReason::Const)),
            "should report const fn as skipped: {skipped_names:?}"
        );
        assert!(
            skipped_names.contains(&("ffi_callback", &SkipReason::ExternAbi)),
            "should report extern fn as skipped: {skipped_names:?}"
        );
        assert!(
            skipped_names.contains(&("Widget::none", &SkipReason::Const)),
            "should report const impl method as skipped: {skipped_names:?}"
        );

        // unsafe fns should NOT be in the skipped list -- guard is pure safe code
        assert!(
            !skipped_names.iter().any(|(name, _)| *name == "dangerous"),
            "unsafe fn should not be skipped: {skipped_names:?}"
        );
        assert!(
            !skipped_names
                .iter()
                .any(|(name, _)| *name == "Widget::raw_ptr"),
            "unsafe impl method should not be skipped: {skipped_names:?}"
        );

        // All skipped functions from this file should have the correct relative path.
        for s in &result.skipped {
            assert_eq!(
                s.path,
                Path::new("src/special_fns.rs"),
                "skipped fn '{}' should have relative path src/special_fns.rs",
                s.name
            );
        }

        let all_fns: Vec<&str> = result
            .targets
            .iter()
            .flat_map(|r| r.functions.iter().map(|qf| qf.minimal.as_str()))
            .collect();
        assert!(all_fns.contains(&"normal_fn"));
        assert!(all_fns.contains(&"Widget::valid_method"));
        // unsafe fns should be in the instrumented list
        assert!(all_fns.contains(&"dangerous"));
        assert!(all_fns.contains(&"Widget::raw_ptr"));
    }

    #[test]
    fn hint_empty_when_only_file_and_mod_specs() {
        // Only --file and --mod specs, no --fn specs.
        let specs = [
            TargetSpec::File("lib.rs".into()),
            TargetSpec::Mod("mymod".into()),
        ];
        let hint = build_suggestion_hint(&specs, &[]);
        assert!(
            hint.is_empty(),
            "hint should be empty when no --fn specs are present, got: {hint:?}"
        );
    }

    #[test]
    fn module_prefix_crate_roots() {
        assert_eq!(module_prefix(Path::new("main.rs")), "");
        assert_eq!(module_prefix(Path::new("lib.rs")), "");
    }

    #[test]
    fn module_prefix_simple_files() {
        assert_eq!(module_prefix(Path::new("db.rs")), "db");
        assert_eq!(module_prefix(Path::new("utils.rs")), "utils");
    }

    #[test]
    fn module_prefix_mod_rs() {
        assert_eq!(module_prefix(Path::new("db/mod.rs")), "db");
        assert_eq!(
            module_prefix(Path::new("api/handlers/mod.rs")),
            "api::handlers"
        );
    }

    #[test]
    fn module_prefix_nested_files() {
        assert_eq!(module_prefix(Path::new("db/query.rs")), "db::query");
        assert_eq!(
            module_prefix(Path::new("api/handlers/user.rs")),
            "api::handlers::user"
        );
    }

    #[cfg(unix)]
    #[test]
    fn module_prefix_non_utf8_fallback() {
        use std::ffi::OsStr;
        use std::os::unix::ffi::OsStrExt;

        // 0x80 is not valid UTF-8; build a path like "<invalid>/valid.rs"
        let bad_dir = OsStr::from_bytes(b"\x80");
        let mut path = std::path::PathBuf::from(bad_dir);
        path.push("query.rs");
        assert_eq!(module_prefix(&path), "_::query");

        // Non-UTF-8 file stem: "valid/<invalid>.rs"
        let bad_stem = OsStr::from_bytes(b"\x80.rs");
        let path2 = Path::new("api").join(bad_stem);
        assert_eq!(module_prefix(&path2), "api::_");
    }

    #[test]
    fn qualify_with_empty_prefix() {
        assert_eq!(qualify("", "walk"), "walk");
        assert_eq!(qualify("", "Walker::walk"), "Walker::walk");
    }

    #[test]
    fn qualify_with_module_prefix() {
        assert_eq!(qualify("db", "execute"), "db::execute");
        assert_eq!(
            qualify("db::query", "validate_input"),
            "db::query::validate_input"
        );
        assert_eq!(
            qualify("api", "Handler::validate_input"),
            "api::Handler::validate_input"
        );
    }

    #[test]
    fn trait_impl_methods_get_disambiguated_names() {
        let dir = TempDir::new().unwrap();
        let src = dir.path().join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(
            src.join("main.rs"),
            r#"
use std::fmt;

struct Point;

impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "point")
    }
}

impl fmt::Debug for Point {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "point")
    }
}

fn main() {}
"#,
        )
        .unwrap();

        let result = resolve_targets(&src, &[], false).unwrap();
        let names: Vec<&str> = result
            .targets
            .iter()
            .flat_map(|t| t.functions.iter().map(|qf| qf.minimal.as_str()))
            .collect();
        assert!(
            names.contains(&"<Point as Display>::fmt"),
            "should have Display-qualified name: {names:?}"
        );
        assert!(
            names.contains(&"<Point as Debug>::fmt"),
            "should have Debug-qualified name: {names:?}"
        );
        // There should be two separate entries, not one merged "Point::fmt"
        let fmt_count = names.iter().filter(|n| n.ends_with("fmt")).count();
        assert_eq!(
            fmt_count, 2,
            "should have 2 distinct fmt entries: {names:?}"
        );
    }

    #[test]
    fn classify_returns_explicit_classification() {
        // Normal fn -> Instrumentable
        assert!(matches!(
            classify(false, None),
            Classification::Instrumentable
        ));

        // const fn -> Skip(Const)
        assert!(matches!(
            classify(true, None),
            Classification::Skip(SkipReason::Const)
        ));

        // extern "C" fn -> Skip(ExternAbi)
        assert!(matches!(
            classify(false, Some("C")),
            Classification::Skip(SkipReason::ExternAbi)
        ));

        // extern fn (bare extern = empty ABI) -> Skip(ExternAbi)
        assert!(matches!(
            classify(false, Some("")),
            Classification::Skip(SkipReason::ExternAbi)
        ));

        // extern "Rust" fn -> Instrumentable (explicit Rust ABI is fine)
        assert!(matches!(
            classify(false, Some("Rust")),
            Classification::Instrumentable
        ));

        // async fn -> Instrumentable (async affects strategy, not filtering)
        // (asyncness is not a classify parameter -- it is a strategy concern)
        assert!(matches!(
            classify(false, None),
            Classification::Instrumentable
        ));
    }

    #[test]
    fn classify_cst_fn_delegates_to_classify() {
        /// Parse a function signature string into a CST `ast::Fn` node.
        fn parse_fn(sig: &str) -> ast::Fn {
            let source = format!("{sig} {{}}");
            let parse = ast::SourceFile::parse(&source, Edition::Edition2024);
            let file = parse.tree();
            file.syntax()
                .descendants()
                .find_map(ast::Fn::cast)
                .expect("should parse fn")
        }

        // Verify classify_cst_fn extracts properties from CST ast::Fn
        // and delegates to the unified classify().
        let func = parse_fn("fn foo()");
        assert!(matches!(
            classify_cst_fn(&func),
            Classification::Instrumentable
        ));

        let func = parse_fn("const fn foo()");
        assert!(matches!(
            classify_cst_fn(&func),
            Classification::Skip(SkipReason::Const)
        ));

        // unsafe fn -> Instrumentable (guard is pure safe code)
        let func = parse_fn("unsafe fn foo()");
        assert!(matches!(
            classify_cst_fn(&func),
            Classification::Instrumentable
        ));

        let func = parse_fn("extern \"C\" fn foo()");
        assert!(matches!(
            classify_cst_fn(&func),
            Classification::Skip(SkipReason::ExternAbi)
        ));

        let func = parse_fn("extern fn foo()");
        assert!(matches!(
            classify_cst_fn(&func),
            Classification::Skip(SkipReason::ExternAbi)
        ));

        let func = parse_fn("extern \"Rust\" fn foo()");
        assert!(matches!(
            classify_cst_fn(&func),
            Classification::Instrumentable
        ));

        let func = parse_fn("async fn foo()");
        assert!(matches!(
            classify_cst_fn(&func),
            Classification::Instrumentable
        ));

        let func = parse_fn("fn foo<T: Clone>(x: T) -> T");
        assert!(matches!(
            classify_cst_fn(&func),
            Classification::Instrumentable
        ));

        let func = parse_fn("fn foo() -> impl std::future::Future<Output = i32>");
        assert!(matches!(
            classify_cst_fn(&func),
            Classification::Instrumentable
        ));
    }

    // --- Pass-through / all_functions tests ---

    /// resolve_targets with selectors returns all_functions containing every
    /// instrumentable function, while targets contains only the selected subset.
    #[test]
    fn all_functions_includes_unselected() {
        let dir = TempDir::new().unwrap();
        create_test_project(dir.path());
        let src = dir.path().join("src");

        // Use --fn to select only "walk" (in walker.rs).
        let specs = vec![TargetSpec::Fn("walk".to_string())];
        let result = resolve_targets(&src, &specs, false).unwrap();

        // targets should contain only matched functions.
        let measured_names: Vec<&str> = result
            .targets
            .iter()
            .flat_map(|t| t.functions.iter().map(|qf| qf.minimal.as_str()))
            .collect();
        assert!(
            measured_names.iter().all(|n| n.contains("walk")),
            "targets should only contain walk-matching functions. Got: {measured_names:?}"
        );

        // all_functions should contain functions from all files, not just matched ones.
        let all_names: Vec<&str> = result
            .all_functions
            .iter()
            .flat_map(|t| t.functions.iter().map(|qf| qf.minimal.as_str()))
            .collect();
        assert!(
            all_names.len() >= measured_names.len(),
            "all_functions should be >= targets. all={}, targets={}",
            all_names.len(),
            measured_names.len()
        );

        // all_functions should include functions not in targets.
        let has_non_walk = all_names.iter().any(|n| !n.contains("walk"));
        assert!(
            has_non_walk,
            "all_functions should include non-walk functions for pass-through. Got: {all_names:?}"
        );
    }

    /// When specs are empty (default), all_functions equals targets.
    #[test]
    fn all_functions_equals_targets_when_no_specs() {
        let dir = TempDir::new().unwrap();
        create_test_project(dir.path());
        let src = dir.path().join("src");

        let specs: Vec<TargetSpec> = Vec::new();
        let result = resolve_targets(&src, &specs, false).unwrap();

        let target_names: std::collections::BTreeSet<String> = result
            .targets
            .iter()
            .flat_map(|t| t.functions.iter().map(|qf| qf.minimal.clone()))
            .collect();
        let all_names: std::collections::BTreeSet<String> = result
            .all_functions
            .iter()
            .flat_map(|t| t.functions.iter().map(|qf| qf.minimal.clone()))
            .collect();
        assert_eq!(
            target_names, all_names,
            "when no selectors, all_functions should equal targets"
        );
    }

    #[test]
    fn macro_in_impl_naming_diagnostic() {
        // Observe what names resolve produces for macro-generated methods.
        let source = r#"
macro_rules! add_method {
    ($name:ident) => {
        fn $name(&self) -> u32 { 42 }
    };
}
struct S;
impl S {
    add_method!(get_value);
    fn regular_method(&self) -> u32 { 99 }
}
fn main() {}
"#;
        let (functions, _) = extract_functions(source, PathBuf::from("test.rs"));
        for f in &functions {
            eprintln!(
                "  minimal={:?}  medium={:?}  full={:?}",
                f.minimal, f.medium, f.full
            );
        }

        let macro_fn = functions.iter().find(|f| f.minimal.contains("get_value"));
        let regular_fn = functions
            .iter()
            .find(|f| f.minimal.contains("regular_method"));

        assert!(
            macro_fn.is_some(),
            "macro-generated method should be discovered"
        );
        assert!(regular_fn.is_some(), "regular method should be discovered");

        // Both should have the same S:: prefix
        assert_eq!(
            macro_fn.unwrap().minimal,
            "S::get_value",
            "macro-generated method should be impl-qualified"
        );
        assert_eq!(
            regular_fn.unwrap().minimal,
            "S::regular_method",
            "regular method should be impl-qualified"
        );
    }
}