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::{ResolvedConfig, RulesConfig, Severity};
8use fallow_types::discover::StableFileKey;
9
10pub use crate::results::{
11    AnalysisResults, DeadCodeAnalysis, DeadCodeAnalysisArtifacts, DeadCodeAnalysisOutput,
12    DeadCodeAnalysisWithHashes, derive_security_severity, enable_security_rules,
13    resolve_security_finding_severity, security_catalogue_title, security_rule_id,
14    security_rules_can_error,
15};
16
17pub use crate::effective_severity::{
18    RuleSeverity, SeveritySource, apply_effective_severities, findings_without_severity,
19    promote_effective_warns,
20};
21
22#[path = "dead_code_config_patterns.rs"]
23mod config_patterns;
24pub use config_patterns::config_pattern_diagnostics;
25
26use crate::{
27    EngineResult, change_scope::ChangeScope,
28    session::analyze_dead_code_with_parse_result_from_config, source::ModuleInfo,
29};
30
31/// Run dead-code analysis from pre-parsed modules.
32///
33/// # Errors
34///
35/// Returns an error if discovery, graph construction, or analysis fails.
36pub(crate) fn analyze_with_parse_result(
37    config: &ResolvedConfig,
38    modules: &[ModuleInfo],
39) -> EngineResult<DeadCodeAnalysisArtifacts> {
40    analyze_dead_code_with_parse_result_from_config(config, modules)
41}
42
43/// Write a stable `finding_id` onto every dead-code finding in `results`.
44///
45/// Every producer calls this on the full result set, before the workspace,
46/// scope, changed-file, ignore, baseline and rule filters. A filter then never
47/// changes the id of a finding that stays in the report.
48pub fn stamp_finding_ids(results: &mut AnalysisResults, root: &Path) {
49    fallow_types::identity::stamp_dead_code_finding_ids(results, root);
50}
51
52/// Give a `finding_id` to each dead-code finding that has none, and keep the
53/// existing ids.
54///
55/// Type-aware refinement adds findings after the scope filters ran. A full
56/// restamp there would compute tiebreak suffixes over the filtered set.
57pub fn stamp_missing_finding_ids(results: &mut AnalysisResults, root: &Path) {
58    fallow_types::identity::stamp_missing_dead_code_finding_ids(results, root);
59}
60
61/// A validated `--finding-id` request: the ids a run reports, in request order.
62///
63/// The filter runs after every other filter and after the baseline, so it
64/// narrows what the run would otherwise report. The ids themselves are
65/// stamped on the full result set before any filter, so a filter never
66/// changes them.
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct FindingIdFilter {
69    requested: Vec<String>,
70    set: FxHashSet<String>,
71}
72
73impl FindingIdFilter {
74    /// Validate the requested ids and drop duplicates. Returns `Ok(None)`
75    /// when `values` is empty.
76    ///
77    /// # Errors
78    ///
79    /// Returns a message that names the first value that is not a current
80    /// dead-code finding id (`dc1:<rule>:<16 hex digits>` with an optional
81    /// `~<k>` suffix). A typo must never read as "the finding is gone".
82    pub fn parse<S: AsRef<str>>(values: &[S]) -> Result<Option<Self>, String> {
83        if values.is_empty() {
84            return Ok(None);
85        }
86        let mut requested = Vec::with_capacity(values.len());
87        let mut set = FxHashSet::default();
88        for value in values {
89            let id = value.as_ref().trim();
90            if !fallow_types::identity::is_dead_code_finding_id(id) {
91                return Err(format!(
92                    "invalid finding id '{id}': expected {}:<rule>:<16 hex digits>, \
93                     optionally with a ~<k> suffix, as printed in the finding_id field",
94                    fallow_types::identity::DEAD_CODE_ID_SCHEME
95                ));
96            }
97            if set.insert(id.to_owned()) {
98                requested.push(id.to_owned());
99            }
100        }
101        Ok(Some(Self { requested, set }))
102    }
103
104    /// The requested ids that a finding in `results` carries. Reads only.
105    #[must_use]
106    pub fn present(&self, results: &mut AnalysisResults) -> FxHashSet<String> {
107        fallow_types::identity::present_dead_code_finding_ids(results, &self.set)
108    }
109
110    /// Keep only the requested findings and build the query answer.
111    ///
112    /// `filtered` holds the requested ids that the analysis found and a filter
113    /// of this run removed. `run_reasons` are the options of this run that
114    /// can hide a finding without a fix. `rule-off` is added when the rule of
115    /// a missing id is `off` in `config`.
116    pub fn apply(
117        &self,
118        results: &mut AnalysisResults,
119        config: &ResolvedConfig,
120        filtered: &FxHashSet<String>,
121        run_reasons: impl IntoIterator<Item = fallow_output::FindingIdQueryReason>,
122    ) -> fallow_output::FindingIdQuery {
123        let found = fallow_types::identity::retain_dead_code_findings_by_id(results, &self.set);
124        let rule_off = self
125            .requested
126            .iter()
127            .filter(|id| !found.contains(*id))
128            .any(|id| finding_id_rule_is_off(id, config));
129        fallow_output::FindingIdQuery::new(
130            self.requested.clone(),
131            |id| found.contains(id),
132            |id| filtered.contains(id),
133            run_reasons
134                .into_iter()
135                .chain(rule_off.then_some(fallow_output::FindingIdQueryReason::RuleOff)),
136            analysis_fingerprint(config),
137        )
138    }
139}
140
141/// Evidence for a finding-id answer, collected around the filter stages of
142/// one run.
143///
144/// A requested id that is present before a filter stage and absent after it
145/// was hidden by this run, not fixed. Those ids end in `filtered`. A stage
146/// that is analysis (type-aware refinement) stays outside every stage, so a
147/// finding it removes counts as gone.
148#[derive(Debug, Clone)]
149pub struct FindingIdTrace {
150    filter: FindingIdFilter,
151    before_stage: FxHashSet<String>,
152    filtered: FxHashSet<String>,
153}
154
155impl FindingIdTrace {
156    /// Start the first filter stage on the full result set.
157    #[must_use]
158    pub fn start(filter: FindingIdFilter, results: &mut AnalysisResults) -> Self {
159        let before_stage = filter.present(results);
160        Self {
161            filter,
162            before_stage,
163            filtered: FxHashSet::default(),
164        }
165    }
166
167    /// Start a filter stage after work that is not a filter.
168    pub fn start_stage(&mut self, results: &mut AnalysisResults) {
169        self.before_stage = self.filter.present(results);
170    }
171
172    /// End a filter stage: the requested ids it removed count as filtered.
173    pub fn end_stage(&mut self, results: &mut AnalysisResults) {
174        let after = self.filter.present(results);
175        self.filtered
176            .extend(self.before_stage.drain().filter(|id| !after.contains(id)));
177    }
178
179    /// Apply the filter and build the answer. See [`FindingIdFilter::apply`].
180    pub fn finish(
181        self,
182        results: &mut AnalysisResults,
183        config: &ResolvedConfig,
184        run_reasons: impl IntoIterator<Item = fallow_output::FindingIdQueryReason>,
185    ) -> fallow_output::FindingIdQuery {
186        self.filter
187            .apply(results, config, &self.filtered, run_reasons)
188    }
189}
190
191/// The version prefix of an analysis fingerprint. A change to the hash inputs
192/// moves it, so an old fingerprint never equals a new one.
193const ANALYSIS_FINGERPRINT_SCHEME: &str = "af1";
194
195/// Ignore files that discovery reads in each directory it walks.
196const IGNORE_FILE_NAMES: &[&str] = &[".gitignore", ".ignore"];
197
198/// Non-source files that import resolution and entry-point discovery read,
199/// in every directory: manifests and TypeScript or JavaScript project files.
200/// The built-in and external plugin config patterns are added to these.
201const RESOLUTION_FILE_GLOBS: &[&str] =
202    &["**/package.json", "**/tsconfig*.json", "**/jsconfig*.json"];
203
204/// The maximum depth of a followed tsconfig `extends` chain.
205const MAX_EXTENDS_DEPTH: usize = 8;
206
207/// A stable hash of every input, other than the source files, that decides
208/// which dead-code findings a run of `config` reports.
209///
210/// The inputs:
211/// - the fallow version;
212/// - the detection config digest (merged user config after `extends`,
213///   external plugins, rule packs);
214/// - the settings that a surface changes after resolution: production mode,
215///   `includeEntryExports`, `showCascade`, the effective rules, the type-aware mode,
216///   requirement and project list, the file size limit;
217/// - the root-relative path and content of the repository ignore files, the
218///   `package.json` files, the `tsconfig*.json` and `jsconfig*.json` files and
219///   the `extends` files they name, and every file that matches a built-in or
220///   external plugin config pattern.
221///
222/// File content is normalized (CRLF to LF, trailing newlines removed) and the
223/// entries are sorted, so two checkouts of one commit give the same value on
224/// every platform. Known exclusions: the global git excludes file and other
225/// machine environment outside the `FALLOW_*` variables.
226#[must_use]
227pub fn analysis_fingerprint(config: &ResolvedConfig) -> String {
228    analysis_fingerprint_for_version(config, env!("CARGO_PKG_VERSION"))
229}
230
231/// [`analysis_fingerprint`] for an explicit fallow version.
232#[must_use]
233pub fn analysis_fingerprint_for_version(config: &ResolvedConfig, version: &str) -> String {
234    let rules = serde_json::to_string(&config.rules).unwrap_or_default();
235    let projects: Vec<String> = config
236        .type_aware
237        .projects
238        .iter()
239        .map(|project| root_relative_text(&config.root, project))
240        .collect();
241    let type_aware = format!(
242        "{}:{}:{}",
243        config.type_aware.enabled,
244        serde_json::to_string(&config.type_aware.require).unwrap_or_default(),
245        projects.join("|")
246    );
247    let max_file_size = config
248        .max_file_size_bytes
249        .map_or_else(|| "none".to_owned(), |bytes| bytes.to_string());
250    let input_files = input_files_digest(config);
251    let hash = fallow_types::identity::fnv1a64_parts(&[
252        ANALYSIS_FINGERPRINT_SCHEME,
253        version,
254        &config.detection_config_digest,
255        if config.production {
256            "production"
257        } else {
258            "all"
259        },
260        if config.include_entry_exports {
261            "entry-exports"
262        } else {
263            "no-entry-exports"
264        },
265        if config.show_cascade {
266            "cascade-shown"
267        } else {
268            "cascade-hidden"
269        },
270        &rules,
271        &type_aware,
272        &max_file_size,
273        &input_files,
274    ]);
275    format!("{ANALYSIS_FINGERPRINT_SCHEME}:{hash}")
276}
277
278/// `path` relative to `root` with forward slashes when it is inside the
279/// root, else the text as given.
280fn root_relative_text(root: &Path, path: &str) -> String {
281    Path::new(path).strip_prefix(root).map_or_else(
282        |_| path.replace('\\', "/"),
283        |relative| StableFileKey::from_relative(relative).as_str().to_owned(),
284    )
285}
286
287/// Normalize file text before it is hashed: CRLF becomes LF and trailing
288/// newlines are removed, so a checkout with `core.autocrlf` hashes the same
289/// as one without it.
290fn normalized_text(content: &[u8]) -> String {
291    String::from_utf8_lossy(content)
292        .replace("\r\n", "\n")
293        .trim_end_matches('\n')
294        .to_owned()
295}
296
297/// The walker for the fingerprint inputs.
298///
299/// It honors the repository `.gitignore`, `.ignore` and `.git/info/exclude`
300/// files, but never the global git excludes file of the machine: that file
301/// would prune directories on one machine and not on another. It skips hidden
302/// directories (the fallow cache lives there) and `node_modules`.
303fn fingerprint_walk_builder(root: &Path) -> ignore::WalkBuilder {
304    let mut builder = ignore::WalkBuilder::new(root);
305    builder
306        .hidden(false)
307        .git_ignore(true)
308        .git_global(false)
309        .git_exclude(true)
310        .filter_entry(|entry| {
311            let is_dir = entry.file_type().is_some_and(|kind| kind.is_dir());
312            if !is_dir || entry.depth() == 0 {
313                return true;
314            }
315            let name = entry.file_name().to_string_lossy();
316            !name.starts_with('.') && name != "node_modules"
317        });
318    builder
319}
320
321/// The globs of the non-source files the analysis reads to resolve imports
322/// and entry points, each also tried under `**/`.
323fn resolution_file_globs(config: &ResolvedConfig) -> globset::GlobSet {
324    let mut builder = globset::GlobSetBuilder::new();
325    let external = config
326        .external_plugins
327        .iter()
328        .flat_map(|plugin| plugin.config_patterns.iter().map(String::as_str));
329    let patterns = crate::core_backend::builtin_config_patterns()
330        .into_iter()
331        .chain(external)
332        .chain(RESOLUTION_FILE_GLOBS.iter().copied());
333    for pattern in patterns {
334        let anywhere = if pattern.starts_with("**/") {
335            pattern.to_owned()
336        } else {
337            format!("**/{pattern}")
338        };
339        for candidate in [pattern.to_owned(), anywhere] {
340            if let Ok(glob) = globset::Glob::new(&candidate) {
341                builder.add(glob);
342            }
343        }
344    }
345    builder
346        .build()
347        .unwrap_or_else(|_| globset::GlobSet::empty())
348}
349
350fn is_project_config_name(name: &str) -> bool {
351    (name.starts_with("tsconfig") || name.starts_with("jsconfig"))
352        && std::path::Path::new(name)
353            .extension()
354            .is_some_and(|ext| ext.eq_ignore_ascii_case("json"))
355}
356
357/// A hash over the root-relative path and normalized content of each
358/// fingerprint input file. See [`analysis_fingerprint`].
359fn input_files_digest(config: &ResolvedConfig) -> String {
360    let root = config.root.as_path();
361    let globs = resolution_file_globs(config);
362    let mut files: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();
363    if let Ok(content) = std::fs::read(root.join(".git/info/exclude")) {
364        files.insert(".git/info/exclude".to_owned(), normalized_text(&content));
365    }
366    let mut project_configs: Vec<PathBuf> = Vec::new();
367    for entry in fingerprint_walk_builder(root).build().flatten() {
368        if entry.file_type().is_none_or(|kind| kind.is_dir()) {
369            continue;
370        }
371        let Ok(relative) = entry.path().strip_prefix(root) else {
372            continue;
373        };
374        let name = entry.file_name().to_string_lossy();
375        let is_ignore_file = IGNORE_FILE_NAMES.contains(&name.as_ref());
376        if !is_ignore_file && !globs.is_match(relative) {
377            continue;
378        }
379        if config.ignore_patterns.is_match(relative) {
380            continue;
381        }
382        if let Ok(content) = std::fs::read(entry.path()) {
383            let key = StableFileKey::from_relative(relative).as_str().to_owned();
384            files.insert(key, normalized_text(&content));
385            if is_project_config_name(&name) {
386                project_configs.push(entry.path().to_path_buf());
387            }
388        }
389    }
390    for project_config in project_configs {
391        add_extends_chain(root, &project_config, &mut files);
392    }
393    let parts: Vec<&str> = files
394        .iter()
395        .flat_map(|(path, content)| [path.as_str(), content.as_str()])
396        .collect();
397    fallow_types::identity::fnv1a64_parts(&parts)
398}
399
400/// Follow the `extends` chain of one tsconfig or jsconfig file and add each
401/// file it names, also a file the walk did not see: one in a hidden
402/// directory, outside the root, or in `node_modules`.
403fn add_extends_chain(
404    root: &Path,
405    project_config: &Path,
406    files: &mut std::collections::BTreeMap<String, String>,
407) {
408    let mut seen: FxHashSet<PathBuf> = FxHashSet::default();
409    let mut frontier: Vec<(PathBuf, usize)> = vec![(project_config.to_path_buf(), 0)];
410    while let Some((current, depth)) = frontier.pop() {
411        if depth >= MAX_EXTENDS_DEPTH || !seen.insert(current.clone()) {
412            continue;
413        }
414        for target in read_extends(&current).unwrap_or_default() {
415            let Some(next) = resolve_extends_target(root, &current, &target) else {
416                continue;
417            };
418            if let Ok(content) = std::fs::read(&next) {
419                files.insert(extends_key(root, &next), normalized_text(&content));
420                frontier.push((next, depth + 1));
421            }
422        }
423    }
424}
425
426/// The `extends` targets of a tsconfig or jsconfig file: one string or an
427/// array of strings.
428fn read_extends(path: &Path) -> Option<Vec<String>> {
429    let content = std::fs::read_to_string(path).ok()?;
430    let value: serde_json::Value = fallow_config::jsonc::parse_to_value(&content).ok()?;
431    match value.get("extends")? {
432        serde_json::Value::String(target) => Some(vec![target.clone()]),
433        serde_json::Value::Array(items) => Some(
434            items
435                .iter()
436                .filter_map(|item| item.as_str().map(str::to_owned))
437                .collect(),
438        ),
439        _ => None,
440    }
441}
442
443/// The file an `extends` target names: a relative path from the extending
444/// file, or a package path under the root `node_modules`.
445fn resolve_extends_target(root: &Path, from: &Path, target: &str) -> Option<PathBuf> {
446    let base = if target.starts_with('.') || Path::new(target).is_absolute() {
447        from.parent()?.join(target)
448    } else {
449        root.join("node_modules").join(target)
450    };
451    let candidates = [
452        base.clone(),
453        base.with_extension("json"),
454        base.join("tsconfig.json"),
455    ];
456    candidates.into_iter().find(|candidate| candidate.is_file())
457}
458
459/// The hash key of an `extends` file: root-relative when inside the root,
460/// else `extends:` plus the file name, which carries no machine path.
461fn extends_key(root: &Path, path: &Path) -> String {
462    path.strip_prefix(root).map_or_else(
463        |_| {
464            format!(
465                "extends:{}",
466                path.file_name()
467                    .map(|name| name.to_string_lossy().into_owned())
468                    .unwrap_or_default()
469            )
470        },
471        |relative| StableFileKey::from_relative(relative).as_str().to_owned(),
472    )
473}
474
475/// Whether the rule of `id` is `off` in the top-level rules or in any
476/// override. An override is file-scoped and the id carries no path, so any
477/// override that turns the rule off counts.
478fn finding_id_rule_is_off(id: &str, config: &ResolvedConfig) -> bool {
479    let Some(kind) = id
480        .split(':')
481        .nth(1)
482        .and_then(fallow_types::suppress::IssueKind::parse)
483    else {
484        return false;
485    };
486    let off = |rules: &RulesConfig| rules.severity_for_kind(kind) == Severity::Off;
487    off(&config.rules)
488        || config.overrides.iter().any(|entry| {
489            let mut rules = config.rules.clone();
490            rules.apply_partial(&entry.rules);
491            off(&rules)
492        })
493}
494
495/// Scope dead-code results to the union of the given workspace roots.
496///
497/// The full cross-workspace graph is still built before this helper runs, so
498/// cross-package imports are resolved. Only reported findings are narrowed.
499pub fn filter_to_workspaces(results: &mut AnalysisResults, ws_roots: &[PathBuf]) {
500    let any_under = |path: &Path| ws_roots.iter().any(|root| path.starts_with(root));
501    let pkg_jsons = ws_roots
502        .iter()
503        .map(|root| root.join("package.json"))
504        .collect::<Vec<_>>();
505    let in_pkg_jsons = |path: &Path| pkg_jsons.iter().any(|pkg| path == pkg);
506
507    filter_workspace_source_findings(results, &any_under);
508    filter_workspace_dependency_findings(results, &any_under, &in_pkg_jsons);
509    filter_workspace_graph_findings(results, &any_under);
510    filter_workspace_policy_findings(results, &any_under);
511}
512
513/// The scope of one dead-code run, as the surface resolved it.
514///
515/// Every field is optional. A field that is `None` does not narrow the run.
516#[derive(Debug, Clone, Copy)]
517pub struct DeadCodeScope<'a> {
518    /// `--workspace`, `--changed-workspaces` and a positional path: the union
519    /// of these roots.
520    pub workspace_roots: Option<&'a [PathBuf]>,
521    /// The resolved change scope: a global changed-file set or the
522    /// configured package baselines.
523    pub changes: Option<&'a ChangeScope>,
524    /// A unified diff, with the root that finding paths resolve against.
525    pub diff: Option<(&'a fallow_output::DiffIndex, &'a Path)>,
526    /// `--file`: the only files to report. Dependency findings are dropped,
527    /// because a file list does not own a manifest.
528    pub files: Option<&'a FxHashSet<PathBuf>>,
529}
530
531/// Narrow dead-code results to the scope of the run.
532///
533/// The CLI, the programmatic API and the MCP typed path call this one function,
534/// so a scope narrows the same way on every surface. The filters run in this
535/// order: workspace roots, changed files, the diff, the file list. Then the
536/// configured `ignoreFindings` patterns run again, because the scope filters
537/// remove owners from a finding with several owners (`duplicate_exports`). A
538/// finding that only ignored owners hold after the scope is hidden, as the
539/// "hidden only when every owner matches" rule says.
540pub fn apply_scope(
541    results: &mut AnalysisResults,
542    scope: &DeadCodeScope<'_>,
543    config: &ResolvedConfig,
544) {
545    // Chain scopes depend on source-owned enforcement, which must resolve before filtering.
546    crate::effective_severity::apply_prop_drilling_severities(results, config);
547    if let Some(roots) = scope.workspace_roots {
548        filter_to_workspaces(results, roots);
549    }
550    if let Some(changes) = scope.changes {
551        changes.retain_dead_code(results);
552    }
553    if let Some((diff, root)) = scope.diff {
554        crate::diff_scope::filter_dead_code_by_diff(results, diff, root);
555    }
556    if let Some(files) = scope.files {
557        filter_by_changed_files(results, files);
558        clear_dependency_findings(results);
559    }
560    filter_configured_ignored_findings(results, config);
561}
562
563fn clear_dependency_findings(results: &mut AnalysisResults) {
564    results.unused_dependencies.clear();
565    results.unused_dev_dependencies.clear();
566    results.unused_optional_dependencies.clear();
567    results.type_only_dependencies.clear();
568    results.test_only_dependencies.clear();
569    results.dev_dependencies_in_production.clear();
570}
571
572/// Scope dead-code results to findings affected by changed files.
573#[expect(
574    clippy::implicit_hasher,
575    reason = "fallow standardizes on FxHashSet across the workspace"
576)]
577pub fn filter_by_changed_files(results: &mut AnalysisResults, changed_files: &FxHashSet<PathBuf>) {
578    crate::changed_files::filter_results_by_changed_files(results, changed_files);
579}
580
581/// Apply configured source-owned finding exclusions to an analysis result.
582///
583/// Analysis stages that append findings after the engine pipeline, such as
584/// type-aware reconciliation, must call this before exposing their final
585/// result.
586pub fn filter_configured_ignored_findings(results: &mut AnalysisResults, config: &ResolvedConfig) {
587    if config.ignore_findings.is_empty() {
588        return;
589    }
590
591    results.remove_ignored_dead_code_findings(|path| {
592        config.ignore_findings.is_ignored_path(&config.root, path)
593    });
594}
595
596fn filter_workspace_source_findings(
597    results: &mut AnalysisResults,
598    any_under: &dyn Fn(&Path) -> bool,
599) {
600    results
601        .unused_files
602        .retain(|finding| any_under(&finding.file.path));
603    results
604        .unused_exports
605        .retain(|finding| any_under(&finding.export.path));
606    results
607        .unused_types
608        .retain(|finding| any_under(&finding.export.path));
609    results
610        .private_type_leaks
611        .retain(|finding| any_under(&finding.leak.path));
612    results
613        .deprecated_exports_in_use
614        .retain(|finding| any_under(&finding.export.path));
615    results
616        .unused_enum_members
617        .retain(|finding| any_under(&finding.member.path));
618    results
619        .unused_class_members
620        .retain(|finding| any_under(&finding.member.path));
621    results
622        .unused_store_members
623        .retain(|finding| any_under(&finding.member.path));
624    results
625        .unused_namespace_members
626        .retain(|finding| any_under(&finding.member.path));
627    results
628        .unprovided_injects
629        .retain(|finding| any_under(&finding.inject.path));
630    results
631        .unrendered_components
632        .retain(|finding| any_under(&finding.component.path));
633    results
634        .unused_component_props
635        .retain(|finding| any_under(&finding.prop.path));
636    results
637        .absent_component_props
638        .retain(|finding| any_under(&finding.prop.path));
639    results
640        .unused_component_emits
641        .retain(|finding| any_under(&finding.emit.path));
642    results
643        .unused_component_inputs
644        .retain(|finding| any_under(&finding.input.path));
645    results
646        .unused_component_outputs
647        .retain(|finding| any_under(&finding.output.path));
648    results
649        .unused_svelte_events
650        .retain(|finding| any_under(&finding.event.path));
651    results
652        .unused_effect_layers
653        .retain(|finding| any_under(&finding.layer.path));
654    results
655        .duplicate_export_aliases
656        .retain(|finding| any_under(&finding.alias.path));
657    results
658        .unused_tagged_errors
659        .retain(|finding| any_under(&finding.error.path));
660    results
661        .unproduced_catch_tags
662        .retain(|finding| any_under(&finding.catch_tag.path));
663    results
664        .unused_server_actions
665        .retain(|finding| any_under(&finding.action.path));
666    results
667        .unused_load_data_keys
668        .retain(|finding| any_under(&finding.key.path));
669    results
670        .unresolved_imports
671        .retain(|finding| any_under(&finding.import.path));
672}
673
674fn filter_workspace_dependency_findings(
675    results: &mut AnalysisResults,
676    any_under: &dyn Fn(&Path) -> bool,
677    in_pkg_jsons: &dyn Fn(&Path) -> bool,
678) {
679    results
680        .unused_dependencies
681        .retain(|finding| in_pkg_jsons(&finding.dep.path));
682    results
683        .unused_dev_dependencies
684        .retain(|finding| in_pkg_jsons(&finding.dep.path));
685    results
686        .unused_optional_dependencies
687        .retain(|finding| in_pkg_jsons(&finding.dep.path));
688    results
689        .type_only_dependencies
690        .retain(|finding| in_pkg_jsons(&finding.dep.path));
691    results
692        .test_only_dependencies
693        .retain(|finding| in_pkg_jsons(&finding.dep.path));
694    results
695        .dev_dependencies_in_production
696        .retain(|finding| in_pkg_jsons(&finding.dep.path));
697
698    results.unlisted_dependencies.retain(|finding| {
699        finding
700            .dep
701            .imported_from
702            .iter()
703            .any(|source| any_under(&source.path))
704    });
705    results.unlisted_binaries.retain(|finding| {
706        finding
707            .binary
708            .used_in
709            .iter()
710            .any(|site| any_under(&site.path))
711    });
712    results.unused_dependency_overrides.clear();
713    results.misconfigured_dependency_overrides.clear();
714}
715
716fn filter_workspace_graph_findings(
717    results: &mut AnalysisResults,
718    any_under: &dyn Fn(&Path) -> bool,
719) {
720    for duplicate in &mut results.duplicate_exports {
721        duplicate
722            .export
723            .locations
724            .retain(|location| any_under(&location.path));
725    }
726    results
727        .duplicate_exports
728        .retain(|duplicate| duplicate.export.locations.len() >= 2);
729
730    results
731        .circular_dependencies
732        .retain(|cycle| cycle.cycle.files.iter().any(|path| any_under(path)));
733
734    results
735        .re_export_cycles
736        .retain(|cycle| cycle.cycle.files.iter().any(|path| any_under(path)));
737
738    results
739        .package_cycles
740        .retain(|cycle| cycle.cycle.edges.iter().any(|edge| any_under(&edge.path)));
741}
742
743fn filter_workspace_policy_findings(
744    results: &mut AnalysisResults,
745    any_under: &dyn Fn(&Path) -> bool,
746) {
747    results
748        .boundary_violations
749        .retain(|finding| any_under(&finding.violation.from_path));
750    results
751        .boundary_coverage_violations
752        .retain(|finding| any_under(&finding.violation.path));
753    results
754        .boundary_call_violations
755        .retain(|finding| any_under(&finding.violation.path));
756    results
757        .policy_violations
758        .retain(|finding| any_under(&finding.violation.path));
759
760    results
761        .stale_suppressions
762        .retain(|finding| any_under(&finding.path));
763
764    results
765        .security_findings
766        .retain(|finding| any_under(&finding.path));
767    results
768        .security_unresolved_callee_diagnostics
769        .retain(|finding| any_under(&finding.path));
770
771    results.unused_catalog_entries.clear();
772    results.empty_catalog_groups.clear();
773    results
774        .unresolved_catalog_references
775        .retain(|finding| any_under(&finding.reference.path));
776
777    results
778        .invalid_client_exports
779        .retain(|finding| any_under(&finding.export.path));
780
781    results
782        .mixed_client_server_barrels
783        .retain(|finding| any_under(&finding.barrel.path));
784
785    results
786        .misplaced_directives
787        .retain(|finding| any_under(&finding.directive_site.path));
788
789    results
790        .route_collisions
791        .retain(|finding| any_under(&finding.collision.path));
792
793    results
794        .dynamic_segment_name_conflicts
795        .retain(|finding| any_under(&finding.conflict.path));
796}
797
798/// Remove findings whose effective severity is `Off` from an analysis result.
799///
800/// Every surface that reports findings runs this pass: the `check` command
801/// (which also serves `dead-code` and the CLI audit), the editor analysis path
802/// behind inline diagnostics and the sidebar, and the programmatic runtime
803/// behind the MCP tools, the decision surface and the Node bindings. Each of
804/// them runs it at the same two points, once over the freshly analyzed set and
805/// once after type-aware reconciliation, because reconciliation can append
806/// findings. The pass removes findings and writes the gate severity of each
807/// finding that stays, so the second run is idempotent when nothing was
808/// appended.
809///
810/// When overrides are configured, per-file rule resolution is used for
811/// file-scoped issue types. Circular dependencies resolve against every file in
812/// the cycle. Non-file-scoped issues (unused deps, unlisted deps, duplicate
813/// exports) use the base rules only.
814pub fn apply_rule_severities(results: &mut AnalysisResults, config: &ResolvedConfig) {
815    let rules = &config.rules;
816    let has_overrides = !config.overrides.is_empty();
817
818    if has_overrides {
819        apply_file_override_rules(results, config);
820        apply_boundary_override_rules(results, config);
821    } else {
822        apply_base_file_rules(results, rules);
823    }
824
825    apply_base_collection_rules(results, rules);
826    hide_cascade_findings(results, config);
827    apply_effective_severities(results, config);
828}
829
830/// Hide the export and member findings of unused files.
831///
832/// Deleting an unused file removes every unused export, unused type, unused
833/// class member and unused enum member in it, so these findings add no
834/// information to the report. The pass runs inside the rule pass, so every
835/// surface that reports findings hides the same set.
836///
837/// A finding is hidden only when the report lists its file in
838/// `unused_files`, or when an inline `fallow-ignore-file unused-file` comment
839/// suppressed that file. A scope, an issue-type selection without unused
840/// files, an `ignoreFindings` pattern or an `off` rule that removes the file
841/// from the report therefore hides nothing in that file. The issue-type
842/// filters clear the suppressed files too, so they must run before this pass.
843/// The baseline runs after this pass, so a baseline entry for the unused file
844/// does not make its findings visible again. `showCascade` keeps every
845/// finding.
846pub fn hide_cascade_findings(results: &mut AnalysisResults, config: &ResolvedConfig) {
847    if config.show_cascade {
848        return;
849    }
850    let reported = results.unused_files.iter().map(|f| &f.file.path);
851    let suppressed = results
852        .cascade
853        .suppressed_unused_files
854        .iter()
855        .filter(|path| config.resolve_rules_for_path(path).unused_files != Severity::Off);
856    let covered: FxHashSet<PathBuf> = reported.chain(suppressed).cloned().collect();
857    if covered.is_empty() {
858        return;
859    }
860    results.hide_cascade_findings(&|path| covered.contains(path));
861}
862
863fn apply_base_collection_rules(results: &mut AnalysisResults, rules: &RulesConfig) {
864    if rules.unused_dependencies == Severity::Off {
865        results.unused_dependencies.clear();
866    }
867    if rules.unused_dev_dependencies == Severity::Off {
868        results.unused_dev_dependencies.clear();
869    }
870    if rules.unused_optional_dependencies == Severity::Off {
871        results.unused_optional_dependencies.clear();
872    }
873    if rules.unlisted_dependencies == Severity::Off {
874        results.unlisted_dependencies.clear();
875    }
876    if rules.unlisted_binaries == Severity::Off {
877        results.unlisted_binaries.clear();
878    }
879    if rules.duplicate_exports == Severity::Off {
880        results.duplicate_exports.clear();
881    }
882    if rules.duplicate_export_aliases == Severity::Off {
883        results.duplicate_export_aliases.clear();
884    }
885    if rules.type_only_dependencies == Severity::Off {
886        results.type_only_dependencies.clear();
887    }
888    if rules.test_only_dependencies == Severity::Off {
889        results.test_only_dependencies.clear();
890    }
891    if rules.dev_dependencies_in_production == Severity::Off {
892        results.dev_dependencies_in_production.clear();
893    }
894    if rules.circular_dependencies == Severity::Off {
895        results.circular_dependencies.clear();
896    }
897    if rules.re_export_cycle == Severity::Off {
898        results.re_export_cycles.clear();
899    }
900    if rules.package_cycle == Severity::Off {
901        results.package_cycles.clear();
902    }
903    if rules.boundary_violation == Severity::Off {
904        results.boundary_violations.clear();
905        results.boundary_coverage_violations.clear();
906        results.boundary_call_violations.clear();
907    }
908    if rules.policy_violation == Severity::Off {
909        results.policy_violations.clear();
910    }
911    if rules.unused_catalog_entries == Severity::Off {
912        results.unused_catalog_entries.clear();
913    }
914    if rules.empty_catalog_groups == Severity::Off {
915        results.empty_catalog_groups.clear();
916    }
917    if rules.unresolved_catalog_references == Severity::Off {
918        results.unresolved_catalog_references.clear();
919    }
920    if rules.unused_dependency_overrides == Severity::Off {
921        results.unused_dependency_overrides.clear();
922    }
923    if rules.misconfigured_dependency_overrides == Severity::Off {
924        results.misconfigured_dependency_overrides.clear();
925    }
926}
927
928fn apply_file_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
929    apply_dead_code_override_rules(results, config);
930    apply_catalog_override_rules(results, config);
931    apply_framework_override_rules(results, config);
932    apply_circular_override_rules(results, config);
933}
934
935fn apply_dead_code_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
936    apply_core_dead_code_override_rules(results, config);
937    apply_component_dead_code_override_rules(results, config);
938}
939
940/// Retain core (non-component) dead-code findings whose per-file rule is not Off.
941fn apply_core_dead_code_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
942    results
943        .unused_files
944        .retain(|f| config.resolve_rules_for_path(&f.file.path).unused_files != Severity::Off);
945    results
946        .unused_exports
947        .retain(|e| config.resolve_rules_for_path(&e.export.path).unused_exports != Severity::Off);
948    results
949        .unused_types
950        .retain(|e| config.resolve_rules_for_path(&e.export.path).unused_types != Severity::Off);
951    results.private_type_leaks.retain(|e| {
952        config
953            .resolve_rules_for_path(&e.leak.path)
954            .private_type_leaks
955            != Severity::Off
956    });
957    results.deprecated_exports_in_use.retain(|e| {
958        config
959            .resolve_rules_for_path(&e.export.path)
960            .deprecated_exports_in_use
961            != Severity::Off
962    });
963    results.unused_enum_members.retain(|m| {
964        config
965            .resolve_rules_for_path(&m.member.path)
966            .unused_enum_members
967            != Severity::Off
968    });
969    results.unused_class_members.retain(|m| {
970        config
971            .resolve_rules_for_path(&m.member.path)
972            .unused_class_members
973            != Severity::Off
974    });
975    results.unused_store_members.retain(|m| {
976        config
977            .resolve_rules_for_path(&m.member.path)
978            .unused_store_members
979            != Severity::Off
980    });
981    results.unused_namespace_members.retain(|m| {
982        config
983            .resolve_rules_for_path(&m.member.path)
984            .unused_namespace_members
985            != Severity::Off
986    });
987    results.unprovided_injects.retain(|f| {
988        config
989            .resolve_rules_for_path(&f.inject.path)
990            .unprovided_injects
991            != Severity::Off
992    });
993    results.unresolved_imports.retain(|i| {
994        config
995            .resolve_rules_for_path(&i.import.path)
996            .unresolved_imports
997            != Severity::Off
998    });
999}
1000
1001/// Retain component-shaped dead-code findings whose per-file rule is not Off.
1002fn apply_component_dead_code_override_rules(
1003    results: &mut AnalysisResults,
1004    config: &ResolvedConfig,
1005) {
1006    results.unrendered_components.retain(|c| {
1007        config
1008            .resolve_rules_for_path(&c.component.path)
1009            .unrendered_components
1010            != Severity::Off
1011    });
1012    results.unused_component_props.retain(|p| {
1013        config
1014            .resolve_rules_for_path(&p.prop.path)
1015            .unused_component_props
1016            != Severity::Off
1017    });
1018    results.absent_component_props.retain(|p| {
1019        config
1020            .resolve_rules_for_path(&p.prop.path)
1021            .absent_component_props
1022            != Severity::Off
1023    });
1024    results.unused_component_emits.retain(|e| {
1025        config
1026            .resolve_rules_for_path(&e.emit.path)
1027            .unused_component_emits
1028            != Severity::Off
1029    });
1030    results.unused_component_inputs.retain(|i| {
1031        config
1032            .resolve_rules_for_path(&i.input.path)
1033            .unused_component_inputs
1034            != Severity::Off
1035    });
1036    results.unused_component_outputs.retain(|o| {
1037        config
1038            .resolve_rules_for_path(&o.output.path)
1039            .unused_component_outputs
1040            != Severity::Off
1041    });
1042    results.unused_svelte_events.retain(|e| {
1043        config
1044            .resolve_rules_for_path(&e.event.path)
1045            .unused_svelte_events
1046            != Severity::Off
1047    });
1048    results.unused_effect_layers.retain(|e| {
1049        config
1050            .resolve_rules_for_path(&e.layer.path)
1051            .unused_effect_layers
1052            != Severity::Off
1053    });
1054    results.duplicate_export_aliases.retain(|finding| {
1055        config
1056            .resolve_rules_for_path(&finding.alias.path)
1057            .duplicate_export_aliases
1058            != Severity::Off
1059    });
1060    results.unused_tagged_errors.retain(|e| {
1061        config
1062            .resolve_rules_for_path(&e.error.path)
1063            .unused_tagged_errors
1064            != Severity::Off
1065    });
1066    results.unproduced_catch_tags.retain(|e| {
1067        config
1068            .resolve_rules_for_path(&e.catch_tag.path)
1069            .unproduced_catch_tags
1070            != Severity::Off
1071    });
1072    results.unused_server_actions.retain(|a| {
1073        config
1074            .resolve_rules_for_path(&a.action.path)
1075            .unused_server_actions
1076            != Severity::Off
1077    });
1078    results.unused_load_data_keys.retain(|k| {
1079        config
1080            .resolve_rules_for_path(&k.key.path)
1081            .unused_load_data_keys
1082            != Severity::Off
1083    });
1084}
1085
1086fn apply_catalog_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
1087    results.stale_suppressions.retain(|s| {
1088        let rules = config.resolve_rules_for_path(&s.path);
1089        if s.missing_reason {
1090            rules.require_suppression_reason != Severity::Off
1091        } else {
1092            rules.stale_suppressions != Severity::Off
1093        }
1094    });
1095    results.unresolved_catalog_references.retain(|r| {
1096        config
1097            .resolve_rules_for_path(&r.reference.path)
1098            .unresolved_catalog_references
1099            != Severity::Off
1100    });
1101    results.empty_catalog_groups.retain(|g| {
1102        config
1103            .resolve_rules_for_path(&g.group.path)
1104            .empty_catalog_groups
1105            != Severity::Off
1106    });
1107    results.unused_dependency_overrides.retain(|o| {
1108        config
1109            .resolve_rules_for_path(&o.entry.path)
1110            .unused_dependency_overrides
1111            != Severity::Off
1112    });
1113    results.misconfigured_dependency_overrides.retain(|o| {
1114        config
1115            .resolve_rules_for_path(&o.entry.path)
1116            .misconfigured_dependency_overrides
1117            != Severity::Off
1118    });
1119}
1120
1121fn apply_framework_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
1122    results.invalid_client_exports.retain(|e| {
1123        config
1124            .resolve_rules_for_path(&e.export.path)
1125            .invalid_client_export
1126            != Severity::Off
1127    });
1128    results.mixed_client_server_barrels.retain(|b| {
1129        config
1130            .resolve_rules_for_path(&b.barrel.path)
1131            .mixed_client_server_barrel
1132            != Severity::Off
1133    });
1134    results.misplaced_directives.retain(|d| {
1135        config
1136            .resolve_rules_for_path(&d.directive_site.path)
1137            .misplaced_directive
1138            != Severity::Off
1139    });
1140    results.route_collisions.retain(|c| {
1141        config
1142            .resolve_rules_for_path(&c.collision.path)
1143            .route_collision
1144            != Severity::Off
1145    });
1146    results.dynamic_segment_name_conflicts.retain(|c| {
1147        config
1148            .resolve_rules_for_path(&c.conflict.path)
1149            .dynamic_segment_name_conflict
1150            != Severity::Off
1151    });
1152}
1153
1154fn apply_circular_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
1155    results.circular_dependencies.retain(|c| {
1156        c.cycle
1157            .files
1158            .iter()
1159            .any(|path| config.resolve_rules_for_path(path).circular_dependencies != Severity::Off)
1160    });
1161}
1162
1163fn apply_base_file_rules(results: &mut AnalysisResults, rules: &RulesConfig) {
1164    clear_base_core_dead_code(results, rules);
1165    clear_base_component_dead_code(results, rules);
1166    clear_base_suppression_and_framework(results, rules);
1167}
1168
1169/// Clear core (non-component) dead-code findings whose base rule is Off.
1170fn clear_base_core_dead_code(results: &mut AnalysisResults, rules: &RulesConfig) {
1171    if rules.unused_files == Severity::Off {
1172        results.unused_files.clear();
1173    }
1174    if rules.unused_exports == Severity::Off {
1175        results.unused_exports.clear();
1176    }
1177    if rules.unused_types == Severity::Off {
1178        results.unused_types.clear();
1179    }
1180    if rules.private_type_leaks == Severity::Off {
1181        results.private_type_leaks.clear();
1182    }
1183    if rules.deprecated_exports_in_use == Severity::Off {
1184        results.deprecated_exports_in_use.clear();
1185    }
1186    if rules.unused_enum_members == Severity::Off {
1187        results.unused_enum_members.clear();
1188    }
1189    if rules.unused_class_members == Severity::Off {
1190        results.unused_class_members.clear();
1191    }
1192    if rules.unused_store_members == Severity::Off {
1193        results.unused_store_members.clear();
1194    }
1195    if rules.unused_namespace_members == Severity::Off {
1196        results.unused_namespace_members.clear();
1197    }
1198    if rules.unprovided_injects == Severity::Off {
1199        results.unprovided_injects.clear();
1200    }
1201    if rules.unresolved_imports == Severity::Off {
1202        results.unresolved_imports.clear();
1203    }
1204}
1205
1206/// Clear component-shaped dead-code findings whose base rule is Off.
1207fn clear_base_component_dead_code(results: &mut AnalysisResults, rules: &RulesConfig) {
1208    if rules.unrendered_components == Severity::Off {
1209        results.unrendered_components.clear();
1210    }
1211    if rules.unused_component_props == Severity::Off {
1212        results.unused_component_props.clear();
1213    }
1214    if rules.absent_component_props == Severity::Off {
1215        results.absent_component_props.clear();
1216    }
1217    if rules.unused_component_emits == Severity::Off {
1218        results.unused_component_emits.clear();
1219    }
1220    if rules.unused_component_inputs == Severity::Off {
1221        results.unused_component_inputs.clear();
1222    }
1223    if rules.unused_component_outputs == Severity::Off {
1224        results.unused_component_outputs.clear();
1225    }
1226    if rules.unused_svelte_events == Severity::Off {
1227        results.unused_svelte_events.clear();
1228    }
1229    if rules.unused_effect_layers == Severity::Off {
1230        results.unused_effect_layers.clear();
1231    }
1232    if rules.unused_tagged_errors == Severity::Off {
1233        results.unused_tagged_errors.clear();
1234    }
1235    if rules.unproduced_catch_tags == Severity::Off {
1236        results.unproduced_catch_tags.clear();
1237    }
1238    if rules.unused_server_actions == Severity::Off {
1239        results.unused_server_actions.clear();
1240    }
1241    if rules.unused_load_data_keys == Severity::Off {
1242        results.unused_load_data_keys.clear();
1243    }
1244}
1245
1246/// Apply base stale-suppression retention and clear framework findings whose
1247/// base rule is Off.
1248fn clear_base_suppression_and_framework(results: &mut AnalysisResults, rules: &RulesConfig) {
1249    results.stale_suppressions.retain(|s| {
1250        if s.missing_reason {
1251            rules.require_suppression_reason != Severity::Off
1252        } else {
1253            rules.stale_suppressions != Severity::Off
1254        }
1255    });
1256    if rules.invalid_client_export == Severity::Off {
1257        results.invalid_client_exports.clear();
1258    }
1259    if rules.mixed_client_server_barrel == Severity::Off {
1260        results.mixed_client_server_barrels.clear();
1261    }
1262    if rules.misplaced_directive == Severity::Off {
1263        results.misplaced_directives.clear();
1264    }
1265    if rules.route_collision == Severity::Off {
1266        results.route_collisions.clear();
1267    }
1268    if rules.dynamic_segment_name_conflict == Severity::Off {
1269        results.dynamic_segment_name_conflicts.clear();
1270    }
1271}
1272
1273fn apply_boundary_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
1274    results.boundary_violations.retain(|v| {
1275        config
1276            .resolve_rules_for_path(&v.violation.from_path)
1277            .boundary_violation
1278            != Severity::Off
1279    });
1280    results.boundary_coverage_violations.retain(|v| {
1281        config
1282            .resolve_rules_for_path(&v.violation.path)
1283            .boundary_violation
1284            != Severity::Off
1285    });
1286    results.boundary_call_violations.retain(|v| {
1287        config
1288            .resolve_rules_for_path(&v.violation.path)
1289            .boundary_violation
1290            != Severity::Off
1291    });
1292    results.policy_violations.retain(|v| {
1293        config
1294            .resolve_rules_for_path(&v.violation.path)
1295            .policy_violation
1296            != Severity::Off
1297    });
1298}
1299
1300#[cfg(test)]
1301#[path = "dead_code_tests.rs"]
1302mod tests;