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