Skip to main content

fallow_engine/
dead_code.rs

1//! Dead-code result helpers exposed through the engine boundary.
2
3use std::path::{Path, PathBuf};
4
5use rustc_hash::FxHashSet;
6
7use fallow_config::{
8    ResolvedConfig, RulesConfig, Severity, WorkspaceDiagnostic, WorkspaceDiagnosticKind,
9};
10use fallow_types::discover::StableFileKey;
11
12pub use crate::results::{
13    AnalysisResults, DeadCodeAnalysis, DeadCodeAnalysisArtifacts, DeadCodeAnalysisOutput,
14    DeadCodeAnalysisWithHashes, derive_security_severity, enable_security_rules,
15    resolve_security_finding_severity, security_catalogue_title, security_rule_id,
16    security_rules_can_error,
17};
18
19pub use crate::effective_severity::{
20    RuleSeverity, SeveritySource, apply_effective_severities, findings_without_severity,
21    promote_effective_warns,
22};
23
24use crate::{
25    EngineResult, change_scope::ChangeScope,
26    session::analyze_dead_code_with_parse_result_from_config, source::ModuleInfo,
27};
28
29/// Run dead-code analysis from pre-parsed modules.
30///
31/// # Errors
32///
33/// Returns an error if discovery, graph construction, or analysis fails.
34pub(crate) fn analyze_with_parse_result(
35    config: &ResolvedConfig,
36    modules: &[ModuleInfo],
37) -> EngineResult<DeadCodeAnalysisArtifacts> {
38    analyze_dead_code_with_parse_result_from_config(config, modules)
39}
40
41/// `workspace_diagnostics[]` entries for the config patterns that matched
42/// nothing in the latest dead-code pass over `config`.
43///
44/// One entry per unmatched `ignoreFindings` pattern and, when
45/// `reports_dependencies` is true, one per unmatched `ignoreDependencies`
46/// glob, in config order. A surface passes `reports_dependencies = false` when
47/// its run does not report dependency findings (an issue-type filter without
48/// the dependency types, or a file scope), because a dependency glob is then
49/// not relevant to what the run shows.
50///
51/// The CLI, the programmatic API and the MCP typed path all build their
52/// envelope from this one function, and the human note reads the same
53/// entries, so every output states the same patterns.
54#[must_use]
55pub fn config_pattern_diagnostics(
56    config: &ResolvedConfig,
57    reports_dependencies: bool,
58) -> Vec<WorkspaceDiagnostic> {
59    let dependency_globs = if reports_dependencies && dependency_rules_on(&config.rules) {
60        config.ignore_dependencies.unmatched_globs()
61    } else {
62        Vec::new()
63    };
64    let finding_patterns = config.ignore_findings.unmatched_patterns();
65    finding_patterns
66        .into_iter()
67        .map(
68            |pattern| WorkspaceDiagnosticKind::IgnoreFindingsPatternUnmatched {
69                pattern: pattern.to_owned(),
70            },
71        )
72        .chain(dependency_globs.into_iter().map(|pattern| {
73            WorkspaceDiagnosticKind::IgnoreDependenciesGlobUnmatched {
74                pattern: pattern.to_owned(),
75            }
76        }))
77        .map(|kind| {
78            WorkspaceDiagnostic::new(&config.root, config.root.clone(), kind)
79                .into_root_relative(&config.root)
80        })
81        .collect()
82}
83
84/// Whether at least one rule that `ignoreDependencies` controls is on. With
85/// every such rule off, the run reports no dependency finding at all.
86fn dependency_rules_on(rules: &RulesConfig) -> bool {
87    [
88        rules.unused_dependencies,
89        rules.unused_dev_dependencies,
90        rules.unused_optional_dependencies,
91        rules.unlisted_dependencies,
92        rules.type_only_dependencies,
93        rules.test_only_dependencies,
94        rules.dev_dependencies_in_production,
95    ]
96    .into_iter()
97    .any(|severity| severity != Severity::Off)
98}
99
100/// Write a stable `finding_id` onto every dead-code finding in `results`.
101///
102/// Every producer calls this on the full result set, before the workspace,
103/// scope, changed-file, ignore, baseline and rule filters. A filter then never
104/// changes the id of a finding that stays in the report.
105pub fn stamp_finding_ids(results: &mut AnalysisResults, root: &Path) {
106    fallow_types::identity::stamp_dead_code_finding_ids(results, root);
107}
108
109/// Give a `finding_id` to each dead-code finding that has none, and keep the
110/// existing ids.
111///
112/// Type-aware refinement adds findings after the scope filters ran. A full
113/// restamp there would compute tiebreak suffixes over the filtered set.
114pub fn stamp_missing_finding_ids(results: &mut AnalysisResults, root: &Path) {
115    fallow_types::identity::stamp_missing_dead_code_finding_ids(results, root);
116}
117
118/// A validated `--finding-id` request: the ids a run reports, in request order.
119///
120/// The filter runs after every other filter and after the baseline, so it
121/// narrows what the run would otherwise report. The ids themselves are
122/// stamped on the full result set before any filter, so a filter never
123/// changes them.
124#[derive(Debug, Clone, PartialEq, Eq)]
125pub struct FindingIdFilter {
126    requested: Vec<String>,
127    set: FxHashSet<String>,
128}
129
130impl FindingIdFilter {
131    /// Validate the requested ids and drop duplicates. Returns `Ok(None)`
132    /// when `values` is empty.
133    ///
134    /// # Errors
135    ///
136    /// Returns a message that names the first value that is not a current
137    /// dead-code finding id (`dc1:<rule>:<16 hex digits>` with an optional
138    /// `~<k>` suffix). A typo must never read as "the finding is gone".
139    pub fn parse<S: AsRef<str>>(values: &[S]) -> Result<Option<Self>, String> {
140        if values.is_empty() {
141            return Ok(None);
142        }
143        let mut requested = Vec::with_capacity(values.len());
144        let mut set = FxHashSet::default();
145        for value in values {
146            let id = value.as_ref().trim();
147            if !fallow_types::identity::is_dead_code_finding_id(id) {
148                return Err(format!(
149                    "invalid finding id '{id}': expected {}:<rule>:<16 hex digits>, \
150                     optionally with a ~<k> suffix, as printed in the finding_id field",
151                    fallow_types::identity::DEAD_CODE_ID_SCHEME
152                ));
153            }
154            if set.insert(id.to_owned()) {
155                requested.push(id.to_owned());
156            }
157        }
158        Ok(Some(Self { requested, set }))
159    }
160
161    /// The requested ids that a finding in `results` carries. Reads only.
162    #[must_use]
163    pub fn present(&self, results: &mut AnalysisResults) -> FxHashSet<String> {
164        fallow_types::identity::present_dead_code_finding_ids(results, &self.set)
165    }
166
167    /// Keep only the requested findings and build the query answer.
168    ///
169    /// `filtered` holds the requested ids that the analysis found and a filter
170    /// of this run removed. `run_reasons` are the options of this run that
171    /// can hide a finding without a fix. `rule-off` is added when the rule of
172    /// a missing id is `off` in `config`.
173    pub fn apply(
174        &self,
175        results: &mut AnalysisResults,
176        config: &ResolvedConfig,
177        filtered: &FxHashSet<String>,
178        run_reasons: impl IntoIterator<Item = fallow_output::FindingIdQueryReason>,
179    ) -> fallow_output::FindingIdQuery {
180        let found = fallow_types::identity::retain_dead_code_findings_by_id(results, &self.set);
181        let rule_off = self
182            .requested
183            .iter()
184            .filter(|id| !found.contains(*id))
185            .any(|id| finding_id_rule_is_off(id, config));
186        fallow_output::FindingIdQuery::new(
187            self.requested.clone(),
188            |id| found.contains(id),
189            |id| filtered.contains(id),
190            run_reasons
191                .into_iter()
192                .chain(rule_off.then_some(fallow_output::FindingIdQueryReason::RuleOff)),
193            analysis_fingerprint(config),
194        )
195    }
196}
197
198/// Evidence for a finding-id answer, collected around the filter stages of
199/// one run.
200///
201/// A requested id that is present before a filter stage and absent after it
202/// was hidden by this run, not fixed. Those ids end in `filtered`. A stage
203/// that is analysis (type-aware refinement) stays outside every stage, so a
204/// finding it removes counts as gone.
205#[derive(Debug, Clone)]
206pub struct FindingIdTrace {
207    filter: FindingIdFilter,
208    before_stage: FxHashSet<String>,
209    filtered: FxHashSet<String>,
210}
211
212impl FindingIdTrace {
213    /// Start the first filter stage on the full result set.
214    #[must_use]
215    pub fn start(filter: FindingIdFilter, results: &mut AnalysisResults) -> Self {
216        let before_stage = filter.present(results);
217        Self {
218            filter,
219            before_stage,
220            filtered: FxHashSet::default(),
221        }
222    }
223
224    /// Start a filter stage after work that is not a filter.
225    pub fn start_stage(&mut self, results: &mut AnalysisResults) {
226        self.before_stage = self.filter.present(results);
227    }
228
229    /// End a filter stage: the requested ids it removed count as filtered.
230    pub fn end_stage(&mut self, results: &mut AnalysisResults) {
231        let after = self.filter.present(results);
232        self.filtered
233            .extend(self.before_stage.drain().filter(|id| !after.contains(id)));
234    }
235
236    /// Apply the filter and build the answer. See [`FindingIdFilter::apply`].
237    pub fn finish(
238        self,
239        results: &mut AnalysisResults,
240        config: &ResolvedConfig,
241        run_reasons: impl IntoIterator<Item = fallow_output::FindingIdQueryReason>,
242    ) -> fallow_output::FindingIdQuery {
243        self.filter
244            .apply(results, config, &self.filtered, run_reasons)
245    }
246}
247
248/// The version prefix of an analysis fingerprint. A change to the hash inputs
249/// moves it, so an old fingerprint never equals a new one.
250const ANALYSIS_FINGERPRINT_SCHEME: &str = "af1";
251
252/// Ignore files that discovery reads in each directory it walks.
253const IGNORE_FILE_NAMES: &[&str] = &[".gitignore", ".ignore"];
254
255/// Non-source files that import resolution and entry-point discovery read,
256/// in every directory: manifests and TypeScript or JavaScript project files.
257/// The built-in and external plugin config patterns are added to these.
258const RESOLUTION_FILE_GLOBS: &[&str] =
259    &["**/package.json", "**/tsconfig*.json", "**/jsconfig*.json"];
260
261/// The maximum depth of a followed tsconfig `extends` chain.
262const MAX_EXTENDS_DEPTH: usize = 8;
263
264/// A stable hash of every input, other than the source files, that decides
265/// which dead-code findings a run of `config` reports.
266///
267/// The inputs:
268/// - the fallow version;
269/// - the detection config digest (merged user config after `extends`,
270///   external plugins, rule packs);
271/// - the settings that a surface changes after resolution: production mode,
272///   `includeEntryExports`, `showCascade`, the effective rules, the type-aware mode,
273///   requirement and project list, the file size limit;
274/// - the root-relative path and content of the repository ignore files, the
275///   `package.json` files, the `tsconfig*.json` and `jsconfig*.json` files and
276///   the `extends` files they name, and every file that matches a built-in or
277///   external plugin config pattern.
278///
279/// File content is normalized (CRLF to LF, trailing newlines removed) and the
280/// entries are sorted, so two checkouts of one commit give the same value on
281/// every platform. Known exclusions: the global git excludes file and other
282/// machine environment outside the `FALLOW_*` variables.
283#[must_use]
284pub fn analysis_fingerprint(config: &ResolvedConfig) -> String {
285    analysis_fingerprint_for_version(config, env!("CARGO_PKG_VERSION"))
286}
287
288/// [`analysis_fingerprint`] for an explicit fallow version.
289#[must_use]
290pub fn analysis_fingerprint_for_version(config: &ResolvedConfig, version: &str) -> String {
291    let rules = serde_json::to_string(&config.rules).unwrap_or_default();
292    let projects: Vec<String> = config
293        .type_aware
294        .projects
295        .iter()
296        .map(|project| root_relative_text(&config.root, project))
297        .collect();
298    let type_aware = format!(
299        "{}:{}:{}",
300        config.type_aware.enabled,
301        serde_json::to_string(&config.type_aware.require).unwrap_or_default(),
302        projects.join("|")
303    );
304    let max_file_size = config
305        .max_file_size_bytes
306        .map_or_else(|| "none".to_owned(), |bytes| bytes.to_string());
307    let input_files = input_files_digest(config);
308    let hash = fallow_types::identity::fnv1a64_parts(&[
309        ANALYSIS_FINGERPRINT_SCHEME,
310        version,
311        &config.detection_config_digest,
312        if config.production {
313            "production"
314        } else {
315            "all"
316        },
317        if config.include_entry_exports {
318            "entry-exports"
319        } else {
320            "no-entry-exports"
321        },
322        if config.show_cascade {
323            "cascade-shown"
324        } else {
325            "cascade-hidden"
326        },
327        &rules,
328        &type_aware,
329        &max_file_size,
330        &input_files,
331    ]);
332    format!("{ANALYSIS_FINGERPRINT_SCHEME}:{hash}")
333}
334
335/// `path` relative to `root` with forward slashes when it is inside the
336/// root, else the text as given.
337fn root_relative_text(root: &Path, path: &str) -> String {
338    Path::new(path).strip_prefix(root).map_or_else(
339        |_| path.replace('\\', "/"),
340        |relative| StableFileKey::from_relative(relative).as_str().to_owned(),
341    )
342}
343
344/// Normalize file text before it is hashed: CRLF becomes LF and trailing
345/// newlines are removed, so a checkout with `core.autocrlf` hashes the same
346/// as one without it.
347fn normalized_text(content: &[u8]) -> String {
348    String::from_utf8_lossy(content)
349        .replace("\r\n", "\n")
350        .trim_end_matches('\n')
351        .to_owned()
352}
353
354/// The walker for the fingerprint inputs.
355///
356/// It honors the repository `.gitignore`, `.ignore` and `.git/info/exclude`
357/// files, but never the global git excludes file of the machine: that file
358/// would prune directories on one machine and not on another. It skips hidden
359/// directories (the fallow cache lives there) and `node_modules`.
360fn fingerprint_walk_builder(root: &Path) -> ignore::WalkBuilder {
361    let mut builder = ignore::WalkBuilder::new(root);
362    builder
363        .hidden(false)
364        .git_ignore(true)
365        .git_global(false)
366        .git_exclude(true)
367        .filter_entry(|entry| {
368            let is_dir = entry.file_type().is_some_and(|kind| kind.is_dir());
369            if !is_dir || entry.depth() == 0 {
370                return true;
371            }
372            let name = entry.file_name().to_string_lossy();
373            !name.starts_with('.') && name != "node_modules"
374        });
375    builder
376}
377
378/// The globs of the non-source files the analysis reads to resolve imports
379/// and entry points, each also tried under `**/`.
380fn resolution_file_globs(config: &ResolvedConfig) -> globset::GlobSet {
381    let mut builder = globset::GlobSetBuilder::new();
382    let external = config
383        .external_plugins
384        .iter()
385        .flat_map(|plugin| plugin.config_patterns.iter().map(String::as_str));
386    let patterns = crate::core_backend::builtin_config_patterns()
387        .into_iter()
388        .chain(external)
389        .chain(RESOLUTION_FILE_GLOBS.iter().copied());
390    for pattern in patterns {
391        let anywhere = if pattern.starts_with("**/") {
392            pattern.to_owned()
393        } else {
394            format!("**/{pattern}")
395        };
396        for candidate in [pattern.to_owned(), anywhere] {
397            if let Ok(glob) = globset::Glob::new(&candidate) {
398                builder.add(glob);
399            }
400        }
401    }
402    builder
403        .build()
404        .unwrap_or_else(|_| globset::GlobSet::empty())
405}
406
407fn is_project_config_name(name: &str) -> bool {
408    (name.starts_with("tsconfig") || name.starts_with("jsconfig"))
409        && std::path::Path::new(name)
410            .extension()
411            .is_some_and(|ext| ext.eq_ignore_ascii_case("json"))
412}
413
414/// A hash over the root-relative path and normalized content of each
415/// fingerprint input file. See [`analysis_fingerprint`].
416fn input_files_digest(config: &ResolvedConfig) -> String {
417    let root = config.root.as_path();
418    let globs = resolution_file_globs(config);
419    let mut files: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();
420    if let Ok(content) = std::fs::read(root.join(".git/info/exclude")) {
421        files.insert(".git/info/exclude".to_owned(), normalized_text(&content));
422    }
423    let mut project_configs: Vec<PathBuf> = Vec::new();
424    for entry in fingerprint_walk_builder(root).build().flatten() {
425        if entry.file_type().is_none_or(|kind| kind.is_dir()) {
426            continue;
427        }
428        let Ok(relative) = entry.path().strip_prefix(root) else {
429            continue;
430        };
431        let name = entry.file_name().to_string_lossy();
432        let is_ignore_file = IGNORE_FILE_NAMES.contains(&name.as_ref());
433        if !is_ignore_file && !globs.is_match(relative) {
434            continue;
435        }
436        if config.ignore_patterns.is_match(relative) {
437            continue;
438        }
439        if let Ok(content) = std::fs::read(entry.path()) {
440            let key = StableFileKey::from_relative(relative).as_str().to_owned();
441            files.insert(key, normalized_text(&content));
442            if is_project_config_name(&name) {
443                project_configs.push(entry.path().to_path_buf());
444            }
445        }
446    }
447    for project_config in project_configs {
448        add_extends_chain(root, &project_config, &mut files);
449    }
450    let parts: Vec<&str> = files
451        .iter()
452        .flat_map(|(path, content)| [path.as_str(), content.as_str()])
453        .collect();
454    fallow_types::identity::fnv1a64_parts(&parts)
455}
456
457/// Follow the `extends` chain of one tsconfig or jsconfig file and add each
458/// file it names, also a file the walk did not see: one in a hidden
459/// directory, outside the root, or in `node_modules`.
460fn add_extends_chain(
461    root: &Path,
462    project_config: &Path,
463    files: &mut std::collections::BTreeMap<String, String>,
464) {
465    let mut seen: FxHashSet<PathBuf> = FxHashSet::default();
466    let mut frontier: Vec<(PathBuf, usize)> = vec![(project_config.to_path_buf(), 0)];
467    while let Some((current, depth)) = frontier.pop() {
468        if depth >= MAX_EXTENDS_DEPTH || !seen.insert(current.clone()) {
469            continue;
470        }
471        for target in read_extends(&current).unwrap_or_default() {
472            let Some(next) = resolve_extends_target(root, &current, &target) else {
473                continue;
474            };
475            if let Ok(content) = std::fs::read(&next) {
476                files.insert(extends_key(root, &next), normalized_text(&content));
477                frontier.push((next, depth + 1));
478            }
479        }
480    }
481}
482
483/// The `extends` targets of a tsconfig or jsconfig file: one string or an
484/// array of strings.
485fn read_extends(path: &Path) -> Option<Vec<String>> {
486    let content = std::fs::read_to_string(path).ok()?;
487    let value: serde_json::Value = fallow_config::jsonc::parse_to_value(&content).ok()?;
488    match value.get("extends")? {
489        serde_json::Value::String(target) => Some(vec![target.clone()]),
490        serde_json::Value::Array(items) => Some(
491            items
492                .iter()
493                .filter_map(|item| item.as_str().map(str::to_owned))
494                .collect(),
495        ),
496        _ => None,
497    }
498}
499
500/// The file an `extends` target names: a relative path from the extending
501/// file, or a package path under the root `node_modules`.
502fn resolve_extends_target(root: &Path, from: &Path, target: &str) -> Option<PathBuf> {
503    let base = if target.starts_with('.') || Path::new(target).is_absolute() {
504        from.parent()?.join(target)
505    } else {
506        root.join("node_modules").join(target)
507    };
508    let candidates = [
509        base.clone(),
510        base.with_extension("json"),
511        base.join("tsconfig.json"),
512    ];
513    candidates.into_iter().find(|candidate| candidate.is_file())
514}
515
516/// The hash key of an `extends` file: root-relative when inside the root,
517/// else `extends:` plus the file name, which carries no machine path.
518fn extends_key(root: &Path, path: &Path) -> String {
519    path.strip_prefix(root).map_or_else(
520        |_| {
521            format!(
522                "extends:{}",
523                path.file_name()
524                    .map(|name| name.to_string_lossy().into_owned())
525                    .unwrap_or_default()
526            )
527        },
528        |relative| StableFileKey::from_relative(relative).as_str().to_owned(),
529    )
530}
531
532/// Whether the rule of `id` is `off` in the top-level rules or in any
533/// override. An override is file-scoped and the id carries no path, so any
534/// override that turns the rule off counts.
535fn finding_id_rule_is_off(id: &str, config: &ResolvedConfig) -> bool {
536    let Some(kind) = id
537        .split(':')
538        .nth(1)
539        .and_then(fallow_types::suppress::IssueKind::parse)
540    else {
541        return false;
542    };
543    let off = |rules: &RulesConfig| rules.severity_for_kind(kind) == Severity::Off;
544    off(&config.rules)
545        || config.overrides.iter().any(|entry| {
546            let mut rules = config.rules.clone();
547            rules.apply_partial(&entry.rules);
548            off(&rules)
549        })
550}
551
552/// Scope dead-code results to the union of the given workspace roots.
553///
554/// The full cross-workspace graph is still built before this helper runs, so
555/// cross-package imports are resolved. Only reported findings are narrowed.
556pub fn filter_to_workspaces(results: &mut AnalysisResults, ws_roots: &[PathBuf]) {
557    let any_under = |path: &Path| ws_roots.iter().any(|root| path.starts_with(root));
558    let pkg_jsons = ws_roots
559        .iter()
560        .map(|root| root.join("package.json"))
561        .collect::<Vec<_>>();
562    let in_pkg_jsons = |path: &Path| pkg_jsons.iter().any(|pkg| path == pkg);
563
564    filter_workspace_source_findings(results, &any_under);
565    filter_workspace_dependency_findings(results, &any_under, &in_pkg_jsons);
566    filter_workspace_graph_findings(results, &any_under);
567    filter_workspace_policy_findings(results, &any_under);
568}
569
570/// The scope of one dead-code run, as the surface resolved it.
571///
572/// Every field is optional. A field that is `None` does not narrow the run.
573#[derive(Debug, Clone, Copy)]
574pub struct DeadCodeScope<'a> {
575    /// `--workspace`, `--changed-workspaces` and a positional path: the union
576    /// of these roots.
577    pub workspace_roots: Option<&'a [PathBuf]>,
578    /// The resolved change scope: a global changed-file set or the
579    /// configured package baselines.
580    pub changes: Option<&'a ChangeScope>,
581    /// A unified diff, with the root that finding paths resolve against.
582    pub diff: Option<(&'a fallow_output::DiffIndex, &'a Path)>,
583    /// `--file`: the only files to report. Dependency findings are dropped,
584    /// because a file list does not own a manifest.
585    pub files: Option<&'a FxHashSet<PathBuf>>,
586}
587
588/// Narrow dead-code results to the scope of the run.
589///
590/// The CLI, the programmatic API and the MCP typed path call this one function,
591/// so a scope narrows the same way on every surface. The filters run in this
592/// order: workspace roots, changed files, the diff, the file list. Then the
593/// configured `ignoreFindings` patterns run again, because the scope filters
594/// remove owners from a finding with several owners (`duplicate_exports`). A
595/// finding that only ignored owners hold after the scope is hidden, as the
596/// "hidden only when every owner matches" rule says.
597pub fn apply_scope(
598    results: &mut AnalysisResults,
599    scope: &DeadCodeScope<'_>,
600    config: &ResolvedConfig,
601) {
602    // Chain scopes depend on source-owned enforcement, which must resolve before filtering.
603    crate::effective_severity::apply_prop_drilling_severities(results, config);
604    if let Some(roots) = scope.workspace_roots {
605        filter_to_workspaces(results, roots);
606    }
607    if let Some(changes) = scope.changes {
608        changes.retain_dead_code(results);
609    }
610    if let Some((diff, root)) = scope.diff {
611        crate::diff_scope::filter_dead_code_by_diff(results, diff, root);
612    }
613    if let Some(files) = scope.files {
614        filter_by_changed_files(results, files);
615        clear_dependency_findings(results);
616    }
617    filter_configured_ignored_findings(results, config);
618}
619
620fn clear_dependency_findings(results: &mut AnalysisResults) {
621    results.unused_dependencies.clear();
622    results.unused_dev_dependencies.clear();
623    results.unused_optional_dependencies.clear();
624    results.type_only_dependencies.clear();
625    results.test_only_dependencies.clear();
626    results.dev_dependencies_in_production.clear();
627}
628
629/// Scope dead-code results to findings affected by changed files.
630#[expect(
631    clippy::implicit_hasher,
632    reason = "fallow standardizes on FxHashSet across the workspace"
633)]
634pub fn filter_by_changed_files(results: &mut AnalysisResults, changed_files: &FxHashSet<PathBuf>) {
635    crate::changed_files::filter_results_by_changed_files(results, changed_files);
636}
637
638/// Apply configured source-owned finding exclusions to an analysis result.
639///
640/// Analysis stages that append findings after the engine pipeline, such as
641/// type-aware reconciliation, must call this before exposing their final
642/// result.
643pub fn filter_configured_ignored_findings(results: &mut AnalysisResults, config: &ResolvedConfig) {
644    if config.ignore_findings.is_empty() {
645        return;
646    }
647
648    results.remove_ignored_dead_code_findings(|path| {
649        config.ignore_findings.is_ignored_path(&config.root, path)
650    });
651}
652
653fn filter_workspace_source_findings(
654    results: &mut AnalysisResults,
655    any_under: &dyn Fn(&Path) -> bool,
656) {
657    results
658        .unused_files
659        .retain(|finding| any_under(&finding.file.path));
660    results
661        .unused_exports
662        .retain(|finding| any_under(&finding.export.path));
663    results
664        .unused_types
665        .retain(|finding| any_under(&finding.export.path));
666    results
667        .private_type_leaks
668        .retain(|finding| any_under(&finding.leak.path));
669    results
670        .deprecated_exports_in_use
671        .retain(|finding| any_under(&finding.export.path));
672    results
673        .unused_enum_members
674        .retain(|finding| any_under(&finding.member.path));
675    results
676        .unused_class_members
677        .retain(|finding| any_under(&finding.member.path));
678    results
679        .unused_store_members
680        .retain(|finding| any_under(&finding.member.path));
681    results
682        .unprovided_injects
683        .retain(|finding| any_under(&finding.inject.path));
684    results
685        .unrendered_components
686        .retain(|finding| any_under(&finding.component.path));
687    results
688        .unused_component_props
689        .retain(|finding| any_under(&finding.prop.path));
690    results
691        .absent_component_props
692        .retain(|finding| any_under(&finding.prop.path));
693    results
694        .unused_component_emits
695        .retain(|finding| any_under(&finding.emit.path));
696    results
697        .unused_component_inputs
698        .retain(|finding| any_under(&finding.input.path));
699    results
700        .unused_component_outputs
701        .retain(|finding| any_under(&finding.output.path));
702    results
703        .unused_svelte_events
704        .retain(|finding| any_under(&finding.event.path));
705    results
706        .unused_effect_layers
707        .retain(|finding| any_under(&finding.layer.path));
708    results
709        .unused_tagged_errors
710        .retain(|finding| any_under(&finding.error.path));
711    results
712        .unproduced_catch_tags
713        .retain(|finding| any_under(&finding.catch_tag.path));
714    results
715        .unused_server_actions
716        .retain(|finding| any_under(&finding.action.path));
717    results
718        .unused_load_data_keys
719        .retain(|finding| any_under(&finding.key.path));
720    results
721        .unresolved_imports
722        .retain(|finding| any_under(&finding.import.path));
723}
724
725fn filter_workspace_dependency_findings(
726    results: &mut AnalysisResults,
727    any_under: &dyn Fn(&Path) -> bool,
728    in_pkg_jsons: &dyn Fn(&Path) -> bool,
729) {
730    results
731        .unused_dependencies
732        .retain(|finding| in_pkg_jsons(&finding.dep.path));
733    results
734        .unused_dev_dependencies
735        .retain(|finding| in_pkg_jsons(&finding.dep.path));
736    results
737        .unused_optional_dependencies
738        .retain(|finding| in_pkg_jsons(&finding.dep.path));
739    results
740        .type_only_dependencies
741        .retain(|finding| in_pkg_jsons(&finding.dep.path));
742    results
743        .test_only_dependencies
744        .retain(|finding| in_pkg_jsons(&finding.dep.path));
745    results
746        .dev_dependencies_in_production
747        .retain(|finding| in_pkg_jsons(&finding.dep.path));
748
749    results.unlisted_dependencies.retain(|finding| {
750        finding
751            .dep
752            .imported_from
753            .iter()
754            .any(|source| any_under(&source.path))
755    });
756    results.unused_dependency_overrides.clear();
757    results.misconfigured_dependency_overrides.clear();
758}
759
760fn filter_workspace_graph_findings(
761    results: &mut AnalysisResults,
762    any_under: &dyn Fn(&Path) -> bool,
763) {
764    for duplicate in &mut results.duplicate_exports {
765        duplicate
766            .export
767            .locations
768            .retain(|location| any_under(&location.path));
769    }
770    results
771        .duplicate_exports
772        .retain(|duplicate| duplicate.export.locations.len() >= 2);
773
774    results
775        .circular_dependencies
776        .retain(|cycle| cycle.cycle.files.iter().any(|path| any_under(path)));
777
778    results
779        .re_export_cycles
780        .retain(|cycle| cycle.cycle.files.iter().any(|path| any_under(path)));
781
782    results
783        .package_cycles
784        .retain(|cycle| cycle.cycle.edges.iter().any(|edge| any_under(&edge.path)));
785}
786
787fn filter_workspace_policy_findings(
788    results: &mut AnalysisResults,
789    any_under: &dyn Fn(&Path) -> bool,
790) {
791    results
792        .boundary_violations
793        .retain(|finding| any_under(&finding.violation.from_path));
794    results
795        .boundary_coverage_violations
796        .retain(|finding| any_under(&finding.violation.path));
797    results
798        .boundary_call_violations
799        .retain(|finding| any_under(&finding.violation.path));
800    results
801        .policy_violations
802        .retain(|finding| any_under(&finding.violation.path));
803
804    results
805        .stale_suppressions
806        .retain(|finding| any_under(&finding.path));
807
808    results
809        .security_findings
810        .retain(|finding| any_under(&finding.path));
811    results
812        .security_unresolved_callee_diagnostics
813        .retain(|finding| any_under(&finding.path));
814
815    results.unused_catalog_entries.clear();
816    results.empty_catalog_groups.clear();
817    results
818        .unresolved_catalog_references
819        .retain(|finding| any_under(&finding.reference.path));
820
821    results
822        .invalid_client_exports
823        .retain(|finding| any_under(&finding.export.path));
824
825    results
826        .mixed_client_server_barrels
827        .retain(|finding| any_under(&finding.barrel.path));
828
829    results
830        .misplaced_directives
831        .retain(|finding| any_under(&finding.directive_site.path));
832
833    results
834        .route_collisions
835        .retain(|finding| any_under(&finding.collision.path));
836
837    results
838        .dynamic_segment_name_conflicts
839        .retain(|finding| any_under(&finding.conflict.path));
840}
841
842/// Remove findings whose effective severity is `Off` from an analysis result.
843///
844/// Every surface that reports findings runs this pass: the `check` command
845/// (which also serves `dead-code` and the CLI audit), the editor analysis path
846/// behind inline diagnostics and the sidebar, and the programmatic runtime
847/// behind the MCP tools, the decision surface and the Node bindings. Each of
848/// them runs it at the same two points, once over the freshly analyzed set and
849/// once after type-aware reconciliation, because reconciliation can append
850/// findings. The pass removes findings and writes the gate severity of each
851/// finding that stays, so the second run is idempotent when nothing was
852/// appended.
853///
854/// When overrides are configured, per-file rule resolution is used for
855/// file-scoped issue types. Circular dependencies resolve against every file in
856/// the cycle. Non-file-scoped issues (unused deps, unlisted deps, duplicate
857/// exports) use the base rules only.
858pub fn apply_rule_severities(results: &mut AnalysisResults, config: &ResolvedConfig) {
859    let rules = &config.rules;
860    let has_overrides = !config.overrides.is_empty();
861
862    if has_overrides {
863        apply_file_override_rules(results, config);
864        apply_boundary_override_rules(results, config);
865    } else {
866        apply_base_file_rules(results, rules);
867    }
868
869    apply_base_collection_rules(results, rules);
870    hide_cascade_findings(results, config);
871    apply_effective_severities(results, config);
872}
873
874/// Hide the export and member findings of unused files.
875///
876/// Deleting an unused file removes every unused export, unused type, unused
877/// class member and unused enum member in it, so these findings add no
878/// information to the report. The pass runs inside the rule pass, so every
879/// surface that reports findings hides the same set.
880///
881/// A finding is hidden only when the report lists its file in
882/// `unused_files`, or when an inline `fallow-ignore-file unused-file` comment
883/// suppressed that file. A scope, an issue-type selection without unused
884/// files, an `ignoreFindings` pattern or an `off` rule that removes the file
885/// from the report therefore hides nothing in that file. The issue-type
886/// filters clear the suppressed files too, so they must run before this pass.
887/// The baseline runs after this pass, so a baseline entry for the unused file
888/// does not make its findings visible again. `showCascade` keeps every
889/// finding.
890pub fn hide_cascade_findings(results: &mut AnalysisResults, config: &ResolvedConfig) {
891    if config.show_cascade {
892        return;
893    }
894    let reported = results.unused_files.iter().map(|f| &f.file.path);
895    let suppressed = results
896        .cascade
897        .suppressed_unused_files
898        .iter()
899        .filter(|path| config.resolve_rules_for_path(path).unused_files != Severity::Off);
900    let covered: FxHashSet<PathBuf> = reported.chain(suppressed).cloned().collect();
901    if covered.is_empty() {
902        return;
903    }
904    results.hide_cascade_findings(&|path| covered.contains(path));
905}
906
907fn apply_base_collection_rules(results: &mut AnalysisResults, rules: &RulesConfig) {
908    if rules.unused_dependencies == Severity::Off {
909        results.unused_dependencies.clear();
910    }
911    if rules.unused_dev_dependencies == Severity::Off {
912        results.unused_dev_dependencies.clear();
913    }
914    if rules.unused_optional_dependencies == Severity::Off {
915        results.unused_optional_dependencies.clear();
916    }
917    if rules.unlisted_dependencies == Severity::Off {
918        results.unlisted_dependencies.clear();
919    }
920    if rules.duplicate_exports == Severity::Off {
921        results.duplicate_exports.clear();
922    }
923    if rules.type_only_dependencies == Severity::Off {
924        results.type_only_dependencies.clear();
925    }
926    if rules.test_only_dependencies == Severity::Off {
927        results.test_only_dependencies.clear();
928    }
929    if rules.dev_dependencies_in_production == Severity::Off {
930        results.dev_dependencies_in_production.clear();
931    }
932    if rules.circular_dependencies == Severity::Off {
933        results.circular_dependencies.clear();
934    }
935    if rules.re_export_cycle == Severity::Off {
936        results.re_export_cycles.clear();
937    }
938    if rules.package_cycle == Severity::Off {
939        results.package_cycles.clear();
940    }
941    if rules.boundary_violation == Severity::Off {
942        results.boundary_violations.clear();
943        results.boundary_coverage_violations.clear();
944        results.boundary_call_violations.clear();
945    }
946    if rules.policy_violation == Severity::Off {
947        results.policy_violations.clear();
948    }
949    if rules.unused_catalog_entries == Severity::Off {
950        results.unused_catalog_entries.clear();
951    }
952    if rules.empty_catalog_groups == Severity::Off {
953        results.empty_catalog_groups.clear();
954    }
955    if rules.unresolved_catalog_references == Severity::Off {
956        results.unresolved_catalog_references.clear();
957    }
958    if rules.unused_dependency_overrides == Severity::Off {
959        results.unused_dependency_overrides.clear();
960    }
961    if rules.misconfigured_dependency_overrides == Severity::Off {
962        results.misconfigured_dependency_overrides.clear();
963    }
964}
965
966fn apply_file_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
967    apply_dead_code_override_rules(results, config);
968    apply_catalog_override_rules(results, config);
969    apply_framework_override_rules(results, config);
970    apply_circular_override_rules(results, config);
971}
972
973fn apply_dead_code_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
974    apply_core_dead_code_override_rules(results, config);
975    apply_component_dead_code_override_rules(results, config);
976}
977
978/// Retain core (non-component) dead-code findings whose per-file rule is not Off.
979fn apply_core_dead_code_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
980    results
981        .unused_files
982        .retain(|f| config.resolve_rules_for_path(&f.file.path).unused_files != Severity::Off);
983    results
984        .unused_exports
985        .retain(|e| config.resolve_rules_for_path(&e.export.path).unused_exports != Severity::Off);
986    results
987        .unused_types
988        .retain(|e| config.resolve_rules_for_path(&e.export.path).unused_types != Severity::Off);
989    results.private_type_leaks.retain(|e| {
990        config
991            .resolve_rules_for_path(&e.leak.path)
992            .private_type_leaks
993            != Severity::Off
994    });
995    results.deprecated_exports_in_use.retain(|e| {
996        config
997            .resolve_rules_for_path(&e.export.path)
998            .deprecated_exports_in_use
999            != Severity::Off
1000    });
1001    results.unused_enum_members.retain(|m| {
1002        config
1003            .resolve_rules_for_path(&m.member.path)
1004            .unused_enum_members
1005            != Severity::Off
1006    });
1007    results.unused_class_members.retain(|m| {
1008        config
1009            .resolve_rules_for_path(&m.member.path)
1010            .unused_class_members
1011            != Severity::Off
1012    });
1013    results.unused_store_members.retain(|m| {
1014        config
1015            .resolve_rules_for_path(&m.member.path)
1016            .unused_store_members
1017            != Severity::Off
1018    });
1019    results.unprovided_injects.retain(|f| {
1020        config
1021            .resolve_rules_for_path(&f.inject.path)
1022            .unprovided_injects
1023            != Severity::Off
1024    });
1025    results.unresolved_imports.retain(|i| {
1026        config
1027            .resolve_rules_for_path(&i.import.path)
1028            .unresolved_imports
1029            != Severity::Off
1030    });
1031}
1032
1033/// Retain component-shaped dead-code findings whose per-file rule is not Off.
1034fn apply_component_dead_code_override_rules(
1035    results: &mut AnalysisResults,
1036    config: &ResolvedConfig,
1037) {
1038    results.unrendered_components.retain(|c| {
1039        config
1040            .resolve_rules_for_path(&c.component.path)
1041            .unrendered_components
1042            != Severity::Off
1043    });
1044    results.unused_component_props.retain(|p| {
1045        config
1046            .resolve_rules_for_path(&p.prop.path)
1047            .unused_component_props
1048            != Severity::Off
1049    });
1050    results.absent_component_props.retain(|p| {
1051        config
1052            .resolve_rules_for_path(&p.prop.path)
1053            .absent_component_props
1054            != Severity::Off
1055    });
1056    results.unused_component_emits.retain(|e| {
1057        config
1058            .resolve_rules_for_path(&e.emit.path)
1059            .unused_component_emits
1060            != Severity::Off
1061    });
1062    results.unused_component_inputs.retain(|i| {
1063        config
1064            .resolve_rules_for_path(&i.input.path)
1065            .unused_component_inputs
1066            != Severity::Off
1067    });
1068    results.unused_component_outputs.retain(|o| {
1069        config
1070            .resolve_rules_for_path(&o.output.path)
1071            .unused_component_outputs
1072            != Severity::Off
1073    });
1074    results.unused_svelte_events.retain(|e| {
1075        config
1076            .resolve_rules_for_path(&e.event.path)
1077            .unused_svelte_events
1078            != Severity::Off
1079    });
1080    results.unused_effect_layers.retain(|e| {
1081        config
1082            .resolve_rules_for_path(&e.layer.path)
1083            .unused_effect_layers
1084            != Severity::Off
1085    });
1086    results.unused_tagged_errors.retain(|e| {
1087        config
1088            .resolve_rules_for_path(&e.error.path)
1089            .unused_tagged_errors
1090            != Severity::Off
1091    });
1092    results.unproduced_catch_tags.retain(|e| {
1093        config
1094            .resolve_rules_for_path(&e.catch_tag.path)
1095            .unproduced_catch_tags
1096            != Severity::Off
1097    });
1098    results.unused_server_actions.retain(|a| {
1099        config
1100            .resolve_rules_for_path(&a.action.path)
1101            .unused_server_actions
1102            != Severity::Off
1103    });
1104    results.unused_load_data_keys.retain(|k| {
1105        config
1106            .resolve_rules_for_path(&k.key.path)
1107            .unused_load_data_keys
1108            != Severity::Off
1109    });
1110}
1111
1112fn apply_catalog_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
1113    results.stale_suppressions.retain(|s| {
1114        let rules = config.resolve_rules_for_path(&s.path);
1115        if s.missing_reason {
1116            rules.require_suppression_reason != Severity::Off
1117        } else {
1118            rules.stale_suppressions != Severity::Off
1119        }
1120    });
1121    results.unresolved_catalog_references.retain(|r| {
1122        config
1123            .resolve_rules_for_path(&r.reference.path)
1124            .unresolved_catalog_references
1125            != Severity::Off
1126    });
1127    results.empty_catalog_groups.retain(|g| {
1128        config
1129            .resolve_rules_for_path(&g.group.path)
1130            .empty_catalog_groups
1131            != Severity::Off
1132    });
1133    results.unused_dependency_overrides.retain(|o| {
1134        config
1135            .resolve_rules_for_path(&o.entry.path)
1136            .unused_dependency_overrides
1137            != Severity::Off
1138    });
1139    results.misconfigured_dependency_overrides.retain(|o| {
1140        config
1141            .resolve_rules_for_path(&o.entry.path)
1142            .misconfigured_dependency_overrides
1143            != Severity::Off
1144    });
1145}
1146
1147fn apply_framework_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
1148    results.invalid_client_exports.retain(|e| {
1149        config
1150            .resolve_rules_for_path(&e.export.path)
1151            .invalid_client_export
1152            != Severity::Off
1153    });
1154    results.mixed_client_server_barrels.retain(|b| {
1155        config
1156            .resolve_rules_for_path(&b.barrel.path)
1157            .mixed_client_server_barrel
1158            != Severity::Off
1159    });
1160    results.misplaced_directives.retain(|d| {
1161        config
1162            .resolve_rules_for_path(&d.directive_site.path)
1163            .misplaced_directive
1164            != Severity::Off
1165    });
1166    results.route_collisions.retain(|c| {
1167        config
1168            .resolve_rules_for_path(&c.collision.path)
1169            .route_collision
1170            != Severity::Off
1171    });
1172    results.dynamic_segment_name_conflicts.retain(|c| {
1173        config
1174            .resolve_rules_for_path(&c.conflict.path)
1175            .dynamic_segment_name_conflict
1176            != Severity::Off
1177    });
1178}
1179
1180fn apply_circular_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
1181    results.circular_dependencies.retain(|c| {
1182        c.cycle
1183            .files
1184            .iter()
1185            .any(|path| config.resolve_rules_for_path(path).circular_dependencies != Severity::Off)
1186    });
1187}
1188
1189fn apply_base_file_rules(results: &mut AnalysisResults, rules: &RulesConfig) {
1190    clear_base_core_dead_code(results, rules);
1191    clear_base_component_dead_code(results, rules);
1192    clear_base_suppression_and_framework(results, rules);
1193}
1194
1195/// Clear core (non-component) dead-code findings whose base rule is Off.
1196fn clear_base_core_dead_code(results: &mut AnalysisResults, rules: &RulesConfig) {
1197    if rules.unused_files == Severity::Off {
1198        results.unused_files.clear();
1199    }
1200    if rules.unused_exports == Severity::Off {
1201        results.unused_exports.clear();
1202    }
1203    if rules.unused_types == Severity::Off {
1204        results.unused_types.clear();
1205    }
1206    if rules.private_type_leaks == Severity::Off {
1207        results.private_type_leaks.clear();
1208    }
1209    if rules.deprecated_exports_in_use == Severity::Off {
1210        results.deprecated_exports_in_use.clear();
1211    }
1212    if rules.unused_enum_members == Severity::Off {
1213        results.unused_enum_members.clear();
1214    }
1215    if rules.unused_class_members == Severity::Off {
1216        results.unused_class_members.clear();
1217    }
1218    if rules.unused_store_members == Severity::Off {
1219        results.unused_store_members.clear();
1220    }
1221    if rules.unprovided_injects == Severity::Off {
1222        results.unprovided_injects.clear();
1223    }
1224    if rules.unresolved_imports == Severity::Off {
1225        results.unresolved_imports.clear();
1226    }
1227}
1228
1229/// Clear component-shaped dead-code findings whose base rule is Off.
1230fn clear_base_component_dead_code(results: &mut AnalysisResults, rules: &RulesConfig) {
1231    if rules.unrendered_components == Severity::Off {
1232        results.unrendered_components.clear();
1233    }
1234    if rules.unused_component_props == Severity::Off {
1235        results.unused_component_props.clear();
1236    }
1237    if rules.absent_component_props == Severity::Off {
1238        results.absent_component_props.clear();
1239    }
1240    if rules.unused_component_emits == Severity::Off {
1241        results.unused_component_emits.clear();
1242    }
1243    if rules.unused_component_inputs == Severity::Off {
1244        results.unused_component_inputs.clear();
1245    }
1246    if rules.unused_component_outputs == Severity::Off {
1247        results.unused_component_outputs.clear();
1248    }
1249    if rules.unused_svelte_events == Severity::Off {
1250        results.unused_svelte_events.clear();
1251    }
1252    if rules.unused_effect_layers == Severity::Off {
1253        results.unused_effect_layers.clear();
1254    }
1255    if rules.unused_tagged_errors == Severity::Off {
1256        results.unused_tagged_errors.clear();
1257    }
1258    if rules.unproduced_catch_tags == Severity::Off {
1259        results.unproduced_catch_tags.clear();
1260    }
1261    if rules.unused_server_actions == Severity::Off {
1262        results.unused_server_actions.clear();
1263    }
1264    if rules.unused_load_data_keys == Severity::Off {
1265        results.unused_load_data_keys.clear();
1266    }
1267}
1268
1269/// Apply base stale-suppression retention and clear framework findings whose
1270/// base rule is Off.
1271fn clear_base_suppression_and_framework(results: &mut AnalysisResults, rules: &RulesConfig) {
1272    results.stale_suppressions.retain(|s| {
1273        if s.missing_reason {
1274            rules.require_suppression_reason != Severity::Off
1275        } else {
1276            rules.stale_suppressions != Severity::Off
1277        }
1278    });
1279    if rules.invalid_client_export == Severity::Off {
1280        results.invalid_client_exports.clear();
1281    }
1282    if rules.mixed_client_server_barrel == Severity::Off {
1283        results.mixed_client_server_barrels.clear();
1284    }
1285    if rules.misplaced_directive == Severity::Off {
1286        results.misplaced_directives.clear();
1287    }
1288    if rules.route_collision == Severity::Off {
1289        results.route_collisions.clear();
1290    }
1291    if rules.dynamic_segment_name_conflict == Severity::Off {
1292        results.dynamic_segment_name_conflicts.clear();
1293    }
1294}
1295
1296fn apply_boundary_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
1297    results.boundary_violations.retain(|v| {
1298        config
1299            .resolve_rules_for_path(&v.violation.from_path)
1300            .boundary_violation
1301            != Severity::Off
1302    });
1303    results.boundary_coverage_violations.retain(|v| {
1304        config
1305            .resolve_rules_for_path(&v.violation.path)
1306            .boundary_violation
1307            != Severity::Off
1308    });
1309    results.boundary_call_violations.retain(|v| {
1310        config
1311            .resolve_rules_for_path(&v.violation.path)
1312            .boundary_violation
1313            != Severity::Off
1314    });
1315    results.policy_violations.retain(|v| {
1316        config
1317            .resolve_rules_for_path(&v.violation.path)
1318            .policy_violation
1319            != Severity::Off
1320    });
1321}
1322
1323#[cfg(test)]
1324mod tests {
1325    use std::path::PathBuf;
1326
1327    use super::*;
1328    use fallow_types::output_dead_code::{
1329        BoundaryViolationFinding, CircularDependencyFinding, DuplicateExportFinding,
1330        PrivateTypeLeakFinding, UnlistedDependencyFinding, UnusedClassMemberFinding,
1331        UnusedEnumMemberFinding, UnusedExportFinding, UnusedFileFinding, UnusedTypeFinding,
1332    };
1333    use fallow_types::results::{
1334        BoundaryViolation, CircularDependency, DuplicateExport, DuplicateLocation, ImportSite,
1335        PrivateTypeLeak, UnlistedDependency, UnusedExport, UnusedFile, UnusedMember,
1336    };
1337
1338    #[test]
1339    fn finding_id_filter_keeps_request_order_and_drops_duplicates() {
1340        let a = "dc1:unused-export:0123456789abcdef";
1341        let b = "dc1:unused-file:0123456789abcdef~1";
1342
1343        let filter = FindingIdFilter::parse(&[b, a, b])
1344            .expect("valid ids")
1345            .expect("a filter");
1346
1347        assert_eq!(filter.requested, vec![b.to_owned(), a.to_owned()]);
1348        assert_eq!(FindingIdFilter::parse::<&str>(&[]), Ok(None));
1349    }
1350
1351    #[test]
1352    fn normalized_text_ignores_line_endings_and_trailing_newlines() {
1353        assert_eq!(normalized_text(b"dist\r\nbuild\r\n"), "dist\nbuild");
1354        assert_eq!(normalized_text(b"dist\nbuild\n\n"), "dist\nbuild");
1355        assert_eq!(normalized_text(b"dist\nbuild"), "dist\nbuild");
1356        assert_ne!(
1357            normalized_text(b"dist\nbuild"),
1358            normalized_text(b"dist\nbuilt")
1359        );
1360    }
1361
1362    #[test]
1363    fn a_crlf_checkout_has_the_same_fingerprint_as_an_lf_checkout() {
1364        let write_project = |line_end: &str| {
1365            let dir = tempfile::tempdir().expect("project");
1366            let root = dir.path();
1367            std::fs::create_dir_all(root.join("src")).expect("src");
1368            std::fs::write(
1369                root.join(".gitignore"),
1370                format!("dist{line_end}coverage{line_end}"),
1371            )
1372            .expect("gitignore");
1373            std::fs::write(
1374                root.join("package.json"),
1375                format!("{{{line_end}  \"name\": \"crlf\"{line_end}}}{line_end}"),
1376            )
1377            .expect("package.json");
1378            dir
1379        };
1380        let config_at = |root: &std::path::Path| {
1381            fallow_config::FallowConfig::default().resolve(
1382                root.to_path_buf(),
1383                fallow_config::OutputFormat::Json,
1384                1,
1385                true,
1386                true,
1387                None,
1388            )
1389        };
1390        let lf = write_project("\n");
1391        let crlf = write_project("\r\n");
1392
1393        assert_eq!(
1394            analysis_fingerprint_for_version(&config_at(lf.path()), "1.0.0"),
1395            analysis_fingerprint_for_version(&config_at(crlf.path()), "1.0.0")
1396        );
1397    }
1398
1399    #[test]
1400    fn a_tsconfig_extends_target_outside_the_walk_is_an_input() {
1401        let dir = tempfile::tempdir().expect("project");
1402        let root = dir.path();
1403        std::fs::create_dir_all(root.join(".config")).expect("hidden dir");
1404        std::fs::write(
1405            root.join("tsconfig.json"),
1406            r#"{ "extends": "./.config/tsconfig.base.json" }"#,
1407        )
1408        .expect("tsconfig");
1409        let base = root.join(".config/tsconfig.base.json");
1410        std::fs::write(&base, r#"{ "compilerOptions": { "baseUrl": "." } }"#).expect("base");
1411        let config = fallow_config::FallowConfig::default().resolve(
1412            root.to_path_buf(),
1413            fallow_config::OutputFormat::Json,
1414            1,
1415            true,
1416            true,
1417            None,
1418        );
1419        let before = analysis_fingerprint_for_version(&config, "1.0.0");
1420
1421        std::fs::write(&base, r#"{ "compilerOptions": { "baseUrl": "src" } }"#).expect("edit");
1422
1423        assert_ne!(analysis_fingerprint_for_version(&config, "1.0.0"), before);
1424    }
1425
1426    #[test]
1427    fn analysis_fingerprint_depends_on_the_version_and_not_on_the_root() {
1428        let config_at = |root: &std::path::Path| {
1429            fallow_config::FallowConfig::default().resolve(
1430                root.to_path_buf(),
1431                fallow_config::OutputFormat::Json,
1432                1,
1433                true,
1434                true,
1435                None,
1436            )
1437        };
1438        let a = tempfile::tempdir().expect("project a");
1439        let b = tempfile::tempdir().expect("project b");
1440        let config_a = config_at(a.path());
1441        let config_b = config_at(b.path());
1442
1443        let base = analysis_fingerprint_for_version(&config_a, "1.0.0");
1444        assert!(base.starts_with("af1:"), "{base}");
1445        assert_eq!(base, analysis_fingerprint_for_version(&config_a, "1.0.0"));
1446        assert_eq!(base, analysis_fingerprint_for_version(&config_b, "1.0.0"));
1447        assert_ne!(base, analysis_fingerprint_for_version(&config_a, "1.0.1"));
1448    }
1449
1450    #[test]
1451    fn finding_id_filter_refuses_a_malformed_id() {
1452        let error = FindingIdFilter::parse(&["dc1:unused-export:helper"])
1453            .expect_err("malformed id refused");
1454
1455        assert!(error.contains("dc1:unused-export:helper"), "{error}");
1456    }
1457
1458    #[test]
1459    fn finding_id_rule_is_off_reads_rules_and_overrides() {
1460        let id = "dc1:unused-export:0123456789abcdef";
1461        let mut config = fallow_config::FallowConfig::default().resolve(
1462            PathBuf::from("/repo"),
1463            fallow_config::OutputFormat::Json,
1464            1,
1465            true,
1466            true,
1467            None,
1468        );
1469        assert!(!finding_id_rule_is_off(id, &config));
1470
1471        config.rules.unused_exports = Severity::Off;
1472        assert!(finding_id_rule_is_off(id, &config));
1473        assert!(!finding_id_rule_is_off(
1474            "dc1:unused-file:0123456789abcdef",
1475            &config
1476        ));
1477
1478        let with_override = serde_json::from_str::<fallow_config::FallowConfig>(
1479            r#"{"overrides":[{"files":["src/a.ts"],"rules":{"unused-exports":"off"}}]}"#,
1480        )
1481        .expect("config parses")
1482        .resolve(
1483            PathBuf::from("/repo"),
1484            fallow_config::OutputFormat::Json,
1485            1,
1486            true,
1487            true,
1488            None,
1489        );
1490        assert!(finding_id_rule_is_off(id, &with_override));
1491    }
1492
1493    #[test]
1494    fn workspace_filter_keeps_findings_under_workspace_root() {
1495        let root = PathBuf::from("/repo/packages/app");
1496        let mut results = AnalysisResults::default();
1497        results
1498            .unused_files
1499            .push(UnusedFileFinding::with_actions(UnusedFile {
1500                path: root.join("src/unused.ts"),
1501            }));
1502        results
1503            .unused_files
1504            .push(UnusedFileFinding::with_actions(UnusedFile {
1505                path: PathBuf::from("/repo/packages/docs/src/unused.ts"),
1506            }));
1507
1508        filter_to_workspaces(&mut results, std::slice::from_ref(&root));
1509
1510        assert_eq!(results.unused_files.len(), 1);
1511        assert_eq!(
1512            results.unused_files[0].file.path,
1513            root.join("src/unused.ts")
1514        );
1515    }
1516
1517    #[test]
1518    fn configured_filter_removes_findings_added_after_engine_analysis() {
1519        let project = tempfile::tempdir().expect("project");
1520        let config = serde_json::from_str::<fallow_config::FallowConfig>(
1521            r#"{"ignoreFindings":["src/hidden.ts"]}"#,
1522        )
1523        .expect("config parses")
1524        .resolve(
1525            project.path().to_path_buf(),
1526            fallow_config::OutputFormat::Human,
1527            1,
1528            true,
1529            true,
1530            None,
1531        );
1532        let mut results = AnalysisResults::default();
1533        results
1534            .private_type_leaks
1535            .push(PrivateTypeLeakFinding::with_actions(PrivateTypeLeak {
1536                path: project.path().join("src/hidden.ts"),
1537                export_name: "publicApi".to_string(),
1538                type_name: "PrivateShape".to_string(),
1539                line: 1,
1540                col: 0,
1541                span_start: 0,
1542                semantic: None,
1543            }));
1544        results
1545            .boundary_violations
1546            .push(BoundaryViolationFinding::with_actions(BoundaryViolation {
1547                from_path: project.path().join("src/hidden.ts"),
1548                to_path: project.path().join("src/data.ts"),
1549                from_zone: "ui".to_string(),
1550                to_zone: "data".to_string(),
1551                import_specifier: "./data".to_string(),
1552                line: 1,
1553                col: 0,
1554                via_path: None,
1555            }));
1556
1557        filter_configured_ignored_findings(&mut results, &config);
1558
1559        assert!(results.private_type_leaks.is_empty());
1560        assert_eq!(results.boundary_violations.len(), 1);
1561    }
1562
1563    fn unmatched_patterns(diagnostics: &[WorkspaceDiagnostic]) -> Vec<(&'static str, String)> {
1564        diagnostics
1565            .iter()
1566            .filter_map(|diagnostic| match &diagnostic.kind {
1567                WorkspaceDiagnosticKind::IgnoreFindingsPatternUnmatched { pattern } => {
1568                    Some(("ignoreFindings", pattern.clone()))
1569                }
1570                WorkspaceDiagnosticKind::IgnoreDependenciesGlobUnmatched { pattern } => {
1571                    Some(("ignoreDependencies", pattern.clone()))
1572                }
1573                _ => None,
1574            })
1575            .collect()
1576    }
1577
1578    fn write_manifest(root: &Path, dependencies: &str) {
1579        std::fs::write(
1580            root.join("package.json"),
1581            format!(
1582                r#"{{"name":"app","private":true,"main":"src/index.ts","dependencies":{dependencies}}}"#
1583            ),
1584        )
1585        .expect("write package.json");
1586    }
1587
1588    #[test]
1589    fn config_pattern_diagnostics_describe_the_latest_pass_only() {
1590        let project = tempfile::tempdir().expect("project");
1591        let root = project.path();
1592        std::fs::create_dir_all(root.join("src")).expect("create src");
1593        std::fs::write(root.join("src/index.ts"), "export const main = 1;\n").expect("write entry");
1594        std::fs::write(root.join("src/orphan.ts"), "export const orphan = 1;\n")
1595            .expect("write orphan");
1596        write_manifest(root, r#"{"@acme/lib":"1.0.0"}"#);
1597        let config = serde_json::from_str::<fallow_config::FallowConfig>(
1598            r#"{"ignoreDependencies":["@acme/*","@typo/*"],"ignoreFindings":["src/legcy/**"]}"#,
1599        )
1600        .expect("config parses")
1601        .resolve(
1602            root.to_path_buf(),
1603            fallow_config::OutputFormat::Human,
1604            1,
1605            true,
1606            true,
1607            None,
1608        );
1609
1610        crate::session::AnalysisSession::from_resolved_config(config.clone())
1611            .expect("session")
1612            .analyze_dead_code()
1613            .expect("first pass");
1614        assert_eq!(
1615            unmatched_patterns(&config_pattern_diagnostics(&config, true)),
1616            vec![
1617                ("ignoreFindings", "src/legcy/**".to_owned()),
1618                ("ignoreDependencies", "@typo/*".to_owned()),
1619            ]
1620        );
1621        assert_eq!(
1622            unmatched_patterns(&config_pattern_diagnostics(&config, false)),
1623            vec![("ignoreFindings", "src/legcy/**".to_owned())],
1624            "a run that reports no dependency findings omits the dependency globs"
1625        );
1626
1627        // A long-lived process keeps the config. The second pass must not
1628        // inherit the `@acme/*` hit of the first pass.
1629        write_manifest(root, r#"{"react":"1.0.0"}"#);
1630        crate::session::AnalysisSession::from_resolved_config(config.clone())
1631            .expect("session")
1632            .analyze_dead_code()
1633            .expect("second pass");
1634        assert_eq!(
1635            unmatched_patterns(&config_pattern_diagnostics(&config, true)),
1636            vec![
1637                ("ignoreFindings", "src/legcy/**".to_owned()),
1638                ("ignoreDependencies", "@acme/*".to_owned()),
1639                ("ignoreDependencies", "@typo/*".to_owned()),
1640            ]
1641        );
1642    }
1643
1644    fn config_with_override(
1645        pattern: &str,
1646        configure: impl FnOnce(&mut fallow_config::PartialRulesConfig),
1647    ) -> ResolvedConfig {
1648        let mut partial = fallow_config::PartialRulesConfig::default();
1649        configure(&mut partial);
1650        fallow_config::FallowConfig {
1651            rules: RulesConfig {
1652                private_type_leaks: Severity::Warn,
1653                ..RulesConfig::default()
1654            },
1655            overrides: vec![fallow_config::ConfigOverride {
1656                files: vec![pattern.to_string()],
1657                rules: partial,
1658            }],
1659            ..fallow_config::FallowConfig::default()
1660        }
1661        .resolve(
1662            PathBuf::from("/project"),
1663            fallow_config::OutputFormat::Human,
1664            1,
1665            true,
1666            true,
1667            None,
1668        )
1669    }
1670
1671    fn unused_export(path: &str) -> UnusedExportFinding {
1672        UnusedExportFinding::with_actions(UnusedExport {
1673            path: PathBuf::from(path),
1674            export_name: "Unused".to_string(),
1675            is_type_only: false,
1676            line: 1,
1677            col: 0,
1678            span_start: 0,
1679            is_re_export: false,
1680            deprecated: false,
1681            deprecated_reason: None,
1682        })
1683    }
1684
1685    fn private_type_leak(path: &str) -> PrivateTypeLeakFinding {
1686        PrivateTypeLeakFinding::with_actions(PrivateTypeLeak {
1687            path: PathBuf::from(path),
1688            export_name: "Unused".to_string(),
1689            type_name: "Props".to_string(),
1690            line: 1,
1691            col: 0,
1692            span_start: 0,
1693            semantic: None,
1694        })
1695    }
1696
1697    fn overridden_fixture() -> AnalysisResults {
1698        let mut results = AnalysisResults::default();
1699        results
1700            .unused_exports
1701            .push(unused_export("/project/src/ui/kit.ts"));
1702        results
1703            .unused_exports
1704            .push(unused_export("/project/src/lib/util.ts"));
1705        results
1706            .private_type_leaks
1707            .push(private_type_leak("/project/src/ui/kit.ts"));
1708        results
1709            .private_type_leaks
1710            .push(private_type_leak("/project/src/lib/util.ts"));
1711        results
1712    }
1713
1714    #[test]
1715    fn rule_severities_drop_findings_only_on_overridden_paths() {
1716        let config = config_with_override("src/ui/**", |rules| {
1717            rules.unused_exports = Some(Severity::Off);
1718            rules.private_type_leaks = Some(Severity::Off);
1719        });
1720        let mut results = overridden_fixture();
1721
1722        apply_rule_severities(&mut results, &config);
1723
1724        assert_eq!(
1725            results
1726                .unused_exports
1727                .iter()
1728                .map(|finding| finding.export.path.clone())
1729                .collect::<Vec<_>>(),
1730            vec![PathBuf::from("/project/src/lib/util.ts")]
1731        );
1732        assert_eq!(
1733            results
1734                .private_type_leaks
1735                .iter()
1736                .map(|finding| finding.leak.path.clone())
1737                .collect::<Vec<_>>(),
1738            vec![PathBuf::from("/project/src/lib/util.ts")]
1739        );
1740    }
1741
1742    #[test]
1743    fn rule_severities_are_idempotent() {
1744        // The editor path resolves severities once after analysis and again
1745        // after type-aware reconciliation, so a second pass must not change
1746        // the result set.
1747        let config = config_with_override("src/ui/**", |rules| {
1748            rules.unused_exports = Some(Severity::Off);
1749            rules.private_type_leaks = Some(Severity::Off);
1750        });
1751
1752        let mut once = overridden_fixture();
1753        apply_rule_severities(&mut once, &config);
1754        let mut twice = overridden_fixture();
1755        apply_rule_severities(&mut twice, &config);
1756        apply_rule_severities(&mut twice, &config);
1757
1758        assert_eq!(
1759            once.unused_exports
1760                .iter()
1761                .map(|finding| finding.export.path.clone())
1762                .collect::<Vec<_>>(),
1763            twice
1764                .unused_exports
1765                .iter()
1766                .map(|finding| finding.export.path.clone())
1767                .collect::<Vec<_>>()
1768        );
1769        assert_eq!(
1770            once.private_type_leaks
1771                .iter()
1772                .map(|finding| finding.leak.path.clone())
1773                .collect::<Vec<_>>(),
1774            twice
1775                .private_type_leaks
1776                .iter()
1777                .map(|finding| finding.leak.path.clone())
1778                .collect::<Vec<_>>()
1779        );
1780    }
1781
1782    #[test]
1783    fn rule_severities_keep_a_cycle_when_any_member_file_stays_enabled() {
1784        let config = config_with_override("src/ui/**", |rules| {
1785            rules.circular_dependencies = Some(Severity::Off);
1786        });
1787        let mut results = AnalysisResults::default();
1788        results
1789            .circular_dependencies
1790            .push(CircularDependencyFinding::with_actions(
1791                CircularDependency {
1792                    files: vec![
1793                        PathBuf::from("/project/src/ui/a.ts"),
1794                        PathBuf::from("/project/src/lib/b.ts"),
1795                    ],
1796                    length: 2,
1797                    line: 1,
1798                    col: 0,
1799                    edges: Vec::new(),
1800                    is_cross_package: false,
1801                },
1802            ));
1803        results
1804            .circular_dependencies
1805            .push(CircularDependencyFinding::with_actions(
1806                CircularDependency {
1807                    files: vec![
1808                        PathBuf::from("/project/src/ui/c.ts"),
1809                        PathBuf::from("/project/src/ui/d.ts"),
1810                    ],
1811                    length: 2,
1812                    line: 1,
1813                    col: 0,
1814                    edges: Vec::new(),
1815                    is_cross_package: false,
1816                },
1817            ));
1818
1819        apply_rule_severities(&mut results, &config);
1820
1821        assert_eq!(results.circular_dependencies.len(), 1);
1822        assert_eq!(
1823            results.circular_dependencies[0].cycle.files[0],
1824            PathBuf::from("/project/src/ui/a.ts")
1825        );
1826    }
1827
1828    #[test]
1829    fn rule_severities_clear_base_rules_without_overrides() {
1830        let config = fallow_config::FallowConfig {
1831            rules: RulesConfig {
1832                unused_exports: Severity::Off,
1833                private_type_leaks: Severity::Warn,
1834                ..RulesConfig::default()
1835            },
1836            ..fallow_config::FallowConfig::default()
1837        }
1838        .resolve(
1839            PathBuf::from("/project"),
1840            fallow_config::OutputFormat::Human,
1841            1,
1842            true,
1843            true,
1844            None,
1845        );
1846        let mut results = overridden_fixture();
1847
1848        apply_rule_severities(&mut results, &config);
1849
1850        assert!(results.unused_exports.is_empty());
1851        assert_eq!(results.private_type_leaks.len(), 2);
1852    }
1853
1854    const DEAD_FILE: &str = "/project/src/dead.ts";
1855    const LIVE_FILE: &str = "/project/src/live.ts";
1856
1857    fn resolve(config: fallow_config::FallowConfig) -> ResolvedConfig {
1858        config.resolve(
1859            PathBuf::from("/project"),
1860            fallow_config::OutputFormat::Human,
1861            1,
1862            true,
1863            true,
1864            None,
1865        )
1866    }
1867
1868    fn member(path: &str, kind: fallow_types::extract::MemberKind) -> UnusedMember {
1869        UnusedMember {
1870            path: PathBuf::from(path),
1871            parent_name: "Parent".to_string(),
1872            member_name: "member".to_string(),
1873            kind,
1874            line: 2,
1875            col: 0,
1876        }
1877    }
1878
1879    fn unused_type(path: &str) -> UnusedTypeFinding {
1880        let mut export = unused_export(path).export;
1881        export.is_type_only = true;
1882        UnusedTypeFinding::with_actions(export)
1883    }
1884
1885    /// One finding of each cascade kind in `DEAD_FILE` and in `LIVE_FILE`,
1886    /// plus findings of other kinds that touch `DEAD_FILE`.
1887    fn cascade_fixture() -> AnalysisResults {
1888        let mut results = AnalysisResults::default();
1889        results
1890            .unused_files
1891            .push(UnusedFileFinding::with_actions(UnusedFile {
1892                path: PathBuf::from(DEAD_FILE),
1893            }));
1894        for path in [DEAD_FILE, LIVE_FILE] {
1895            results.unused_exports.push(unused_export(path));
1896            results.unused_types.push(unused_type(path));
1897            results
1898                .unused_enum_members
1899                .push(UnusedEnumMemberFinding::with_actions(member(
1900                    path,
1901                    fallow_types::extract::MemberKind::EnumMember,
1902                )));
1903            results
1904                .unused_class_members
1905                .push(UnusedClassMemberFinding::with_actions(member(
1906                    path,
1907                    fallow_types::extract::MemberKind::ClassMethod,
1908                )));
1909        }
1910        results
1911            .duplicate_exports
1912            .push(DuplicateExportFinding::with_actions(DuplicateExport {
1913                export_name: "Shared".to_string(),
1914                locations: [DEAD_FILE, LIVE_FILE]
1915                    .iter()
1916                    .map(|path| DuplicateLocation {
1917                        path: PathBuf::from(path),
1918                        line: 1,
1919                        col: 0,
1920                    })
1921                    .collect(),
1922            }));
1923        results
1924            .circular_dependencies
1925            .push(CircularDependencyFinding::with_actions(
1926                CircularDependency {
1927                    files: vec![PathBuf::from(DEAD_FILE), PathBuf::from(LIVE_FILE)],
1928                    length: 2,
1929                    line: 1,
1930                    col: 0,
1931                    edges: Vec::new(),
1932                    is_cross_package: false,
1933                },
1934            ));
1935        results
1936            .unlisted_dependencies
1937            .push(UnlistedDependencyFinding::with_actions(
1938                UnlistedDependency {
1939                    package_name: "left-pad".to_string(),
1940                    imported_from: vec![ImportSite {
1941                        path: PathBuf::from(DEAD_FILE),
1942                        line: 1,
1943                        col: 0,
1944                    }],
1945                },
1946            ));
1947        results
1948            .boundary_violations
1949            .push(BoundaryViolationFinding::with_actions(BoundaryViolation {
1950                from_path: PathBuf::from(DEAD_FILE),
1951                to_path: PathBuf::from(LIVE_FILE),
1952                from_zone: "ui".to_string(),
1953                to_zone: "data".to_string(),
1954                import_specifier: "./live".to_string(),
1955                line: 1,
1956                col: 0,
1957                via_path: None,
1958            }));
1959        results
1960    }
1961
1962    fn cascade_paths(results: &AnalysisResults) -> Vec<Vec<PathBuf>> {
1963        vec![
1964            results
1965                .unused_exports
1966                .iter()
1967                .map(|f| f.export.path.clone())
1968                .collect(),
1969            results
1970                .unused_types
1971                .iter()
1972                .map(|f| f.export.path.clone())
1973                .collect(),
1974            results
1975                .unused_enum_members
1976                .iter()
1977                .map(|f| f.member.path.clone())
1978                .collect(),
1979            results
1980                .unused_class_members
1981                .iter()
1982                .map(|f| f.member.path.clone())
1983                .collect(),
1984        ]
1985    }
1986
1987    #[test]
1988    fn rule_pass_hides_the_cascade_kinds_of_unused_files() {
1989        let config = resolve(fallow_config::FallowConfig::default());
1990        let mut results = cascade_fixture();
1991
1992        apply_rule_severities(&mut results, &config);
1993
1994        let live = vec![PathBuf::from(LIVE_FILE)];
1995        assert_eq!(cascade_paths(&results), vec![live; 4]);
1996        assert_eq!(results.cascade_hidden, 4);
1997        assert_eq!(results.cascade.hidden.len(), 4);
1998        assert_eq!(results.unused_files.len(), 1, "the unused file stays");
1999    }
2000
2001    #[test]
2002    fn rule_pass_keeps_other_kinds_in_unused_files() {
2003        let config = resolve(fallow_config::FallowConfig::default());
2004        let mut results = cascade_fixture();
2005
2006        apply_rule_severities(&mut results, &config);
2007
2008        assert_eq!(results.duplicate_exports.len(), 1);
2009        assert_eq!(results.circular_dependencies.len(), 1);
2010        assert_eq!(results.unlisted_dependencies.len(), 1);
2011        assert_eq!(results.boundary_violations.len(), 1);
2012    }
2013
2014    #[test]
2015    fn show_cascade_keeps_every_finding() {
2016        let config = resolve(fallow_config::FallowConfig {
2017            show_cascade: true,
2018            ..fallow_config::FallowConfig::default()
2019        });
2020        let mut results = cascade_fixture();
2021
2022        apply_rule_severities(&mut results, &config);
2023
2024        let both = vec![PathBuf::from(DEAD_FILE), PathBuf::from(LIVE_FILE)];
2025        assert_eq!(cascade_paths(&results), vec![both; 4]);
2026        assert_eq!(results.cascade_hidden, 0);
2027    }
2028
2029    #[test]
2030    fn unused_files_rule_off_for_the_file_keeps_its_findings() {
2031        let config = config_with_override("src/dead.ts", |rules| {
2032            rules.unused_files = Some(Severity::Off);
2033        });
2034        let mut results = cascade_fixture();
2035
2036        apply_rule_severities(&mut results, &config);
2037
2038        assert!(results.unused_files.is_empty());
2039        let both = vec![PathBuf::from(DEAD_FILE), PathBuf::from(LIVE_FILE)];
2040        assert_eq!(cascade_paths(&results), vec![both; 4]);
2041        assert_eq!(results.cascade_hidden, 0);
2042    }
2043
2044    #[test]
2045    fn a_suppressed_unused_file_still_hides_its_findings() {
2046        // An inline `fallow-ignore-file unused-file` comment removes the file
2047        // from `unused_files`, and the detector records it as suppressed.
2048        let config = resolve(fallow_config::FallowConfig::default());
2049        let mut results = cascade_fixture();
2050        results.unused_files.clear();
2051        results.cascade.suppressed_unused_files = vec![PathBuf::from(DEAD_FILE)];
2052
2053        apply_rule_severities(&mut results, &config);
2054
2055        let live = vec![PathBuf::from(LIVE_FILE)];
2056        assert_eq!(cascade_paths(&results), vec![live; 4]);
2057        assert_eq!(results.cascade_hidden, 4);
2058    }
2059
2060    #[test]
2061    fn a_file_missing_from_the_report_hides_nothing() {
2062        // An issue-type filter without `unused-files`, a scope or a rule can
2063        // remove the unused file from the report. Its findings must then stay,
2064        // or the report loses them without a pointer to the file.
2065        let config = resolve(fallow_config::FallowConfig::default());
2066        let mut results = cascade_fixture();
2067        results.unused_files.clear();
2068
2069        apply_rule_severities(&mut results, &config);
2070
2071        let both = vec![PathBuf::from(DEAD_FILE), PathBuf::from(LIVE_FILE)];
2072        assert_eq!(cascade_paths(&results), vec![both; 4]);
2073        assert_eq!(results.cascade_hidden, 0);
2074    }
2075
2076    #[test]
2077    fn cascade_hiding_is_idempotent() {
2078        let config = resolve(fallow_config::FallowConfig::default());
2079        let mut results = cascade_fixture();
2080
2081        apply_rule_severities(&mut results, &config);
2082        apply_rule_severities(&mut results, &config);
2083
2084        assert_eq!(results.cascade_hidden, 4);
2085        assert_eq!(results.cascade.hidden.len(), 4);
2086    }
2087
2088    #[test]
2089    fn cascade_hidden_serializes_only_when_not_zero() {
2090        let config = resolve(fallow_config::FallowConfig::default());
2091        let mut results = cascade_fixture();
2092        let before = serde_json::to_value(&results).expect("serializes");
2093        assert!(before.get("cascade_hidden").is_none());
2094
2095        apply_rule_severities(&mut results, &config);
2096
2097        let after = serde_json::to_value(&results).expect("serializes");
2098        assert_eq!(after["cascade_hidden"], 4);
2099        assert!(after.get("cascade").is_none());
2100    }
2101}