Skip to main content

fallow_engine/
test_side_imports.rs

1//! The imports of the files that production mode leaves out (issue #5251).
2//!
3//! A production run excludes test, story, fixture and bench files, the
4//! `production.ignore` globs, and the files that only a support entry seeds.
5//! Its graph has no edge from these files, so an export that only they import
6//! reads as unused. The scan builds the graph of the same project without
7//! production mode, and reads the references of the asked exports from the
8//! test-side files of that graph. [`TestSideMatcher`] decides which files are
9//! test-side.
10//!
11//! The scan keeps its persisted caches in a subfolder of the cache directory.
12//! The graph cache holds one graph, so with a shared folder each production
13//! run would replace the graph of the other mode.
14
15use std::path::{Path, PathBuf};
16
17use fallow_config::ResolvedConfig;
18use fallow_graph::graph::{ExportNamespace, ModuleGraph, ModuleNode};
19use fallow_types::output_dead_code::TestImporters;
20use fallow_types::results::AnalysisResults;
21use rustc_hash::FxHashMap;
22
23use crate::EngineResult;
24use crate::core_backend::TestSideMatcher;
25use crate::session::AnalysisSession;
26use crate::thread_pool::{WORKER_STACK_SIZE, register_thread_stack};
27
28/// The subfolder of the cache directory that the scan uses.
29const SCAN_CACHE_DIR: &str = "test-side-scan";
30
31/// One test-side file that references an export.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct TestSideImporter {
34    /// Absolute path of the referencing file.
35    pub path: PathBuf,
36    /// True when the file uses the export as a value, false for a type-only
37    /// use.
38    pub value: bool,
39}
40
41/// The test-side importers of the exports that a scan was asked about.
42#[derive(Debug, Default)]
43pub struct TestSideImports {
44    importers: FxHashMap<(PathBuf, String), Vec<TestSideImporter>>,
45}
46
47impl TestSideImports {
48    /// The importers of `export_name` in `path`, sorted by path. Empty when no
49    /// test-side file references the export, or when the scan was not asked
50    /// about it.
51    #[must_use]
52    pub fn importers(&self, path: &Path, export_name: &str) -> &[TestSideImporter] {
53        self.importers
54            .get(&(path.to_path_buf(), export_name.to_string()))
55            .map_or(&[], Vec::as_slice)
56    }
57}
58
59/// Find the test-side importers of each export in `targets`, in a graph of
60/// the project of `config` without production mode. Each target is the
61/// absolute path of the declaring file and the export name.
62///
63/// # Errors
64///
65/// Returns an error when the scan analysis fails.
66pub fn scan(
67    config: &ResolvedConfig,
68    targets: &[(PathBuf, String)],
69) -> EngineResult<TestSideImports> {
70    if targets.is_empty() {
71        return Ok(TestSideImports::default());
72    }
73    // The scan is a second analysis of the same root. Its diagnostics, and
74    // its warnings on stderr, are about the non-production view, so they must
75    // not reach the report of the production run. Both guards are per thread,
76    // and a scoped thread runs no other work. A worker of the thread pool
77    // could pick up a task of a parallel analysis, such as the duplication
78    // pass of a combined run, while it waits. The thread gets the stack size
79    // of a pool worker, because the analysis recurses on deep inputs.
80    std::thread::scope(|scope| {
81        let spawned = std::thread::Builder::new()
82            .name("fallow-test-side-scan".to_string())
83            .stack_size(WORKER_STACK_SIZE)
84            .spawn_scoped(scope, || {
85                register_thread_stack(WORKER_STACK_SIZE);
86                fallow_types::diagnostic_scope::with_scratch_diagnostics(|| {
87                    tracing::subscriber::with_default(
88                        tracing::subscriber::NoSubscriber::default(),
89                        || scan_on_this_thread(config, targets),
90                    )
91                })
92            });
93        let handle = spawned.map_err(|error| {
94            crate::EngineError::new(format!(
95                "failed to start the test-side import scan: {error}"
96            ))
97        })?;
98        handle
99            .join()
100            .unwrap_or_else(|panic| std::panic::resume_unwind(panic))
101    })
102}
103
104fn scan_on_this_thread(
105    config: &ResolvedConfig,
106    targets: &[(PathBuf, String)],
107) -> EngineResult<TestSideImports> {
108    let mut scan_config = config.clone();
109    scan_config.production = false;
110    scan_config.quiet = true;
111    scan_config.cache_dir = config.cache_dir.join(SCAN_CACHE_DIR);
112    let session = AnalysisSession::from_resolved_config(scan_config)?;
113    let graph = session.build_module_graph()?;
114    Ok(collect_importers(
115        graph.as_graph(),
116        &TestSideMatcher::new(config),
117        targets,
118    ))
119}
120
121/// Read the test-side references of each target export from `graph`, a
122/// graph that has the test edges.
123#[must_use]
124fn collect_importers(
125    graph: &ModuleGraph,
126    matcher: &TestSideMatcher,
127    targets: &[(PathBuf, String)],
128) -> TestSideImports {
129    let modules: FxHashMap<&Path, &ModuleNode> = graph
130        .modules()
131        .iter()
132        .map(|module| (module.path.as_path(), module))
133        .collect();
134    let mut importers: FxHashMap<(PathBuf, String), Vec<TestSideImporter>> = FxHashMap::default();
135    for (path, export_name) in targets {
136        let Some(module) = modules.get(path.as_path()) else {
137            continue;
138        };
139        let Some(export) = module
140            .exports
141            .iter()
142            .find(|export| export.name.matches_str(export_name))
143        else {
144            continue;
145        };
146        let mut found: FxHashMap<&Path, bool> = FxHashMap::default();
147        for reference in &export.references {
148            let Some(from) = graph
149                .module(reference.from_file)
150                .filter(|node| matcher.is_test_side(node))
151            else {
152                continue;
153            };
154            *found.entry(from.path.as_path()).or_default() |=
155                reference.namespace == ExportNamespace::Value;
156        }
157        if found.is_empty() {
158            continue;
159        }
160        let mut list: Vec<TestSideImporter> = found
161            .into_iter()
162            .map(|(path, value)| TestSideImporter {
163                path: path.to_path_buf(),
164                value,
165            })
166            .collect();
167        list.sort_unstable_by(|a, b| a.path.cmp(&b.path));
168        importers.insert((path.clone(), export_name.clone()), list);
169    }
170    TestSideImports { importers }
171}
172
173/// Set `test_importers` on each unused-export and unused-type finding of a
174/// production run that a test-side file imports. Does nothing outside
175/// production mode or when the run has no such finding.
176///
177/// # Errors
178///
179/// Returns an error when the scan analysis fails.
180pub(crate) fn attach_test_importers(
181    results: &mut AnalysisResults,
182    config: &ResolvedConfig,
183) -> EngineResult<()> {
184    if !config.production || (results.unused_exports.is_empty() && results.unused_types.is_empty())
185    {
186        return Ok(());
187    }
188    let targets: Vec<(PathBuf, String)> = results
189        .unused_exports
190        .iter()
191        .map(|finding| &finding.export)
192        .chain(results.unused_types.iter().map(|finding| &finding.export))
193        .map(|export| (export.path.clone(), export.export_name.clone()))
194        .collect();
195    let imports = scan(config, &targets)?;
196    let importers_of = |export: &fallow_types::results::UnusedExport| {
197        TestImporters::from_files(
198            imports
199                .importers(&export.path, &export.export_name)
200                .iter()
201                .map(|importer| importer.path.clone())
202                .collect(),
203        )
204    };
205    for finding in &mut results.unused_exports {
206        finding.test_importers = importers_of(&finding.export);
207    }
208    for finding in &mut results.unused_types {
209        finding.test_importers = importers_of(&finding.export);
210    }
211    Ok(())
212}