Skip to main content

fallow_graph/graph/
cycle_edge_span.rs

1//! The source position of one edge of an import cycle.
2
3use fallow_types::discover::FileId;
4
5use super::ModuleGraph;
6
7impl ModuleGraph {
8    /// Find the byte offset of the import statement from `source` to `target`.
9    ///
10    /// Mixed imports to the same target are stored as one edge. Prefer the
11    /// first eager value import, then the first value-carrying import, so
12    /// runtime-cycle diagnostics and line suppressions anchor on the import
13    /// that actually participates in the cycle. With lazy edges skipped, a
14    /// lazy `import()` on a mixed edge is not part of the cycle. An edge that
15    /// only a re-export makes anchors on the `export ... from` declaration.
16    /// Returns `None` if no edge exists or the edge has no symbols.
17    #[must_use]
18    pub fn find_import_span_start(&self, source: FileId, target: FileId) -> Option<u32> {
19        let idx = source.0 as usize;
20        if idx >= self.modules.len() {
21            return None;
22        }
23        let module = &self.modules[idx];
24        for edge in &self.edges[module.edge_range.clone()] {
25            if edge.target == target {
26                let symbol = edge
27                    .symbols
28                    .iter()
29                    .find(|s| s.is_eager_value())
30                    .or_else(|| edge.symbols.iter().find(|s| !s.is_type_only))
31                    .or_else(|| edge.symbols.first())?;
32                if symbol.import_span.is_empty() {
33                    // A re-export adds a side-effect symbol without a span to
34                    // the edge. The re-export edge of the module has the span.
35                    if let Some(re_export) = module.re_exports.iter().find(|re| {
36                        re.source_file == target
37                            && re.is_type_only == symbol.is_type_only
38                            && !re.span.is_empty()
39                    }) {
40                        return Some(re_export.span.start);
41                    }
42                }
43                return Some(symbol.import_span.start);
44            }
45        }
46        None
47    }
48}