fallow-engine 3.48.0

Typed analysis engine facade for fallow consumers
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
//! Dead-code result helpers exposed through the engine boundary.

use std::path::{Path, PathBuf};

use rustc_hash::FxHashSet;

use fallow_config::{ResolvedConfig, RulesConfig, Severity};
use fallow_types::discover::StableFileKey;
use fallow_types::results::SecurityFinding;

pub use crate::results::{
    AnalysisResults, DeadCodeAnalysis, DeadCodeAnalysisArtifacts, DeadCodeAnalysisOutput,
    DeadCodeAnalysisWithHashes, derive_security_severity, enable_security_rules,
    resolve_security_finding_severity, security_catalogue_title, security_rule_id,
    security_rules_can_error,
};

pub use crate::effective_severity::{
    RuleSeverity, SeveritySource, apply_effective_severities, findings_without_severity,
    promote_effective_warns,
};

#[path = "dead_code_config_patterns.rs"]
mod config_patterns;
pub use config_patterns::config_pattern_diagnostics;

use crate::result_scope::{
    Anchor, ComponentRule, OwnerRule, ProjectFinding, ResultScope, SiteRule,
};
use crate::{
    EngineResult, change_scope::ChangeScope,
    session::analyze_dead_code_with_parse_result_from_config, source::ModuleInfo,
    workspace_scope::WorkspaceScope,
};

/// Run dead-code analysis from pre-parsed modules.
///
/// # Errors
///
/// Returns an error if discovery, graph construction, or analysis fails.
pub(crate) fn analyze_with_parse_result(
    config: &ResolvedConfig,
    modules: &[ModuleInfo],
) -> EngineResult<DeadCodeAnalysisArtifacts> {
    analyze_dead_code_with_parse_result_from_config(config, modules)
}

/// Write a stable `finding_id` onto every dead-code finding in `results`.
///
/// Every producer calls this on the full result set, before the workspace,
/// scope, changed-file, ignore, baseline and rule filters. A filter then never
/// changes the id of a finding that stays in the report.
pub(crate) fn stamp_finding_ids(results: &mut AnalysisResults, root: &Path) {
    fallow_types::identity::stamp_dead_code_finding_ids(results, root);
}

/// Give a `finding_id` to each dead-code finding that has none, and keep the
/// existing ids.
///
/// Type-aware refinement adds findings after the scope filters ran. A full
/// restamp there would compute tiebreak suffixes over the filtered set.
pub fn stamp_missing_finding_ids(results: &mut AnalysisResults, root: &Path) {
    fallow_types::identity::stamp_missing_dead_code_finding_ids(results, root);
}

/// A validated `--finding-id` request: the ids a run reports, in request order.
///
/// The filter runs after every other filter and after the baseline, so it
/// narrows what the run would otherwise report. The ids themselves are
/// stamped on the full result set before any filter, so a filter never
/// changes them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FindingIdFilter {
    requested: Vec<String>,
    set: FxHashSet<String>,
}

impl FindingIdFilter {
    /// Validate the requested ids and drop duplicates. Returns `Ok(None)`
    /// when `values` is empty.
    ///
    /// # Errors
    ///
    /// Returns a message that names the first value that is not a current
    /// dead-code finding id (`dc1:<rule>:<16 hex digits>` with an optional
    /// `~<k>` suffix). A typo must never read as "the finding is gone".
    pub fn parse<S: AsRef<str>>(values: &[S]) -> Result<Option<Self>, String> {
        if values.is_empty() {
            return Ok(None);
        }
        let mut requested = Vec::with_capacity(values.len());
        let mut set = FxHashSet::default();
        for value in values {
            let id = value.as_ref().trim();
            if !fallow_types::identity::is_dead_code_finding_id(id) {
                return Err(format!(
                    "invalid finding id '{id}': expected {}:<rule>:<16 hex digits>, \
                     optionally with a ~<k> suffix, as printed in the finding_id field",
                    fallow_types::identity::DEAD_CODE_ID_SCHEME
                ));
            }
            if set.insert(id.to_owned()) {
                requested.push(id.to_owned());
            }
        }
        Ok(Some(Self { requested, set }))
    }

    /// The requested ids that a finding in `results` carries. Reads only.
    #[must_use]
    pub fn present(&self, results: &mut AnalysisResults) -> FxHashSet<String> {
        fallow_types::identity::present_dead_code_finding_ids(results, &self.set)
    }

    /// Keep only the requested findings and build the query answer.
    ///
    /// `filtered` holds the requested ids that the analysis found and a filter
    /// of this run removed. `run_reasons` are the options of this run that
    /// can hide a finding without a fix. `rule-off` is added when the rule of
    /// a missing id is `off` in `config`.
    pub fn apply(
        &self,
        results: &mut AnalysisResults,
        config: &ResolvedConfig,
        filtered: &FxHashSet<String>,
        run_reasons: impl IntoIterator<Item = fallow_output::FindingIdQueryReason>,
    ) -> fallow_output::FindingIdQuery {
        let found = fallow_types::identity::retain_dead_code_findings_by_id(results, &self.set);
        let rule_off = self
            .requested
            .iter()
            .filter(|id| !found.contains(*id))
            .any(|id| finding_id_rule_is_off(id, config));
        fallow_output::FindingIdQuery::new(
            self.requested.clone(),
            |id| found.contains(id),
            |id| filtered.contains(id),
            run_reasons
                .into_iter()
                .chain(rule_off.then_some(fallow_output::FindingIdQueryReason::RuleOff)),
            analysis_fingerprint(config),
        )
    }
}

/// Evidence for a finding-id answer, collected around the filter stages of
/// one run.
///
/// A requested id that is present before a filter stage and absent after it
/// was hidden by this run, not fixed. Those ids end in `filtered`. A stage
/// that is analysis (type-aware refinement) stays outside every stage, so a
/// finding it removes counts as gone.
#[derive(Debug, Clone)]
pub struct FindingIdTrace {
    filter: FindingIdFilter,
    before_stage: FxHashSet<String>,
    filtered: FxHashSet<String>,
}

impl FindingIdTrace {
    /// Start the first filter stage on the full result set.
    #[must_use]
    pub fn start(filter: FindingIdFilter, results: &mut AnalysisResults) -> Self {
        let before_stage = filter.present(results);
        Self {
            filter,
            before_stage,
            filtered: FxHashSet::default(),
        }
    }

    /// Start a filter stage after work that is not a filter.
    pub fn start_stage(&mut self, results: &mut AnalysisResults) {
        self.before_stage = self.filter.present(results);
    }

    /// End a filter stage: the requested ids it removed count as filtered.
    pub fn end_stage(&mut self, results: &mut AnalysisResults) {
        let after = self.filter.present(results);
        self.filtered
            .extend(self.before_stage.drain().filter(|id| !after.contains(id)));
    }

    /// Apply the filter and build the answer. See [`FindingIdFilter::apply`].
    pub fn finish(
        self,
        results: &mut AnalysisResults,
        config: &ResolvedConfig,
        run_reasons: impl IntoIterator<Item = fallow_output::FindingIdQueryReason>,
    ) -> fallow_output::FindingIdQuery {
        self.filter
            .apply(results, config, &self.filtered, run_reasons)
    }
}

/// The version prefix of an analysis fingerprint. A change to the hash inputs
/// moves it, so an old fingerprint never equals a new one.
const ANALYSIS_FINGERPRINT_SCHEME: &str = "af1";

/// Ignore files that discovery reads in each directory it walks.
const IGNORE_FILE_NAMES: &[&str] = &[".gitignore", ".ignore"];

/// Non-source files that import resolution and entry-point discovery read,
/// in every directory: manifests and TypeScript or JavaScript project files.
/// The built-in and external plugin config patterns are added to these.
const RESOLUTION_FILE_GLOBS: &[&str] =
    &["**/package.json", "**/tsconfig*.json", "**/jsconfig*.json"];

/// The maximum depth of a followed tsconfig `extends` chain.
const MAX_EXTENDS_DEPTH: usize = 8;

/// A stable hash of every input, other than the source files, that decides
/// which dead-code findings a run of `config` reports.
///
/// The inputs:
/// - the fallow version;
/// - the detection config digest (merged user config after `extends`,
///   external plugins, rule packs);
/// - the settings that a surface changes after resolution: production mode,
///   `includeEntryExports`, `showCascade`, the effective rules, the type-aware mode,
///   requirement and project list, the file size limit;
/// - the root-relative path and content of the repository ignore files, the
///   `package.json` files, the `tsconfig*.json` and `jsconfig*.json` files and
///   the `extends` files they name, and every file that matches a built-in or
///   external plugin config pattern.
///
/// File content is normalized (CRLF to LF, trailing newlines removed) and the
/// entries are sorted, so two checkouts of one commit give the same value on
/// every platform. Known exclusions: the global git excludes file and other
/// machine environment outside the `FALLOW_*` variables.
#[must_use]
fn analysis_fingerprint(config: &ResolvedConfig) -> String {
    analysis_fingerprint_for_version(config, env!("CARGO_PKG_VERSION"))
}

/// [`analysis_fingerprint`] for an explicit fallow version.
#[must_use]
fn analysis_fingerprint_for_version(config: &ResolvedConfig, version: &str) -> String {
    let rules = serde_json::to_string(&config.rules).unwrap_or_default();
    let projects: Vec<String> = config
        .type_aware
        .projects
        .iter()
        .map(|project| root_relative_text(&config.root, project))
        .collect();
    let type_aware = format!(
        "{}:{}:{}",
        config.type_aware.enabled,
        serde_json::to_string(&config.type_aware.require).unwrap_or_default(),
        projects.join("|")
    );
    let max_file_size = config
        .max_file_size_bytes
        .map_or_else(|| "none".to_owned(), |bytes| bytes.to_string());
    let input_files = input_files_digest(config);
    let hash = fallow_types::identity::fnv1a64_parts(&[
        ANALYSIS_FINGERPRINT_SCHEME,
        version,
        &config.detection_config_digest,
        if config.production {
            "production"
        } else {
            "all"
        },
        if config.include_entry_exports {
            "entry-exports"
        } else {
            "no-entry-exports"
        },
        if config.show_cascade {
            "cascade-shown"
        } else {
            "cascade-hidden"
        },
        &rules,
        &type_aware,
        &max_file_size,
        &input_files,
    ]);
    format!("{ANALYSIS_FINGERPRINT_SCHEME}:{hash}")
}

/// `path` relative to `root` with forward slashes when it is inside the
/// root, else the text as given.
fn root_relative_text(root: &Path, path: &str) -> String {
    Path::new(path).strip_prefix(root).map_or_else(
        |_| path.replace('\\', "/"),
        |relative| StableFileKey::from_relative(relative).as_str().to_owned(),
    )
}

/// Normalize file text before it is hashed: CRLF becomes LF and trailing
/// newlines are removed, so a checkout with `core.autocrlf` hashes the same
/// as one without it.
fn normalized_text(content: &[u8]) -> String {
    String::from_utf8_lossy(content)
        .replace("\r\n", "\n")
        .trim_end_matches('\n')
        .to_owned()
}

/// The walker for the fingerprint inputs.
///
/// It honors the repository `.gitignore`, `.ignore` and `.git/info/exclude`
/// files, but never the global git excludes file of the machine: that file
/// would prune directories on one machine and not on another. It skips hidden
/// directories (the fallow cache lives there) and `node_modules`.
fn fingerprint_walk_builder(root: &Path) -> ignore::WalkBuilder {
    let mut builder = ignore::WalkBuilder::new(root);
    builder
        .hidden(false)
        .git_ignore(true)
        .git_global(false)
        .git_exclude(true)
        .filter_entry(|entry| {
            let is_dir = entry.file_type().is_some_and(|kind| kind.is_dir());
            if !is_dir || entry.depth() == 0 {
                return true;
            }
            let name = entry.file_name().to_string_lossy();
            !name.starts_with('.') && name != "node_modules"
        });
    builder
}

/// The globs of the non-source files the analysis reads to resolve imports
/// and entry points, each also tried under `**/`.
fn resolution_file_globs(config: &ResolvedConfig) -> globset::GlobSet {
    let mut builder = globset::GlobSetBuilder::new();
    let external = config
        .external_plugins
        .iter()
        .flat_map(|plugin| plugin.config_patterns.iter().map(String::as_str));
    let patterns = crate::core_backend::builtin_config_patterns()
        .into_iter()
        .chain(external)
        .chain(RESOLUTION_FILE_GLOBS.iter().copied());
    for pattern in patterns {
        let anywhere = if pattern.starts_with("**/") {
            pattern.to_owned()
        } else {
            format!("**/{pattern}")
        };
        for candidate in [pattern.to_owned(), anywhere] {
            if let Ok(glob) = globset::Glob::new(&candidate) {
                builder.add(glob);
            }
        }
    }
    builder
        .build()
        .unwrap_or_else(|_| globset::GlobSet::empty())
}

fn is_project_config_name(name: &str) -> bool {
    (name.starts_with("tsconfig") || name.starts_with("jsconfig"))
        && std::path::Path::new(name)
            .extension()
            .is_some_and(|ext| ext.eq_ignore_ascii_case("json"))
}

/// A hash over the root-relative path and normalized content of each
/// fingerprint input file. See [`analysis_fingerprint`].
fn input_files_digest(config: &ResolvedConfig) -> String {
    let root = config.root.as_path();
    let globs = resolution_file_globs(config);
    let mut files: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();
    if let Ok(content) = std::fs::read(root.join(".git/info/exclude")) {
        files.insert(".git/info/exclude".to_owned(), normalized_text(&content));
    }
    let mut project_configs: Vec<PathBuf> = Vec::new();
    for entry in fingerprint_walk_builder(root).build().flatten() {
        if entry.file_type().is_none_or(|kind| kind.is_dir()) {
            continue;
        }
        let Ok(relative) = entry.path().strip_prefix(root) else {
            continue;
        };
        let name = entry.file_name().to_string_lossy();
        let is_ignore_file = IGNORE_FILE_NAMES.contains(&name.as_ref());
        if !is_ignore_file && !globs.is_match(relative) {
            continue;
        }
        if config.ignore_patterns.is_match(relative) {
            continue;
        }
        if let Ok(content) = std::fs::read(entry.path()) {
            let key = StableFileKey::from_relative(relative).as_str().to_owned();
            files.insert(key, normalized_text(&content));
            if is_project_config_name(&name) {
                project_configs.push(entry.path().to_path_buf());
            }
        }
    }
    for project_config in project_configs {
        add_extends_chain(root, &project_config, &mut files);
    }
    let parts: Vec<&str> = files
        .iter()
        .flat_map(|(path, content)| [path.as_str(), content.as_str()])
        .collect();
    fallow_types::identity::fnv1a64_parts(&parts)
}

/// Follow the `extends` chain of one tsconfig or jsconfig file and add each
/// file it names, also a file the walk did not see: one in a hidden
/// directory, outside the root, or in `node_modules`.
fn add_extends_chain(
    root: &Path,
    project_config: &Path,
    files: &mut std::collections::BTreeMap<String, String>,
) {
    let mut seen: FxHashSet<PathBuf> = FxHashSet::default();
    let mut frontier: Vec<(PathBuf, usize)> = vec![(project_config.to_path_buf(), 0)];
    while let Some((current, depth)) = frontier.pop() {
        if depth >= MAX_EXTENDS_DEPTH || !seen.insert(current.clone()) {
            continue;
        }
        for target in read_extends(&current).unwrap_or_default() {
            let Some(next) = resolve_extends_target(root, &current, &target) else {
                continue;
            };
            if let Ok(content) = std::fs::read(&next) {
                files.insert(extends_key(root, &next), normalized_text(&content));
                frontier.push((next, depth + 1));
            }
        }
    }
}

/// The `extends` targets of a tsconfig or jsconfig file: one string or an
/// array of strings.
fn read_extends(path: &Path) -> Option<Vec<String>> {
    let content = std::fs::read_to_string(path).ok()?;
    let value: serde_json::Value = fallow_config::jsonc::parse_to_value(&content).ok()?;
    match value.get("extends")? {
        serde_json::Value::String(target) => Some(vec![target.clone()]),
        serde_json::Value::Array(items) => Some(
            items
                .iter()
                .filter_map(|item| item.as_str().map(str::to_owned))
                .collect(),
        ),
        _ => None,
    }
}

/// The file an `extends` target names: a relative path from the extending
/// file, or a package path under the root `node_modules`.
fn resolve_extends_target(root: &Path, from: &Path, target: &str) -> Option<PathBuf> {
    let base = if target.starts_with('.') || Path::new(target).is_absolute() {
        from.parent()?.join(target)
    } else {
        root.join("node_modules").join(target)
    };
    let candidates = [
        base.clone(),
        base.with_extension("json"),
        base.join("tsconfig.json"),
    ];
    candidates.into_iter().find(|candidate| candidate.is_file())
}

/// The hash key of an `extends` file: root-relative when inside the root,
/// else `extends:` plus the file name, which carries no machine path.
fn extends_key(root: &Path, path: &Path) -> String {
    path.strip_prefix(root).map_or_else(
        |_| {
            format!(
                "extends:{}",
                path.file_name()
                    .map(|name| name.to_string_lossy().into_owned())
                    .unwrap_or_default()
            )
        },
        |relative| StableFileKey::from_relative(relative).as_str().to_owned(),
    )
}

/// Whether the rule of `id` is `off` in the top-level rules or in any
/// override. An override is file-scoped and the id carries no path, so any
/// override that turns the rule off counts.
fn finding_id_rule_is_off(id: &str, config: &ResolvedConfig) -> bool {
    let Some(kind) = id
        .split(':')
        .nth(1)
        .and_then(fallow_types::suppress::IssueKind::parse)
    else {
        return false;
    };
    let off = |rules: &RulesConfig| rules.severity_for_kind(kind) == Severity::Off;
    off(&config.rules)
        || config.overrides.iter().any(|entry| {
            let mut rules = config.rules.clone();
            rules.apply_partial(&entry.rules);
            off(&rules)
        })
}

/// Scope dead-code results to the union of the given workspace roots.
///
/// The full cross-workspace graph is still built before this helper runs, so
/// cross-package imports are resolved. Only reported findings are narrowed.
pub fn filter_to_workspaces(results: &mut AnalysisResults, scope: &WorkspaceScope) {
    let members = WorkspaceMembers {
        scope,
        manifests: scope
            .roots()
            .iter()
            .map(|root| root.join("package.json"))
            .collect(),
    };
    crate::result_scope::retain_in_scope(results, &members);
}

/// A workspace selection as a result scope.
struct WorkspaceMembers<'a> {
    scope: &'a WorkspaceScope,
    /// The `package.json` of each selected root.
    manifests: Vec<PathBuf>,
}

impl ResultScope for WorkspaceMembers<'_> {
    fn keeps(&self, anchor: Anchor<'_>) -> bool {
        match anchor {
            Anchor::Line { path, .. } | Anchor::File { path } => self.scope.contains(path),
        }
    }

    /// A dependency finding stays when its manifest is the manifest of a
    /// selected root. Catalogs and overrides belong to the whole project, so a
    /// workspace selection drops them.
    fn keeps_project_finding(&self, finding: ProjectFinding<'_>) -> bool {
        match finding {
            ProjectFinding::ManifestDependency { manifest } => {
                self.manifests.iter().any(|pkg| manifest == pkg)
            }
            ProjectFinding::CatalogReference { path } => self.scope.contains(path),
            ProjectFinding::CatalogEntry
            | ProjectFinding::EmptyCatalogGroup { .. }
            | ProjectFinding::DependencyOverride { .. } => false,
        }
    }

    fn keeps_security_finding(&self, finding: &SecurityFinding) -> bool {
        self.scope.contains(&finding.path)
    }

    fn site_rule(&self) -> SiteRule {
        SiteRule::AnySite
    }

    fn owner_rule(&self) -> OwnerRule {
        OwnerRule::TrimOwners
    }

    fn component_rule(&self) -> ComponentRule {
        ComponentRule::All
    }
}

/// The scope of one dead-code run, as the surface resolved it.
///
/// Every field is optional. A field that is `None` does not narrow the run.
#[derive(Debug, Clone, Copy)]
pub struct DeadCodeScope<'a> {
    /// `--workspace`, `--changed-workspaces` and a positional path.
    pub workspace_roots: Option<&'a WorkspaceScope>,
    /// The resolved change scope: a global changed-file set or the
    /// configured package baselines.
    pub changes: Option<&'a ChangeScope>,
    /// A unified diff, with the root that finding paths resolve against.
    pub diff: Option<(&'a fallow_output::DiffIndex, &'a Path)>,
    /// `--file`: the only files to report. Dependency findings are dropped,
    /// because a file list does not own a manifest.
    pub files: Option<&'a FxHashSet<PathBuf>>,
}

/// Narrow dead-code results to the scope of the run.
///
/// The CLI, the programmatic API and the MCP typed path call this one function,
/// so a scope narrows the same way on every surface. The filters run in this
/// order: workspace roots, changed files, the diff, the file list. Then the
/// configured `ignoreFindings` patterns run again, because the scope filters
/// remove owners from a finding with several owners (`duplicate_exports`). A
/// finding that only ignored owners hold after the scope is hidden, as the
/// "hidden only when every owner matches" rule says.
pub fn apply_scope(
    results: &mut AnalysisResults,
    scope: &DeadCodeScope<'_>,
    config: &ResolvedConfig,
) {
    // The component scopes read source-owned enforcement (prop-drilling chains, thin
    // wrappers, duplicate prop shapes), so the severities must resolve before filtering.
    crate::effective_severity::apply_prop_drilling_severities(results, config);
    crate::effective_severity::apply_component_shape_severities(results, config);
    if let Some(roots) = scope.workspace_roots {
        filter_to_workspaces(results, roots);
    }
    if let Some(changes) = scope.changes {
        changes.retain_dead_code(results);
    }
    if let Some((diff, root)) = scope.diff {
        crate::diff_scope::filter_dead_code_by_diff(results, diff, root);
    }
    if let Some(files) = scope.files {
        filter_by_changed_files(results, files);
        clear_dependency_findings(results);
    }
    filter_configured_ignored_findings(results, config);
}

fn clear_dependency_findings(results: &mut AnalysisResults) {
    results.unused_dependencies.clear();
    results.unused_dev_dependencies.clear();
    results.unused_optional_dependencies.clear();
    results.type_only_dependencies.clear();
    results.test_only_dependencies.clear();
    results.dev_dependencies_in_production.clear();
}

/// Scope dead-code results to findings affected by changed files.
#[expect(
    clippy::implicit_hasher,
    reason = "fallow standardizes on FxHashSet across the workspace"
)]
pub fn filter_by_changed_files(results: &mut AnalysisResults, changed_files: &FxHashSet<PathBuf>) {
    crate::changed_files::filter_results_by_changed_files(results, changed_files);
}

/// Apply configured source-owned finding exclusions to an analysis result.
///
/// Analysis stages that append findings after the engine pipeline, such as
/// type-aware reconciliation, must call this before exposing their final
/// result.
pub fn filter_configured_ignored_findings(results: &mut AnalysisResults, config: &ResolvedConfig) {
    if config.ignore_findings.is_empty() {
        return;
    }

    results.remove_ignored_dead_code_findings(|path| {
        config.ignore_findings.is_ignored_path(&config.root, path)
    });
}

/// Remove findings whose effective severity is `Off` from an analysis result.
///
/// Every surface that reports findings runs this pass: the `check` command
/// (which also serves `dead-code` and the CLI audit), the editor analysis path
/// behind inline diagnostics and the sidebar, and the programmatic runtime
/// behind the MCP tools, the decision surface and the Node bindings. Each of
/// them runs it at the same two points, once over the freshly analyzed set and
/// once after type-aware reconciliation, because reconciliation can append
/// findings. The pass removes findings and writes the gate severity of each
/// finding that stays, so the second run is idempotent when nothing was
/// appended.
///
/// When overrides are configured, per-file rule resolution is used for
/// file-scoped issue types. Circular dependencies resolve against every file in
/// the cycle. Non-file-scoped issues (unused deps, unlisted deps, duplicate
/// exports) use the base rules only.
pub fn apply_rule_severities(results: &mut AnalysisResults, config: &ResolvedConfig) {
    let rules = &config.rules;
    let has_overrides = !config.overrides.is_empty();

    if has_overrides {
        apply_file_override_rules(results, config);
        apply_boundary_override_rules(results, config);
    } else {
        apply_base_file_rules(results, rules);
    }

    apply_base_collection_rules(results, rules);
    hide_cascade_findings(results, config);
    apply_effective_severities(results, config);
    crate::dead_code_export_hints::add_unused_export_config_actions(results, config);
}

/// Hide the export and member findings of unused files.
///
/// Deleting an unused file removes every unused export, unused type, unused
/// class member and unused enum member in it, so these findings add no
/// information to the report. The pass runs inside the rule pass, so every
/// surface that reports findings hides the same set.
///
/// A finding is hidden only when the report lists its file in
/// `unused_files`, or when an inline `fallow-ignore-file unused-file` comment
/// suppressed that file. A scope, an issue-type selection without unused
/// files, an `ignoreFindings` pattern or an `off` rule that removes the file
/// from the report therefore hides nothing in that file. The issue-type
/// filters clear the suppressed files too, so they must run before this pass.
/// The baseline runs after this pass, so a baseline entry for the unused file
/// does not make its findings visible again. `showCascade` keeps every
/// finding.
pub fn hide_cascade_findings(results: &mut AnalysisResults, config: &ResolvedConfig) {
    if config.show_cascade {
        return;
    }
    let reported = results.unused_files.iter().map(|f| &f.file.path);
    let suppressed = results
        .cascade
        .suppressed_unused_files
        .iter()
        .filter(|path| config.resolve_rules_for_path(path).unused_files != Severity::Off);
    let covered: FxHashSet<PathBuf> = reported.chain(suppressed).cloned().collect();
    if covered.is_empty() {
        return;
    }
    results.hide_cascade_findings(&|path| covered.contains(path));
}

fn apply_base_collection_rules(results: &mut AnalysisResults, rules: &RulesConfig) {
    if rules.unused_dependencies == Severity::Off {
        results.unused_dependencies.clear();
    }
    if rules.unused_dev_dependencies == Severity::Off {
        results.unused_dev_dependencies.clear();
    }
    if rules.unused_optional_dependencies == Severity::Off {
        results.unused_optional_dependencies.clear();
    }
    if rules.unlisted_dependencies == Severity::Off {
        results.unlisted_dependencies.clear();
    }
    if rules.unlisted_binaries == Severity::Off {
        results.unlisted_binaries.clear();
    }
    if rules.duplicate_exports == Severity::Off {
        results.duplicate_exports.clear();
    }
    if rules.duplicate_export_aliases == Severity::Off {
        results.duplicate_export_aliases.clear();
    }
    if rules.type_only_dependencies == Severity::Off {
        results.type_only_dependencies.clear();
    }
    if rules.test_only_dependencies == Severity::Off {
        results.test_only_dependencies.clear();
    }
    if rules.dev_dependencies_in_production == Severity::Off {
        results.dev_dependencies_in_production.clear();
    }
    if rules.circular_dependencies == Severity::Off {
        results.circular_dependencies.clear();
    }
    if rules.re_export_cycle == Severity::Off {
        results.re_export_cycles.clear();
    }
    if rules.package_cycle == Severity::Off {
        results.package_cycles.clear();
    }
    if rules.boundary_violation == Severity::Off {
        results.boundary_violations.clear();
        results.boundary_coverage_violations.clear();
        results.boundary_call_violations.clear();
    }
    if rules.policy_violation == Severity::Off {
        results.policy_violations.clear();
    }
    if rules.unused_catalog_entries == Severity::Off {
        results.unused_catalog_entries.clear();
    }
    if rules.empty_catalog_groups == Severity::Off {
        results.empty_catalog_groups.clear();
    }
    if rules.unresolved_catalog_references == Severity::Off {
        results.unresolved_catalog_references.clear();
    }
    if rules.unused_dependency_overrides == Severity::Off {
        results.unused_dependency_overrides.clear();
    }
    if rules.misconfigured_dependency_overrides == Severity::Off {
        results.misconfigured_dependency_overrides.clear();
    }
}

fn apply_file_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
    apply_dead_code_override_rules(results, config);
    apply_catalog_override_rules(results, config);
    apply_framework_override_rules(results, config);
    apply_circular_override_rules(results, config);
}

fn apply_dead_code_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
    apply_core_dead_code_override_rules(results, config);
    apply_component_dead_code_override_rules(results, config);
}

/// Retain core (non-component) dead-code findings whose per-file rule is not Off.
fn apply_core_dead_code_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
    results
        .unused_files
        .retain(|f| config.resolve_rules_for_path(&f.file.path).unused_files != Severity::Off);
    results
        .unused_exports
        .retain(|e| config.resolve_rules_for_path(&e.export.path).unused_exports != Severity::Off);
    results
        .unused_types
        .retain(|e| config.resolve_rules_for_path(&e.export.path).unused_types != Severity::Off);
    results.private_type_leaks.retain(|e| {
        config
            .resolve_rules_for_path(&e.leak.path)
            .private_type_leaks
            != Severity::Off
    });
    results.deprecated_exports_in_use.retain(|e| {
        config
            .resolve_rules_for_path(&e.export.path)
            .deprecated_exports_in_use
            != Severity::Off
    });
    results.unused_enum_members.retain(|m| {
        config
            .resolve_rules_for_path(&m.member.path)
            .unused_enum_members
            != Severity::Off
    });
    results.unused_class_members.retain(|m| {
        config
            .resolve_rules_for_path(&m.member.path)
            .unused_class_members
            != Severity::Off
    });
    results.unused_store_members.retain(|m| {
        config
            .resolve_rules_for_path(&m.member.path)
            .unused_store_members
            != Severity::Off
    });
    results.unused_namespace_members.retain(|m| {
        config
            .resolve_rules_for_path(&m.member.path)
            .unused_namespace_members
            != Severity::Off
    });
    results.unused_protected_class_members.retain(|m| {
        config
            .resolve_rules_for_path(&m.member.path)
            .unused_protected_class_members
            != Severity::Off
    });
    results.namespace_escapes.retain(|e| {
        config
            .resolve_rules_for_path(&e.escape.path)
            .namespace_escapes
            != Severity::Off
    });
    results.unprovided_injects.retain(|f| {
        config
            .resolve_rules_for_path(&f.inject.path)
            .unprovided_injects
            != Severity::Off
    });
    results.unresolved_imports.retain(|i| {
        config
            .resolve_rules_for_path(&i.import.path)
            .unresolved_imports
            != Severity::Off
    });
}

/// Retain component-shaped dead-code findings whose per-file rule is not Off.
fn apply_component_dead_code_override_rules(
    results: &mut AnalysisResults,
    config: &ResolvedConfig,
) {
    results.unrendered_components.retain(|c| {
        config
            .resolve_rules_for_path(&c.component.path)
            .unrendered_components
            != Severity::Off
    });
    results.unused_component_props.retain(|p| {
        config
            .resolve_rules_for_path(&p.prop.path)
            .unused_component_props
            != Severity::Off
    });
    results.absent_component_props.retain(|p| {
        config
            .resolve_rules_for_path(&p.prop.path)
            .absent_component_props
            != Severity::Off
    });
    results.constant_parameters.retain(|p| {
        config
            .resolve_rules_for_path(&p.parameter.path)
            .constant_parameters
            != Severity::Off
    });
    results.unused_component_emits.retain(|e| {
        config
            .resolve_rules_for_path(&e.emit.path)
            .unused_component_emits
            != Severity::Off
    });
    results.unused_component_inputs.retain(|i| {
        config
            .resolve_rules_for_path(&i.input.path)
            .unused_component_inputs
            != Severity::Off
    });
    results.unused_component_outputs.retain(|o| {
        config
            .resolve_rules_for_path(&o.output.path)
            .unused_component_outputs
            != Severity::Off
    });
    results.unused_svelte_events.retain(|e| {
        config
            .resolve_rules_for_path(&e.event.path)
            .unused_svelte_events
            != Severity::Off
    });
    results.unused_effect_layers.retain(|e| {
        config
            .resolve_rules_for_path(&e.layer.path)
            .unused_effect_layers
            != Severity::Off
    });
    results.duplicate_export_aliases.retain(|finding| {
        config
            .resolve_rules_for_path(&finding.alias.path)
            .duplicate_export_aliases
            != Severity::Off
    });
    results.unused_tagged_errors.retain(|e| {
        config
            .resolve_rules_for_path(&e.error.path)
            .unused_tagged_errors
            != Severity::Off
    });
    results.unproduced_catch_tags.retain(|e| {
        config
            .resolve_rules_for_path(&e.catch_tag.path)
            .unproduced_catch_tags
            != Severity::Off
    });
    results.unused_server_actions.retain(|a| {
        config
            .resolve_rules_for_path(&a.action.path)
            .unused_server_actions
            != Severity::Off
    });
    results.unused_load_data_keys.retain(|k| {
        config
            .resolve_rules_for_path(&k.key.path)
            .unused_load_data_keys
            != Severity::Off
    });
}

fn apply_catalog_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
    results.stale_suppressions.retain(|s| {
        let rules = config.resolve_rules_for_path(&s.path);
        if s.missing_reason {
            rules.require_suppression_reason != Severity::Off
        } else {
            rules.stale_suppressions != Severity::Off
        }
    });
    results.unresolved_catalog_references.retain(|r| {
        config
            .resolve_rules_for_path(&r.reference.path)
            .unresolved_catalog_references
            != Severity::Off
    });
    results.empty_catalog_groups.retain(|g| {
        config
            .resolve_rules_for_path(&g.group.path)
            .empty_catalog_groups
            != Severity::Off
    });
    results.unused_dependency_overrides.retain(|o| {
        config
            .resolve_rules_for_path(&o.entry.path)
            .unused_dependency_overrides
            != Severity::Off
    });
    results.misconfigured_dependency_overrides.retain(|o| {
        config
            .resolve_rules_for_path(&o.entry.path)
            .misconfigured_dependency_overrides
            != Severity::Off
    });
}

fn apply_framework_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
    results.invalid_client_exports.retain(|e| {
        config
            .resolve_rules_for_path(&e.export.path)
            .invalid_client_export
            != Severity::Off
    });
    results.mixed_client_server_barrels.retain(|b| {
        config
            .resolve_rules_for_path(&b.barrel.path)
            .mixed_client_server_barrel
            != Severity::Off
    });
    results.misplaced_directives.retain(|d| {
        config
            .resolve_rules_for_path(&d.directive_site.path)
            .misplaced_directive
            != Severity::Off
    });
    results.route_collisions.retain(|c| {
        config
            .resolve_rules_for_path(&c.collision.path)
            .route_collision
            != Severity::Off
    });
    results.dynamic_segment_name_conflicts.retain(|c| {
        config
            .resolve_rules_for_path(&c.conflict.path)
            .dynamic_segment_name_conflict
            != Severity::Off
    });
}

fn apply_circular_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
    results.circular_dependencies.retain(|c| {
        c.cycle
            .files
            .iter()
            .any(|path| config.resolve_rules_for_path(path).circular_dependencies != Severity::Off)
    });
}

fn apply_base_file_rules(results: &mut AnalysisResults, rules: &RulesConfig) {
    clear_base_core_dead_code(results, rules);
    clear_base_component_dead_code(results, rules);
    clear_base_suppression_and_framework(results, rules);
}

/// Clear core (non-component) dead-code findings whose base rule is Off.
fn clear_base_core_dead_code(results: &mut AnalysisResults, rules: &RulesConfig) {
    if rules.unused_files == Severity::Off {
        results.unused_files.clear();
    }
    if rules.unused_exports == Severity::Off {
        results.unused_exports.clear();
    }
    if rules.unused_types == Severity::Off {
        results.unused_types.clear();
    }
    if rules.private_type_leaks == Severity::Off {
        results.private_type_leaks.clear();
    }
    if rules.deprecated_exports_in_use == Severity::Off {
        results.deprecated_exports_in_use.clear();
    }
    if rules.unused_enum_members == Severity::Off {
        results.unused_enum_members.clear();
    }
    if rules.unused_class_members == Severity::Off {
        results.unused_class_members.clear();
    }
    if rules.unused_store_members == Severity::Off {
        results.unused_store_members.clear();
    }
    if rules.unused_namespace_members == Severity::Off {
        results.unused_namespace_members.clear();
    }
    if rules.unused_protected_class_members == Severity::Off {
        results.unused_protected_class_members.clear();
    }
    if rules.namespace_escapes == Severity::Off {
        results.namespace_escapes.clear();
    }
    if rules.unprovided_injects == Severity::Off {
        results.unprovided_injects.clear();
    }
    if rules.unresolved_imports == Severity::Off {
        results.unresolved_imports.clear();
    }
}

/// Clear component-shaped dead-code findings whose base rule is Off.
fn clear_base_component_dead_code(results: &mut AnalysisResults, rules: &RulesConfig) {
    if rules.unrendered_components == Severity::Off {
        results.unrendered_components.clear();
    }
    if rules.unused_component_props == Severity::Off {
        results.unused_component_props.clear();
    }
    if rules.absent_component_props == Severity::Off {
        results.absent_component_props.clear();
    }
    if rules.constant_parameters == Severity::Off {
        results.constant_parameters.clear();
    }
    if rules.unused_component_emits == Severity::Off {
        results.unused_component_emits.clear();
    }
    if rules.unused_component_inputs == Severity::Off {
        results.unused_component_inputs.clear();
    }
    if rules.unused_component_outputs == Severity::Off {
        results.unused_component_outputs.clear();
    }
    if rules.unused_svelte_events == Severity::Off {
        results.unused_svelte_events.clear();
    }
    if rules.unused_effect_layers == Severity::Off {
        results.unused_effect_layers.clear();
    }
    if rules.unused_tagged_errors == Severity::Off {
        results.unused_tagged_errors.clear();
    }
    if rules.unproduced_catch_tags == Severity::Off {
        results.unproduced_catch_tags.clear();
    }
    if rules.unused_server_actions == Severity::Off {
        results.unused_server_actions.clear();
    }
    if rules.unused_load_data_keys == Severity::Off {
        results.unused_load_data_keys.clear();
    }
}

/// Apply base stale-suppression retention and clear framework findings whose
/// base rule is Off.
fn clear_base_suppression_and_framework(results: &mut AnalysisResults, rules: &RulesConfig) {
    results.stale_suppressions.retain(|s| {
        if s.missing_reason {
            rules.require_suppression_reason != Severity::Off
        } else {
            rules.stale_suppressions != Severity::Off
        }
    });
    if rules.invalid_client_export == Severity::Off {
        results.invalid_client_exports.clear();
    }
    if rules.mixed_client_server_barrel == Severity::Off {
        results.mixed_client_server_barrels.clear();
    }
    if rules.misplaced_directive == Severity::Off {
        results.misplaced_directives.clear();
    }
    if rules.route_collision == Severity::Off {
        results.route_collisions.clear();
    }
    if rules.dynamic_segment_name_conflict == Severity::Off {
        results.dynamic_segment_name_conflicts.clear();
    }
}

fn apply_boundary_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
    results.boundary_violations.retain(|v| {
        config
            .resolve_rules_for_path(&v.violation.from_path)
            .boundary_violation
            != Severity::Off
    });
    results.boundary_coverage_violations.retain(|v| {
        config
            .resolve_rules_for_path(&v.violation.path)
            .boundary_violation
            != Severity::Off
    });
    results.boundary_call_violations.retain(|v| {
        config
            .resolve_rules_for_path(&v.violation.path)
            .boundary_violation
            != Severity::Off
    });
    results.policy_violations.retain(|v| {
        config
            .resolve_rules_for_path(&v.violation.path)
            .policy_violation
            != Severity::Off
    });
}

#[cfg(test)]
#[path = "dead_code_tests.rs"]
mod tests;