Skip to main content

fallow_graph/graph/
shortest_import_path.rs

1//! Shortest import path between two modules.
2//!
3//! `impact_closure` answers "what does a change reach"; this answers "HOW does
4//! one module reach another". It is a plain FIFO breadth-first search over the
5//! forward import edges, so the first path found is a shortest one.
6//!
7//! Determinism is a contract, not a coincidence: the JSON must stay
8//! byte-identical across runs and platforms. Successors are expanded in
9//! ascending `FileId` order and a node keeps the predecessor that discovered it
10//! first, which makes the reported route the lexicographically smallest
11//! `FileId` sequence among all shortest routes. The proof is inductive: the
12//! level-0 frontier is the single source, and a level is enqueued while its
13//! predecessors are dequeued in that same order, so within every level the
14//! queue order equals the lexicographic order of the routes reaching it.
15//!
16//! Type-only hops are REPORTED, never skipped. An `import type` chain is a real
17//! compile-time coupling, and silently dropping it would answer "unreachable"
18//! for a route a reader can see in the source.
19
20use std::collections::VecDeque;
21
22use fallow_types::discover::FileId;
23use fixedbitset::FixedBitSet;
24use rustc_hash::FxHashMap;
25
26use super::{ImportedName, ModuleGraph, ModuleLoadMechanism};
27
28/// One import edge on a shortest import path.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct ImportPathHop {
31    /// The importing module.
32    pub from: FileId,
33    /// The imported module.
34    pub to: FileId,
35    /// Whether every symbol on this edge is type-only, so the hop exists at
36    /// compile time only. Reported rather than skipped.
37    pub all_type_only: bool,
38    /// Byte offset in `from` of the imported binding that creates this edge,
39    /// as [`ModuleGraph::outgoing_edge_summaries`] reports it: the first
40    /// value-carrying symbol, or the first symbol when every symbol is
41    /// type-only. The caller owns the source text and resolves it to a line.
42    /// On an eager-only route it is the first static value symbol.
43    pub import_span_start: Option<u32>,
44    /// Whether the edge carries a runtime value but no static one, so the
45    /// target loads only on demand (`import()`, a lazy pattern) or on another
46    /// thread. False for a static hop and for a type-only hop.
47    pub dynamic: bool,
48}
49
50impl ModuleGraph {
51    /// The shortest import path from `from` to `to`, following import edges in
52    /// the import direction.
53    ///
54    /// Returns `None` when `to` is not reachable from `from`, and
55    /// `Some(empty)` when `from` and `to` are the same module: zero hops is a
56    /// real answer, distinct from no answer at all. Out-of-range file ids have
57    /// no outgoing edges and therefore reach nothing.
58    #[must_use]
59    pub fn shortest_import_path(&self, from: FileId, to: FileId) -> Option<Vec<ImportPathHop>> {
60        self.shortest_import_path_over(from, to, false)
61    }
62
63    /// [`Self::shortest_import_path`] over eager edges only: edges with a
64    /// static symbol that carries a runtime value. The route answers why a
65    /// module loads before `from` runs; `import()`, lazy patterns, worker
66    /// loads and `import type` never qualify.
67    #[must_use]
68    pub fn shortest_eager_import_path(
69        &self,
70        from: FileId,
71        to: FileId,
72    ) -> Option<Vec<ImportPathHop>> {
73        self.shortest_import_path_over(from, to, true)
74    }
75
76    fn shortest_import_path_over(
77        &self,
78        from: FileId,
79        to: FileId,
80        eager_only: bool,
81    ) -> Option<Vec<ImportPathHop>> {
82        if from == to {
83            return Some(Vec::new());
84        }
85        let capacity = self.modules.len();
86        if from.0 as usize >= capacity || to.0 as usize >= capacity {
87            return None;
88        }
89
90        let mut visited = FixedBitSet::with_capacity(capacity);
91        visited.insert(from.0 as usize);
92        let mut predecessor: FxHashMap<FileId, ImportPathHop> = FxHashMap::default();
93        let mut queue: VecDeque<FileId> = VecDeque::new();
94        queue.push_back(from);
95
96        while let Some(current) = queue.pop_front() {
97            for hop in self.ordered_outgoing_hops(current, eager_only) {
98                let idx = hop.to.0 as usize;
99                if idx >= capacity || visited.contains(idx) {
100                    continue;
101                }
102                visited.insert(idx);
103                predecessor.insert(hop.to, hop);
104                if hop.to == to {
105                    return Some(rebuild_path(self, &predecessor, from, to));
106                }
107                queue.push_back(hop.to);
108            }
109        }
110        None
111    }
112
113    /// Outgoing edges of `file_id` as hops, in ascending target order and with
114    /// one hop per target. When a target is reachable over both a value edge
115    /// and a type-only edge, the value edge wins: it is the hop a reader can
116    /// follow at runtime. With `eager_only`, only edges with a static value
117    /// symbol qualify, and the hop anchors on that symbol.
118    fn ordered_outgoing_hops(&self, file_id: FileId, eager_only: bool) -> Vec<ImportPathHop> {
119        let mut hops: Vec<ImportPathHop> = self
120            .outgoing_symbol_edges(file_id)
121            .filter(|&(target, _)| target != file_id)
122            .filter_map(|(target, symbols)| {
123                let eager = symbols.iter().find(|s| s.is_eager_value());
124                if eager_only && eager.is_none() {
125                    return None;
126                }
127                let all_type_only = !symbols.is_empty() && symbols.iter().all(|s| s.is_type_only);
128                let anchor = if eager_only {
129                    eager
130                } else {
131                    symbols
132                        .iter()
133                        .find(|s| !s.is_type_only)
134                        .or_else(|| symbols.first())
135                };
136                let import_span_start = anchor.and_then(|s| {
137                    let re_export = s.import_span.is_empty()
138                        && s.imported_name == ImportedName::SideEffect
139                        && s.mechanism == ModuleLoadMechanism::EsModule;
140                    (!re_export).then_some(s.import_span.start)
141                });
142                Some(ImportPathHop {
143                    from: file_id,
144                    to: target,
145                    all_type_only,
146                    import_span_start,
147                    dynamic: !all_type_only && eager.is_none(),
148                })
149            })
150            .collect();
151        hops.sort_unstable_by_key(|hop| (hop.to.0, hop.all_type_only, hop.import_span_start));
152        hops.dedup_by_key(|hop| hop.to);
153        hops
154    }
155}
156
157/// Walk the predecessor chain back from `to` and return it in import order.
158fn rebuild_path(
159    graph: &ModuleGraph,
160    predecessor: &FxHashMap<FileId, ImportPathHop>,
161    from: FileId,
162    to: FileId,
163) -> Vec<ImportPathHop> {
164    let mut reversed = Vec::new();
165    let mut cursor = to;
166    while cursor != from {
167        let Some(mut hop) = predecessor.get(&cursor).copied() else {
168            break;
169        };
170        // Only the returned route needs source positions. Looking up every
171        // outgoing hop of a barrel would scan its re-exports for each target.
172        if hop.import_span_start.is_none() {
173            hop.import_span_start =
174                graph.modules[hop.from.0 as usize].re_export_span_start(hop.to, hop.all_type_only);
175        }
176        reversed.push(hop);
177        cursor = hop.from;
178    }
179    reversed.reverse();
180    reversed
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186    use crate::resolve::{ResolveResult, ResolvedImport, ResolvedModule};
187    use fallow_types::discover::{DiscoveredFile, EntryPoint, EntryPointSource};
188    use fallow_types::extract::{ExportInfo, ExportName, ImportInfo, ImportedName, VisibilityTag};
189    use std::path::PathBuf;
190
191    fn module_path(id: u32) -> PathBuf {
192        PathBuf::from(format!("/p/src/m{id}.ts"))
193    }
194
195    fn import(target: u32, span_start: u32, type_only: bool) -> ResolvedImport {
196        ResolvedImport {
197            info: ImportInfo {
198                source: format!("./m{target}"),
199                imported_name: ImportedName::Named("value".to_string()),
200                local_name: "value".to_string(),
201                is_type_only: type_only,
202                is_type_only_star: false,
203                from_style: false,
204                span: oxc_span::Span::new(span_start, span_start + 10),
205                source_span: oxc_span::Span::default(),
206            },
207            target: ResolveResult::InternalModule(FileId(target)),
208        }
209    }
210
211    fn value_export() -> ExportInfo {
212        ExportInfo {
213            name: ExportName::Named("value".to_string()),
214            local_name: Some("value".to_string()),
215            is_type_only: false,
216            visibility: VisibilityTag::None,
217            expected_unused_reason: None,
218            span: oxc_span::Span::new(0, 20),
219            members: vec![],
220            is_side_effect_used: false,
221            super_class: None,
222            deprecated: false,
223            deprecated_reason: None,
224        }
225    }
226
227    /// Build a graph from `(source, targets)` pairs. Every edge carries one
228    /// value symbol whose import span starts at `source * 100 + target`, so a
229    /// hop's reported span identifies the edge it came from.
230    fn graph_with_edges(module_count: u32, edges: &[(u32, &[u32])]) -> ModuleGraph {
231        graph_with_typed_edges(module_count, edges, &[])
232    }
233
234    /// Same, with `type_only_edges` naming the `(source, target)` pairs whose
235    /// import is spelled `import type`.
236    fn graph_with_typed_edges(
237        module_count: u32,
238        edges: &[(u32, &[u32])],
239        type_only_edges: &[(u32, u32)],
240    ) -> ModuleGraph {
241        let files: Vec<DiscoveredFile> = (0..module_count)
242            .map(|id| DiscoveredFile {
243                id: FileId(id),
244                path: module_path(id),
245                size_bytes: 10,
246            })
247            .collect();
248        let entry_points = vec![EntryPoint {
249            path: module_path(0),
250            source: EntryPointSource::PackageJsonMain,
251        }];
252        let resolved: Vec<ResolvedModule> = (0..module_count)
253            .map(|id| {
254                let resolved_imports = edges
255                    .iter()
256                    .find(|(source, _)| *source == id)
257                    .map(|(source, targets)| {
258                        targets
259                            .iter()
260                            .map(|&target| {
261                                import(
262                                    target,
263                                    source * 100 + target,
264                                    type_only_edges.contains(&(*source, target)),
265                                )
266                            })
267                            .collect()
268                    })
269                    .unwrap_or_default();
270                ResolvedModule {
271                    file_id: FileId(id),
272                    path: module_path(id),
273                    resolved_imports,
274                    exports: vec![value_export()].into(),
275                    ..Default::default()
276                }
277            })
278            .collect();
279        ModuleGraph::build(&resolved, &entry_points, &files)
280    }
281
282    #[test]
283    fn same_module_is_zero_hops_not_unreachable() {
284        let graph = graph_with_edges(2, &[(0, &[1])]);
285        assert_eq!(
286            graph.shortest_import_path(FileId(0), FileId(0)),
287            Some(vec![])
288        );
289    }
290
291    #[test]
292    fn unreachable_target_has_no_path() {
293        let graph = graph_with_edges(3, &[(0, &[1])]);
294        assert_eq!(graph.shortest_import_path(FileId(0), FileId(2)), None);
295        // Edges are directed: the importer is not reachable from the imported.
296        assert_eq!(graph.shortest_import_path(FileId(1), FileId(0)), None);
297    }
298
299    #[test]
300    fn direct_import_is_one_hop_with_its_import_span() {
301        let graph = graph_with_edges(2, &[(0, &[1])]);
302        let path = graph
303            .shortest_import_path(FileId(0), FileId(1))
304            .expect("direct import is reachable");
305        assert_eq!(path.len(), 1);
306        assert_eq!(path[0].from, FileId(0));
307        assert_eq!(path[0].to, FileId(1));
308        assert!(!path[0].all_type_only);
309        assert_eq!(path[0].import_span_start, Some(1));
310    }
311
312    #[test]
313    fn breadth_first_prefers_the_shorter_route() {
314        // Two routes to 5: two hops through 1, four hops through 2. A LIFO walk
315        // drains the deeper branch first and reports the four-hop detour.
316        let graph = graph_with_edges(
317            6,
318            &[(0, &[1, 2]), (1, &[5]), (2, &[3]), (3, &[4]), (4, &[5])],
319        );
320        let path = graph
321            .shortest_import_path(FileId(0), FileId(5))
322            .expect("target is reachable");
323        assert_eq!(
324            path.iter().map(|hop| hop.to).collect::<Vec<_>>(),
325            vec![FileId(1), FileId(5)]
326        );
327    }
328
329    #[test]
330    fn equal_length_routes_resolve_to_the_smallest_file_id_sequence() {
331        // Two two-hop routes to 3: through 2 and through 1. The smaller
332        // intermediate wins regardless of the order the edges were declared in.
333        let graph = graph_with_edges(4, &[(0, &[2, 1]), (1, &[3]), (2, &[3])]);
334        let path = graph
335            .shortest_import_path(FileId(0), FileId(3))
336            .expect("target is reachable");
337        assert_eq!(
338            path.iter().map(|hop| hop.to).collect::<Vec<_>>(),
339            vec![FileId(1), FileId(3)]
340        );
341    }
342
343    #[test]
344    fn a_cycle_does_not_stall_the_walk() {
345        let graph = graph_with_edges(4, &[(0, &[1]), (1, &[2]), (2, &[1, 3])]);
346        let path = graph
347            .shortest_import_path(FileId(0), FileId(3))
348            .expect("target is reachable behind a cycle");
349        assert_eq!(path.len(), 3);
350    }
351
352    #[test]
353    fn out_of_range_ids_reach_nothing() {
354        let graph = graph_with_edges(2, &[(0, &[1])]);
355        assert_eq!(graph.shortest_import_path(FileId(0), FileId(9)), None);
356        assert_eq!(graph.shortest_import_path(FileId(9), FileId(1)), None);
357    }
358
359    #[test]
360    fn a_type_only_hop_is_reported_not_skipped() {
361        let graph = graph_with_typed_edges(2, &[(0, &[1])], &[(0, 1)]);
362        let path = graph
363            .shortest_import_path(FileId(0), FileId(1))
364            .expect("a type-only import is still a route");
365        assert_eq!(path.len(), 1);
366        assert!(path[0].all_type_only);
367        assert!(!path[0].dynamic, "a type-only hop is not a lazy load");
368        assert_eq!(
369            graph.shortest_eager_import_path(FileId(0), FileId(1)),
370            None,
371            "import type loads nothing, so no eager route exists"
372        );
373    }
374
375    #[test]
376    fn the_eager_route_matches_the_plain_route_over_static_edges() {
377        let graph = graph_with_edges(3, &[(0, &[1]), (1, &[2])]);
378        let plain = graph.shortest_import_path(FileId(0), FileId(2));
379        assert_eq!(
380            graph.shortest_eager_import_path(FileId(0), FileId(2)),
381            plain
382        );
383        assert!(plain.expect("reachable").iter().all(|hop| !hop.dynamic));
384    }
385}