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(crate) 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]
227fn 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]
233fn 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    if let Some(inventory) = &mut results.shared_state {
502        inventory.retain_sites(|site| any_under(&site.path));
503    }
504    let pkg_jsons = ws_roots
505        .iter()
506        .map(|root| root.join("package.json"))
507        .collect::<Vec<_>>();
508    let in_pkg_jsons = |path: &Path| pkg_jsons.iter().any(|pkg| path == pkg);
509
510    filter_workspace_source_findings(results, &any_under);
511    filter_workspace_dependency_findings(results, &any_under, &in_pkg_jsons);
512    filter_workspace_graph_findings(results, &any_under);
513    filter_workspace_policy_findings(results, &any_under);
514}
515
516/// The scope of one dead-code run, as the surface resolved it.
517///
518/// Every field is optional. A field that is `None` does not narrow the run.
519#[derive(Debug, Clone, Copy)]
520pub struct DeadCodeScope<'a> {
521    /// `--workspace`, `--changed-workspaces` and a positional path: the union
522    /// of these roots.
523    pub workspace_roots: Option<&'a [PathBuf]>,
524    /// The resolved change scope: a global changed-file set or the
525    /// configured package baselines.
526    pub changes: Option<&'a ChangeScope>,
527    /// A unified diff, with the root that finding paths resolve against.
528    pub diff: Option<(&'a fallow_output::DiffIndex, &'a Path)>,
529    /// `--file`: the only files to report. Dependency findings are dropped,
530    /// because a file list does not own a manifest.
531    pub files: Option<&'a FxHashSet<PathBuf>>,
532}
533
534/// Narrow dead-code results to the scope of the run.
535///
536/// The CLI, the programmatic API and the MCP typed path call this one function,
537/// so a scope narrows the same way on every surface. The filters run in this
538/// order: workspace roots, changed files, the diff, the file list. Then the
539/// configured `ignoreFindings` patterns run again, because the scope filters
540/// remove owners from a finding with several owners (`duplicate_exports`). A
541/// finding that only ignored owners hold after the scope is hidden, as the
542/// "hidden only when every owner matches" rule says.
543pub fn apply_scope(
544    results: &mut AnalysisResults,
545    scope: &DeadCodeScope<'_>,
546    config: &ResolvedConfig,
547) {
548    // Chain scopes depend on source-owned enforcement, which must resolve before filtering.
549    crate::effective_severity::apply_prop_drilling_severities(results, config);
550    if let Some(roots) = scope.workspace_roots {
551        filter_to_workspaces(results, roots);
552    }
553    if let Some(changes) = scope.changes {
554        changes.retain_dead_code(results);
555    }
556    if let Some((diff, root)) = scope.diff {
557        crate::diff_scope::filter_dead_code_by_diff(results, diff, root);
558    }
559    if let Some(files) = scope.files {
560        filter_by_changed_files(results, files);
561        clear_dependency_findings(results);
562    }
563    filter_configured_ignored_findings(results, config);
564}
565
566fn clear_dependency_findings(results: &mut AnalysisResults) {
567    results.unused_dependencies.clear();
568    results.unused_dev_dependencies.clear();
569    results.unused_optional_dependencies.clear();
570    results.type_only_dependencies.clear();
571    results.test_only_dependencies.clear();
572    results.dev_dependencies_in_production.clear();
573}
574
575/// Scope dead-code results to findings affected by changed files.
576#[expect(
577    clippy::implicit_hasher,
578    reason = "fallow standardizes on FxHashSet across the workspace"
579)]
580pub fn filter_by_changed_files(results: &mut AnalysisResults, changed_files: &FxHashSet<PathBuf>) {
581    crate::changed_files::filter_results_by_changed_files(results, changed_files);
582}
583
584/// Apply configured source-owned finding exclusions to an analysis result.
585///
586/// Analysis stages that append findings after the engine pipeline, such as
587/// type-aware reconciliation, must call this before exposing their final
588/// result.
589pub fn filter_configured_ignored_findings(results: &mut AnalysisResults, config: &ResolvedConfig) {
590    if config.ignore_findings.is_empty() {
591        return;
592    }
593
594    results.remove_ignored_dead_code_findings(|path| {
595        config.ignore_findings.is_ignored_path(&config.root, path)
596    });
597}
598
599fn filter_workspace_source_findings(
600    results: &mut AnalysisResults,
601    any_under: &dyn Fn(&Path) -> bool,
602) {
603    results
604        .unused_files
605        .retain(|finding| any_under(&finding.file.path));
606    results
607        .unused_exports
608        .retain(|finding| any_under(&finding.export.path));
609    results
610        .unused_types
611        .retain(|finding| any_under(&finding.export.path));
612    results
613        .private_type_leaks
614        .retain(|finding| any_under(&finding.leak.path));
615    results
616        .deprecated_exports_in_use
617        .retain(|finding| any_under(&finding.export.path));
618    results
619        .unused_enum_members
620        .retain(|finding| any_under(&finding.member.path));
621    results
622        .unused_class_members
623        .retain(|finding| any_under(&finding.member.path));
624    results
625        .unused_store_members
626        .retain(|finding| any_under(&finding.member.path));
627    results
628        .unused_namespace_members
629        .retain(|finding| any_under(&finding.member.path));
630    results
631        .unprovided_injects
632        .retain(|finding| any_under(&finding.inject.path));
633    results
634        .unrendered_components
635        .retain(|finding| any_under(&finding.component.path));
636    results
637        .unused_component_props
638        .retain(|finding| any_under(&finding.prop.path));
639    results
640        .absent_component_props
641        .retain(|finding| any_under(&finding.prop.path));
642    results
643        .constant_parameters
644        .retain(|finding| any_under(&finding.parameter.path));
645    results
646        .unused_component_emits
647        .retain(|finding| any_under(&finding.emit.path));
648    results
649        .unused_component_inputs
650        .retain(|finding| any_under(&finding.input.path));
651    results
652        .unused_component_outputs
653        .retain(|finding| any_under(&finding.output.path));
654    results
655        .unused_svelte_events
656        .retain(|finding| any_under(&finding.event.path));
657    results
658        .unused_effect_layers
659        .retain(|finding| any_under(&finding.layer.path));
660    results
661        .duplicate_export_aliases
662        .retain(|finding| any_under(&finding.alias.path));
663    results
664        .unused_tagged_errors
665        .retain(|finding| any_under(&finding.error.path));
666    results
667        .unproduced_catch_tags
668        .retain(|finding| any_under(&finding.catch_tag.path));
669    results
670        .unused_server_actions
671        .retain(|finding| any_under(&finding.action.path));
672    results
673        .unused_load_data_keys
674        .retain(|finding| any_under(&finding.key.path));
675    results
676        .unresolved_imports
677        .retain(|finding| any_under(&finding.import.path));
678}
679
680fn filter_workspace_dependency_findings(
681    results: &mut AnalysisResults,
682    any_under: &dyn Fn(&Path) -> bool,
683    in_pkg_jsons: &dyn Fn(&Path) -> bool,
684) {
685    results
686        .unused_dependencies
687        .retain(|finding| in_pkg_jsons(&finding.dep.path));
688    results
689        .unused_dev_dependencies
690        .retain(|finding| in_pkg_jsons(&finding.dep.path));
691    results
692        .unused_optional_dependencies
693        .retain(|finding| in_pkg_jsons(&finding.dep.path));
694    results
695        .type_only_dependencies
696        .retain(|finding| in_pkg_jsons(&finding.dep.path));
697    results
698        .test_only_dependencies
699        .retain(|finding| in_pkg_jsons(&finding.dep.path));
700    results
701        .dev_dependencies_in_production
702        .retain(|finding| in_pkg_jsons(&finding.dep.path));
703
704    results.unlisted_dependencies.retain(|finding| {
705        finding
706            .dep
707            .imported_from
708            .iter()
709            .any(|source| any_under(&source.path))
710    });
711    results.unlisted_binaries.retain(|finding| {
712        finding
713            .binary
714            .used_in
715            .iter()
716            .any(|site| any_under(&site.path))
717    });
718    results.unused_dependency_overrides.clear();
719    results.misconfigured_dependency_overrides.clear();
720}
721
722fn filter_workspace_graph_findings(
723    results: &mut AnalysisResults,
724    any_under: &dyn Fn(&Path) -> bool,
725) {
726    for duplicate in &mut results.duplicate_exports {
727        duplicate
728            .export
729            .locations
730            .retain(|location| any_under(&location.path));
731    }
732    results
733        .duplicate_exports
734        .retain(|duplicate| duplicate.export.locations.len() >= 2);
735
736    results
737        .circular_dependencies
738        .retain(|cycle| cycle.cycle.files.iter().any(|path| any_under(path)));
739
740    results
741        .re_export_cycles
742        .retain(|cycle| cycle.cycle.files.iter().any(|path| any_under(path)));
743
744    results
745        .package_cycles
746        .retain(|cycle| cycle.cycle.edges.iter().any(|edge| any_under(&edge.path)));
747}
748
749fn filter_workspace_policy_findings(
750    results: &mut AnalysisResults,
751    any_under: &dyn Fn(&Path) -> bool,
752) {
753    results
754        .boundary_violations
755        .retain(|finding| any_under(&finding.violation.from_path));
756    results
757        .boundary_coverage_violations
758        .retain(|finding| any_under(&finding.violation.path));
759    results
760        .boundary_call_violations
761        .retain(|finding| any_under(&finding.violation.path));
762    results
763        .policy_violations
764        .retain(|finding| any_under(&finding.violation.path));
765
766    results
767        .stale_suppressions
768        .retain(|finding| any_under(&finding.path));
769
770    results
771        .security_findings
772        .retain(|finding| any_under(&finding.path));
773    results
774        .security_unresolved_callee_diagnostics
775        .retain(|finding| any_under(&finding.path));
776
777    results.unused_catalog_entries.clear();
778    results.empty_catalog_groups.clear();
779    results
780        .unresolved_catalog_references
781        .retain(|finding| any_under(&finding.reference.path));
782
783    results
784        .invalid_client_exports
785        .retain(|finding| any_under(&finding.export.path));
786
787    results
788        .mixed_client_server_barrels
789        .retain(|finding| any_under(&finding.barrel.path));
790
791    results
792        .misplaced_directives
793        .retain(|finding| any_under(&finding.directive_site.path));
794
795    results
796        .route_collisions
797        .retain(|finding| any_under(&finding.collision.path));
798
799    results
800        .dynamic_segment_name_conflicts
801        .retain(|finding| any_under(&finding.conflict.path));
802}
803
804/// Remove findings whose effective severity is `Off` from an analysis result.
805///
806/// Every surface that reports findings runs this pass: the `check` command
807/// (which also serves `dead-code` and the CLI audit), the editor analysis path
808/// behind inline diagnostics and the sidebar, and the programmatic runtime
809/// behind the MCP tools, the decision surface and the Node bindings. Each of
810/// them runs it at the same two points, once over the freshly analyzed set and
811/// once after type-aware reconciliation, because reconciliation can append
812/// findings. The pass removes findings and writes the gate severity of each
813/// finding that stays, so the second run is idempotent when nothing was
814/// appended.
815///
816/// When overrides are configured, per-file rule resolution is used for
817/// file-scoped issue types. Circular dependencies resolve against every file in
818/// the cycle. Non-file-scoped issues (unused deps, unlisted deps, duplicate
819/// exports) use the base rules only.
820pub fn apply_rule_severities(results: &mut AnalysisResults, config: &ResolvedConfig) {
821    let rules = &config.rules;
822    let has_overrides = !config.overrides.is_empty();
823
824    if has_overrides {
825        apply_file_override_rules(results, config);
826        apply_boundary_override_rules(results, config);
827    } else {
828        apply_base_file_rules(results, rules);
829    }
830
831    apply_base_collection_rules(results, rules);
832    hide_cascade_findings(results, config);
833    apply_effective_severities(results, config);
834}
835
836/// Hide the export and member findings of unused files.
837///
838/// Deleting an unused file removes every unused export, unused type, unused
839/// class member and unused enum member in it, so these findings add no
840/// information to the report. The pass runs inside the rule pass, so every
841/// surface that reports findings hides the same set.
842///
843/// A finding is hidden only when the report lists its file in
844/// `unused_files`, or when an inline `fallow-ignore-file unused-file` comment
845/// suppressed that file. A scope, an issue-type selection without unused
846/// files, an `ignoreFindings` pattern or an `off` rule that removes the file
847/// from the report therefore hides nothing in that file. The issue-type
848/// filters clear the suppressed files too, so they must run before this pass.
849/// The baseline runs after this pass, so a baseline entry for the unused file
850/// does not make its findings visible again. `showCascade` keeps every
851/// finding.
852pub fn hide_cascade_findings(results: &mut AnalysisResults, config: &ResolvedConfig) {
853    if config.show_cascade {
854        return;
855    }
856    let reported = results.unused_files.iter().map(|f| &f.file.path);
857    let suppressed = results
858        .cascade
859        .suppressed_unused_files
860        .iter()
861        .filter(|path| config.resolve_rules_for_path(path).unused_files != Severity::Off);
862    let covered: FxHashSet<PathBuf> = reported.chain(suppressed).cloned().collect();
863    if covered.is_empty() {
864        return;
865    }
866    results.hide_cascade_findings(&|path| covered.contains(path));
867}
868
869fn apply_base_collection_rules(results: &mut AnalysisResults, rules: &RulesConfig) {
870    if rules.unused_dependencies == Severity::Off {
871        results.unused_dependencies.clear();
872    }
873    if rules.unused_dev_dependencies == Severity::Off {
874        results.unused_dev_dependencies.clear();
875    }
876    if rules.unused_optional_dependencies == Severity::Off {
877        results.unused_optional_dependencies.clear();
878    }
879    if rules.unlisted_dependencies == Severity::Off {
880        results.unlisted_dependencies.clear();
881    }
882    if rules.unlisted_binaries == Severity::Off {
883        results.unlisted_binaries.clear();
884    }
885    if rules.duplicate_exports == Severity::Off {
886        results.duplicate_exports.clear();
887    }
888    if rules.duplicate_export_aliases == Severity::Off {
889        results.duplicate_export_aliases.clear();
890    }
891    if rules.type_only_dependencies == Severity::Off {
892        results.type_only_dependencies.clear();
893    }
894    if rules.test_only_dependencies == Severity::Off {
895        results.test_only_dependencies.clear();
896    }
897    if rules.dev_dependencies_in_production == Severity::Off {
898        results.dev_dependencies_in_production.clear();
899    }
900    if rules.circular_dependencies == Severity::Off {
901        results.circular_dependencies.clear();
902    }
903    if rules.re_export_cycle == Severity::Off {
904        results.re_export_cycles.clear();
905    }
906    if rules.package_cycle == Severity::Off {
907        results.package_cycles.clear();
908    }
909    if rules.boundary_violation == Severity::Off {
910        results.boundary_violations.clear();
911        results.boundary_coverage_violations.clear();
912        results.boundary_call_violations.clear();
913    }
914    if rules.policy_violation == Severity::Off {
915        results.policy_violations.clear();
916    }
917    if rules.unused_catalog_entries == Severity::Off {
918        results.unused_catalog_entries.clear();
919    }
920    if rules.empty_catalog_groups == Severity::Off {
921        results.empty_catalog_groups.clear();
922    }
923    if rules.unresolved_catalog_references == Severity::Off {
924        results.unresolved_catalog_references.clear();
925    }
926    if rules.unused_dependency_overrides == Severity::Off {
927        results.unused_dependency_overrides.clear();
928    }
929    if rules.misconfigured_dependency_overrides == Severity::Off {
930        results.misconfigured_dependency_overrides.clear();
931    }
932}
933
934fn apply_file_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
935    apply_dead_code_override_rules(results, config);
936    apply_catalog_override_rules(results, config);
937    apply_framework_override_rules(results, config);
938    apply_circular_override_rules(results, config);
939}
940
941fn apply_dead_code_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
942    apply_core_dead_code_override_rules(results, config);
943    apply_component_dead_code_override_rules(results, config);
944}
945
946/// Retain core (non-component) dead-code findings whose per-file rule is not Off.
947fn apply_core_dead_code_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
948    results
949        .unused_files
950        .retain(|f| config.resolve_rules_for_path(&f.file.path).unused_files != Severity::Off);
951    results
952        .unused_exports
953        .retain(|e| config.resolve_rules_for_path(&e.export.path).unused_exports != Severity::Off);
954    results
955        .unused_types
956        .retain(|e| config.resolve_rules_for_path(&e.export.path).unused_types != Severity::Off);
957    results.private_type_leaks.retain(|e| {
958        config
959            .resolve_rules_for_path(&e.leak.path)
960            .private_type_leaks
961            != Severity::Off
962    });
963    results.deprecated_exports_in_use.retain(|e| {
964        config
965            .resolve_rules_for_path(&e.export.path)
966            .deprecated_exports_in_use
967            != Severity::Off
968    });
969    results.unused_enum_members.retain(|m| {
970        config
971            .resolve_rules_for_path(&m.member.path)
972            .unused_enum_members
973            != Severity::Off
974    });
975    results.unused_class_members.retain(|m| {
976        config
977            .resolve_rules_for_path(&m.member.path)
978            .unused_class_members
979            != Severity::Off
980    });
981    results.unused_store_members.retain(|m| {
982        config
983            .resolve_rules_for_path(&m.member.path)
984            .unused_store_members
985            != Severity::Off
986    });
987    results.unused_namespace_members.retain(|m| {
988        config
989            .resolve_rules_for_path(&m.member.path)
990            .unused_namespace_members
991            != Severity::Off
992    });
993    results.unprovided_injects.retain(|f| {
994        config
995            .resolve_rules_for_path(&f.inject.path)
996            .unprovided_injects
997            != Severity::Off
998    });
999    results.unresolved_imports.retain(|i| {
1000        config
1001            .resolve_rules_for_path(&i.import.path)
1002            .unresolved_imports
1003            != Severity::Off
1004    });
1005}
1006
1007/// Retain component-shaped dead-code findings whose per-file rule is not Off.
1008fn apply_component_dead_code_override_rules(
1009    results: &mut AnalysisResults,
1010    config: &ResolvedConfig,
1011) {
1012    results.unrendered_components.retain(|c| {
1013        config
1014            .resolve_rules_for_path(&c.component.path)
1015            .unrendered_components
1016            != Severity::Off
1017    });
1018    results.unused_component_props.retain(|p| {
1019        config
1020            .resolve_rules_for_path(&p.prop.path)
1021            .unused_component_props
1022            != Severity::Off
1023    });
1024    results.absent_component_props.retain(|p| {
1025        config
1026            .resolve_rules_for_path(&p.prop.path)
1027            .absent_component_props
1028            != Severity::Off
1029    });
1030    results.constant_parameters.retain(|p| {
1031        config
1032            .resolve_rules_for_path(&p.parameter.path)
1033            .constant_parameters
1034            != Severity::Off
1035    });
1036    results.unused_component_emits.retain(|e| {
1037        config
1038            .resolve_rules_for_path(&e.emit.path)
1039            .unused_component_emits
1040            != Severity::Off
1041    });
1042    results.unused_component_inputs.retain(|i| {
1043        config
1044            .resolve_rules_for_path(&i.input.path)
1045            .unused_component_inputs
1046            != Severity::Off
1047    });
1048    results.unused_component_outputs.retain(|o| {
1049        config
1050            .resolve_rules_for_path(&o.output.path)
1051            .unused_component_outputs
1052            != Severity::Off
1053    });
1054    results.unused_svelte_events.retain(|e| {
1055        config
1056            .resolve_rules_for_path(&e.event.path)
1057            .unused_svelte_events
1058            != Severity::Off
1059    });
1060    results.unused_effect_layers.retain(|e| {
1061        config
1062            .resolve_rules_for_path(&e.layer.path)
1063            .unused_effect_layers
1064            != Severity::Off
1065    });
1066    results.duplicate_export_aliases.retain(|finding| {
1067        config
1068            .resolve_rules_for_path(&finding.alias.path)
1069            .duplicate_export_aliases
1070            != Severity::Off
1071    });
1072    results.unused_tagged_errors.retain(|e| {
1073        config
1074            .resolve_rules_for_path(&e.error.path)
1075            .unused_tagged_errors
1076            != Severity::Off
1077    });
1078    results.unproduced_catch_tags.retain(|e| {
1079        config
1080            .resolve_rules_for_path(&e.catch_tag.path)
1081            .unproduced_catch_tags
1082            != Severity::Off
1083    });
1084    results.unused_server_actions.retain(|a| {
1085        config
1086            .resolve_rules_for_path(&a.action.path)
1087            .unused_server_actions
1088            != Severity::Off
1089    });
1090    results.unused_load_data_keys.retain(|k| {
1091        config
1092            .resolve_rules_for_path(&k.key.path)
1093            .unused_load_data_keys
1094            != Severity::Off
1095    });
1096}
1097
1098fn apply_catalog_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
1099    results.stale_suppressions.retain(|s| {
1100        let rules = config.resolve_rules_for_path(&s.path);
1101        if s.missing_reason {
1102            rules.require_suppression_reason != Severity::Off
1103        } else {
1104            rules.stale_suppressions != Severity::Off
1105        }
1106    });
1107    results.unresolved_catalog_references.retain(|r| {
1108        config
1109            .resolve_rules_for_path(&r.reference.path)
1110            .unresolved_catalog_references
1111            != Severity::Off
1112    });
1113    results.empty_catalog_groups.retain(|g| {
1114        config
1115            .resolve_rules_for_path(&g.group.path)
1116            .empty_catalog_groups
1117            != Severity::Off
1118    });
1119    results.unused_dependency_overrides.retain(|o| {
1120        config
1121            .resolve_rules_for_path(&o.entry.path)
1122            .unused_dependency_overrides
1123            != Severity::Off
1124    });
1125    results.misconfigured_dependency_overrides.retain(|o| {
1126        config
1127            .resolve_rules_for_path(&o.entry.path)
1128            .misconfigured_dependency_overrides
1129            != Severity::Off
1130    });
1131}
1132
1133fn apply_framework_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
1134    results.invalid_client_exports.retain(|e| {
1135        config
1136            .resolve_rules_for_path(&e.export.path)
1137            .invalid_client_export
1138            != Severity::Off
1139    });
1140    results.mixed_client_server_barrels.retain(|b| {
1141        config
1142            .resolve_rules_for_path(&b.barrel.path)
1143            .mixed_client_server_barrel
1144            != Severity::Off
1145    });
1146    results.misplaced_directives.retain(|d| {
1147        config
1148            .resolve_rules_for_path(&d.directive_site.path)
1149            .misplaced_directive
1150            != Severity::Off
1151    });
1152    results.route_collisions.retain(|c| {
1153        config
1154            .resolve_rules_for_path(&c.collision.path)
1155            .route_collision
1156            != Severity::Off
1157    });
1158    results.dynamic_segment_name_conflicts.retain(|c| {
1159        config
1160            .resolve_rules_for_path(&c.conflict.path)
1161            .dynamic_segment_name_conflict
1162            != Severity::Off
1163    });
1164}
1165
1166fn apply_circular_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
1167    results.circular_dependencies.retain(|c| {
1168        c.cycle
1169            .files
1170            .iter()
1171            .any(|path| config.resolve_rules_for_path(path).circular_dependencies != Severity::Off)
1172    });
1173}
1174
1175fn apply_base_file_rules(results: &mut AnalysisResults, rules: &RulesConfig) {
1176    clear_base_core_dead_code(results, rules);
1177    clear_base_component_dead_code(results, rules);
1178    clear_base_suppression_and_framework(results, rules);
1179}
1180
1181/// Clear core (non-component) dead-code findings whose base rule is Off.
1182fn clear_base_core_dead_code(results: &mut AnalysisResults, rules: &RulesConfig) {
1183    if rules.unused_files == Severity::Off {
1184        results.unused_files.clear();
1185    }
1186    if rules.unused_exports == Severity::Off {
1187        results.unused_exports.clear();
1188    }
1189    if rules.unused_types == Severity::Off {
1190        results.unused_types.clear();
1191    }
1192    if rules.private_type_leaks == Severity::Off {
1193        results.private_type_leaks.clear();
1194    }
1195    if rules.deprecated_exports_in_use == Severity::Off {
1196        results.deprecated_exports_in_use.clear();
1197    }
1198    if rules.unused_enum_members == Severity::Off {
1199        results.unused_enum_members.clear();
1200    }
1201    if rules.unused_class_members == Severity::Off {
1202        results.unused_class_members.clear();
1203    }
1204    if rules.unused_store_members == Severity::Off {
1205        results.unused_store_members.clear();
1206    }
1207    if rules.unused_namespace_members == Severity::Off {
1208        results.unused_namespace_members.clear();
1209    }
1210    if rules.unprovided_injects == Severity::Off {
1211        results.unprovided_injects.clear();
1212    }
1213    if rules.unresolved_imports == Severity::Off {
1214        results.unresolved_imports.clear();
1215    }
1216}
1217
1218/// Clear component-shaped dead-code findings whose base rule is Off.
1219fn clear_base_component_dead_code(results: &mut AnalysisResults, rules: &RulesConfig) {
1220    if rules.unrendered_components == Severity::Off {
1221        results.unrendered_components.clear();
1222    }
1223    if rules.unused_component_props == Severity::Off {
1224        results.unused_component_props.clear();
1225    }
1226    if rules.absent_component_props == Severity::Off {
1227        results.absent_component_props.clear();
1228    }
1229    if rules.constant_parameters == Severity::Off {
1230        results.constant_parameters.clear();
1231    }
1232    if rules.unused_component_emits == Severity::Off {
1233        results.unused_component_emits.clear();
1234    }
1235    if rules.unused_component_inputs == Severity::Off {
1236        results.unused_component_inputs.clear();
1237    }
1238    if rules.unused_component_outputs == Severity::Off {
1239        results.unused_component_outputs.clear();
1240    }
1241    if rules.unused_svelte_events == Severity::Off {
1242        results.unused_svelte_events.clear();
1243    }
1244    if rules.unused_effect_layers == Severity::Off {
1245        results.unused_effect_layers.clear();
1246    }
1247    if rules.unused_tagged_errors == Severity::Off {
1248        results.unused_tagged_errors.clear();
1249    }
1250    if rules.unproduced_catch_tags == Severity::Off {
1251        results.unproduced_catch_tags.clear();
1252    }
1253    if rules.unused_server_actions == Severity::Off {
1254        results.unused_server_actions.clear();
1255    }
1256    if rules.unused_load_data_keys == Severity::Off {
1257        results.unused_load_data_keys.clear();
1258    }
1259}
1260
1261/// Apply base stale-suppression retention and clear framework findings whose
1262/// base rule is Off.
1263fn clear_base_suppression_and_framework(results: &mut AnalysisResults, rules: &RulesConfig) {
1264    results.stale_suppressions.retain(|s| {
1265        if s.missing_reason {
1266            rules.require_suppression_reason != Severity::Off
1267        } else {
1268            rules.stale_suppressions != Severity::Off
1269        }
1270    });
1271    if rules.invalid_client_export == Severity::Off {
1272        results.invalid_client_exports.clear();
1273    }
1274    if rules.mixed_client_server_barrel == Severity::Off {
1275        results.mixed_client_server_barrels.clear();
1276    }
1277    if rules.misplaced_directive == Severity::Off {
1278        results.misplaced_directives.clear();
1279    }
1280    if rules.route_collision == Severity::Off {
1281        results.route_collisions.clear();
1282    }
1283    if rules.dynamic_segment_name_conflict == Severity::Off {
1284        results.dynamic_segment_name_conflicts.clear();
1285    }
1286}
1287
1288fn apply_boundary_override_rules(results: &mut AnalysisResults, config: &ResolvedConfig) {
1289    results.boundary_violations.retain(|v| {
1290        config
1291            .resolve_rules_for_path(&v.violation.from_path)
1292            .boundary_violation
1293            != Severity::Off
1294    });
1295    results.boundary_coverage_violations.retain(|v| {
1296        config
1297            .resolve_rules_for_path(&v.violation.path)
1298            .boundary_violation
1299            != Severity::Off
1300    });
1301    results.boundary_call_violations.retain(|v| {
1302        config
1303            .resolve_rules_for_path(&v.violation.path)
1304            .boundary_violation
1305            != Severity::Off
1306    });
1307    results.policy_violations.retain(|v| {
1308        config
1309            .resolve_rules_for_path(&v.violation.path)
1310            .policy_violation
1311            != Severity::Off
1312    });
1313}
1314
1315#[cfg(test)]
1316#[path = "dead_code_tests.rs"]
1317mod tests;