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