Skip to main content

fallow_graph/graph/
entry_load.rs

1//! Load closures of one entry module, split by when each module loads, and
2//! the single imports that dominate the eager closure.
3//!
4//! The eager closure follows only edges with a static, value-carrying symbol:
5//! the code that loads before the entry runs. The deferred closure adds
6//! `import()` and pattern edges, and the out-of-thread closure adds worker,
7//! fork and loader-hook edges. Type-only symbols never load a module, and a
8//! declaration file never loads.
9//!
10//! A dominating import is an edge `importer -> target` that is the only way
11//! into `target` from outside the part of the eager closure that `target`
12//! dominates. If that edge became an `import()`, the whole dominator subtree
13//! of `target` would leave the eager closure. Every result is a pure function
14//! of the edge set, and every list is ordered by `FileId`, so repeated runs
15//! give identical output.
16
17use fallow_types::discover::FileId;
18use fixedbitset::FixedBitSet;
19use rustc_hash::FxHashMap;
20
21use super::{ImportedSymbol, ModuleGraph, is_declaration_file_path};
22use fallow_types::extract::ImportLoadKind;
23
24/// The modules that one entry reaches, split by when they load.
25#[derive(Debug, Clone, Default, PartialEq, Eq)]
26pub struct EntryLoadClosure {
27    /// Modules that load before the entry runs, the entry included, in
28    /// ascending `FileId` order.
29    pub eager: Vec<FileId>,
30    /// Modules that load on demand on the same thread (`import()` or a lazy
31    /// pattern) and are not eager, in ascending `FileId` order.
32    pub deferred: Vec<FileId>,
33    /// Modules that only an out-of-thread load reaches (a worker, a fork, a
34    /// loader hook), in ascending `FileId` order.
35    pub out_of_thread: Vec<FileId>,
36}
37
38/// One import edge that alone keeps a subtree of the eager closure eager.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub struct DominatingImport {
41    /// The module that contains the import.
42    pub importer: FileId,
43    /// The imported module; the root of the subtree that the edge keeps eager.
44    pub target: FileId,
45    /// Byte offset of the first static, value-carrying binding on the edge.
46    /// `None` for an edge without a binding span, such as a re-export or an
47    /// eager glob match.
48    pub import_span_start: Option<u32>,
49    /// Modules that leave the eager closure if the edge becomes an `import()`.
50    pub exclusive_modules: usize,
51    /// Summed weight of those modules.
52    pub exclusive_weight: u64,
53}
54
55const NO_NODE: u32 = u32::MAX;
56
57impl ModuleGraph {
58    /// Split the modules that `entry` reaches by when they load.
59    ///
60    /// Returns an empty closure for an out-of-range `entry`.
61    #[must_use]
62    pub fn entry_load_closure(&self, entry: FileId) -> EntryLoadClosure {
63        if entry.0 as usize >= self.modules.len() {
64            return EntryLoadClosure::default();
65        }
66        let eager = self.symbol_closure(&[entry], ImportedSymbol::is_eager_value);
67        let eager_ids = set_members(&eager);
68        // A macro import runs its target only in the bundler, so no closure
69        // follows it.
70        let same_thread = self.symbol_closure(&eager_ids, |symbol| {
71            !symbol.is_type_only
72                && symbol.loads_target()
73                && symbol.load_kind().runs_at_runtime()
74                && symbol.load_kind() != ImportLoadKind::OutOfThread
75        });
76        let same_thread_ids = set_members(&same_thread);
77        let everything = self.symbol_closure(&same_thread_ids, |symbol| {
78            !symbol.is_type_only && symbol.loads_target() && symbol.load_kind().runs_at_runtime()
79        });
80
81        let mut deferred = same_thread.clone();
82        deferred.difference_with(&eager);
83        let mut out_of_thread = everything;
84        out_of_thread.difference_with(&same_thread);
85
86        EntryLoadClosure {
87            eager: eager_ids,
88            deferred: set_members(&deferred),
89            out_of_thread: set_members(&out_of_thread),
90        }
91    }
92
93    /// The import edges that each keep a subtree of the eager closure eager,
94    /// ordered by exclusive weight (heaviest first), then exclusive module
95    /// count, then importer and target `FileId`.
96    ///
97    /// `eager` must be the eager closure of `entry` from
98    /// [`Self::entry_load_closure`]. `weight` gives the weight of one module,
99    /// for example its source size in bytes.
100    #[must_use]
101    pub fn eager_dominating_imports(
102        &self,
103        entry: FileId,
104        eager: &[FileId],
105        weight: impl Fn(FileId) -> u64,
106    ) -> Vec<DominatingImport> {
107        let subgraph = EagerSubgraph::new(self, entry, eager);
108        let Some(subgraph) = subgraph else {
109            return Vec::new();
110        };
111        let tree = DominatorTree::new(&subgraph);
112
113        let mut subtree_modules = vec![1_usize; subgraph.nodes.len()];
114        let mut subtree_weight: Vec<u64> = subgraph.nodes.iter().map(|&id| weight(id)).collect();
115        for &node in tree.reverse_postorder.iter().rev() {
116            let parent = tree.idom[node as usize];
117            if parent == node || parent == NO_NODE {
118                continue;
119            }
120            subtree_modules[parent as usize] += subtree_modules[node as usize];
121            subtree_weight[parent as usize] =
122                subtree_weight[parent as usize].saturating_add(subtree_weight[node as usize]);
123        }
124
125        let mut imports = Vec::new();
126        for (node, predecessors) in subgraph.predecessors.iter().enumerate() {
127            if node as u32 == subgraph.root {
128                continue;
129            }
130            let mut external = predecessors
131                .iter()
132                .filter(|(pred, _)| !tree.dominates(node as u32, *pred));
133            let (Some(&(importer, span)), None) = (external.next(), external.next()) else {
134                continue;
135            };
136            imports.push(DominatingImport {
137                importer: subgraph.nodes[importer as usize],
138                target: subgraph.nodes[node],
139                import_span_start: span,
140                exclusive_modules: subtree_modules[node],
141                exclusive_weight: subtree_weight[node],
142            });
143        }
144        imports.sort_by(|a, b| {
145            b.exclusive_weight
146                .cmp(&a.exclusive_weight)
147                .then_with(|| b.exclusive_modules.cmp(&a.exclusive_modules))
148                .then_with(|| a.importer.0.cmp(&b.importer.0))
149                .then_with(|| a.target.0.cmp(&b.target.0))
150        });
151        imports
152    }
153
154    /// Modules reachable from `seeds` over edges with at least one symbol
155    /// that `follows` accepts. The seeds are part of the result.
156    ///
157    /// A declaration file is never a target: even a value import of one
158    /// compiles away, so it and its own imports never load at runtime.
159    fn symbol_closure(
160        &self,
161        seeds: &[FileId],
162        follows: impl Fn(&ImportedSymbol) -> bool,
163    ) -> FixedBitSet {
164        let capacity = self.modules.len();
165        let mut visited = FixedBitSet::with_capacity(capacity);
166        let mut stack: Vec<FileId> = Vec::new();
167        for &seed in seeds {
168            let idx = seed.0 as usize;
169            if idx < capacity && !visited.contains(idx) {
170                visited.insert(idx);
171                stack.push(seed);
172            }
173        }
174        while let Some(current) = stack.pop() {
175            let range = self.modules[current.0 as usize].edge_range.clone();
176            for edge in &self.edges[range] {
177                let idx = edge.target.0 as usize;
178                if idx < capacity
179                    && !visited.contains(idx)
180                    && edge.symbols.iter().any(&follows)
181                    && !is_declaration_file_path(&self.modules[idx].path)
182                {
183                    visited.insert(idx);
184                    stack.push(edge.target);
185                }
186            }
187        }
188        visited
189    }
190}
191
192fn set_members(set: &FixedBitSet) -> Vec<FileId> {
193    set.ones()
194        .map(|idx| FileId(u32::try_from(idx).unwrap_or(u32::MAX)))
195        .collect()
196}
197
198/// The eager closure as a compact graph with local node indices.
199struct EagerSubgraph {
200    /// Local index to `FileId`, in ascending `FileId` order.
201    nodes: Vec<FileId>,
202    /// Local index of the entry.
203    root: u32,
204    /// Eager successors of each node, in ascending order.
205    successors: Vec<Vec<u32>>,
206    /// Eager predecessors of each node with the binding span of the edge.
207    predecessors: Vec<Vec<(u32, Option<u32>)>>,
208}
209
210impl EagerSubgraph {
211    fn new(graph: &ModuleGraph, entry: FileId, eager: &[FileId]) -> Option<Self> {
212        let local: FxHashMap<FileId, u32> = eager
213            .iter()
214            .enumerate()
215            .map(|(idx, &id)| (id, u32::try_from(idx).unwrap_or(NO_NODE)))
216            .collect();
217        let root = *local.get(&entry)?;
218        let mut successors = vec![Vec::new(); eager.len()];
219        let mut predecessors = vec![Vec::new(); eager.len()];
220        for (source_idx, &source) in eager.iter().enumerate() {
221            let Some(module) = graph.modules.get(source.0 as usize) else {
222                continue;
223            };
224            for edge in &graph.edges[module.edge_range.clone()] {
225                let Some(&target_idx) = local.get(&edge.target) else {
226                    continue;
227                };
228                let Some(symbol) = edge.symbols.iter().find(|s| s.is_eager_value()) else {
229                    continue;
230                };
231                if target_idx as usize == source_idx {
232                    continue;
233                }
234                let span = (symbol.import_span.end > symbol.import_span.start)
235                    .then_some(symbol.import_span.start);
236                let source_local = u32::try_from(source_idx).unwrap_or(NO_NODE);
237                successors[source_idx].push(target_idx);
238                predecessors[target_idx as usize].push((source_local, span));
239            }
240        }
241        for list in &mut successors {
242            list.sort_unstable();
243            list.dedup();
244        }
245        for list in &mut predecessors {
246            list.sort_unstable_by_key(|(pred, _)| *pred);
247            list.dedup_by_key(|(pred, _)| *pred);
248        }
249        Some(Self {
250            nodes: eager.to_vec(),
251            root,
252            successors,
253            predecessors,
254        })
255    }
256}
257
258/// Immediate dominators by the iterative Cooper, Harvey and Kennedy method,
259/// plus tree intervals for a constant-time dominance test.
260struct DominatorTree {
261    idom: Vec<u32>,
262    reverse_postorder: Vec<u32>,
263    entry_time: Vec<u32>,
264    exit_time: Vec<u32>,
265}
266
267impl DominatorTree {
268    fn new(graph: &EagerSubgraph) -> Self {
269        let count = graph.nodes.len();
270        let reverse_postorder = reverse_postorder(graph);
271        let mut order = vec![NO_NODE; count];
272        for (position, &node) in reverse_postorder.iter().enumerate() {
273            order[node as usize] = u32::try_from(position).unwrap_or(NO_NODE);
274        }
275
276        let mut idom = vec![NO_NODE; count];
277        idom[graph.root as usize] = graph.root;
278        let mut changed = true;
279        while changed {
280            changed = false;
281            for &node in reverse_postorder.iter().skip(1) {
282                let mut new_idom = NO_NODE;
283                for &(pred, _) in &graph.predecessors[node as usize] {
284                    if idom[pred as usize] == NO_NODE {
285                        continue;
286                    }
287                    new_idom = if new_idom == NO_NODE {
288                        pred
289                    } else {
290                        intersect(&idom, &order, pred, new_idom)
291                    };
292                }
293                if new_idom != NO_NODE && idom[node as usize] != new_idom {
294                    idom[node as usize] = new_idom;
295                    changed = true;
296                }
297            }
298        }
299
300        let (entry_time, exit_time) = tree_intervals(graph.root, &idom, &reverse_postorder);
301        Self {
302            idom,
303            reverse_postorder,
304            entry_time,
305            exit_time,
306        }
307    }
308
309    /// Whether `dominator` dominates `node` (every node dominates itself).
310    fn dominates(&self, dominator: u32, node: u32) -> bool {
311        let (d, n) = (dominator as usize, node as usize);
312        self.entry_time[d] <= self.entry_time[n] && self.exit_time[n] <= self.exit_time[d]
313    }
314}
315
316fn intersect(idom: &[u32], order: &[u32], mut left: u32, mut right: u32) -> u32 {
317    while left != right {
318        while order[left as usize] > order[right as usize] {
319            left = idom[left as usize];
320        }
321        while order[right as usize] > order[left as usize] {
322            right = idom[right as usize];
323        }
324    }
325    left
326}
327
328/// Reverse postorder of the nodes reachable from the root, by an iterative
329/// depth-first search that visits successors in ascending order.
330fn reverse_postorder(graph: &EagerSubgraph) -> Vec<u32> {
331    let mut visited = FixedBitSet::with_capacity(graph.nodes.len());
332    let mut postorder = Vec::with_capacity(graph.nodes.len());
333    let mut stack: Vec<(u32, usize)> = vec![(graph.root, 0)];
334    visited.insert(graph.root as usize);
335    while let Some((node, next_child)) = stack.last_mut() {
336        let children = &graph.successors[*node as usize];
337        if let Some(&child) = children.get(*next_child) {
338            *next_child += 1;
339            if !visited.contains(child as usize) {
340                visited.insert(child as usize);
341                stack.push((child, 0));
342            }
343        } else {
344            postorder.push(*node);
345            stack.pop();
346        }
347    }
348    postorder.reverse();
349    postorder
350}
351
352/// Pre- and post-order times of the dominator tree, for the interval test.
353fn tree_intervals(root: u32, idom: &[u32], reverse_postorder: &[u32]) -> (Vec<u32>, Vec<u32>) {
354    let count = idom.len();
355    let mut children = vec![Vec::new(); count];
356    for &node in reverse_postorder {
357        let parent = idom[node as usize];
358        if node != root && parent != NO_NODE {
359            children[parent as usize].push(node);
360        }
361    }
362    let mut entry_time = vec![u32::MAX; count];
363    let mut exit_time = vec![0_u32; count];
364    let mut clock = 0_u32;
365    let mut stack: Vec<(u32, usize)> = vec![(root, 0)];
366    entry_time[root as usize] = clock;
367    while let Some((node, next_child)) = stack.last_mut() {
368        if let Some(&child) = children[*node as usize].get(*next_child) {
369            *next_child += 1;
370            clock += 1;
371            entry_time[child as usize] = clock;
372            stack.push((child, 0));
373        } else {
374            clock += 1;
375            exit_time[*node as usize] = clock;
376            stack.pop();
377        }
378    }
379    (entry_time, exit_time)
380}
381
382#[cfg(test)]
383mod tests {
384    use std::path::PathBuf;
385
386    use fallow_types::discover::{DiscoveredFile, EntryPoint, EntryPointSource, FileId};
387    use fallow_types::extract::{ImportInfo, ImportedName};
388
389    use crate::graph::ModuleGraph;
390    use crate::resolve::{ResolveResult, ResolvedImport, ResolvedModule};
391
392    fn import(to: u32, start: u32) -> ResolvedImport {
393        ResolvedImport {
394            info: ImportInfo {
395                source: format!("./m{to}"),
396                imported_name: ImportedName::SideEffect,
397                local_name: String::new(),
398                is_type_only: false,
399                is_type_only_star: false,
400                from_style: false,
401                span: oxc_span::Span::new(start, start + 10),
402                source_span: oxc_span::Span::default(),
403            },
404            target: ResolveResult::InternalModule(FileId(to)),
405        }
406    }
407
408    /// Static edges only; `edges[i]` lists the targets of module `i`.
409    fn graph(edges: &[&[u32]]) -> ModuleGraph {
410        graph_with_paths(edges, |i| PathBuf::from(format!("/p/m{i}.ts")))
411    }
412
413    /// [`graph`] where `path` names the file of module `i`.
414    fn graph_with_paths(edges: &[&[u32]], path: impl Fn(usize) -> PathBuf) -> ModuleGraph {
415        let files: Vec<DiscoveredFile> = (0..edges.len())
416            .map(|i| DiscoveredFile {
417                id: FileId(u32::try_from(i).unwrap_or(u32::MAX)),
418                path: path(i),
419                size_bytes: 10,
420            })
421            .collect();
422        let modules: Vec<ResolvedModule> = edges
423            .iter()
424            .enumerate()
425            .map(|(i, targets)| ResolvedModule {
426                file_id: FileId(u32::try_from(i).unwrap_or(u32::MAX)),
427                path: path(i),
428                resolved_imports: targets
429                    .iter()
430                    .zip(0_u32..)
431                    .map(|(&to, n)| import(to, n * 20))
432                    .collect(),
433                ..Default::default()
434            })
435            .collect();
436        let entry = vec![EntryPoint {
437            path: path(0),
438            source: EntryPointSource::PackageJsonMain,
439        }];
440        ModuleGraph::build(&modules, &entry, &files)
441    }
442
443    #[test]
444    fn a_cycle_back_into_a_subtree_does_not_hide_its_dominating_import() {
445        // m0 -> m1 -> m2 -> m1: the back edge m2 -> m1 comes from inside the
446        // subtree that m1 dominates, so m0 -> m1 still removes m1 and m2.
447        let graph = graph(&[&[1], &[2], &[1]]);
448        let closure = graph.entry_load_closure(FileId(0));
449        let imports = graph.eager_dominating_imports(FileId(0), &closure.eager, |_| 10);
450        let first = imports.first().expect("m0 -> m1 dominates the cycle");
451        assert_eq!((first.importer, first.target), (FileId(0), FileId(1)));
452        assert_eq!(first.exclusive_modules, 2);
453        assert_eq!(first.exclusive_weight, 20);
454    }
455
456    #[test]
457    fn a_diamond_has_no_single_dominating_import_for_the_shared_module() {
458        // m0 -> m1 -> m3 and m0 -> m2 -> m3: two eager importers keep m3.
459        let graph = graph(&[&[1, 2], &[3], &[3], &[]]);
460        let closure = graph.entry_load_closure(FileId(0));
461        let imports = graph.eager_dominating_imports(FileId(0), &closure.eager, |_| 10);
462        assert!(imports.iter().all(|import| import.target != FileId(3)));
463        assert_eq!(
464            imports.len(),
465            2,
466            "m0 -> m1 and m0 -> m2 each remove one module"
467        );
468    }
469
470    #[test]
471    fn a_declaration_file_never_loads_at_runtime() {
472        // m0 -> m1.d.ts -> m3 and m0 -> m2: a value import of a declaration
473        // file compiles away, so neither it nor its imports load.
474        let graph = graph_with_paths(&[&[1, 2], &[3], &[], &[]], |i| {
475            if i == 1 {
476                PathBuf::from("/p/m1.d.ts")
477            } else {
478                PathBuf::from(format!("/p/m{i}.ts"))
479            }
480        });
481        let closure = graph.entry_load_closure(FileId(0));
482        assert_eq!(closure.eager, vec![FileId(0), FileId(2)]);
483        assert!(closure.deferred.is_empty());
484        assert!(closure.out_of_thread.is_empty());
485        let imports = graph.eager_dominating_imports(FileId(0), &closure.eager, |_| 10);
486        assert!(imports.iter().all(|import| import.target != FileId(1)));
487    }
488
489    #[test]
490    fn an_out_of_range_entry_has_an_empty_closure() {
491        let graph = graph(&[&[]]);
492        assert_eq!(graph.entry_load_closure(FileId(9)).eager, Vec::new());
493    }
494}