Skip to main content

fallow_engine/
module_graph.rs

1//! Module graph contracts owned by the engine boundary.
2
3#![allow(
4    clippy::implicit_hasher,
5    reason = "engine graph helpers use FxHashSet changed-file sets consistently with the rest of fallow"
6)]
7
8use std::path::{Path, PathBuf};
9
10use fallow_output::TestAdjacency;
11use fallow_types::discover::FileId;
12use rustc_hash::{FxHashMap, FxHashSet};
13
14use fallow_graph::graph::{
15    CoordinationGapPaths as GraphCoordinationGapPaths,
16    FocusFileFactsPaths as GraphFocusFileFactsPaths, ImpactClosurePaths as GraphImpactClosurePaths,
17    ModuleGraph, PartitionOrderPaths as GraphPartitionOrderPaths,
18    ReviewUnitPaths as GraphReviewUnitPaths,
19};
20use fallow_graph::graph::{
21    DirectImporterSummary as GraphDirectImporterSummary,
22    ImportedSymbolSummary as GraphImportedSymbolSummary,
23};
24use fallow_graph::graph::{
25    ExportTestReach as GraphExportTestReach, ExportTestReachResult as GraphExportTestReachResult,
26    TestMaskingState as GraphTestMaskingState,
27};
28
29/// Engine-owned retained graph handle.
30///
31/// Downstream crates can request stable graph facts through engine helpers
32/// without depending on `fallow-graph` node internals.
33#[derive(Debug)]
34pub struct RetainedModuleGraph {
35    inner: ModuleGraph,
36}
37
38impl RetainedModuleGraph {
39    /// Wrap a freshly built module graph for engine result contracts.
40    #[must_use]
41    const fn new(inner: ModuleGraph) -> Self {
42        Self { inner }
43    }
44
45    pub(crate) const fn as_graph(&self) -> &ModuleGraph {
46        &self.inner
47    }
48
49    /// Borrow the shared static test-coverage view for health analysis.
50    pub(crate) const fn static_test_coverage(&self) -> StaticTestCoverage<'_> {
51        StaticTestCoverage::new(&self.inner)
52    }
53
54    /// Number of modules in the retained graph.
55    #[must_use]
56    pub fn module_count(&self) -> usize {
57        self.inner.module_count()
58    }
59
60    /// Number of edges in the retained graph.
61    #[must_use]
62    pub fn edge_count(&self) -> usize {
63        self.inner.edge_count()
64    }
65
66    /// Build public export keys for a precomputed public-entry set.
67    #[must_use]
68    pub(crate) fn public_export_keys(
69        &self,
70        public_entries: &FxHashSet<FileId>,
71        root: &Path,
72    ) -> FxHashSet<String> {
73        self.inner.public_export_keys(public_entries, root)
74    }
75
76    /// Count direct importer modules for one file id.
77    #[must_use]
78    pub fn direct_importer_count(&self, file_id: FileId) -> usize {
79        self.inner
80            .reverse_deps
81            .get(file_id.0 as usize)
82            .map_or(0, Vec::len)
83    }
84
85    /// Summaries for modules that directly import one file.
86    #[must_use]
87    pub fn direct_importer_summaries(&self, target: FileId) -> Vec<DirectImporterSummary> {
88        self.inner
89            .direct_importer_summaries(target)
90            .into_iter()
91            .map(DirectImporterSummary::from)
92            .collect()
93    }
94}
95
96/// Engine-owned view of root-correlated static test reachability.
97///
98/// This keeps health consumers on one contract while the graph crate owns the
99/// traversal and replacement-mask representation.
100///
101/// A view can read a second graph that holds the test files. Production mode
102/// keeps test files out of the analysis graph, so health reads test
103/// reachability from a graph of the full project. `file_map` then maps each
104/// analysis file id to the file id of the same path in that graph.
105#[derive(Clone, Copy)]
106pub(crate) struct StaticTestCoverage<'a> {
107    graph: &'a ModuleGraph,
108    file_map: Option<&'a FxHashMap<FileId, FileId>>,
109}
110
111impl<'a> StaticTestCoverage<'a> {
112    pub(crate) const fn new(graph: &'a ModuleGraph) -> Self {
113        Self {
114            graph,
115            file_map: None,
116        }
117    }
118
119    /// Read test reachability from `graph`, a graph built over a different
120    /// file set. `file_map` maps the caller's file ids to the ids in `graph`.
121    pub(crate) const fn mapped(
122        graph: &'a ModuleGraph,
123        file_map: &'a FxHashMap<FileId, FileId>,
124    ) -> Self {
125        Self {
126            graph,
127            file_map: Some(file_map),
128        }
129    }
130
131    fn graph_file_id(self, file_id: FileId) -> Option<FileId> {
132        match self.file_map {
133            Some(file_map) => file_map.get(&file_id).copied(),
134            None => Some(file_id),
135        }
136    }
137
138    /// The export in the coverage graph that has the name of `export`.
139    fn graph_export<'b>(
140        self,
141        file_id: FileId,
142        export: &'b fallow_graph::graph::ExportSymbol,
143    ) -> Option<(FileId, &'b fallow_graph::graph::ExportSymbol)>
144    where
145        'a: 'b,
146    {
147        if self.file_map.is_none() {
148            return Some((file_id, export));
149        }
150        let graph_file_id = self.graph_file_id(file_id)?;
151        let node = self.graph.modules.get(graph_file_id.0 as usize)?;
152        node.exports
153            .iter()
154            .find(|candidate| candidate.name == export.name)
155            .map(|candidate| (graph_file_id, candidate))
156    }
157
158    pub(crate) fn covers_file(self, file_id: FileId) -> bool {
159        self.graph_file_id(file_id)
160            .is_some_and(|graph_file_id| self.graph.is_test_reachable(graph_file_id))
161    }
162
163    pub(crate) fn covers_any_reference(
164        self,
165        file_id: FileId,
166        export: &fallow_graph::graph::ExportSymbol,
167    ) -> bool {
168        self.graph_export(file_id, export)
169            .is_some_and(|(_, export)| self.graph.is_any_test_reference_covered(export))
170    }
171
172    /// Whether only tests that mock a module on the reference path reference
173    /// `export`. Call it for an export without a covered reference.
174    pub(crate) fn is_mocked_only(
175        self,
176        file_id: FileId,
177        export: &fallow_graph::graph::ExportSymbol,
178    ) -> bool {
179        if self.graph.test_masking_state() != GraphTestMaskingState::Active {
180            return false;
181        }
182        self.graph_export(file_id, export)
183            .is_some_and(|(graph_file_id, export)| {
184                self.graph
185                    .export_test_reach(graph_file_id, export, &|_| false)
186                    .reach
187                    == GraphExportTestReach::MockedOnly
188            })
189    }
190}
191
192impl From<ModuleGraph> for RetainedModuleGraph {
193    fn from(inner: ModuleGraph) -> Self {
194        Self::new(inner)
195    }
196}
197
198/// One named re-export statement entry, such as `export { a as b } from './mod'`.
199#[derive(Debug, Clone, PartialEq, Eq)]
200pub struct NamedReExport {
201    /// Absolute path of the module that holds the re-export.
202    pub path: PathBuf,
203    /// The name that the module exports (`b` in the example).
204    pub exported_name: String,
205    /// Absolute path of the module that the re-export reads from.
206    pub source_path: PathBuf,
207    /// The name that the re-export reads from the source module (`a`).
208    pub imported_name: String,
209}
210
211/// Return every named re-export that a source statement declares.
212///
213/// Star re-exports (`export * from`, `export * as ns from`) name no single
214/// export of the source module, so they are not in the result. Edges that the
215/// graph synthesized for star chains have no source statement and are also
216/// left out.
217#[must_use]
218pub fn named_re_exports(graph: &RetainedModuleGraph) -> Vec<NamedReExport> {
219    let graph = graph.as_graph();
220    graph
221        .modules
222        .iter()
223        .flat_map(|node| {
224            node.re_exports
225                .iter()
226                .filter(|edge| {
227                    edge.imported_name != "*"
228                        && edge.exported_name != "*"
229                        && !(edge.span.start == 0 && edge.span.end == 0)
230                })
231                .filter_map(|edge| {
232                    let source = graph.modules.get(edge.source_file.0 as usize)?;
233                    Some(NamedReExport {
234                        path: node.path.clone(),
235                        exported_name: edge.exported_name.clone(),
236                        source_path: source.path.clone(),
237                        imported_name: edge.imported_name.clone(),
238                    })
239                })
240        })
241        .collect()
242}
243
244/// Engine-owned importer details for one file that directly imports a target module.
245#[derive(Debug, Clone, PartialEq, Eq)]
246pub struct DirectImporterSummary {
247    /// File containing the import statement.
248    pub source: FileId,
249    /// Symbols this importer pulls from the target module.
250    pub symbols: Vec<ImportedSymbolSummary>,
251}
252
253impl From<GraphDirectImporterSummary> for DirectImporterSummary {
254    fn from(summary: GraphDirectImporterSummary) -> Self {
255        Self {
256            source: summary.source,
257            symbols: summary.symbols.into_iter().map(Into::into).collect(),
258        }
259    }
260}
261
262/// Engine-owned symbol details for a direct import edge.
263#[derive(Debug, Clone, PartialEq, Eq)]
264pub struct ImportedSymbolSummary {
265    /// Exported name as declared by the target module.
266    pub imported: String,
267    /// Local binding name at the import site.
268    pub local: String,
269    /// True for type-only imports, which do not count as value usage.
270    pub type_only: bool,
271}
272
273impl From<GraphImportedSymbolSummary> for ImportedSymbolSummary {
274    fn from(symbol: GraphImportedSymbolSummary) -> Self {
275        Self {
276            imported: symbol.imported,
277            local: symbol.local,
278            type_only: symbol.type_only,
279        }
280    }
281}
282
283/// Engine-owned snapshot of one value export in a module graph.
284#[derive(Debug, Clone, PartialEq, Eq)]
285pub struct ModuleValueExport {
286    /// File declaring the export.
287    pub file_id: FileId,
288    /// Exported name.
289    pub name: String,
290    /// Byte offset where the export declaration starts.
291    pub span_start: u32,
292    /// True when a test file references this export.
293    pub test_referenced: bool,
294}
295
296/// Engine-owned impact closure with file ids resolved to paths.
297#[derive(Debug, Clone, Default, PartialEq, Eq)]
298pub struct ImpactClosurePaths {
299    /// Changed files that are part of the diff under review.
300    pub in_diff: Vec<String>,
301    /// Files affected through the import closure but absent from the diff.
302    pub affected_not_shown: Vec<String>,
303    /// Changed contracts whose consumers were not updated in the same diff.
304    pub coordination_gap: Vec<CoordinationGapPaths>,
305}
306
307impl From<GraphImpactClosurePaths> for ImpactClosurePaths {
308    fn from(paths: GraphImpactClosurePaths) -> Self {
309        Self {
310            in_diff: paths.in_diff,
311            affected_not_shown: paths.affected_not_shown,
312            coordination_gap: paths
313                .coordination_gap
314                .into_iter()
315                .map(CoordinationGapPaths::from)
316                .collect(),
317        }
318    }
319}
320
321/// Engine-owned coordination gap between a changed contract and consumer.
322#[derive(Debug, Clone, PartialEq, Eq)]
323pub struct CoordinationGapPaths {
324    /// Path of the changed file whose contract moved.
325    pub changed_file: String,
326    /// Path of the consumer that was not updated alongside it.
327    pub consumer_file: String,
328    /// Symbols the consumer imports from the changed file.
329    pub consumed_symbols: Vec<String>,
330}
331
332impl From<GraphCoordinationGapPaths> for CoordinationGapPaths {
333    fn from(paths: GraphCoordinationGapPaths) -> Self {
334        Self {
335            changed_file: paths.changed_file,
336            consumer_file: paths.consumer_file,
337            consumed_symbols: paths.consumed_symbols,
338        }
339    }
340}
341
342/// Engine-owned review partition and dependency-sensible order.
343#[derive(Debug, Clone, Default, PartialEq, Eq)]
344pub struct PartitionOrderPaths {
345    /// Changed files partitioned into per-module review units.
346    pub units: Vec<ReviewUnitPaths>,
347    /// File paths in dependency-sensible review order (dependencies first).
348    pub order: Vec<String>,
349    /// Connected components of the inter-unit dependency graph: units that
350    /// share no import edge with any unit outside their slice.
351    pub independent_slices: Vec<Vec<String>>,
352}
353
354impl From<GraphPartitionOrderPaths> for PartitionOrderPaths {
355    fn from(paths: GraphPartitionOrderPaths) -> Self {
356        Self {
357            units: paths.units.into_iter().map(ReviewUnitPaths::from).collect(),
358            order: paths.order,
359            independent_slices: paths.independent_slices,
360        }
361    }
362}
363
364/// Engine-owned changed-file review unit.
365#[derive(Debug, Clone, PartialEq, Eq)]
366pub struct ReviewUnitPaths {
367    /// Directory the unit's files share.
368    pub module_dir: String,
369    /// Changed files grouped into this unit.
370    pub files: Vec<String>,
371}
372
373impl From<GraphReviewUnitPaths> for ReviewUnitPaths {
374    fn from(paths: GraphReviewUnitPaths) -> Self {
375        Self {
376            module_dir: paths.module_dir,
377            files: paths.files,
378        }
379    }
380}
381
382/// Engine-owned focus facts for one changed file.
383#[derive(Debug, Clone, PartialEq, Eq)]
384pub struct FocusFileFactsPaths {
385    /// Path of the changed file the facts describe.
386    pub file: String,
387    /// Count of distinct files importing this file (blast radius), excluding
388    /// the file itself.
389    pub fan_in: u32,
390    /// Count of distinct files this file imports, excluding the file itself.
391    pub fan_out: u32,
392    /// True when the file has a dynamic-import edge in either direction, so
393    /// its static reachability signal is not complete. Conservative: a file
394    /// that MAY be dynamically wired carries the flag.
395    pub dynamic_dispatch: bool,
396    /// True when the file's reachability runs through re-export indirection,
397    /// so direct importer counts understate its reach.
398    pub re_export_indirection: bool,
399}
400
401impl From<GraphFocusFileFactsPaths> for FocusFileFactsPaths {
402    fn from(paths: GraphFocusFileFactsPaths) -> Self {
403        Self {
404            file: paths.file,
405            fan_in: paths.fan_in,
406            fan_out: paths.fan_out,
407            dynamic_dispatch: paths.dynamic_dispatch,
408            re_export_indirection: paths.re_export_indirection,
409        }
410    }
411}
412
413/// Return value exports with test-reference state without exposing graph node
414/// internals to downstream crates.
415#[must_use]
416pub fn module_value_exports(graph: &RetainedModuleGraph) -> Vec<ModuleValueExport> {
417    module_value_exports_with_test_reach(graph, None)
418}
419
420/// Return value exports of `graph` with test-reference state.
421///
422/// When `test_reach` is given, test-reference state comes from that
423/// full-project graph. Production mode needs this because its analysis graph
424/// has no test files.
425#[must_use]
426pub fn module_value_exports_with_test_reach(
427    graph: &RetainedModuleGraph,
428    test_reach: Option<&crate::health::TestReachGraph>,
429) -> Vec<ModuleValueExport> {
430    let test_coverage = test_reach.map_or_else(
431        || graph.static_test_coverage(),
432        crate::health::TestReachGraph::static_test_coverage,
433    );
434    let graph = graph.as_graph();
435
436    graph
437        .modules
438        .iter()
439        .flat_map(|node| {
440            node.exports
441                .iter()
442                .filter(|export| !export.is_type_only)
443                .map(|export| ModuleValueExport {
444                    file_id: node.file_id,
445                    name: export.name.to_string(),
446                    span_start: export.span.start,
447                    test_referenced: test_coverage.covers_any_reference(node.file_id, export),
448                })
449        })
450        .collect()
451}
452
453/// Compute a path-resolved impact closure for absolute changed paths.
454#[must_use]
455pub fn impact_closure_for_changed_paths(
456    graph: &RetainedModuleGraph,
457    root: &Path,
458    changed_files: &FxHashSet<PathBuf>,
459) -> Option<ImpactClosurePaths> {
460    let graph = graph.as_graph();
461    let changed_ids = changed_file_ids(graph, changed_files);
462    if changed_ids.is_empty() {
463        return None;
464    }
465
466    let closure = graph.impact_closure(&changed_ids);
467    Some(graph.closure_with_paths(&closure, root).into())
468}
469
470/// Compute path-resolved partition order for absolute changed paths.
471#[must_use]
472pub fn partition_order_for_changed_paths(
473    graph: &RetainedModuleGraph,
474    root: &Path,
475    changed_files: &FxHashSet<PathBuf>,
476) -> Option<PartitionOrderPaths> {
477    let graph = graph.as_graph();
478    let changed_ids = changed_file_ids(graph, changed_files);
479    if changed_ids.is_empty() {
480        return None;
481    }
482
483    let partition = graph.partition_order(&changed_ids);
484    Some(graph.partition_order_with_paths(&partition, root).into())
485}
486
487/// Compute path-resolved focus graph facts for absolute changed paths.
488#[must_use]
489pub fn focus_facts_for_changed_paths(
490    graph: &RetainedModuleGraph,
491    root: &Path,
492    changed_files: &FxHashSet<PathBuf>,
493) -> Option<Vec<FocusFileFactsPaths>> {
494    let graph = graph.as_graph();
495    let changed_ids = changed_file_ids(graph, changed_files);
496    if changed_ids.is_empty() {
497        return None;
498    }
499
500    let facts = graph.focus_file_facts(&changed_ids);
501    Some(
502        graph
503            .focus_facts_with_paths(&facts, root)
504            .into_iter()
505            .map(FocusFileFactsPaths::from)
506            .collect(),
507    )
508}
509
510/// Compute changed-file export line anchors without exposing graph nodes.
511#[must_use]
512pub fn export_lines_for_changed_paths(
513    graph: &RetainedModuleGraph,
514    root: &Path,
515    changed_files: &FxHashSet<PathBuf>,
516) -> Option<FxHashMap<String, Vec<(String, u32)>>> {
517    let graph = graph.as_graph();
518    let changed_norm = normalized_changed_paths(changed_files);
519    let mut map: FxHashMap<String, Vec<(String, u32)>> = FxHashMap::default();
520    for module in &graph.modules {
521        let abs = normalize_path(&module.path);
522        if !changed_norm.contains(&abs) || module.exports.is_empty() {
523            continue;
524        }
525        let Ok(content) = std::fs::read_to_string(&module.path) else {
526            continue;
527        };
528        let offsets = fallow_types::extract::compute_line_offsets(&content);
529        let exports: Vec<(String, u32)> = module
530            .exports
531            .iter()
532            .map(|export| {
533                let (line, _) =
534                    fallow_types::extract::byte_offset_to_line_col(&offsets, export.span.start);
535                (export.name.to_string(), line)
536            })
537            .collect();
538        map.insert(relative_key_path(&module.path, root), exports);
539    }
540    Some(map)
541}
542
543/// One consumer that a whole-word text search for an export name does not
544/// find, or finds only under another local name.
545#[derive(Debug, Clone, PartialEq, Eq)]
546pub struct ConsumerSearchGapPaths {
547    /// Root-relative path of the consumer, forward-slashed.
548    pub consumer_file: String,
549    /// The literal-search check for the consumer.
550    pub check: crate::search_visibility::SearchCheck,
551}
552
553/// Literal-search gaps for one export of a changed file.
554#[derive(Debug, Clone, PartialEq, Eq)]
555pub struct ExportSearchGapPaths {
556    /// Root-relative path of the changed file, forward-slashed.
557    pub file: String,
558    /// The export name, `default` for a default export.
559    pub export_name: String,
560    /// 1-based line of the export.
561    pub line: u32,
562    /// 1-based first and last line of the top-level statement that declares
563    /// the export.
564    pub declaration_lines: (u32, u32),
565    /// The `missed` and `renamed` consumers outside the changed files, sorted
566    /// by path.
567    pub consumers: Vec<ConsumerSearchGapPaths>,
568}
569
570/// The names of the exports that `source` declares, parsed as the file at
571/// `path`. The names use the format of [`ChangedExport::export_name`].
572#[must_use]
573pub fn export_names_in_source(path: &Path, source: &str) -> FxHashSet<String> {
574    let module = fallow_extract::parse_source_to_module(FileId(0), path, source, 0, false);
575    module
576        .exports
577        .iter()
578        .map(|export| export.name.to_string())
579        .collect()
580}
581
582/// One export of a changed file, with the line facts that the review brief
583/// joins on the diff.
584///
585/// [`changed_exports_for_changed_paths`] reads and parses each changed file
586/// once. The literal-search gap pass and the test reach pass share the list.
587#[derive(Debug, Clone, PartialEq, Eq)]
588pub struct ChangedExport {
589    file_id: FileId,
590    export_index: usize,
591    /// Root-relative path of the changed file, forward-slashed.
592    pub file: String,
593    /// The export name, `default` for a default export.
594    pub export_name: String,
595    /// 1-based line of the export.
596    pub line: u32,
597    /// 1-based first and last line of the top-level statement that declares
598    /// the export.
599    pub declaration_lines: (u32, u32),
600    /// True for a type-only export.
601    pub is_type_only: bool,
602    /// True when the export is a variable whose initializer is a literal, or
603    /// an object or array of literals.
604    pub literal_value: bool,
605    /// True when a re-export statement (`export { x } from`) makes the export.
606    pub is_re_export: bool,
607}
608
609/// List the exports of absolute changed paths with their declaration lines.
610///
611/// Each changed file is read and parsed once. The exports keep graph order
612/// within a file, and the files are in `FileId` order. `None` when no module
613/// matches a changed path.
614#[must_use]
615pub fn changed_exports_for_changed_paths(
616    graph: &RetainedModuleGraph,
617    root: &Path,
618    changed_files: &FxHashSet<PathBuf>,
619) -> Option<Vec<ChangedExport>> {
620    let graph = graph.as_graph();
621    let mut changed_ids = changed_file_ids(graph, changed_files);
622    if changed_ids.is_empty() {
623        return None;
624    }
625    changed_ids.sort_unstable_by_key(|id| id.0);
626    let mut changed_exports = Vec::new();
627    for file_id in changed_ids {
628        let Some(module) = graph.modules.get(file_id.0 as usize) else {
629            continue;
630        };
631        if module.exports.is_empty() {
632            continue;
633        }
634        let Ok(source) = std::fs::read_to_string(&module.path) else {
635            continue;
636        };
637        changed_exports.extend(module_exports(graph, root, file_id, &source));
638    }
639    Some(changed_exports)
640}
641
642/// List the exports of one module with their declaration lines. `source` is
643/// the current text of the module. The exports keep graph order.
644pub(crate) fn module_exports(
645    graph: &ModuleGraph,
646    root: &Path,
647    file_id: FileId,
648    source: &str,
649) -> Vec<ChangedExport> {
650    let Some(module) = graph.modules.get(file_id.0 as usize) else {
651        return Vec::new();
652    };
653    if module.exports.is_empty() {
654        return Vec::new();
655    }
656    let offsets = fallow_types::extract::compute_line_offsets(source);
657    let starts: Vec<u32> = module
658        .exports
659        .iter()
660        .map(|export| export.span.start)
661        .collect();
662    let declarations = crate::search_visibility::export_declarations(&module.path, source, &starts);
663    let file = relative_key_path(&module.path, root);
664    module
665        .exports
666        .iter()
667        .enumerate()
668        .map(|(export_index, export)| {
669            let line =
670                fallow_types::extract::byte_offset_to_line_col(&offsets, export.span.start).0;
671            let declaration = declarations.get(&export.span.start);
672            ChangedExport {
673                file_id,
674                export_index,
675                file: file.clone(),
676                export_name: export.name.to_string(),
677                line,
678                declaration_lines: declaration.map_or((line, line), |found| found.lines),
679                is_type_only: export.is_type_only,
680                literal_value: declaration.is_some_and(|found| found.literal_value),
681                is_re_export: declaration.is_some_and(|found| found.is_re_export),
682            }
683        })
684        .collect()
685}
686
687/// Compute the literal-search gaps of the changed exports.
688///
689/// For each export of a changed file, the consumers outside the changed set
690/// are checked against a whole-word text search for the export name. Only
691/// exports with at least one `missed` or `renamed` consumer are returned. The
692/// consumer sources are read on demand.
693#[must_use]
694pub fn search_gaps_for_changed_paths(
695    graph: &RetainedModuleGraph,
696    root: &Path,
697    changed_files: &FxHashSet<PathBuf>,
698    changed_exports: &[ChangedExport],
699) -> Option<Vec<ExportSearchGapPaths>> {
700    use crate::search_visibility::{SearchTarget, SourceCache};
701    use fallow_graph::graph::ExportNamespace;
702    use fallow_types::trace::SearchVisibility;
703
704    let graph = graph.as_graph();
705    let changed_set: FxHashSet<FileId> =
706        changed_file_ids(graph, changed_files).into_iter().collect();
707    if changed_set.is_empty() {
708        return None;
709    }
710    let mut sources = SourceCache::new(graph);
711    let mut gaps = Vec::new();
712    for changed in changed_exports {
713        let Some(export) = graph
714            .modules
715            .get(changed.file_id.0 as usize)
716            .and_then(|module| module.exports.get(changed.export_index))
717        else {
718            continue;
719        };
720        let mut seen = FxHashSet::default();
721        let candidates: Vec<_> = export
722            .references
723            .iter()
724            .filter(|reference| {
725                !changed_set.contains(&reference.from_file)
726                    && graph
727                        .modules
728                        .get(reference.from_file.0 as usize)
729                        .is_some_and(fallow_graph::graph::ModuleNode::is_reachable)
730                    && seen.insert(reference.from_file)
731            })
732            .collect();
733        if candidates.is_empty() {
734            continue;
735        }
736        let namespace = if export.is_type_only {
737            ExportNamespace::Type
738        } else {
739            ExportNamespace::Value
740        };
741        let target = SearchTarget::new(
742            graph,
743            &mut sources,
744            changed.file_id,
745            &changed.export_name,
746            namespace,
747        );
748        let mut consumers: Vec<ConsumerSearchGapPaths> = candidates
749            .into_iter()
750            .filter_map(|reference| {
751                let check = target.check(graph, &mut sources, reference)?;
752                if check.visibility == SearchVisibility::Found {
753                    return None;
754                }
755                let consumer = graph.modules.get(reference.from_file.0 as usize)?;
756                Some(ConsumerSearchGapPaths {
757                    consumer_file: relative_key_path(&consumer.path, root),
758                    check,
759                })
760            })
761            .collect();
762        if consumers.is_empty() {
763            continue;
764        }
765        consumers.sort_by(|a, b| a.consumer_file.cmp(&b.consumer_file));
766        gaps.push(ExportSearchGapPaths {
767            file: changed.file.clone(),
768            export_name: changed.export_name.clone(),
769            line: changed.line,
770            declaration_lines: changed.declaration_lines,
771            consumers,
772        });
773    }
774    Some(gaps)
775}
776
777/// Package names whose presence marks an end-to-end test runner. Such tests
778/// drive a running app and do not import the source files.
779const E2E_RUNNER_PACKAGES: &[&str] = &["@playwright/test", "playwright", "cypress"];
780
781/// How tests reach one export.
782#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize)]
783#[serde(rename_all = "kebab-case")]
784pub enum ExportTestReach {
785    /// A test file references the export, and a test root covers it.
786    Direct,
787    /// A covered reference exists, but no test file names the export.
788    Transitive,
789    /// No reference is covered, and a mock replaces a module on a reference
790    /// path.
791    MockedOnly,
792    /// A test root reaches the declaring file, but no reference is covered.
793    None,
794    /// No test root reaches the declaring file.
795    NoneFile,
796}
797
798impl From<GraphExportTestReach> for ExportTestReach {
799    fn from(reach: GraphExportTestReach) -> Self {
800        match reach {
801            GraphExportTestReach::Direct => Self::Direct,
802            GraphExportTestReach::Transitive => Self::Transitive,
803            GraphExportTestReach::MockedOnly => Self::MockedOnly,
804            GraphExportTestReach::None => Self::None,
805            GraphExportTestReach::NoneFile => Self::NoneFile,
806        }
807    }
808}
809
810/// Why replacement masking is or is not active for test reachability.
811#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
812pub enum TestMaskingState {
813    /// At least one test root replaces a module with a closed factory mock.
814    Active,
815    /// No test root declares a closed factory mock.
816    NoMocks,
817    /// Too many distinct mock sets, so masking is off.
818    Capped,
819}
820
821impl From<GraphTestMaskingState> for TestMaskingState {
822    fn from(state: GraphTestMaskingState) -> Self {
823        match state {
824            GraphTestMaskingState::Active => Self::Active,
825            GraphTestMaskingState::NoMocks => Self::NoMocks,
826            GraphTestMaskingState::Capped => Self::Capped,
827        }
828    }
829}
830
831/// How tests reach one changed value export.
832#[derive(Debug, Clone, PartialEq, Eq)]
833pub struct ExportTestReachPaths {
834    /// Root-relative path of the changed file, forward-slashed.
835    pub file: String,
836    /// The export name, `default` for a default export.
837    pub export_name: String,
838    /// 1-based line of the export.
839    pub line: u32,
840    /// 1-based first and last line of the declaring statement.
841    pub declaration_lines: (u32, u32),
842    /// True when the export is a variable with a literal initializer.
843    pub literal_value: bool,
844    /// The reach class.
845    pub reach: ExportTestReach,
846    /// Test files that name the export, sorted: the covered test references
847    /// for `Direct`, the masked test references for `MockedOnly`.
848    pub tests: Vec<String>,
849    /// For `MockedOnly`: the masked modules on the reference paths, sorted.
850    pub mocked_targets: Vec<String>,
851}
852
853/// Test reach of the changed value exports of a diff.
854#[derive(Debug, Clone, PartialEq, Eq)]
855pub struct TestReachPaths {
856    /// False when the project has no test entry points. Every export is then
857    /// `NoneFile`.
858    pub has_tests: bool,
859    /// Whether test reachability applies replacement masks.
860    pub masking: TestMaskingState,
861    /// True when the project imports an end-to-end test runner package.
862    pub has_e2e_runner: bool,
863    /// One row per changed value export of a changed source file.
864    pub exports: Vec<ExportTestReachPaths>,
865}
866
867/// Classify how tests reach the value exports in `changed_exports`.
868///
869/// Type-only exports, re-exports, exports of test files, of declaration files
870/// and of stylesheets are skipped. `is_test_path` classifies a root-relative,
871/// forward-slashed path; a test entry point always counts as a test file.
872/// The rows keep the order of `changed_exports`. `None` when the list holds no
873/// such export.
874#[must_use]
875pub fn test_reach_for_changed_paths(
876    graph: &RetainedModuleGraph,
877    root: &Path,
878    changed_exports: &[ChangedExport],
879    is_test_path: &dyn Fn(&str) -> bool,
880) -> Option<TestReachPaths> {
881    let graph = graph.as_graph();
882    let mut test_files: FxHashMap<FileId, bool> = FxHashMap::default();
883    let mut is_test_file = |file_id: FileId| -> bool {
884        *test_files.entry(file_id).or_insert_with(|| {
885            graph.test_entry_points.contains(&file_id)
886                || graph
887                    .modules
888                    .get(file_id.0 as usize)
889                    .is_some_and(|module| is_test_path(&relative_key_path(&module.path, root)))
890        })
891    };
892    let has_tests = !graph.test_entry_points.is_empty();
893    let exports: Vec<ExportTestReachPaths> = changed_exports
894        .iter()
895        .filter_map(|changed| classify_export_test_reach(graph, root, changed, &mut is_test_file))
896        .collect();
897    if exports.is_empty() {
898        return None;
899    }
900    let has_e2e_runner = E2E_RUNNER_PACKAGES.iter().any(|name| {
901        graph.package_usage.contains_key(*name) || graph.type_only_package_usage.contains_key(*name)
902    });
903    Some(TestReachPaths {
904        has_tests,
905        masking: graph.test_masking_state().into(),
906        has_e2e_runner,
907        exports,
908    })
909}
910
911/// Classify how tests reach one export. `None` for a type-only export, a
912/// re-export, an export of a test file, of a declaration file or of a
913/// stylesheet. `is_test_file` decides which referencing files are tests. In a
914/// project with no test entry points, the class is `NoneFile`.
915pub(crate) fn classify_export_test_reach(
916    graph: &ModuleGraph,
917    root: &Path,
918    changed: &ChangedExport,
919    is_test_file: &mut dyn FnMut(FileId) -> bool,
920) -> Option<ExportTestReachPaths> {
921    if changed.is_type_only || changed.is_re_export {
922        return None;
923    }
924    let module = graph.modules.get(changed.file_id.0 as usize)?;
925    let export = module.exports.get(changed.export_index)?;
926    if !is_reach_subject(&module.path) || is_test_file(changed.file_id) {
927        return None;
928    }
929    let result = if graph.test_entry_points.is_empty() {
930        GraphExportTestReachResult {
931            reach: GraphExportTestReach::NoneFile,
932            tests: Vec::new(),
933            mocked_targets: Vec::new(),
934        }
935    } else {
936        let test_flags: FxHashMap<FileId, bool> = export
937            .references
938            .iter()
939            .map(|reference| (reference.from_file, is_test_file(reference.from_file)))
940            .collect();
941        graph.export_test_reach(changed.file_id, export, &|file_id| {
942            test_flags.get(&file_id).copied().unwrap_or(false)
943        })
944    };
945    let paths_of = |files: &[FileId]| -> Vec<String> {
946        let mut paths: Vec<String> = files
947            .iter()
948            .filter_map(|file_id| graph.modules.get(file_id.0 as usize))
949            .map(|node| relative_key_path(&node.path, root))
950            .collect();
951        paths.sort_unstable();
952        paths
953    };
954    Some(ExportTestReachPaths {
955        file: changed.file.clone(),
956        export_name: changed.export_name.clone(),
957        line: changed.line,
958        declaration_lines: changed.declaration_lines,
959        literal_value: changed.literal_value,
960        reach: result.reach.into(),
961        tests: paths_of(&result.tests),
962        mocked_targets: paths_of(&result.mocked_targets),
963    })
964}
965
966/// Whether test reach applies to a file: runtime source code, not a
967/// declaration file or a stylesheet.
968fn is_reach_subject(path: &Path) -> bool {
969    if fallow_graph::graph::is_declaration_file_path(path) {
970        return false;
971    }
972    !path
973        .extension()
974        .and_then(|extension| extension.to_str())
975        .is_some_and(|extension| matches!(extension, "css" | "scss" | "less" | "sass"))
976}
977
978/// Compute direct non-diff internal consumer counts for absolute changed paths.
979#[must_use]
980pub fn internal_consumers_for_changed_paths(
981    graph: &RetainedModuleGraph,
982    root: &Path,
983    changed_files: &FxHashSet<PathBuf>,
984) -> Option<FxHashMap<String, u64>> {
985    let graph = graph.as_graph();
986    let changed_norm = normalized_changed_paths(changed_files);
987    let id_to_norm: FxHashMap<FileId, String> = graph
988        .modules
989        .iter()
990        .map(|module| (module.file_id, normalize_path(&module.path)))
991        .collect();
992
993    let mut map: FxHashMap<String, u64> = FxHashMap::default();
994    for module in &graph.modules {
995        let abs = normalize_path(&module.path);
996        if !changed_norm.contains(&abs) {
997            continue;
998        }
999        let count = graph
1000            .importers_of(module.file_id)
1001            .iter()
1002            .filter(|imp| {
1003                id_to_norm
1004                    .get(imp)
1005                    .is_none_or(|p| !changed_norm.contains(p))
1006            })
1007            .count() as u64;
1008        map.insert(relative_key_path(&module.path, root), count);
1009    }
1010    Some(map)
1011}
1012
1013/// Compute per-changed-file test adjacency for the review direction: whether a
1014/// test file imports the changed module directly, and whether one of those tests
1015/// is itself in the changed set. `is_test_path` classifies a root-relative,
1016/// forward-slashed path; the caller owns that definition so the brief's
1017/// weakening and direction surfaces agree on it. Changed test files get no
1018/// entry of their own. `None` when no module matches a changed path.
1019#[must_use]
1020pub fn test_adjacency_for_changed_paths(
1021    graph: &RetainedModuleGraph,
1022    root: &Path,
1023    changed_files: &FxHashSet<PathBuf>,
1024    is_test_path: &dyn Fn(&str) -> bool,
1025) -> Option<FxHashMap<String, TestAdjacency>> {
1026    let graph = graph.as_graph();
1027    // A project with no test files at all gets no adjacency claims: "no direct
1028    // test" on every unit would say nothing about the change.
1029    if !graph
1030        .modules
1031        .iter()
1032        .any(|module| is_test_path(&relative_key_path(&module.path, root)))
1033    {
1034        return None;
1035    }
1036    let changed_norm = normalized_changed_paths(changed_files);
1037    let mut map: FxHashMap<String, TestAdjacency> = FxHashMap::default();
1038    for module in &graph.modules {
1039        if !changed_norm.contains(&normalize_path(&module.path)) {
1040            continue;
1041        }
1042        let rel = relative_key_path(&module.path, root);
1043        if is_test_path(&rel) {
1044            continue;
1045        }
1046        let mut adjacency = TestAdjacency::None;
1047        for importer in graph.importers_of(module.file_id) {
1048            let Some(node) = graph.modules.get(importer.0 as usize) else {
1049                continue;
1050            };
1051            if !is_test_path(&relative_key_path(&node.path, root)) {
1052                continue;
1053            }
1054            if changed_norm.contains(&normalize_path(&node.path)) {
1055                adjacency = TestAdjacency::Changed;
1056                break;
1057            }
1058            adjacency = TestAdjacency::Untouched;
1059        }
1060        map.insert(rel, adjacency);
1061    }
1062    if map.is_empty() {
1063        return None;
1064    }
1065    Some(map)
1066}
1067
1068/// In-repo importer counts for one third-party package.
1069#[derive(Debug, Clone, Default, PartialEq, Eq)]
1070pub struct PackageImporters {
1071    /// Modules that import the package (value imports only), id-sorted. Kept
1072    /// as ids rather than a count so a decision that batches several packages
1073    /// can take the union instead of double-counting a module that imports
1074    /// more than one of them.
1075    pub importers: Vec<FileId>,
1076    /// The subset of `importers` outside the changed set, id-sorted.
1077    pub out_of_diff: Vec<FileId>,
1078}
1079
1080/// Compute per-package in-repo importer counts for every third-party package
1081/// the graph saw an import of, value or type-only, split by whether the
1082/// importer is in the changed set. Type-only importers count because a major
1083/// bump of a types package is a compile-wide change even when no value
1084/// crosses the boundary. The dependency decision arm reads these so a new or
1085/// bumped `package.json` entry carries the modules it actually reaches. `None`
1086/// when the graph recorded no package usage.
1087#[must_use]
1088pub fn package_importers_for_changed_paths(
1089    graph: &RetainedModuleGraph,
1090    changed_files: &FxHashSet<PathBuf>,
1091) -> Option<FxHashMap<String, PackageImporters>> {
1092    let graph = graph.as_graph();
1093    if graph.package_usage.is_empty() && graph.type_only_package_usage.is_empty() {
1094        return None;
1095    }
1096    let changed_norm = normalized_changed_paths(changed_files);
1097    let id_to_norm: FxHashMap<FileId, String> = graph
1098        .modules
1099        .iter()
1100        .map(|module| (module.file_id, normalize_path(&module.path)))
1101        .collect();
1102    let mut usage: FxHashMap<&str, Vec<FileId>> = FxHashMap::default();
1103    for (package, files) in graph
1104        .package_usage
1105        .iter()
1106        .chain(graph.type_only_package_usage.iter())
1107    {
1108        usage
1109            .entry(package.as_str())
1110            .or_default()
1111            .extend(files.iter().copied());
1112    }
1113    let map = usage
1114        .into_iter()
1115        .map(|(package, files)| {
1116            let mut importers: Vec<FileId> = files;
1117            importers.sort_unstable_by_key(|id| id.0);
1118            importers.dedup();
1119            let out_of_diff: Vec<FileId> = importers
1120                .iter()
1121                .copied()
1122                .filter(|id| id_to_norm.get(id).is_none_or(|p| !changed_norm.contains(p)))
1123                .collect();
1124            (
1125                package.to_string(),
1126                PackageImporters {
1127                    importers,
1128                    out_of_diff,
1129                },
1130            )
1131        })
1132        .collect();
1133    Some(map)
1134}
1135
1136fn changed_file_ids(graph: &ModuleGraph, changed_files: &FxHashSet<PathBuf>) -> Vec<FileId> {
1137    let path_to_id: FxHashMap<String, FileId> = graph
1138        .modules
1139        .iter()
1140        .map(|module| (normalize_path(&module.path), module.file_id))
1141        .collect();
1142
1143    changed_files
1144        .iter()
1145        .filter_map(|path| path_to_id.get(&normalize_path(path)).copied())
1146        .collect()
1147}
1148
1149fn normalized_changed_paths(changed_files: &FxHashSet<PathBuf>) -> FxHashSet<String> {
1150    changed_files
1151        .iter()
1152        .map(|path| normalize_path(path))
1153        .collect()
1154}
1155
1156fn normalize_path(path: &Path) -> String {
1157    path.to_string_lossy().replace('\\', "/")
1158}
1159
1160/// Canonical path form used inside audit attribution keys: root-relative with
1161/// forward slashes on every platform. Paths outside `root` keep their
1162/// simplified absolute form so keys stay unique.
1163///
1164/// The engine keys its per-module maps with this function, and
1165/// `fallow-api` builds its lookup keys with the same function, so both sides
1166/// of the join always agree.
1167pub fn relative_key_path(path: &Path, root: &Path) -> String {
1168    let simple_path = dunce::simplified(path);
1169    let simple_root = dunce::simplified(root);
1170    simple_path
1171        .strip_prefix(simple_root)
1172        .unwrap_or(simple_path)
1173        .to_string_lossy()
1174        .replace('\\', "/")
1175}
1176
1177#[cfg(test)]
1178mod tests {
1179    use super::{RetainedModuleGraph, module_value_exports};
1180    use fallow_graph::graph::ModuleGraph;
1181    use fallow_graph::resolve::{
1182        ResolveResult, ResolvedImport, ResolvedModule, ResolvedReplacedModuleTarget,
1183    };
1184    use fallow_types::discover::{DiscoveredFile, EntryPoint, EntryPointSource, FileId};
1185    use fallow_types::extract::{ExportInfo, ExportName, ImportInfo, ImportedName, VisibilityTag};
1186    use std::path::PathBuf;
1187
1188    fn import(target: FileId, imported_name: ImportedName) -> ResolvedImport {
1189        import_with_mechanism(target, imported_name, false)
1190    }
1191
1192    fn import_with_mechanism(
1193        target: FileId,
1194        imported_name: ImportedName,
1195        commonjs: bool,
1196    ) -> ResolvedImport {
1197        ResolvedImport {
1198            info: ImportInfo {
1199                source: "./target".to_string(),
1200                imported_name,
1201                local_name: "target".to_string(),
1202                is_type_only: false,
1203                is_type_only_star: false,
1204                from_style: false,
1205                span: oxc_span::Span::new(0, 10),
1206                source_span: oxc_span::Span::default(),
1207            },
1208            target: if commonjs {
1209                ResolveResult::CommonJsInternalModule(target)
1210            } else {
1211                ResolveResult::InternalModule(target)
1212            },
1213        }
1214    }
1215
1216    fn value_export(name: &str, span_start: u32) -> ExportInfo {
1217        ExportInfo {
1218            name: ExportName::Named(name.to_string()),
1219            local_name: Some(name.to_string()),
1220            is_type_only: false,
1221            visibility: VisibilityTag::None,
1222            expected_unused_reason: None,
1223            span: oxc_span::Span::new(span_start, span_start + 10),
1224            members: Vec::new(),
1225            is_side_effect_used: false,
1226            super_class: None,
1227            deprecated: false,
1228            deprecated_reason: None,
1229        }
1230    }
1231
1232    fn mixed_root_graph(unmasked_root_imports_export: bool) -> RetainedModuleGraph {
1233        let files: Vec<_> = (0..3)
1234            .map(|id| DiscoveredFile {
1235                id: FileId(id),
1236                path: PathBuf::from(format!("/project/file{id}.ts")),
1237                size_bytes: 1,
1238            })
1239            .collect();
1240        let modules = vec![
1241            ResolvedModule {
1242                file_id: FileId(0),
1243                path: files[0].path.clone(),
1244                resolved_imports: vec![import(
1245                    FileId(2),
1246                    ImportedName::Named("target".to_string()),
1247                )],
1248                ..ResolvedModule::default()
1249            },
1250            ResolvedModule {
1251                file_id: FileId(1),
1252                path: files[1].path.clone(),
1253                resolved_imports: vec![import(
1254                    FileId(2),
1255                    if unmasked_root_imports_export {
1256                        ImportedName::Named("target".to_string())
1257                    } else {
1258                        ImportedName::SideEffect
1259                    },
1260                )],
1261                ..ResolvedModule::default()
1262            },
1263            ResolvedModule {
1264                file_id: FileId(2),
1265                path: files[2].path.clone(),
1266                exports: vec![value_export("target", 0)].into(),
1267                ..ResolvedModule::default()
1268            },
1269        ];
1270        let test_entry_points = vec![
1271            EntryPoint {
1272                path: files[0].path.clone(),
1273                source: EntryPointSource::TestFile,
1274            },
1275            EntryPoint {
1276                path: files[1].path.clone(),
1277                source: EntryPointSource::TestFile,
1278            },
1279        ];
1280        let graph = ModuleGraph::build_with_reachability_roots_and_replacements(
1281            &modules,
1282            &[ResolvedReplacedModuleTarget {
1283                source_file: FileId(0),
1284                target_file: FileId(2),
1285            }],
1286            &test_entry_points,
1287            &[],
1288            &test_entry_points,
1289            &files,
1290        );
1291        RetainedModuleGraph::from(graph)
1292    }
1293
1294    #[test]
1295    fn export_coverage_requires_one_root_to_reach_consumer_and_target() {
1296        let graph = mixed_root_graph(false);
1297
1298        let exports = module_value_exports(&graph);
1299
1300        assert_eq!(exports.len(), 1);
1301        assert!(!exports[0].test_referenced);
1302    }
1303
1304    #[test]
1305    fn export_coverage_accepts_an_unmasked_correlated_reference() {
1306        let graph = mixed_root_graph(true);
1307
1308        let exports = module_value_exports(&graph);
1309
1310        assert_eq!(exports.len(), 1);
1311        assert!(exports[0].test_referenced);
1312    }
1313
1314    #[test]
1315    fn commonjs_reference_does_not_credit_a_mocked_esm_export() {
1316        let files: Vec<_> = (0..2)
1317            .map(|id| DiscoveredFile {
1318                id: FileId(id),
1319                path: PathBuf::from(format!("/project/file{id}.ts")),
1320                size_bytes: 1,
1321            })
1322            .collect();
1323        let modules = vec![
1324            ResolvedModule {
1325                file_id: FileId(0),
1326                path: files[0].path.clone(),
1327                resolved_imports: vec![
1328                    import_with_mechanism(
1329                        FileId(1),
1330                        ImportedName::Named("esmOnly".to_string()),
1331                        false,
1332                    ),
1333                    import_with_mechanism(
1334                        FileId(1),
1335                        ImportedName::Named("required".to_string()),
1336                        true,
1337                    ),
1338                ],
1339                ..ResolvedModule::default()
1340            },
1341            ResolvedModule {
1342                file_id: FileId(1),
1343                path: files[1].path.clone(),
1344                exports: vec![value_export("esmOnly", 0), value_export("required", 20)].into(),
1345                ..ResolvedModule::default()
1346            },
1347        ];
1348        let test_entry_points = vec![EntryPoint {
1349            path: files[0].path.clone(),
1350            source: EntryPointSource::TestFile,
1351        }];
1352        let graph =
1353            RetainedModuleGraph::from(ModuleGraph::build_with_reachability_roots_and_replacements(
1354                &modules,
1355                &[ResolvedReplacedModuleTarget {
1356                    source_file: FileId(0),
1357                    target_file: FileId(1),
1358                }],
1359                &test_entry_points,
1360                &[],
1361                &test_entry_points,
1362                &files,
1363            ));
1364
1365        let exports = module_value_exports(&graph);
1366        let coverage: rustc_hash::FxHashMap<_, _> = exports
1367            .into_iter()
1368            .map(|export| (export.name, export.test_referenced))
1369            .collect();
1370
1371        assert_eq!(coverage.get("esmOnly"), Some(&false));
1372        assert_eq!(coverage.get("required"), Some(&true));
1373    }
1374
1375    #[test]
1376    fn type_only_test_import_does_not_credit_a_value_export() {
1377        let files: Vec<_> = (0..3)
1378            .map(|id| DiscoveredFile {
1379                id: FileId(id),
1380                path: PathBuf::from(format!("/project/file{id}.ts")),
1381                size_bytes: 1,
1382            })
1383            .collect();
1384        let mut type_only = import(FileId(1), ImportedName::Named("typed".to_string()));
1385        type_only.info.is_type_only = true;
1386        let modules = vec![
1387            ResolvedModule {
1388                file_id: FileId(0),
1389                path: files[0].path.clone(),
1390                resolved_imports: vec![
1391                    type_only,
1392                    import(FileId(2), ImportedName::Named("called".to_string())),
1393                ],
1394                ..ResolvedModule::default()
1395            },
1396            ResolvedModule {
1397                file_id: FileId(1),
1398                path: files[1].path.clone(),
1399                exports: vec![value_export("typed", 0)].into(),
1400                ..ResolvedModule::default()
1401            },
1402            ResolvedModule {
1403                file_id: FileId(2),
1404                path: files[2].path.clone(),
1405                exports: vec![value_export("called", 0)].into(),
1406                ..ResolvedModule::default()
1407            },
1408        ];
1409        let test_entry_points = vec![EntryPoint {
1410            path: files[0].path.clone(),
1411            source: EntryPointSource::TestFile,
1412        }];
1413        let graph =
1414            RetainedModuleGraph::from(ModuleGraph::build_with_reachability_roots_and_replacements(
1415                &modules,
1416                &[],
1417                &test_entry_points,
1418                &[],
1419                &test_entry_points,
1420                &files,
1421            ));
1422
1423        let coverage: rustc_hash::FxHashMap<_, _> = module_value_exports(&graph)
1424            .into_iter()
1425            .map(|export| (export.name, export.test_referenced))
1426            .collect();
1427
1428        assert_eq!(coverage.get("typed"), Some(&false));
1429        assert_eq!(coverage.get("called"), Some(&true));
1430    }
1431}