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