basta 0.3.0

Dead code detection — unused files, exports, symbols and imports across JavaScript, TypeScript, Vue, Svelte, Astro and Python, and Rust through cargo's diagnostics
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
//! Turning a resolved graph into the findings a reader acts on.
//!
//! The graph knows what is reachable. This module decides which of the
//! unreachable things are worth saying out loud, in what words, and with how
//! much confidence — and, just as importantly, which to stay quiet about.
//!
//! The suppressions matter as much as the rules. A declaration inside a file
//! that is itself unused is not reported: the file is the finding, and
//! listing its twenty exports underneath would bury it. A member whose name
//! is read anywhere in the project is not reported, because basta infers no
//! types and cannot tell one `render` from another. A declaration the parser
//! never saw is never guessed at.

use crate::confidence::{Evidence, score};
use crate::config::BastaConfig;
use crate::finding::Finding;
use crate::graph::Graph;
use crate::model::{Module, Symbol, SymbolFlags, SymbolKind};
use cpd_core::deadcode::Category;

/// Every finding the configuration asks for, ordered for a reader: whole
/// files first, then by path, then down the file.
pub fn findings(graph: &Graph, config: &BastaConfig) -> Vec<Finding> {
    let unparsed = graph.has_unparsed_modules();
    let mut out = Vec::new();

    for module in &graph.modules {
        if module.parse_failed {
            continue; // Nothing was read; nothing can be claimed.
        }
        // Two file-level verdicts, both of which make everything inside the
        // file moot: nothing runs it at all, or only the test suite does.
        // Reporting one file beats reporting its twenty exports.
        let dead = !graph.is_module_reachable(module.id);
        let test_only = !module.is_test && graph.is_module_used_only_by_tests(module.id);
        if dead || test_only {
            if config.reports(Category::UnusedFile) {
                out.push(unused_file(graph, module, test_only, unparsed, config));
            }
            continue;
        }
        if module.is_test && !config.include_tests {
            continue;
        }
        // Everything in an ambient declaration file is declared for a compiler
        // rather than imported by a module — an `interface Array` there
        // augments a global, and nothing will ever name it. The file itself is
        // still checked above; only its contents are off limits.
        if module.traits.ambient_declarations {
            continue;
        }

        for symbol in graph.symbols_of(module.id) {
            if let Some(finding) = classify_symbol(graph, module, symbol, config, unparsed) {
                out.push(finding);
            }
        }
    }

    out.retain(|f| f.confidence >= config.min_confidence && f.lines >= config.min_lines);
    out.sort_by(|a, b| {
        (a.category != Category::UnusedFile)
            .cmp(&(b.category != Category::UnusedFile))
            .then_with(|| a.path.cmp(&b.path))
            .then_with(|| a.start.line.cmp(&b.start.line))
            .then_with(|| a.name.cmp(&b.name))
    });
    out
}

fn classify_symbol(
    graph: &Graph,
    module: &Module,
    symbol: &Symbol,
    config: &BastaConfig,
    unparsed: bool,
) -> Option<Finding> {
    let category = category_for(graph, module, symbol, config)?;
    if !config.reports(category) {
        return None;
    }
    // A declaration whose name basta could not read cannot be matched against
    // anything, so it is never reported rather than always reported.
    if symbol.name.starts_with('<') {
        return None;
    }

    let evidence = gather_evidence(graph, module, symbol, category, unparsed);

    let (confidence, reasons) = score(category, &evidence);
    let parent = symbol
        .parent
        .map(|p| graph.symbol(p).name.clone())
        .filter(|name| !name.is_empty());
    Some(Finding {
        message: message_for(
            category,
            symbol,
            parent.as_deref(),
            &module.path,
            graph.is_used_only_by_tests(symbol.id),
        ),
        category,
        path: module.path.clone(),
        name: symbol.name.clone(),
        exported_as: symbol
            .export_name()
            .filter(|name| *name != symbol.name)
            .map(str::to_string),
        symbol_kind: Some(symbol.kind),
        parent,
        language: module.language.to_string(),
        start: symbol.start.clone(),
        end: symbol.end.clone(),
        lines: symbol.lines,
        confidence,
        reasons,
    })
}

/// Which rule, if any, a declaration falls under.
///
/// The question every branch answers is the same one: does this run when the
/// shipped program runs? A declaration the test suite reaches and production
/// does not still counts as a finding — the confidence model marks it — but
/// one the program itself reaches never does.
fn category_for(
    graph: &Graph,
    module: &Module,
    symbol: &Symbol,
    config: &BastaConfig,
) -> Option<Category> {
    // An import the module also exports is a re-export: the binding *is* the
    // module's public surface, so it is judged by whether anything imports it
    // onward, not by whether the file that wrote it also uses it. A package
    // `__init__.py` is made almost entirely of these.
    if symbol.kind == SymbolKind::Import && !symbol.is_exported() {
        // Used in the file that wrote it, or imported onward out of it. The
        // second is how a barrel file works: `phases.py` imports a name only
        // so that `orchestrator.py` can import it from `phases`, and nothing
        // in `phases.py` itself ever mentions it again.
        let used = graph.is_import_used(symbol.id)
            || graph.is_export_imported(symbol.module, &symbol.name);
        return (!used).then_some(Category::UnusedImport);
    }
    // A name the project's framework reads by convention is used by the
    // framework. The graph roots it, which keeps what it calls alive; this
    // keeps the declaration itself out of the report, where an entry point's
    // `--include-entry-exports` or a member no code names would put it.
    if symbol.flags.contains(SymbolFlags::FRAMEWORK_GLOBAL) {
        return None;
    }
    if symbol.kind.is_member() {
        // Without types, `x.render()` could be a call to any `render`, so a
        // name nobody reads *anywhere* is the only member basta can honestly
        // call dead. Reachability is deliberately not consulted: the graph
        // keeps a live class's members reachable so the chain through them
        // holds, which says nothing about whether any of them is called.
        if graph.is_member_name_read(&symbol.name) {
            return None;
        }
        // A member of a declaration that is itself dead is covered by that
        // declaration's finding; repeating it per method buries the one line
        // a reader needs.
        if symbol
            .parent
            .is_some_and(|parent| !graph.is_symbol_production_reachable(parent))
        {
            return None;
        }
        return Some(Category::UnusedMember);
    }
    if !symbol.flags.contains(SymbolFlags::TOP_LEVEL) {
        // A nested declaration is reported through its enclosing one: if the
        // outer function is dead the file already says so, and if it is alive
        // a closure inside it is part of that body.
        return None;
    }
    if symbol.is_exported() {
        let export_name = symbol.export_name().unwrap_or(&symbol.name);
        // Imported by name from a module that runs: used, entry point or not.
        // A module something namespace-imports can be reached without naming,
        // so its exports are only reported when no member access anywhere in
        // the scan could be that reach.
        if graph.is_export_imported_by_production(symbol.module, export_name)
            || (graph.is_wildcarded(symbol.module) && graph.is_member_name_read(export_name))
        {
            return None;
        }
        // An entry point's exports are the surface the outside world calls.
        // Nothing in the scan is meant to import them, so reachability says
        // nothing about them — the graph roots them on purpose — and they are
        // reported only on request.
        if module.is_entry {
            return config
                .include_entry_exports
                .then_some(Category::UnusedExport);
        }
        // An export its own module uses, in a module that runs, is alive.
        // That the `export` keyword is then unnecessary is a style question,
        // not dead code, and basta does not raise it.
        if graph.is_symbol_production_reachable(symbol.id) {
            return None;
        }
        return Some(Category::UnusedExport);
    }
    (!graph.is_symbol_production_reachable(symbol.id)).then_some(Category::UnusedSymbol)
}

/// The last two segments of a module's path, extension off — `handlers/island`
/// for `src/runtime/handlers/island.ts`, and `handlers/island` again for
/// `…/handlers/island/index.ts`, which is the same thing to whoever names it.
/// This is the key path-shaped strings are remembered under.
fn path_tail(path: &str) -> Option<String> {
    let path = path.replace('\\', "/");
    let mut segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    let file = segments.pop()?;
    let stem = file.split('.').next().filter(|stem| !stem.is_empty())?;
    if stem != "index" {
        segments.push(stem);
    }
    let from = segments.len().checked_sub(2)?;
    Some(segments[from..].join("/"))
}

fn unused_file(
    graph: &Graph,
    module: &Module,
    test_only: bool,
    unparsed: bool,
    config: &BastaConfig,
) -> Finding {
    let evidence = Evidence {
        path_in_string: path_tail(&module.path).is_some_and(|tail| graph.appears_in_string(&tail)),
        in_test_file: module.is_test && !config.include_tests,
        unparsed_module: unparsed,
        package_surface: module.traits.package_surface,
        used_only_by_tests: test_only,
        ..Evidence::default()
    };
    let (confidence, reasons) = score(Category::UnusedFile, &evidence);
    let message = if test_only {
        format!("{} is only imported by tests", module.path)
    } else {
        format!(
            "{} is never imported and is not an entry point",
            module.path
        )
    };
    Finding {
        category: Category::UnusedFile,
        message,
        path: module.path.clone(),
        name: String::new(),
        exported_as: None,
        symbol_kind: None,
        parent: None,
        language: module.language.to_string(),
        start: cpd_core::models::Location {
            line: 1,
            column: 0,
            offset: 0,
        },
        end: cpd_core::models::Location {
            line: module.lines.max(1),
            column: 0,
            offset: 0,
        },
        lines: module.lines,
        confidence,
        reasons,
    }
}

/// Everything that bears on whether this finding is really dead.
///
/// Only what can apply to the category is collected. A string literal cannot
/// keep an import *binding* alive, and a member has no module boundary to be
/// public across, so filling those in would subtract points for evidence that
/// is not evidence.
fn gather_evidence(
    graph: &Graph,
    module: &Module,
    symbol: &Symbol,
    category: Category,
    unparsed: bool,
) -> Evidence {
    // True of any finding, whatever rule produced it.
    let mut evidence = Evidence {
        in_test_file: module.is_test,
        unparsed_module: unparsed,
        // Code that evaluates source or resolves names at runtime can reach
        // anything, including an import binding.
        dynamic_module: module.has_dynamic_access,
        ..Evidence::default()
    };
    if category == Category::UnusedImport {
        // An unreferenced binding is a fact about one file, not an inference
        // about the project; nothing else can make it wrong.
        return evidence;
    }

    // True of any finding about a named declaration.
    evidence.name_in_string = graph.appears_in_string(&symbol.name);
    evidence.decorated = symbol.flags.contains(SymbolFlags::DECORATED);

    match category {
        Category::UnusedMember => {
            // A member is resolved by name alone, so who declared it and who
            // implements it matter more than any module boundary.
            evidence.abstract_declaration = symbol.flags.contains(SymbolFlags::ABSTRACT);
            evidence.overrides = symbol.flags.contains(SymbolFlags::OVERRIDE);
            evidence.ambiguous_name = graph.is_name_ambiguous(&symbol.name);
        }
        Category::UnusedSymbol | Category::UnusedExport => {
            // Where top-level names are attributes of the module object, a
            // member-style read of the name anywhere may be this declaration.
            evidence.name_read_as_attribute =
                module.traits.names_are_attributes && graph.is_member_name_read(&symbol.name);
            evidence.package_surface = module.traits.package_surface;
            evidence.used_only_by_tests = graph.is_used_only_by_tests(symbol.id);
            if category == Category::UnusedExport {
                // Only an export can be called from outside the scan, and
                // only an export is matched against another module's imports,
                // which a name two modules declare makes unreliable.
                evidence.public_api = module.is_entry;
                evidence.wildcarded = graph.is_wildcarded(module.id);
                evidence.ambiguous_name = graph.is_name_ambiguous(&symbol.name);
            }
        }
        Category::UnusedImport | Category::UnusedFile => {}
    }
    evidence
}

fn message_for(
    category: Category,
    symbol: &Symbol,
    parent: Option<&str>,
    path: &str,
    test_only: bool,
) -> String {
    let noun = symbol.kind.noun();
    let name = &symbol.name;
    match category {
        Category::UnusedImport => format!("`{name}` is imported but never used"),
        Category::UnusedSymbol if test_only => {
            format!("{noun} `{name}` is only used by tests")
        }
        Category::UnusedSymbol => {
            format!("{noun} `{name}` is never used in {path}")
        }
        Category::UnusedExport if test_only => {
            format!("exported {noun} `{name}` is only imported by tests")
        }
        Category::UnusedExport => match symbol.export_name() {
            Some(exported) if exported != name => {
                format!("{noun} `{name}` is exported as `{exported}` but nothing imports it")
            }
            _ => format!("exported {noun} `{name}` is never imported"),
        },
        Category::UnusedMember => match parent {
            Some(owner) => format!("{noun} `{owner}.{name}` is never accessed"),
            None => format!("{noun} `{name}` is never accessed"),
        },
        Category::UnusedFile => format!("{path} is never imported"),
    }
}

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

    struct Scan {
        graph: Graph,
    }

    fn scan(files: &[(&str, &str)], entries: &[&str]) -> Scan {
        scan_with(files, entries, &[])
    }

    fn scan_with(files: &[(&str, &str)], entries: &[&str], tests: &[&str]) -> Scan {
        Scan {
            graph: crate::test_scan::build(files, entries, tests),
        }
    }

    impl Scan {
        fn findings(&self, config: &BastaConfig) -> Vec<Finding> {
            findings(&self.graph, config)
        }

        /// Neither a file nor an export reported: everything scanned is used.
        fn assert_all_used(&self) {
            let all = self.all();
            assert!(names(&all, Category::UnusedFile).is_empty(), "{all:?}");
            assert!(names(&all, Category::UnusedExport).is_empty(), "{all:?}");
        }

        fn all(&self) -> Vec<Finding> {
            self.findings(&BastaConfig {
                categories: Category::ALL.to_vec(),
                min_confidence: 0,
                ..BastaConfig::default()
            })
        }
    }

    fn names(findings: &[Finding], category: Category) -> Vec<String> {
        let mut out: Vec<String> = findings
            .iter()
            .filter(|f| f.category == category)
            .map(|f| {
                if f.name.is_empty() {
                    f.path.clone()
                } else {
                    f.name.clone()
                }
            })
            .collect();
        out.sort();
        out
    }

    #[test]
    fn a_module_a_glob_reaches_has_its_exports_read() {
        // A bundler hands the importer the whole module object and the code
        // reads members off it by a computed name, so nothing about the
        // expansion says which export is used: all of them are.
        let scan = scan(
            &[
                (
                    "i18n.js",
                    "const catalogs = import.meta.glob('./locales/*.js', { eager: true });\n\
                     export function translate(key) {\n\
                       return catalogs['./locales/en.js'].messages[key];\n\
                     }\n",
                ),
                (
                    "locales/en.js",
                    "export const messages = { home: 'Home' };\n",
                ),
                (
                    "locales/uk.js",
                    "export const messages = { home: 'Home' };\n",
                ),
                (
                    "main.js",
                    "import { translate } from './i18n.js';\ntranslate('home');\n",
                ),
            ],
            &["main.js"],
        );
        scan.assert_all_used();
    }

    #[test]
    fn a_glob_reaches_what_its_pattern_matches_and_nothing_nested_below() {
        // `*` stays within one directory for the bundler, so a file one level
        // down is not loaded and is as unused as any other.
        let files = |pattern: &str| {
            vec![
                (
                    "i18n.js".to_string(),
                    format!(
                        "const all = import.meta.glob('{pattern}', {{ eager: true }});\nexport const t = (k) => all[k];\n"
                    ),
                ),
                (
                    "locales/en.js".to_string(),
                    "export const m = 1;\n".to_string(),
                ),
                (
                    "locales/archive/old.js".to_string(),
                    "export const m = 0;\n".to_string(),
                ),
                (
                    "main.js".to_string(),
                    "import { t } from './i18n.js';\nt('a');\n".to_string(),
                ),
            ]
        };
        let unused = |pattern: &str| {
            let owned = files(pattern);
            let borrowed: Vec<(&str, &str)> = owned
                .iter()
                .map(|(p, s)| (p.as_str(), s.as_str()))
                .collect();
            names(&scan(&borrowed, &["main.js"]).all(), Category::UnusedFile)
        };
        assert_eq!(
            unused("./locales/*.js"),
            vec!["locales/archive/old.js".to_string()]
        );
        assert!(unused("./locales/**/*.js").is_empty(), "`**` does descend");
        // The template-literal form is held to the same pattern.
        let scan = scan(
            &[
                (
                    "router.js",
                    "export const open = (n) => import(`./pages/${n}.vue`);\n",
                ),
                ("pages/home.vue", "<template><p>home</p></template>\n"),
                ("pages/notes.md.js", "export default 1;\n"),
                (
                    "main.js",
                    "import { open } from './router.js';\nopen('home');\n",
                ),
            ],
            &["main.js"],
        );
        assert_eq!(
            names(&scan.all(), Category::UnusedFile),
            vec!["pages/notes.md.js".to_string()]
        );
    }

    #[test]
    fn a_module_only_an_astro_client_script_imports_is_used() {
        let scan = scan(
            &[
                (
                    "pages/index.astro",
                    "---\nconst title = 'Home';\n---\n<h1>{title}</h1>\n<script>\nimport { mount } from '../widget.ts';\nmount();\n</script>\n",
                ),
                ("widget.ts", "export function mount() {}\n"),
            ],
            &["pages/index.astro"],
        );
        scan.assert_all_used();
    }

    #[test]
    fn a_route_table_loaded_by_name_keeps_its_own_findings_confident() {
        // Computing which page to load is not dynamic access to the router's
        // own exports: an export nobody imports is as unused as anywhere.
        let scan = scan(
            &[
                (
                    "router.js",
                    "export const open = (n) => import(`./pages/${n}.js`);\n\
                     export const preload = (n) => import(`./pages/${n}.js`);\n",
                ),
                ("pages/home.js", "export default 'home';\n"),
                (
                    "main.js",
                    "import { open } from './router.js';\nopen('home');\n",
                ),
            ],
            &["main.js"],
        );
        let exports: Vec<_> = scan
            .all()
            .into_iter()
            .filter(|f| f.category == Category::UnusedExport)
            .collect();
        assert_eq!(exports.len(), 1, "{exports:?}");
        assert_eq!(exports[0].name, "preload");
        assert!(
            exports[0].confidence >= 85,
            "no dynamic-access penalty for a resolved glob: {:?}",
            exports[0]
        );
    }

    #[test]
    fn each_rule_reports_the_thing_it_is_named_after() {
        let scan = scan(
            &[
                (
                    "index.ts",
                    "import { used, spare } from './api';\nused();\n",
                ),
                (
                    "api.ts",
                    "export function used() { helper(); }\n\
                     function helper() {}\n\
                     function deadHelper() {}\n\
                     export function spare() {}\n\
                     export function neverImported() {}\n",
                ),
                ("orphan.ts", "export const x = 1;\n"),
            ],
            &["index.ts"],
        );
        let found = scan.all();
        assert_eq!(names(&found, Category::UnusedFile), vec!["orphan.ts"]);
        assert_eq!(names(&found, Category::UnusedImport), vec!["spare"]);
        assert_eq!(names(&found, Category::UnusedSymbol), vec!["deadHelper"]);
        assert_eq!(
            names(&found, Category::UnusedExport),
            vec!["neverImported"],
            "`spare` is imported, so the import is the finding, not the export"
        );
    }

    #[test]
    fn a_dead_file_swallows_the_findings_inside_it() {
        let scan = scan(
            &[
                ("index.ts", "export const kept = 1;\n"),
                (
                    "orphan.ts",
                    "import { missing } from './nowhere';\n\
                     export function a() {}\n\
                     export function b() {}\n\
                     function c() {}\n",
                ),
            ],
            &["index.ts"],
        );
        let found = scan.all();
        let in_orphan: Vec<&Finding> = found.iter().filter(|f| f.path == "orphan.ts").collect();
        assert_eq!(
            in_orphan.len(),
            1,
            "one unused file, not four findings inside it: {:?}",
            in_orphan.iter().map(|f| &f.message).collect::<Vec<_>>()
        );
        assert_eq!(in_orphan[0].category, Category::UnusedFile);
    }

    #[test]
    fn a_member_whose_name_is_read_anywhere_is_never_reported() {
        let scan = scan(
            &[(
                "index.ts",
                "export class A {\n  render() {}\n}\n\
                 export class B {\n  render() {}\n  onlyHere() {}\n}\n\
                 declare const a: A;\na.render();\n",
            )],
            &["index.ts"],
        );
        let found = scan.all();
        assert_eq!(
            names(&found, Category::UnusedMember),
            vec!["onlyHere"],
            "without types basta cannot tell A.render from B.render"
        );
    }

    #[test]
    fn findings_below_the_confidence_threshold_are_dropped() {
        let scan = scan(
            &[
                ("index.ts", "import './api';\n"),
                (
                    "api.ts",
                    "export function unusedButNamed() {}\nexport const hint = 'unusedButNamed';\n",
                ),
            ],
            &["index.ts"],
        );
        let strict = scan.findings(&BastaConfig {
            categories: Category::ALL.to_vec(),
            min_confidence: 90,
            ..BastaConfig::default()
        });
        assert!(
            !strict.iter().any(|f| f.name == "unusedButNamed"),
            "a name that appears in a string is not a 90-confidence finding"
        );
        let lenient = scan.all();
        let finding = lenient
            .iter()
            .find(|f| f.name == "unusedButNamed")
            .expect("reported at min_confidence 0");
        assert!(finding.reasons.contains(&Reason::NameAppearsInString));
    }

    #[test]
    fn min_lines_filters_out_one_line_declarations() {
        let scan = scan(
            &[(
                "index.ts",
                "const short = 1;\n\
                 function long() {\n  const a = 1;\n  return a;\n}\n\
                 export const kept = 2;\n",
            )],
            &["index.ts"],
        );
        let found = scan.findings(&BastaConfig {
            categories: Category::ALL.to_vec(),
            min_confidence: 0,
            min_lines: 3,
            ..BastaConfig::default()
        });
        assert_eq!(names(&found, Category::UnusedSymbol), vec!["long"]);
    }

    #[test]
    fn test_files_are_quiet_by_default_and_reported_on_request() {
        let files = [
            ("index.ts", "export const used = 1;\n"),
            (
                "a.test.ts",
                "import { used } from './index';\nfunction deadInTest() {}\nconsole.log(used);\n",
            ),
        ];
        let scan = scan_with(&files, &["index.ts"], &["a.test.ts"]);
        assert!(
            !scan.all().iter().any(|f| f.path == "a.test.ts"),
            "a test file's own dead code is noise by default"
        );

        let including = scan.findings(&BastaConfig {
            categories: Category::ALL.to_vec(),
            min_confidence: 0,
            include_tests: true,
            ..BastaConfig::default()
        });
        assert!(including.iter().any(|f| f.name == "deadInTest"));
    }

    #[test]
    fn python_private_helpers_and_public_names_land_in_different_categories() {
        let scan = scan(
            &[
                ("app/__main__.py", "from .core import main\n\nmain()\n"),
                (
                    "app/core.py",
                    "def main():\n    pass\n\n\ndef _unused_helper():\n    pass\n\n\ndef public_unused():\n    pass\n",
                ),
            ],
            &["app/__main__.py"],
        );
        let found = scan.all();
        assert_eq!(
            names(&found, Category::UnusedSymbol),
            vec!["_unused_helper"]
        );
        assert_eq!(names(&found, Category::UnusedExport), vec!["public_unused"]);
    }

    #[test]
    fn messages_name_the_thing_and_read_as_sentences() {
        let scan = scan(
            &[
                ("index.ts", "import { unusedImport } from './api';\n"),
                (
                    "api.ts",
                    "function inner() {}\nexport { inner as outer };\nexport function unusedImport() {}\n",
                ),
            ],
            &["index.ts"],
        );
        let found = scan.all();
        let messages: Vec<&str> = found.iter().map(|f| f.message.as_str()).collect();
        assert!(
            messages.contains(&"`unusedImport` is imported but never used"),
            "{messages:?}"
        );
        assert!(
            messages
                .iter()
                .any(|m| m.contains("`inner` is exported as `outer` but nothing imports it")),
            "{messages:?}"
        );
    }

    #[test]
    fn findings_are_ordered_files_first_then_by_path_and_line() {
        let scan = scan(
            &[
                (
                    "index.ts",
                    "function b() {}\nfunction a() {}\nexport const kept = 1;\n",
                ),
                ("z-orphan.ts", "export const x = 1;\n"),
            ],
            &["index.ts"],
        );
        let found = scan.all();
        assert_eq!(found[0].category, Category::UnusedFile);
        let in_index: Vec<&str> = found
            .iter()
            .filter(|f| f.path == "index.ts")
            .map(|f| f.name.as_str())
            .collect();
        assert_eq!(
            in_index,
            vec!["b", "a"],
            "declaration order, not alphabetical"
        );
    }

    #[test]
    fn an_unparsable_file_lowers_confidence_everywhere_rather_than_being_reported() {
        let scan = scan(
            &[
                ("index.ts", "export function orphaned() {}\n"),
                ("broken.ts", "function ( { { {\n"),
            ],
            &["index.ts"],
        );
        let found = scan.all();
        assert!(
            !found.iter().any(|f| f.path == "broken.ts"),
            "a file basta could not read is never a finding"
        );
        assert!(
            found
                .iter()
                .all(|f| f.reasons.contains(&Reason::UnparsedModule)),
            "every finding says a file in the scan did not parse"
        );
    }

    #[test]
    fn an_entry_points_exports_are_its_public_surface_not_dead_code() {
        let files = [(
            "src/index.ts",
            "export function published() {}\nfunction unusedHelper() {}\n",
        )];
        let scan = scan(&files, &["src/index.ts"]);
        assert_eq!(
            names(&scan.all(), Category::UnusedExport),
            Vec::<String>::new(),
            "nothing inside the scan is supposed to import a published API"
        );
        assert_eq!(
            names(&scan.all(), Category::UnusedSymbol),
            vec!["unusedHelper"]
        );

        let including = scan.findings(&BastaConfig {
            categories: Category::ALL.to_vec(),
            min_confidence: 0,
            include_entry_exports: true,
            ..BastaConfig::default()
        });
        assert_eq!(names(&including, Category::UnusedExport), vec!["published"]);
    }

    #[test]
    fn include_entry_exports_reports_only_the_entry_exports_nothing_imports() {
        let scan = scan(
            &[
                (
                    "src/index.ts",
                    "export function imported() {}\nexport function orphaned() {}\n",
                ),
                (
                    "src/other.ts",
                    "import { imported } from './index';\nexport const x = imported();\n",
                ),
            ],
            &["src/index.ts", "src/other.ts"],
        );
        let including = scan.findings(&BastaConfig {
            categories: Category::ALL.to_vec(),
            min_confidence: 0,
            include_entry_exports: true,
            ..BastaConfig::default()
        });
        let reported = names(&including, Category::UnusedExport);
        assert!(reported.contains(&"orphaned".to_string()), "{reported:?}");
        assert!(
            !reported.contains(&"imported".to_string()),
            "an entry export another module imports is used, flag or no flag: {reported:?}"
        );
    }

    #[test]
    fn a_test_file_is_an_entry_point_and_is_never_an_unused_file() {
        let scan = scan_with(
            &[
                ("index.ts", "export const used = 1;\n"),
                (
                    "a.test.ts",
                    "import { used } from './index';\nconsole.log(used);\n",
                ),
            ],
            &["index.ts"],
            &["a.test.ts"],
        );
        assert!(
            !scan
                .all()
                .iter()
                .any(|f| f.path == "a.test.ts" && f.category == Category::UnusedFile),
            "a test runner starts a test file, so nothing needs to import it"
        );
    }

    #[test]
    fn an_export_only_the_tests_import_says_so() {
        let scan = scan_with(
            &[
                ("index.ts", "import { shipped } from './api';\nshipped();\n"),
                (
                    "api.ts",
                    "export function shipped() {}\nexport function forTestsOnly() {}\n",
                ),
                (
                    "api.test.ts",
                    "import { forTestsOnly } from './api';\nforTestsOnly();\n",
                ),
            ],
            &["index.ts"],
            &["api.test.ts"],
        );
        let found = scan.all();
        let finding = found
            .iter()
            .find(|f| f.name == "forTestsOnly")
            .expect("an export only tests reach is still worth reporting");
        assert_eq!(finding.category, Category::UnusedExport);
        assert!(finding.reasons.contains(&Reason::UsedOnlyByTests));
        assert!(
            finding.message.contains("only imported by tests"),
            "{}",
            finding.message
        );
        assert!(
            !found.iter().any(|f| f.name == "shipped"),
            "an export the program imports is not a finding"
        );
    }

    #[test]
    fn a_file_only_the_tests_import_is_one_finding_not_many() {
        let scan = scan_with(
            &[
                ("index.ts", "export const shipped = 1;\n"),
                (
                    "helpers.ts",
                    "export function makeUser() {}\nexport function makeOrder() {}\n",
                ),
                (
                    "a.test.ts",
                    "import { makeUser } from './helpers';\nmakeUser();\n",
                ),
            ],
            &["index.ts"],
            &["a.test.ts"],
        );
        let in_helpers: Vec<&Finding> = scan
            .all()
            .into_iter()
            .filter(|f| f.path == "helpers.ts")
            .collect::<Vec<_>>()
            .leak()
            .iter()
            .collect();
        assert_eq!(in_helpers.len(), 1, "{in_helpers:?}");
        assert_eq!(in_helpers[0].category, Category::UnusedFile);
        assert!(in_helpers[0].message.contains("only imported by tests"));
    }

    #[test]
    fn an_export_clause_does_not_keep_its_own_symbol_alive() {
        let scan = scan(
            &[
                ("index.ts", "import './api';\n"),
                (
                    "api.ts",
                    "function inner() {}\nexport { inner as outer };\n",
                ),
            ],
            &["index.ts"],
        );
        assert_eq!(
            names(&scan.all(), Category::UnusedExport),
            vec!["inner"],
            "`export {{ inner }}` is not a use of inner"
        );
    }

    #[test]
    fn declarations_in_an_ambient_file_are_left_alone() {
        let scan = scan(
            &[
                ("index.ts", "export const a = 1;\n"),
                (
                    "globals.d.ts",
                    "interface Array<T> {\n  toSorted(): T[];\n}\ndeclare const VERSION: string;\n",
                ),
            ],
            // A `.d.ts` is an entry point in a real run (`entry::detect`
            // matches it), so the file-level rule never fires on one.
            &["index.ts", "globals.d.ts"],
        );
        assert!(
            !scan.all().iter().any(|f| f.path == "globals.d.ts"),
            "an ambient declaration augments a global; no import will ever name it"
        );
    }

    #[test]
    fn a_barrel_file_import_is_used_by_whoever_imports_it_onward() {
        let scan = scan(
            &[
                (
                    "app/__main__.py",
                    "from app.phases import run_phase\n\nrun_phase()\n",
                ),
                ("app/phases.py", "from app.verify import run_phase\n"),
                ("app/verify.py", "def run_phase():\n    pass\n"),
            ],
            &["app/__main__.py"],
        );
        assert!(
            !scan
                .all()
                .iter()
                .any(|f| f.path == "app/phases.py" && f.name == "run_phase"),
            "phases.py imports the name so that __main__ can import it from phases"
        );
    }

    #[test]
    fn disabled_categories_produce_nothing() {
        let scan = scan(
            &[
                ("index.ts", "import { spare } from './api';\n"),
                ("api.ts", "export function spare() {}\n"),
                ("orphan.ts", "export const x = 1;\n"),
            ],
            &["index.ts"],
        );
        let only_files = scan.findings(&BastaConfig {
            categories: vec![Category::UnusedFile],
            min_confidence: 0,
            ..BastaConfig::default()
        });
        assert!(
            only_files
                .iter()
                .all(|f| f.category == Category::UnusedFile)
        );
        assert_eq!(only_files.len(), 1);
    }
}