Skip to main content

fallow_engine/
session_graph.rs

1//! What a dead-code run of an [`AnalysisSession`] keeps of its module graph.
2
3use fallow_types::cache_rejection::CacheRejection;
4use fallow_types::extract::ModuleInfo;
5
6use crate::EngineResult;
7use crate::core_backend;
8use crate::module_graph::RetainedModuleGraph;
9use crate::results::{DeadCodeAnalysisArtifacts, SharedDeadCodeAnalysisArtifacts};
10use crate::session::{AnalysisSession, SharedParsedModules};
11
12/// What a dead-code run keeps of its module graph.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum GraphChoice {
15    /// Drop the graph after the analysis.
16    Drop,
17    /// Keep the graph, and collect the trace provenance (with the plugin
18    /// export credits) and the pipeline timings.
19    WithTrace,
20    /// Keep the graph without the trace provenance and the timings.
21    GraphOnly,
22}
23
24/// The choice of a caller that passes the `retain_graph` flag.
25impl From<bool> for GraphChoice {
26    fn from(retain_graph: bool) -> Self {
27        if retain_graph {
28            Self::WithTrace
29        } else {
30            Self::Drop
31        }
32    }
33}
34
35impl GraphChoice {
36    pub const fn keeps_graph(self) -> bool {
37        matches!(self, Self::WithTrace | Self::GraphOnly)
38    }
39
40    /// True when the run collects the trace provenance and the timings.
41    pub const fn traces(self) -> bool {
42        matches!(self, Self::WithTrace)
43    }
44}
45
46impl AnalysisSession {
47    /// Run dead-code analysis and keep the module graph, without the trace
48    /// provenance and pipeline timings that
49    /// [`Self::analyze_dead_code_with_artifacts`] also collects when it keeps
50    /// the graph. `fallow fix` reads graph facts such as the named
51    /// re-exports and needs no trace data.
52    ///
53    /// # Errors
54    ///
55    /// Returns an error if parsing or analysis fails.
56    pub fn analyze_dead_code_keeping_graph(&self) -> EngineResult<DeadCodeAnalysisArtifacts> {
57        self.analyze_dead_code_with_reuse_artifacts(false, GraphChoice::GraphOnly, false)
58            .map(SharedDeadCodeAnalysisArtifacts::into_owned)
59    }
60
61    /// Build the module graph of this session without the dead-code
62    /// detectors. The graph has the reachability flags and the export
63    /// references, and it uses the persisted graph cache of the session.
64    ///
65    /// # Errors
66    ///
67    /// Returns an error when the prelude fails or the caller cancels.
68    pub(crate) fn build_module_graph(&self) -> EngineResult<RetainedModuleGraph> {
69        self.ensure_not_cancelled("parsing")?;
70        let SharedParsedModules { modules, .. } =
71            self.parse_modules(false, self.cancellation.as_deref());
72        self.ensure_not_cancelled("the module graph")?;
73        let prelude =
74            core_backend::prepare_dead_code_backend_prelude(&self.config, &self.discovery)?;
75        let entry_points = core_backend::discover_dead_code_entry_points(&prelude);
76        let (_resolved, graph, _rejection) =
77            resolve_or_build_dead_code_graph(&prelude, &entry_points, &modules);
78        prelude.finish();
79        Ok(graph.graph)
80    }
81}
82
83/// Reuse the persisted module graph, or rebuild it and carry the reason the
84/// persisted one was refused.
85///
86/// The reason is the third element rather than a discarded `Option`: a warm run
87/// that paid for a multi-megabyte decode and reused none of it is the case the
88/// perf table exists to explain, and every engine-backed command reaches the
89/// pipeline through here.
90pub fn resolve_or_build_dead_code_graph(
91    prelude: &core_backend::DeadCodeBackendPrelude,
92    entry_points: &core_backend::DeadCodeEntryPoints,
93    modules: &[ModuleInfo],
94) -> (
95    core_backend::DeadCodeResolvedModules,
96    core_backend::DeadCodeGraphRun,
97    Option<CacheRejection>,
98) {
99    let rejection =
100        match core_backend::try_load_dead_code_graph_cache(prelude, entry_points, modules) {
101            Ok((resolved, graph)) => return (resolved, graph, None),
102            Err(rejection) => rejection,
103        };
104
105    let mut resolved = core_backend::resolve_dead_code_imports(prelude, modules);
106    let graph =
107        core_backend::build_dead_code_graph(prelude, &mut resolved.project, entry_points, modules);
108    (resolved, graph, rejection)
109}