Skip to main content

fallow_api/runtime/
dead_code.rs

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