Skip to main content

fallow_api/runtime/
combined.rs

1use std::{path::PathBuf, time::Instant};
2
3use fallow_config::WorkspaceInfo;
4use fallow_engine::{
5    dead_code::DeadCodeAnalysisArtifacts,
6    project_analysis::{ProjectAnalysisArtifactOptions, ProjectAnalysisArtifacts},
7    session::AnalysisSession,
8};
9use fallow_output::{CombinedNextStepsInput, build_combined_next_steps};
10use rustc_hash::FxHashSet;
11
12use crate::{
13    AnalysisOptions, CombinedOptions, CombinedProgrammaticOutput, ComplexityOptions,
14    DeadCodeFilters, DeadCodeOptions, DuplicationOptions, ProgrammaticError,
15    analysis_context::{changed_files_for_run, resolve_programmatic_analysis_context},
16    next_steps::{
17        audit_changed_applicable, default_workspace_ref, default_workspace_ref_for_workspaces,
18        setup_pointer_applicable, suggestions_enabled,
19    },
20};
21
22use super::{
23    ProductionModes, ProgrammaticResult, health_may_consume_dead_code_artifacts,
24    health_may_consume_duplication_report, resolve_effective_production_modes, run_duplication,
25    run_health, run_health_with_session_artifacts,
26};
27
28struct PreparedCombinedOptions {
29    dead_code: DeadCodeOptions,
30    duplication: DuplicationOptions,
31    health: ComplexityOptions,
32}
33
34struct CombinedSectionRun {
35    dead_code: Option<crate::DeadCodeProgrammaticOutput>,
36    duplication: Option<crate::DuplicationProgrammaticOutput>,
37    health: Option<crate::HealthProgrammaticOutput>,
38    root: PathBuf,
39    workspaces: Option<Vec<WorkspaceInfo>>,
40}
41
42struct DeadCodeSessionRun<'a> {
43    options: &'a CombinedOptions,
44    resolved: &'a crate::analysis_context::ProgrammaticAnalysisContext,
45    prepared: &'a PreparedCombinedOptions,
46    changed_files: Option<&'a FxHashSet<PathBuf>>,
47    session: &'a AnalysisSession,
48}
49
50/// Run bare combined analysis through one programmatic analysis session.
51///
52/// # Errors
53///
54/// Returns a structured programmatic error for invalid options, config load
55/// failures, or analysis failures. When the dead-code or health section runs
56/// and the environment or `typeAware.enabled` turns on type-aware analysis
57/// that the options leave off, it returns
58/// [`super::TYPE_AWARE_CONFIG_UNSUPPORTED`].
59pub fn run_combined(options: &CombinedOptions) -> ProgrammaticResult<CombinedProgrammaticOutput> {
60    if !(options.dead_code || options.duplication || options.health) {
61        return Err(ProgrammaticError::new(
62            "combined analysis requires at least one enabled section",
63            2,
64        )
65        .with_code("FALLOW_COMBINED_EMPTY")
66        .with_context("combined"));
67    }
68
69    let start = Instant::now();
70    let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
71    // Bare `fallow` makes dead code type-aware and adds type coupling to
72    // health from config. The shared-session paths below do not pass through
73    // the checks of `run_dead_code` and `run_health`, so the check runs here.
74    if options.dead_code || options.health {
75        super::type_aware_config::reject_config_type_aware(
76            &options.analysis.type_aware,
77            &resolved,
78            super::type_aware_config::TypeAwareCommand::Analysis,
79        )?;
80    }
81    let options = &options_with_duplicates_config(options, &resolved)?;
82    resolved.install(|| {
83        resolved.ensure_not_cancelled("combined analysis")?;
84        let production_modes = resolve_effective_production_modes(
85            &resolved,
86            options.production_dead_code,
87            options.production_health,
88            options.production_dupes,
89        )?;
90        let prepared = prepare_combined_options(options, production_modes);
91        let changed_files = changed_files_for_run(&resolved)?;
92        let sections = run_combined_sections(
93            options,
94            &resolved,
95            &prepared,
96            changed_files.as_ref(),
97            production_modes,
98        )?;
99
100        let next_steps = combined_next_steps(
101            sections.dead_code.as_ref(),
102            sections.duplication.as_ref(),
103            sections.health.as_ref(),
104            &sections.root,
105            sections.workspaces.as_deref(),
106        );
107
108        Ok(CombinedProgrammaticOutput {
109            dead_code: sections.dead_code,
110            duplication: sections.duplication,
111            health: sections.health,
112            root: sections.root,
113            elapsed: start.elapsed(),
114            explain: options.analysis.explain,
115            next_steps,
116            telemetry_analysis_run_id: None,
117            request_outcomes: resolved.request_outcomes(),
118        })
119    })
120}
121
122/// Plan the duplication domain with [`fallow_config::plan_run`], as the bare
123/// `fallow` command does. A run that selects only the duplication domain
124/// names it. A run with another domain runs duplication by default, so
125/// `duplicates.enabled: false` turns it off.
126fn options_with_duplicates_config(
127    options: &CombinedOptions,
128    resolved: &crate::analysis_context::ProgrammaticAnalysisContext,
129) -> ProgrammaticResult<CombinedOptions> {
130    let request = fallow_config::RunRequest::from_booleans(
131        fallow_config::RunCommand::Combined,
132        options.dead_code,
133        options.duplication,
134        options.health,
135    );
136    Ok(CombinedOptions {
137        duplication: super::plan_run(resolved, request)?.duplication.runs(),
138        ..options.clone()
139    })
140}
141
142fn prepare_combined_options(
143    options: &CombinedOptions,
144    production_modes: ProductionModes,
145) -> PreparedCombinedOptions {
146    PreparedCombinedOptions {
147        dead_code: combined_dead_code_options(options, production_modes.dead_code),
148        duplication: combined_duplication_options(options, production_modes.dupes),
149        health: combined_health_options(options, production_modes.health),
150    }
151}
152
153fn run_combined_sections(
154    options: &CombinedOptions,
155    resolved: &crate::analysis_context::ProgrammaticAnalysisContext,
156    prepared: &PreparedCombinedOptions,
157    changed_files: Option<&FxHashSet<PathBuf>>,
158    production_modes: ProductionModes,
159) -> ProgrammaticResult<CombinedSectionRun> {
160    let share_health =
161        options.dead_code && options.health && production_modes.dead_code_matches_health();
162    let share_dupes =
163        options.dead_code && options.duplication && production_modes.dead_code_matches_dupes();
164    if share_health || share_dupes {
165        return run_combined_with_dead_code_session(
166            options,
167            resolved,
168            prepared,
169            changed_files,
170            share_health,
171            share_dupes,
172        );
173    }
174    run_combined_sections_isolated(options, resolved, prepared)
175}
176
177fn run_combined_with_dead_code_session(
178    options: &CombinedOptions,
179    resolved: &crate::analysis_context::ProgrammaticAnalysisContext,
180    prepared: &PreparedCombinedOptions,
181    changed_files: Option<&FxHashSet<PathBuf>>,
182    share_health: bool,
183    share_dupes: bool,
184) -> ProgrammaticResult<CombinedSectionRun> {
185    resolved.ensure_not_cancelled("config load and file discovery")?;
186    let session = super::dead_code::load_dead_code_session_in_mode(
187        &prepared.dead_code,
188        resolved,
189        prepared.dead_code.analysis.production_override,
190    )?;
191    super::dead_code::resolve_package_map_before_analysis(resolved, &session)?;
192    if share_dupes {
193        return run_combined_with_project_artifacts(CombinedProjectArtifactRun {
194            options,
195            resolved,
196            prepared,
197            changed_files,
198            share_health,
199            session: &session,
200        });
201    }
202    let ctx = DeadCodeSessionRun {
203        options,
204        resolved,
205        prepared,
206        changed_files,
207        session: &session,
208    };
209    let (dead_code, dead_code_artifacts) =
210        run_dead_code_with_optional_artifacts(&ctx, options.health && share_health)?;
211    let duplication = run_combined_duplication(&ctx, share_dupes)?;
212    resolved.ensure_not_cancelled("the health section")?;
213    let health = run_combined_health(&ctx, share_health, dead_code_artifacts, None)?;
214    Ok(CombinedSectionRun {
215        dead_code,
216        duplication,
217        health,
218        root: session.root().to_path_buf(),
219        workspaces: Some(session.workspaces().to_vec()),
220    })
221}
222
223#[derive(Clone, Copy)]
224struct CombinedProjectArtifactRun<'a> {
225    options: &'a CombinedOptions,
226    resolved: &'a crate::analysis_context::ProgrammaticAnalysisContext,
227    prepared: &'a PreparedCombinedOptions,
228    changed_files: Option<&'a FxHashSet<PathBuf>>,
229    share_health: bool,
230    session: &'a AnalysisSession,
231}
232
233fn run_combined_with_project_artifacts(
234    run: CombinedProjectArtifactRun<'_>,
235) -> ProgrammaticResult<CombinedSectionRun> {
236    let CombinedProjectArtifactRun {
237        options,
238        resolved,
239        prepared,
240        changed_files,
241        share_health,
242        session,
243    } = run;
244    let retain_dead_code_artifacts =
245        share_health && health_may_consume_dead_code_artifacts(&prepared.health, session.config());
246    let section_start = Instant::now();
247    let project = analyze_project_artifacts_for_combined(&run, retain_dead_code_artifacts)?;
248    let dead_code = super::dead_code::run_dead_code_from_artifacts(
249        &prepared.dead_code,
250        resolved,
251        session,
252        changed_files,
253        project.dead_code,
254        section_start,
255    )?;
256    let pre_computed_duplication_for_health =
257        should_precompute_duplication_for_combined_health(options, prepared, share_health)
258            .then(|| project.duplication.clone());
259    let duplication = run_project_artifact_duplication(&run, project.duplication, section_start)?;
260    let super::dead_code::DeadCodeProgrammaticRunWithArtifacts {
261        output: dead_code,
262        artifacts,
263    } = dead_code;
264    let dead_code_artifacts = retain_dead_code_artifacts.then_some(artifacts);
265    resolved.ensure_not_cancelled("the health section")?;
266    let health = run_combined_health(
267        &DeadCodeSessionRun {
268            options,
269            resolved,
270            prepared,
271            changed_files,
272            session,
273        },
274        share_health,
275        dead_code_artifacts,
276        pre_computed_duplication_for_health,
277    )?;
278
279    Ok(CombinedSectionRun {
280        dead_code: Some(dead_code),
281        duplication,
282        health,
283        root: session.root().to_path_buf(),
284        workspaces: Some(session.workspaces().to_vec()),
285    })
286}
287
288fn run_project_artifact_duplication(
289    run: &CombinedProjectArtifactRun<'_>,
290    duplication: fallow_engine::duplicates::DuplicationReport,
291    section_start: Instant,
292) -> ProgrammaticResult<Option<crate::DuplicationProgrammaticOutput>> {
293    let CombinedProjectArtifactRun {
294        options,
295        resolved,
296        prepared,
297        changed_files,
298        session,
299        ..
300    } = *run;
301    options
302        .duplication
303        .then(|| {
304            let change_scope =
305                resolved.change_scope(changed_files, session.config(), session.workspaces())?;
306            super::duplication::run_duplication_report_with_session(
307                &prepared.duplication,
308                resolved,
309                session,
310                duplication,
311                &change_scope,
312                section_start,
313            )
314        })
315        .transpose()
316}
317
318fn should_precompute_duplication_for_combined_health(
319    options: &CombinedOptions,
320    prepared: &PreparedCombinedOptions,
321    share_health: bool,
322) -> bool {
323    options.health
324        && share_health
325        && health_may_consume_duplication_report(&prepared.health)
326        && duplication_options_preserve_health_config(&prepared.duplication)
327}
328
329fn analyze_project_artifacts_for_combined(
330    run: &CombinedProjectArtifactRun<'_>,
331    retain_dead_code_artifacts: bool,
332) -> ProgrammaticResult<ProjectAnalysisArtifacts> {
333    let dupes_config = super::duplication::build_dupes_config(
334        &run.prepared.duplication,
335        &run.session.config().duplicates,
336    );
337    run.session
338        .analyze_project_with_artifacts(
339            &dupes_config,
340            ProjectAnalysisArtifactOptions {
341                retain_complexity_artifacts: retain_dead_code_artifacts,
342                retain_graph: retain_dead_code_artifacts,
343                changed_files: run.changed_files.cloned(),
344                collect_source_fingerprints: false,
345            },
346        )
347        .map_err(|err| {
348            super::dead_code::map_engine_error(
349                &err,
350                "combined analysis failed",
351                "FALLOW_COMBINED_FAILED",
352                "combined",
353            )
354        })
355}
356
357fn run_dead_code_with_optional_artifacts(
358    ctx: &DeadCodeSessionRun<'_>,
359    share_health: bool,
360) -> ProgrammaticResult<(
361    Option<crate::DeadCodeProgrammaticOutput>,
362    Option<DeadCodeAnalysisArtifacts>,
363)> {
364    let retain_artifacts = share_health
365        && health_may_consume_dead_code_artifacts(&ctx.prepared.health, ctx.session.config());
366    if retain_artifacts {
367        let dead_code = super::dead_code::run_dead_code_with_session_artifacts(
368            &ctx.prepared.dead_code,
369            ctx.resolved,
370            ctx.session,
371            ctx.changed_files,
372            |_| {},
373            Instant::now(),
374        )?;
375        return Ok((Some(dead_code.output), Some(dead_code.artifacts)));
376    }
377    let dead_code = super::dead_code::run_dead_code_with_session(
378        &ctx.prepared.dead_code,
379        ctx.resolved,
380        ctx.session,
381        ctx.changed_files,
382        |_| {},
383        Instant::now(),
384    )?;
385    Ok((Some(dead_code), None))
386}
387
388fn run_combined_duplication(
389    ctx: &DeadCodeSessionRun<'_>,
390    share_dupes: bool,
391) -> ProgrammaticResult<Option<crate::DuplicationProgrammaticOutput>> {
392    if !ctx.options.duplication {
393        return Ok(None);
394    }
395    if !share_dupes {
396        return run_duplication(&ctx.prepared.duplication).map(Some);
397    }
398    super::duplication::run_duplication_with_session(
399        &ctx.prepared.duplication,
400        ctx.resolved,
401        ctx.session,
402        ctx.changed_files,
403        Instant::now(),
404    )
405    .map(Some)
406}
407
408fn run_combined_health(
409    ctx: &DeadCodeSessionRun<'_>,
410    share_health: bool,
411    dead_code_artifacts: Option<DeadCodeAnalysisArtifacts>,
412    pre_computed_duplication: Option<fallow_engine::duplicates::DuplicationReport>,
413) -> ProgrammaticResult<Option<crate::HealthProgrammaticOutput>> {
414    if !ctx.options.health {
415        return Ok(None);
416    }
417    if !share_health {
418        return run_health(&ctx.prepared.health).map(Some);
419    }
420    run_health_with_session_artifacts(
421        &ctx.prepared.health,
422        ctx.resolved,
423        ctx.session,
424        ctx.changed_files,
425        dead_code_artifacts,
426        pre_computed_duplication,
427    )
428    .map(Some)
429}
430
431fn run_combined_sections_isolated(
432    options: &CombinedOptions,
433    resolved: &crate::analysis_context::ProgrammaticAnalysisContext,
434    prepared: &PreparedCombinedOptions,
435) -> ProgrammaticResult<CombinedSectionRun> {
436    Ok(CombinedSectionRun {
437        dead_code: options
438            .dead_code
439            .then(|| super::dead_code::run_dead_code(&prepared.dead_code))
440            .transpose()?,
441        duplication: options
442            .duplication
443            .then(|| run_duplication(&prepared.duplication))
444            .transpose()?,
445        health: options
446            .health
447            .then(|| run_health(&prepared.health))
448            .transpose()?,
449        root: resolved.root().to_path_buf(),
450        workspaces: None,
451    })
452}
453
454fn combined_dead_code_options(options: &CombinedOptions, production: bool) -> DeadCodeOptions {
455    DeadCodeOptions {
456        finding_ids: Vec::new(),
457        analysis: analysis_with_effective_production(&options.analysis, production),
458        filters: DeadCodeFilters::default(),
459        files: Vec::new(),
460        include_entry_exports: options.include_entry_exports,
461        show_cascade: options.show_cascade,
462    }
463}
464
465fn combined_duplication_options(options: &CombinedOptions, production: bool) -> DuplicationOptions {
466    let mut duplication = options.duplication_options.clone();
467    duplication.analysis = analysis_with_effective_production(&options.analysis, production);
468    duplication
469}
470
471fn duplication_options_preserve_health_config(options: &DuplicationOptions) -> bool {
472    options.mode.is_none()
473        && options.min_tokens.is_none()
474        && options.min_lines.is_none()
475        && options.min_occurrences.is_none()
476        && options.threshold.is_none()
477        && options.skip_local.is_none()
478        && options.ignore_symlinks.is_none()
479        && options.cross_language.is_none()
480        && options.ignore_imports.is_none()
481}
482
483fn combined_health_options(options: &CombinedOptions, production: bool) -> ComplexityOptions {
484    let mut health = options.health_options.clone();
485    health.analysis = analysis_with_effective_production(&options.analysis, production);
486    health.config_activates_coverage_gaps = true;
487    health
488}
489
490fn analysis_with_effective_production(
491    analysis: &AnalysisOptions,
492    production: bool,
493) -> AnalysisOptions {
494    AnalysisOptions {
495        production,
496        production_override: Some(production),
497        ..analysis.clone()
498    }
499}
500
501fn combined_next_steps(
502    dead_code: Option<&crate::DeadCodeProgrammaticOutput>,
503    duplication: Option<&crate::DuplicationProgrammaticOutput>,
504    health: Option<&crate::HealthProgrammaticOutput>,
505    root: &std::path::Path,
506    workspaces: Option<&[WorkspaceInfo]>,
507) -> Vec<fallow_types::output::NextStep> {
508    let clone_fingerprints = duplication
509        .map(|duplication| {
510            duplication
511                .output
512                .report
513                .clone_groups
514                .iter()
515                .map(|group| group.fingerprint.as_str())
516                .collect::<Vec<_>>()
517        })
518        .unwrap_or_default();
519    let audit_changed = audit_changed_applicable(root);
520    let workspace_ref = audit_changed
521        .then(|| {
522            workspaces.map_or_else(
523                || default_workspace_ref(root),
524                |workspaces| default_workspace_ref_for_workspaces(root, workspaces),
525            )
526        })
527        .flatten();
528    build_combined_next_steps(&CombinedNextStepsInput {
529        suggestions_enabled: suggestions_enabled(),
530        has_dead_code_findings: dead_code
531            .is_some_and(|dead_code| dead_code.output.results.total_issues() > 0),
532        trace_unused_export: dead_code.and_then(|dead_code| {
533            fallow_output::trace_unused_export_input(&dead_code.output.results, root)
534        }),
535        workspace_ref: workspace_ref.as_deref(),
536        clone_fingerprints: &clone_fingerprints,
537        has_complexity_findings: health.is_some_and(|health| !health.report.findings.is_empty()),
538        offer_setup: setup_pointer_applicable(root),
539        impact_digest: None,
540        audit_changed,
541        has_external_plugins: !fallow_config::discover_external_plugins(root, &[]).is_empty(),
542        has_unused_files: dead_code
543            .is_some_and(|dead_code| !dead_code.output.results.unused_files.is_empty()),
544        // The programmatic runtime has no process-wide record of a loaded
545        // baseline to read, and its caller passes the paths itself, so there is
546        // nothing to point a re-check at here.
547        baseline_recheck: None,
548    })
549}
550
551#[cfg(test)]
552mod tests {
553    use super::*;
554    use crate::DuplicationMode;
555
556    #[test]
557    fn health_reuses_combined_duplication_only_without_detector_overrides() {
558        assert!(duplication_options_preserve_health_config(
559            &DuplicationOptions::default()
560        ));
561        assert!(!duplication_options_preserve_health_config(
562            &DuplicationOptions {
563                min_tokens: Some(1),
564                ..DuplicationOptions::default()
565            }
566        ));
567        assert!(!duplication_options_preserve_health_config(
568            &DuplicationOptions {
569                mode: Some(DuplicationMode::Semantic),
570                ..DuplicationOptions::default()
571            }
572        ));
573    }
574}