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