Skip to main content

fallow_api/runtime/
dead_code.rs

1use std::path::Path;
2use std::time::Instant;
3
4use fallow_config::{PlannedAnalysis, ResolvedConfig};
5use fallow_engine::{
6    change_scope::ChangeScope, dead_code::DeadCodeAnalysisArtifacts, session::AnalysisSession,
7};
8use fallow_output::{
9    CheckEnvelope, CheckOutputInput, DeadCodeNextStepsInput, architecture_meta, build_check_output,
10    build_dead_code_next_steps, check_meta,
11};
12use fallow_types::path_util::is_absolute_path_any_platform;
13use fallow_types::results::AnalysisResults;
14use rustc_hash::FxHashSet;
15
16use crate::{
17    AnalysisOptions, ArchitectureOptions, ArchitectureProgrammaticOutput,
18    BoundaryViolationsProgrammaticOutput, CircularDependenciesProgrammaticOutput, DeadCodeFilters,
19    DeadCodeOptions, DeadCodeProgrammaticOutput, ProgrammaticError,
20    analysis_context::{
21        ProgrammaticAnalysisContext, changed_files_for_run, resolve_programmatic_analysis_context,
22        workspace_roots_for_session,
23    },
24    next_steps::{
25        audit_changed_applicable, default_workspace_ref_for_workspaces, setup_pointer_applicable,
26        suggestions_enabled,
27    },
28    run::{ProgrammaticEntry, ResolvedRun, RouteSettings, resolve_route_run},
29};
30
31use super::ProgrammaticResult;
32
33pub(super) struct DeadCodeProgrammaticRunWithArtifacts {
34    pub output: DeadCodeProgrammaticOutput,
35    pub artifacts: DeadCodeAnalysisArtifacts,
36}
37
38/// Run dead-code analysis and return typed API output before serialization.
39///
40/// # Errors
41///
42/// Returns a structured programmatic error for unsupported options, invalid
43/// options, config load failures, analysis failures, or git changed-file
44/// failures. When the environment or `typeAware.enabled` turns on type-aware
45/// analysis that the options leave off, it returns
46/// [`super::TYPE_AWARE_CONFIG_UNSUPPORTED`].
47pub fn run_dead_code(options: &DeadCodeOptions) -> ProgrammaticResult<DeadCodeProgrammaticOutput> {
48    run_dead_code_with_baseline(options, None)
49}
50
51/// Run dead-code analysis and hide the findings of a saved dead-code baseline.
52///
53/// The baseline is the file that `fallow dead-code --save-baseline` writes. It
54/// is applied by the same engine function as `fallow dead-code --baseline`, so
55/// both hide the same findings. A file that another command saved suppresses
56/// nothing, as on the CLI.
57///
58/// # Errors
59///
60/// Returns the errors of [`run_dead_code`], and a structured error when the
61/// baseline cannot be read, is not valid, or was saved with an incompatible
62/// analysis identity.
63pub fn run_dead_code_with_baseline(
64    options: &DeadCodeOptions,
65    baseline: Option<&Path>,
66) -> ProgrammaticResult<DeadCodeProgrammaticOutput> {
67    let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
68    resolved.install(|| {
69        resolved.ensure_not_cancelled("config load and file discovery")?;
70        let run = resolve_dead_code_run_refusing_type_aware(options, &resolved)?;
71        run_dead_code_in_context(options, baseline, &resolved, &run)
72    })
73}
74
75/// The run of a dead-code route, with the `include_entry_exports` option of
76/// `options`.
77pub(super) fn resolve_dead_code_run(
78    options: &DeadCodeOptions,
79    entry: &ProgrammaticEntry,
80) -> ProgrammaticResult<ResolvedRun> {
81    resolve_route_run(
82        &options.analysis,
83        entry,
84        RouteSettings {
85            include_entry_exports: options.include_entry_exports,
86            audit_base: None,
87        },
88    )
89}
90
91/// The run of a dead-code route. `fallow dead-code` turns type-aware analysis
92/// on from the environment and `typeAware.enabled`. The typed route runs it
93/// only on request, see [`super::TYPE_AWARE_CONFIG_UNSUPPORTED`].
94fn resolve_dead_code_run_refusing_type_aware(
95    options: &DeadCodeOptions,
96    resolved: &ProgrammaticAnalysisContext,
97) -> ProgrammaticResult<ResolvedRun> {
98    super::type_aware_config::resolve_run_refusing_type_aware(
99        &options.analysis,
100        super::type_aware_config::TypeAwareCommand::Analysis,
101        super::type_aware_config::ConfigLocation::of(resolved),
102        || resolve_dead_code_run(options, &ProgrammaticEntry::DeadCode),
103    )
104}
105
106/// Run dead-code analysis in a context and a run that the caller resolved.
107/// Audit uses this to hand the change scope of every section to itself.
108pub(super) fn run_dead_code_in_context(
109    options: &DeadCodeOptions,
110    baseline: Option<&Path>,
111    resolved: &ProgrammaticAnalysisContext,
112    run: &ResolvedRun,
113) -> ProgrammaticResult<DeadCodeProgrammaticOutput> {
114    resolved.install(|| {
115        let start = Instant::now();
116        resolved.ensure_not_cancelled("config load and file discovery")?;
117        let finding_ids = parse_finding_ids(options)?;
118        let session = load_dead_code_session(options, resolved, run)?;
119        resolve_package_map_before_analysis(resolved, &session)?;
120        let (mut results, finished) =
121            analyze_dead_code_results(options, resolved, &session, finding_ids)?;
122        let FinishedDeadCode {
123            type_aware_meta,
124            mut finding_id_trace,
125            change_reason,
126            package_baselines,
127        } = finished;
128        if let Some(trace) = finding_id_trace.as_mut() {
129            trace.start_stage(&mut results);
130        }
131        let install_state = match baseline {
132            Some(baseline) => apply_baseline(
133                &mut results,
134                baseline,
135                session.root(),
136                type_aware_meta.as_ref(),
137            )?,
138            None => None,
139        };
140        let finding_id_query = finding_id_trace.map(|mut trace| {
141            trace.end_stage(&mut results);
142            trace.finish(
143                &mut results,
144                session.config(),
145                finding_id_run_reasons(
146                    options,
147                    resolved,
148                    &session,
149                    RunScope {
150                        change_reason,
151                        baseline: baseline.is_some(),
152                    },
153                ),
154            )
155        });
156        let mut output = build_dead_code_programmatic_output(
157            options,
158            resolved,
159            &session,
160            DeadCodeReport {
161                results,
162                type_aware_meta,
163                package_baselines,
164            },
165            start,
166            CheckEnvelope::DeadCode,
167        );
168        output.output.finding_id_query = finding_id_query;
169        output.output.workspace_diagnostics.extend(install_state);
170        Ok(output)
171    })
172}
173
174/// Validate `finding_ids`. A malformed id is an error, so a typo never reads
175/// as "the finding is gone".
176fn parse_finding_ids(
177    options: &DeadCodeOptions,
178) -> ProgrammaticResult<Option<fallow_engine::dead_code::FindingIdFilter>> {
179    if options.filters.shared_state {
180        reject_finding_ids(options)?;
181    }
182    fallow_engine::dead_code::FindingIdFilter::parse(&options.finding_ids).map_err(|message| {
183        ProgrammaticError::new(message, 2)
184            .with_code("FALLOW_INVALID_FINDING_ID")
185            .with_context("findingIds")
186    })
187}
188
189/// Refuse `finding_ids` on the analyses that narrow the result to one issue
190/// family: a missing id there says nothing about the other families.
191fn reject_finding_ids(options: &DeadCodeOptions) -> ProgrammaticResult<()> {
192    if options.finding_ids.is_empty() {
193        return Ok(());
194    }
195    Err(
196        ProgrammaticError::new("findingIds is supported only by the dead-code analysis", 2)
197            .with_code("FALLOW_UNSUPPORTED_OPTION")
198            .with_context("findingIds"),
199    )
200}
201
202/// The run facts that finding-id reasons read beyond the options.
203#[derive(Clone, Copy)]
204struct RunScope {
205    /// The change channel that narrowed the run: a global ref or the package
206    /// map.
207    change_reason: Option<fallow_output::ScopeReason>,
208    /// A saved baseline hid findings.
209    baseline: bool,
210}
211
212/// The options of this run that can hide a finding without a fix. Mirrors the
213/// CLI list: the scope channels, the issue-type filters, production mode and
214/// the baseline.
215fn finding_id_run_reasons(
216    options: &DeadCodeOptions,
217    resolved: &ProgrammaticAnalysisContext,
218    session: &AnalysisSession,
219    run: RunScope,
220) -> Vec<fallow_output::FindingIdQueryReason> {
221    use fallow_output::FindingIdQueryReason as Reason;
222
223    [
224        (resolved.diff.is_some(), Reason::Diff),
225        (
226            run.change_reason == Some(fallow_output::ScopeReason::ChangedSince)
227                || options.analysis.ambient_changed_since.is_some(),
228            Reason::ChangedSince,
229        ),
230        (
231            run.change_reason == Some(fallow_output::ScopeReason::PackageBaselines),
232            Reason::PackageBaselines,
233        ),
234        (resolved.workspace().is_some(), Reason::Workspace),
235        (
236            resolved.changed_workspaces().is_some(),
237            Reason::ChangedWorkspaces,
238        ),
239        (!options.files.is_empty(), Reason::File),
240        (options.filters.any_active(), Reason::IssueTypeFilter),
241        (session.config().production, Reason::Production),
242        (
243            session.config().include_entry_exports,
244            Reason::IncludeEntryExports,
245        ),
246        (run.baseline, Reason::Baseline),
247    ]
248    .into_iter()
249    .filter_map(|(active, reason)| active.then_some(reason))
250    .collect()
251}
252
253/// Turn an engine failure into a programmatic error, keeping a cancelled run
254/// distinguishable from a failed one.
255///
256/// The engine's cancellation message already names the pipeline boundary the
257/// run stopped at, so it is carried through rather than replaced.
258pub(super) fn map_engine_error(
259    err: &fallow_engine::EngineError,
260    failure_message: &str,
261    failure_code: &'static str,
262    context: &'static str,
263) -> ProgrammaticError {
264    if err.is_cancelled() {
265        return crate::analysis_context::cancelled_error_message(err.message())
266            .with_context(context);
267    }
268    ProgrammaticError::new(format!("{failure_message}: {err}"), 2)
269        .with_code(failure_code)
270        .with_context(context)
271}
272
273/// Run circular-dependency analysis and return typed API output before JSON.
274///
275/// # Errors
276///
277/// Returns the same structured errors as [`run_dead_code`].
278pub fn run_circular_dependencies(
279    options: &DeadCodeOptions,
280) -> ProgrammaticResult<CircularDependenciesProgrammaticOutput> {
281    reject_finding_ids(options)?;
282    let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
283    resolved.install(|| {
284        run_dead_code_inner(options, &resolved, keep_circular_dependencies).map(Into::into)
285    })
286}
287
288/// Run the analysis of `fallow architecture` and return typed API output
289/// before JSON: import cycles, boundary violations and rule-pack policy
290/// violations.
291///
292/// The selectors keep one kind each, and no selector keeps all of them, as on
293/// the CLI. The output is the dead-code envelope with the `architecture`
294/// schema version, the architecture `_meta` and next steps that name
295/// `fallow architecture`.
296///
297/// # Errors
298///
299/// Returns the same structured errors as [`run_dead_code`].
300pub fn run_architecture(
301    options: &ArchitectureOptions,
302) -> ProgrammaticResult<ArchitectureProgrammaticOutput> {
303    let dead_code = options.dead_code_options();
304    let resolved = resolve_programmatic_analysis_context(&dead_code.analysis)?;
305    resolved.install(|| {
306        let start = Instant::now();
307        resolved.ensure_not_cancelled("config load and file discovery")?;
308        let run = resolve_dead_code_run(&dead_code, &ProgrammaticEntry::DeadCode)?;
309        let session = load_dead_code_session(&dead_code, &resolved, &run)?;
310        resolve_package_map_before_analysis(&resolved, &session)?;
311        let mut output = run_dead_code_with_changed_files(
312            &dead_code,
313            &resolved,
314            &session,
315            SessionRun {
316                changed_files: None,
317                start,
318                envelope: CheckEnvelope::Architecture,
319            },
320            |_| {},
321        )?;
322        output.output.workspace_diagnostics = fallow_types::workspace::merge_workspace_diagnostics(
323            std::mem::take(&mut output.output.workspace_diagnostics),
324            fallow_engine::requested_rule_off::requested_rule_off_diagnostics(
325                session.config(),
326                &options.requested_flags(),
327                true,
328            ),
329        );
330        Ok(output.into())
331    })
332}
333
334/// Run boundary-family analysis and return typed API output before JSON.
335///
336/// # Errors
337///
338/// Returns the same structured errors as [`run_dead_code`].
339pub fn run_boundary_violations(
340    options: &DeadCodeOptions,
341) -> ProgrammaticResult<BoundaryViolationsProgrammaticOutput> {
342    reject_finding_ids(options)?;
343    let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
344    resolved.install(|| {
345        run_dead_code_inner(options, &resolved, keep_boundary_violations).map(Into::into)
346    })
347}
348
349fn run_dead_code_inner(
350    options: &DeadCodeOptions,
351    resolved: &ProgrammaticAnalysisContext,
352    post_filter: impl FnOnce(&mut AnalysisResults),
353) -> ProgrammaticResult<DeadCodeProgrammaticOutput> {
354    let start = Instant::now();
355    resolved.ensure_not_cancelled("config load and file discovery")?;
356    let run = resolve_dead_code_run_refusing_type_aware(options, resolved)?;
357    let session = load_dead_code_session(options, resolved, &run)?;
358    resolve_package_map_before_analysis(resolved, &session)?;
359    run_dead_code_with_session(options, resolved, &session, None, post_filter, start)
360}
361
362pub(super) fn run_dead_code_with_session(
363    options: &DeadCodeOptions,
364    resolved: &ProgrammaticAnalysisContext,
365    session: &AnalysisSession,
366    changed_files: Option<&FxHashSet<std::path::PathBuf>>,
367    post_filter: impl FnOnce(&mut AnalysisResults),
368    start: Instant,
369) -> ProgrammaticResult<DeadCodeProgrammaticOutput> {
370    run_dead_code_with_changed_files(
371        options,
372        resolved,
373        session,
374        SessionRun {
375            changed_files,
376            start,
377            envelope: CheckEnvelope::DeadCode,
378        },
379        post_filter,
380    )
381}
382
383/// The run facts of one session run that are not options: the changed-file
384/// set, the start time, and the member of the dead-code family that writes
385/// the output.
386#[derive(Clone, Copy)]
387struct SessionRun<'a> {
388    changed_files: Option<&'a FxHashSet<std::path::PathBuf>>,
389    start: Instant,
390    envelope: CheckEnvelope,
391}
392
393fn run_dead_code_with_changed_files(
394    options: &DeadCodeOptions,
395    resolved: &ProgrammaticAnalysisContext,
396    session: &AnalysisSession,
397    run: SessionRun<'_>,
398    post_filter: impl FnOnce(&mut AnalysisResults),
399) -> ProgrammaticResult<DeadCodeProgrammaticOutput> {
400    let SessionRun {
401        changed_files,
402        start,
403        envelope,
404    } = run;
405    resolved.ensure_not_cancelled("dead-code analysis")?;
406    let mut results = analyze_session_dead_code(session)?;
407    let unfiltered_unused_files = results.unused_files.clone();
408    let finished = finish_dead_code_results(
409        DeadCodeReportInputs {
410            options,
411            resolved,
412            session,
413            changed_files,
414            unfiltered_unused_files,
415            finding_ids: None,
416        },
417        &mut results,
418        post_filter,
419    )?;
420    Ok(build_dead_code_programmatic_output(
421        options,
422        resolved,
423        session,
424        finished.into_report(results),
425        start,
426        envelope,
427    ))
428}
429
430/// The reported dead-code findings of one session run and what the reporting
431/// tail learned about them.
432fn analyze_dead_code_results(
433    options: &DeadCodeOptions,
434    resolved: &ProgrammaticAnalysisContext,
435    session: &AnalysisSession,
436    finding_ids: Option<fallow_engine::dead_code::FindingIdFilter>,
437) -> ProgrammaticResult<(AnalysisResults, FinishedDeadCode)> {
438    resolved.ensure_not_cancelled("dead-code analysis")?;
439    let mut results = analyze_session_dead_code(session)?;
440    let unfiltered_unused_files = results.unused_files.clone();
441
442    let finished = finish_dead_code_results(
443        DeadCodeReportInputs {
444            options,
445            resolved,
446            session,
447            changed_files: None,
448            unfiltered_unused_files,
449            finding_ids,
450        },
451        &mut results,
452        |_| {},
453    )?;
454    Ok((results, finished))
455}
456
457fn analyze_session_dead_code(session: &AnalysisSession) -> ProgrammaticResult<AnalysisResults> {
458    session
459        .analyze_dead_code()
460        .map(|analysis| analysis.results)
461        .map_err(|err| {
462            map_engine_error(
463                &err,
464                "dead-code analysis failed",
465                "FALLOW_DEAD_CODE_FAILED",
466                "dead-code",
467            )
468        })
469}
470
471/// Hide the findings of a saved dead-code baseline, as `--baseline` does.
472///
473/// Returns the `baseline-install-state-mismatch` diagnostic when the baseline
474/// was saved in another install state than this run.
475fn apply_baseline(
476    results: &mut AnalysisResults,
477    baseline: &Path,
478    root: &Path,
479    type_aware_meta: Option<&fallow_types::envelope::TypeAwareMeta>,
480) -> ProgrammaticResult<Option<fallow_types::workspace::WorkspaceDiagnostic>> {
481    use fallow_engine::baseline::{DeadCodeBaselineError, apply_dead_code_baseline};
482
483    let path = if is_absolute_path_any_platform(baseline) {
484        baseline.to_path_buf()
485    } else {
486        root.join(baseline)
487    };
488    let content = std::fs::read_to_string(&path).map_err(|err| {
489        ProgrammaticError::new(
490            format!("failed to read baseline {}: {err}", path.display()),
491            2,
492        )
493        .with_code("FALLOW_BASELINE_READ_FAILED")
494        .with_context("baseline")
495    })?;
496    let identity = type_aware_meta
497        .and_then(|meta| meta.identity.clone())
498        .unwrap_or_default();
499    let run_state = fallow_config::node_modules_state(root);
500    apply_dead_code_baseline(results, &content, root, &identity, false)
501        .map(|_| {
502            fallow_engine::baseline::install_state_diagnostic(root, &path, &content, run_state)
503        })
504        .map_err(|err| match err {
505            DeadCodeBaselineError::Parse(message) => ProgrammaticError::new(
506                format!("failed to parse baseline {}: {message}", path.display()),
507                2,
508            )
509            .with_code("FALLOW_BASELINE_INVALID")
510            .with_context("baseline"),
511            DeadCodeBaselineError::IncompatibleIdentity(fields) => ProgrammaticError::new(
512                format!(
513                    "baseline analysis identity is incompatible in: {}. Save it again with the same analysis options",
514                    fields.join(", ")
515                ),
516                2,
517            )
518            .with_code("FALLOW_BASELINE_IDENTITY_INCOMPATIBLE")
519            .with_context("baseline"),
520        })
521}
522
523pub(super) fn run_dead_code_with_session_artifacts(
524    options: &DeadCodeOptions,
525    resolved: &ProgrammaticAnalysisContext,
526    session: &AnalysisSession,
527    changed_files: Option<&FxHashSet<std::path::PathBuf>>,
528    post_filter: impl FnOnce(&mut AnalysisResults),
529    start: Instant,
530) -> ProgrammaticResult<DeadCodeProgrammaticRunWithArtifacts> {
531    resolved.ensure_not_cancelled("dead-code analysis")?;
532    let mut artifacts = session
533        .analyze_dead_code_with_artifacts(true, true)
534        .map_err(|err| {
535            map_engine_error(
536                &err,
537                "dead-code analysis failed",
538                "FALLOW_DEAD_CODE_FAILED",
539                "dead-code",
540            )
541        })?;
542    let unfiltered_unused_files = artifacts.results.unused_files.clone();
543
544    let finished = finish_dead_code_results(
545        DeadCodeReportInputs {
546            options,
547            resolved,
548            session,
549            changed_files,
550            unfiltered_unused_files,
551            finding_ids: None,
552        },
553        &mut artifacts.results,
554        post_filter,
555    )?;
556
557    Ok(build_dead_code_run_with_artifacts(
558        options, resolved, session, artifacts, finished, start,
559    ))
560}
561
562pub(super) fn run_dead_code_from_artifacts(
563    options: &DeadCodeOptions,
564    resolved: &ProgrammaticAnalysisContext,
565    session: &AnalysisSession,
566    changed_files: Option<&FxHashSet<std::path::PathBuf>>,
567    mut artifacts: DeadCodeAnalysisArtifacts,
568    start: Instant,
569) -> ProgrammaticResult<DeadCodeProgrammaticRunWithArtifacts> {
570    let unfiltered_unused_files = artifacts.results.unused_files.clone();
571    let finished = finish_dead_code_results(
572        DeadCodeReportInputs {
573            options,
574            resolved,
575            session,
576            changed_files,
577            unfiltered_unused_files,
578            finding_ids: None,
579        },
580        &mut artifacts.results,
581        |_| {},
582    )?;
583
584    Ok(build_dead_code_run_with_artifacts(
585        options, resolved, session, artifacts, finished, start,
586    ))
587}
588
589/// Inputs the reporting tail needs from whichever entry point produced the
590/// analysis.
591struct DeadCodeReportInputs<'a> {
592    options: &'a DeadCodeOptions,
593    resolved: &'a ProgrammaticAnalysisContext,
594    session: &'a AnalysisSession,
595    changed_files: Option<&'a FxHashSet<std::path::PathBuf>>,
596    /// Unused files as the engine reported them, before scope narrowing, which
597    /// type-aware refinement needs to reason about the whole project.
598    unfiltered_unused_files: Vec<fallow_types::output_dead_code::UnusedFileFinding>,
599    /// The requested finding ids, when the caller asked for some. The trace
600    /// starts on the full result set, before the scope.
601    finding_ids: Option<fallow_engine::dead_code::FindingIdFilter>,
602}
603
604/// What the reporting tail learned about one run.
605struct FinishedDeadCode {
606    type_aware_meta: Option<fallow_types::envelope::TypeAwareMeta>,
607    finding_id_trace: Option<fallow_engine::dead_code::FindingIdTrace>,
608    /// The change channel that narrowed the run.
609    change_reason: Option<fallow_output::ScopeReason>,
610    /// The package baselines that narrowed the run.
611    package_baselines: Vec<fallow_output::PackageBaselineStatus>,
612}
613
614impl FinishedDeadCode {
615    fn into_report(self, results: AnalysisResults) -> DeadCodeReport {
616        DeadCodeReport {
617            results,
618            type_aware_meta: self.type_aware_meta,
619            package_baselines: self.package_baselines,
620        }
621    }
622}
623
624/// The findings of one run and the envelope facts that travel with them.
625struct DeadCodeReport {
626    results: AnalysisResults,
627    type_aware_meta: Option<fallow_types::envelope::TypeAwareMeta>,
628    package_baselines: Vec<fallow_output::PackageBaselineStatus>,
629}
630
631/// Shared reporting tail for every programmatic dead-code entry point: scope,
632/// issue-type filters, effective rule severities, the caller's family filter,
633/// and type-aware refinement.
634///
635/// The severity pass belongs here rather than at each entry point. Spelling
636/// the sequence out per entry point is what let the programmatic runtime
637/// report findings for rules a project had turned off while the CLI and the
638/// editor did not. The change scope is resolved here once for the same reason.
639fn finish_dead_code_results(
640    inputs: DeadCodeReportInputs<'_>,
641    results: &mut AnalysisResults,
642    post_filter: impl FnOnce(&mut AnalysisResults),
643) -> ProgrammaticResult<FinishedDeadCode> {
644    let DeadCodeReportInputs {
645        options,
646        resolved,
647        session,
648        changed_files,
649        unfiltered_unused_files,
650        finding_ids,
651    } = inputs;
652    let mut finding_id_trace =
653        finding_ids.map(|filter| fallow_engine::dead_code::FindingIdTrace::start(filter, results));
654    let resolved_changed_files = if changed_files.is_some() {
655        None
656    } else {
657        changed_files_for_run(resolved)?
658    };
659    let global_files = changed_files.or(resolved_changed_files.as_ref());
660    if global_files.is_some() {
661        resolved
662            .measure_changed_since_scope(session.files().iter().map(|file| file.path.as_path()));
663    }
664    let change_scope =
665        resolved.change_scope(global_files, session.config(), session.workspaces())?;
666    apply_dead_code_scope(options, resolved, session, &change_scope, results)?;
667    apply_dead_code_filters(&options.filters, results);
668    fallow_engine::dead_code::apply_rule_severities(results, session.config());
669    post_filter(results);
670    if let Some(trace) = finding_id_trace.as_mut() {
671        trace.end_stage(results);
672    }
673    let type_aware_meta = refine_with_unfiltered_unused_files(
674        &options.analysis.type_aware,
675        &options.filters,
676        session,
677        results,
678        unfiltered_unused_files,
679    )?;
680    if type_aware_meta.is_some() {
681        // Refinement can add findings, such as private-type leaks, anywhere in
682        // the project. The scope narrows the final result, so it runs again.
683        apply_dead_code_scope(options, resolved, session, &change_scope, results)?;
684    }
685    Ok(FinishedDeadCode {
686        type_aware_meta,
687        finding_id_trace,
688        change_reason: change_scope.scope_reason(),
689        package_baselines: change_scope.package_baselines(),
690    })
691}
692
693fn refine_with_unfiltered_unused_files(
694    options: &crate::TypeAwareOptions,
695    filters: &DeadCodeFilters,
696    session: &AnalysisSession,
697    results: &mut AnalysisResults,
698    unfiltered_unused_files: Vec<fallow_types::output_dead_code::UnusedFileFinding>,
699) -> ProgrammaticResult<Option<fallow_types::envelope::TypeAwareMeta>> {
700    let reported_unused_files =
701        std::mem::replace(&mut results.unused_files, unfiltered_unused_files);
702    let outcome =
703        crate::type_aware::refine_programmatic_dead_code(options, filters, session, results);
704    results.unused_files = reported_unused_files;
705    if options.requested() {
706        // Reconciliation can add findings, so rule severities are resolved
707        // again over the refined set. The pass removes findings and writes
708        // each gate severity again, so repeating it is idempotent. Mirrors
709        // EditorAnalysisSession.
710        fallow_engine::dead_code::apply_rule_severities(results, session.config());
711    }
712    outcome
713}
714
715fn build_dead_code_run_with_artifacts(
716    options: &DeadCodeOptions,
717    resolved: &ProgrammaticAnalysisContext,
718    session: &AnalysisSession,
719    artifacts: DeadCodeAnalysisArtifacts,
720    finished: FinishedDeadCode,
721    start: Instant,
722) -> DeadCodeProgrammaticRunWithArtifacts {
723    let output = build_dead_code_programmatic_output(
724        options,
725        resolved,
726        session,
727        finished.into_report(artifacts.results.clone()),
728        start,
729        CheckEnvelope::DeadCode,
730    );
731    DeadCodeProgrammaticRunWithArtifacts { output, artifacts }
732}
733
734fn build_dead_code_programmatic_output(
735    options: &DeadCodeOptions,
736    resolved: &ProgrammaticAnalysisContext,
737    session: &AnalysisSession,
738    report: DeadCodeReport,
739    start: Instant,
740    envelope: CheckEnvelope,
741) -> DeadCodeProgrammaticOutput {
742    let DeadCodeReport {
743        results,
744        type_aware_meta,
745        package_baselines,
746    } = report;
747    let root = session.root();
748    let next_steps = build_dead_code_next_steps(DeadCodeNextStepsInput {
749        suggestions_enabled: suggestions_enabled(),
750        results: &results,
751        root,
752        offer_setup: setup_pointer_applicable(root),
753        impact_digest: None,
754        workspace_ref: default_workspace_ref_for_workspaces(root, session.workspaces()).as_deref(),
755        audit_changed: audit_changed_applicable(root),
756        has_external_plugins: !fallow_config::discover_external_plugins(root, &[]).is_empty(),
757        // The programmatic runtime loads no baseline, so there is never one to
758        // re-check.
759        baseline_recheck: None,
760        command: envelope.command(),
761    });
762    let config_fixable =
763        fallow_config::is_config_fixable(&resolved.root, resolved.config_path.as_ref());
764    let mut meta = options.analysis.explain.then(|| match envelope {
765        CheckEnvelope::DeadCode => check_meta(),
766        CheckEnvelope::Architecture => architecture_meta(),
767    });
768    if let Some(type_aware) = type_aware_meta {
769        meta.get_or_insert_with(Default::default).type_aware = Some(type_aware);
770    }
771    // A `files` run drops dependency findings, like a filter without the
772    // dependency issue types. The CLI applies the same rule.
773    let reports_dependencies =
774        options.filters.reports_dependency_findings() && options.files.is_empty();
775    // The filters of an architecture run hold no request: no selector sets
776    // every filter. `run_architecture` adds the entries of its own selectors.
777    let requested_flags = match envelope {
778        CheckEnvelope::DeadCode => options.filters.requested_flags(),
779        CheckEnvelope::Architecture => Vec::new(),
780    };
781    let workspace_diagnostics = fallow_types::workspace::merge_workspace_diagnostics(
782        session.current_workspace_diagnostics(),
783        fallow_engine::dead_code::config_pattern_diagnostics(
784            session.config(),
785            reports_dependencies,
786        )
787        .into_iter()
788        .chain(
789            fallow_engine::requested_rule_off::requested_rule_off_diagnostics(
790                session.config(),
791                &requested_flags,
792                reports_dependencies,
793            ),
794        )
795        .collect(),
796    );
797    let mut output = build_check_output(CheckOutputInput {
798        schema_version: envelope.schema_version(),
799        version: env!("CARGO_PKG_VERSION").to_string(),
800        elapsed: start.elapsed(),
801        results,
802        config_fixable,
803        meta,
804        workspace_diagnostics,
805        next_steps,
806    });
807    output.request_outcomes = resolved.request_outcomes();
808    output.package_baselines = package_baselines;
809    DeadCodeProgrammaticOutput {
810        output,
811        root: session.root().to_path_buf(),
812        config_fixable,
813        telemetry_analysis_run_id: None,
814    }
815}
816
817fn keep_circular_dependencies(results: &mut AnalysisResults) {
818    let entry_point_summary = results.entry_point_summary.take();
819    let circular_dependencies = std::mem::take(&mut results.circular_dependencies);
820    *results = AnalysisResults::default();
821    results.entry_point_summary = entry_point_summary;
822    results.circular_dependencies = circular_dependencies;
823}
824
825fn keep_boundary_violations(results: &mut AnalysisResults) {
826    let entry_point_summary = results.entry_point_summary.take();
827    let boundary_violations = std::mem::take(&mut results.boundary_violations);
828    let boundary_coverage_violations = std::mem::take(&mut results.boundary_coverage_violations);
829    let boundary_call_violations = std::mem::take(&mut results.boundary_call_violations);
830    *results = AnalysisResults::default();
831    results.entry_point_summary = entry_point_summary;
832    results.boundary_violations = boundary_violations;
833    results.boundary_coverage_violations = boundary_coverage_violations;
834    results.boundary_call_violations = boundary_call_violations;
835}
836
837/// Open the dead-code session of `run`, with the rule settings of
838/// `options`.
839pub(super) fn load_dead_code_session(
840    options: &DeadCodeOptions,
841    resolved: &ProgrammaticAnalysisContext,
842    run: &ResolvedRun,
843) -> ProgrammaticResult<AnalysisSession> {
844    let dead_code = crate::run::runnable(run, PlannedAnalysis::DeadCode)?;
845    let session = crate::run::open_session_adjusted(&dead_code, |config| {
846        configure_dead_code(config, options);
847    })?;
848    Ok(attach_cancellation(session, resolved))
849}
850
851/// Resolve the package map before the analysis starts, so a malformed map
852/// fails fast. The call context keeps the result for the scope step.
853///
854/// Only the entry points that apply the change scope call this. Their changed
855/// files come from the call's own ref, so the request here matches the one
856/// the scope step makes. Trace and decision-surface sessions never read the map.
857pub(super) fn resolve_package_map_before_analysis(
858    resolved: &ProgrammaticAnalysisContext,
859    session: &AnalysisSession,
860) -> ProgrammaticResult<()> {
861    resolved
862        .change_scope(None, session.config(), session.workspaces())
863        .map(drop)
864}
865
866/// Hand the caller's cancellation token to the engine session.
867///
868/// Without this the session runs to completion no matter what the API layer
869/// checks between its own stages.
870pub(super) fn attach_cancellation(
871    session: AnalysisSession,
872    resolved: &ProgrammaticAnalysisContext,
873) -> AnalysisSession {
874    match resolved.cancellation() {
875        Some(cancellation) => session.with_cancellation(std::sync::Arc::clone(cancellation)),
876        None => session,
877    }
878}
879
880/// The dead-code options of a route that runs the dead-code analysis with
881/// the shared options of `analysis` only, such as a trace.
882pub(super) fn default_dead_code_options(analysis: &AnalysisOptions) -> DeadCodeOptions {
883    DeadCodeOptions {
884        finding_ids: Vec::new(),
885        analysis: analysis.clone(),
886        filters: DeadCodeFilters::default(),
887        files: Vec::new(),
888        include_entry_exports: false,
889        show_cascade: false,
890    }
891}
892
893/// The rule settings of the dead-code options. The run decides
894/// `include_entry_exports` (see [`resolve_dead_code_run`]).
895fn configure_dead_code(config: &mut ResolvedConfig, options: &DeadCodeOptions) {
896    if options.filters.shared_state {
897        config.request_shared_state();
898    }
899    if options.show_cascade {
900        config.show_cascade = true;
901    }
902    activate_explicit_dead_code_opt_ins(&options.filters, &mut config.rules);
903    apply_explicit_type_aware_choice(options, config);
904}
905
906/// Write an explicit `type_aware` choice into the resolved config, as the
907/// `--type-aware` and `--no-type-aware` flags do. Detection reads
908/// `typeAware.enabled` itself: it holds framework class-member rules back for
909/// semantic verification, and a syntactic run must credit them instead.
910/// A type-aware run turns the opt-in `private-type-leaks` rule on, as the CLI
911/// does, unless a filter is active or the config sets the rule.
912fn apply_explicit_type_aware_choice(
913    options: &DeadCodeOptions,
914    config: &mut fallow_config::ResolvedConfig,
915) {
916    let Some(enabled) = options.analysis.type_aware.enabled else {
917        return;
918    };
919    config.type_aware.enabled = enabled;
920    if enabled
921        && !options.filters.any_active()
922        && config.rules.private_type_leaks == fallow_config::Severity::Off
923        && !config.rules.private_type_leaks_configured
924    {
925        config.rules.private_type_leaks = fallow_config::Severity::Warn;
926    }
927}
928
929fn activate_explicit_dead_code_opt_ins(
930    filters: &DeadCodeFilters,
931    rules: &mut fallow_config::RulesConfig,
932) {
933    if filters.absent_component_props
934        && rules.absent_component_props == fallow_config::Severity::Off
935    {
936        rules.absent_component_props = fallow_config::Severity::Warn;
937    }
938    if filters.constant_parameters && rules.constant_parameters == fallow_config::Severity::Off {
939        rules.constant_parameters = fallow_config::Severity::Warn;
940    }
941    if filters.private_type_leaks && rules.private_type_leaks == fallow_config::Severity::Off {
942        rules.private_type_leaks = fallow_config::Severity::Warn;
943    }
944    if filters.deprecated_exports_in_use
945        && rules.deprecated_exports_in_use == fallow_config::Severity::Off
946    {
947        rules.deprecated_exports_in_use = fallow_config::Severity::Warn;
948    }
949    if filters.unused_protected_class_members
950        && rules.unused_protected_class_members == fallow_config::Severity::Off
951    {
952        rules.unused_protected_class_members = fallow_config::Severity::Warn;
953    }
954}
955
956fn apply_dead_code_scope(
957    options: &DeadCodeOptions,
958    resolved: &ProgrammaticAnalysisContext,
959    session: &AnalysisSession,
960    change_scope: &ChangeScope,
961    results: &mut AnalysisResults,
962) -> ProgrammaticResult<()> {
963    let workspace_roots = workspace_roots_for_session(resolved, session.workspaces())?;
964    let files = file_scope(options, session.root());
965    fallow_engine::dead_code::apply_scope(
966        results,
967        &fallow_engine::dead_code::DeadCodeScope {
968            workspace_roots: workspace_roots.as_ref(),
969            changes: Some(change_scope),
970            diff: resolved.diff.as_ref().map(|diff| (diff, session.root())),
971            files: files.as_ref(),
972        },
973        session.config(),
974    );
975    Ok(())
976}
977
978/// The `files` option resolved against the root, or `None` when it is empty.
979fn file_scope(options: &DeadCodeOptions, root: &Path) -> Option<FxHashSet<std::path::PathBuf>> {
980    if options.files.is_empty() {
981        return None;
982    }
983    Some(
984        options
985            .files
986            .iter()
987            .map(|path| {
988                if is_absolute_path_any_platform(path) {
989                    path.clone()
990                } else {
991                    root.join(path)
992                }
993            })
994            .collect(),
995    )
996}
997
998fn apply_dead_code_filters(filters: &DeadCodeFilters, results: &mut AnalysisResults) {
999    if !dead_code_filters_active(filters) {
1000        return;
1001    }
1002    apply_dead_code_core_filters(filters, results);
1003    apply_dead_code_component_filters(filters, results);
1004    apply_dead_code_graph_filters(filters, results);
1005    apply_dead_code_policy_filters(filters, results);
1006    apply_dead_code_catalog_filters(filters, results);
1007}
1008
1009fn dead_code_filters_active(filters: &DeadCodeFilters) -> bool {
1010    filters.shared_state
1011        || filters.unused_files
1012        || filters.unused_exports
1013        || filters.unused_deps
1014        || filters.unused_types
1015        || filters.private_type_leaks
1016        || filters.deprecated_exports_in_use
1017        || filters.unused_enum_members
1018        || filters.unused_class_members
1019        || filters.unused_namespace_members
1020        || filters.unused_protected_class_members
1021        || filters.unused_store_members
1022        || filters.unprovided_injects
1023        || filters.unrendered_components
1024        || filters.unused_component_props
1025        || filters.absent_component_props
1026        || filters.constant_parameters
1027        || filters.unused_component_emits
1028        || filters.unused_component_inputs
1029        || filters.unused_component_outputs
1030        || filters.unused_svelte_events
1031        || filters.unused_effect_layers
1032        || filters.unused_tagged_errors
1033        || filters.unproduced_catch_tags
1034        || filters.unused_server_actions
1035        || filters.unused_load_data_keys
1036        || filters.unresolved_imports
1037        || filters.unlisted_deps
1038        || filters.unlisted_binaries
1039        || filters.duplicate_exports
1040        || filters.duplicate_export_aliases
1041        || filters.circular_deps
1042        || filters.re_export_cycles
1043        || filters.package_cycles
1044        || filters.boundary_violations
1045        || filters.policy_violations
1046        || filters.stale_suppressions
1047        || filters.unused_catalog_entries
1048        || filters.empty_catalog_groups
1049        || filters.unresolved_catalog_references
1050        || filters.unused_dependency_overrides
1051        || filters.misconfigured_dependency_overrides
1052}
1053
1054fn apply_dead_code_core_filters(filters: &DeadCodeFilters, results: &mut AnalysisResults) {
1055    if !filters.unused_files {
1056        results.unused_files.clear();
1057        results.cascade.suppressed_unused_files.clear();
1058    }
1059    if !filters.unused_exports {
1060        results.unused_exports.clear();
1061    }
1062    if !filters.unused_types {
1063        results.unused_types.clear();
1064    }
1065    if !filters.private_type_leaks {
1066        results.private_type_leaks.clear();
1067    }
1068    if !filters.deprecated_exports_in_use {
1069        results.deprecated_exports_in_use.clear();
1070    }
1071    if !filters.unused_deps {
1072        clear_dead_code_dependency_findings(results);
1073    }
1074    if !filters.unused_enum_members {
1075        results.unused_enum_members.clear();
1076    }
1077    if !filters.unused_class_members {
1078        results.unused_class_members.clear();
1079    }
1080    if !filters.unused_store_members {
1081        results.unused_store_members.clear();
1082    }
1083    if !filters.unused_namespace_members {
1084        results.unused_namespace_members.clear();
1085    }
1086    if !filters.unused_protected_class_members {
1087        results.unused_protected_class_members.clear();
1088    }
1089    if !filters.unlisted_deps {
1090        results.unlisted_dependencies.clear();
1091    }
1092    if !filters.unlisted_binaries {
1093        results.unlisted_binaries.clear();
1094    }
1095}
1096
1097fn clear_dead_code_dependency_findings(results: &mut AnalysisResults) {
1098    results.unused_dependencies.clear();
1099    results.unused_dev_dependencies.clear();
1100    results.unused_optional_dependencies.clear();
1101    results.type_only_dependencies.clear();
1102    results.test_only_dependencies.clear();
1103    results.dev_dependencies_in_production.clear();
1104}
1105
1106fn apply_dead_code_component_filters(filters: &DeadCodeFilters, results: &mut AnalysisResults) {
1107    if !filters.unprovided_injects {
1108        results.unprovided_injects.clear();
1109    }
1110    if !filters.unrendered_components {
1111        results.unrendered_components.clear();
1112    }
1113    if !filters.absent_component_props {
1114        results.absent_component_props.clear();
1115    }
1116    if !filters.constant_parameters {
1117        results.constant_parameters.clear();
1118    }
1119    if !filters.unused_component_props {
1120        results.unused_component_props.clear();
1121    }
1122    if !filters.unused_component_emits {
1123        results.unused_component_emits.clear();
1124    }
1125    if !filters.unused_component_inputs {
1126        results.unused_component_inputs.clear();
1127    }
1128    if !filters.unused_component_outputs {
1129        results.unused_component_outputs.clear();
1130    }
1131    if !filters.unused_svelte_events {
1132        results.unused_svelte_events.clear();
1133    }
1134    if !filters.unused_effect_layers {
1135        results.unused_effect_layers.clear();
1136    }
1137    if !filters.unused_tagged_errors {
1138        results.unused_tagged_errors.clear();
1139    }
1140    if !filters.unproduced_catch_tags {
1141        results.unproduced_catch_tags.clear();
1142    }
1143    if !filters.unused_server_actions {
1144        results.unused_server_actions.clear();
1145    }
1146    if !filters.unused_load_data_keys {
1147        results.unused_load_data_keys.clear();
1148    }
1149    if !filters.unresolved_imports {
1150        results.unresolved_imports.clear();
1151    }
1152}
1153
1154fn apply_dead_code_graph_filters(filters: &DeadCodeFilters, results: &mut AnalysisResults) {
1155    if !filters.duplicate_exports {
1156        results.duplicate_exports.clear();
1157    }
1158    if !filters.duplicate_export_aliases {
1159        results.duplicate_export_aliases.clear();
1160    }
1161    if !filters.circular_deps {
1162        results.circular_dependencies.clear();
1163    }
1164    if !filters.re_export_cycles {
1165        results.re_export_cycles.clear();
1166    }
1167    if !filters.package_cycles {
1168        results.package_cycles.clear();
1169    }
1170    if !filters.boundary_violations {
1171        results.boundary_violations.clear();
1172        results.boundary_coverage_violations.clear();
1173        results.boundary_call_violations.clear();
1174    }
1175}
1176
1177fn apply_dead_code_policy_filters(filters: &DeadCodeFilters, results: &mut AnalysisResults) {
1178    if !filters.policy_violations {
1179        results.policy_violations.clear();
1180    }
1181    if !filters.stale_suppressions {
1182        results.stale_suppressions.clear();
1183    }
1184}
1185
1186fn apply_dead_code_catalog_filters(filters: &DeadCodeFilters, results: &mut AnalysisResults) {
1187    if !filters.unused_catalog_entries {
1188        results.unused_catalog_entries.clear();
1189    }
1190    if !filters.empty_catalog_groups {
1191        results.empty_catalog_groups.clear();
1192    }
1193    if !filters.unresolved_catalog_references {
1194        results.unresolved_catalog_references.clear();
1195    }
1196    if !filters.unused_dependency_overrides {
1197        results.unused_dependency_overrides.clear();
1198    }
1199    if !filters.misconfigured_dependency_overrides {
1200        results.misconfigured_dependency_overrides.clear();
1201    }
1202}