Skip to main content

fallow_graph/graph/
cycles.rs

1//! Circular dependency detection via Tarjan's SCC algorithm + elementary cycle enumeration.
2
3use std::ops::Range;
4use std::path::Path;
5
6use fixedbitset::FixedBitSet;
7use rustc_hash::FxHashSet;
8
9use fallow_types::discover::FileId;
10
11use super::import_elision::{DecoratorMetadata, ImportElision, ImporterElision};
12use super::types::ModuleNode;
13use super::{ImportedSymbol, ModuleGraph};
14
15/// Options for [`ModuleGraph::find_cycles_with`].
16#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
17pub struct CycleOptions {
18    /// Skip edges on which no symbol loads its target eagerly with a runtime
19    /// value, so an edge made only of `import()`, lazy patterns or
20    /// other-thread loads does not take part in cycle detection. An edge
21    /// that also carries an eager import stays.
22    pub ignore_lazy_imports: bool,
23}
24
25/// The most cycles that the detector lists for one strongly connected group
26/// of files. A dense group has very many cycles, so the detector stops here.
27pub const MAX_CYCLES_PER_SCC: usize = 20;
28
29/// The most files that a listed cycle has. The detector does not look for
30/// longer cycles.
31pub const MAX_CYCLE_LENGTH: usize = 12;
32
33/// The result of [`ModuleGraph::find_cycles_accepting`].
34#[derive(Debug, Default, Clone, PartialEq, Eq)]
35pub struct CycleSearch {
36    /// The listed cycles that the `accept` callback did not accept, in the
37    /// order of [`ModuleGraph::find_cycles`].
38    pub cycles: Vec<Vec<FileId>>,
39    /// The strongly connected groups whose enumeration stopped at
40    /// [`MAX_CYCLES_PER_SCC`]. Such a group can have cycles that are not
41    /// listed and not given to the `accept` callback.
42    pub capped_sccs: Vec<Vec<FileId>>,
43}
44
45impl ModuleGraph {
46    /// Find all circular dependency cycles in the module graph.
47    ///
48    /// Uses an iterative implementation of Tarjan's strongly connected components
49    /// algorithm (O(V + E)) to find all SCCs with 2 or more nodes. Each such SCC
50    /// represents a set of files involved in a circular dependency.
51    ///
52    /// Returns cycles sorted by length (shortest first), with files within each
53    /// cycle sorted by path for deterministic output.
54    ///
55    /// # Panics
56    ///
57    /// Panics if the internal file-to-path lookup is inconsistent with the module list.
58    #[must_use]
59    pub fn find_cycles(&self) -> Vec<Vec<FileId>> {
60        self.find_cycles_with(CycleOptions::default())
61    }
62
63    /// Find all circular dependency cycles, with the edge filter that
64    /// `options` selects. See [`Self::find_cycles`] for the output order.
65    ///
66    /// The filter runs before the SCC pass, so a skipped edge cannot merge
67    /// files into one SCC and cannot use a slot of the per-SCC cycle cap.
68    #[must_use]
69    pub fn find_cycles_with(&self, options: CycleOptions) -> Vec<Vec<FileId>> {
70        self.find_cycles_accepting(
71            options,
72            &mut |_| ImportElision::RemoveUnread(DecoratorMetadata::Off),
73            &mut |_| false,
74        )
75        .cycles
76    }
77
78    /// Find the cycles like [`Self::find_cycles_with`], and drop each cycle
79    /// that `accept` accepts. An accepted cycle does not use a slot of the
80    /// per-group cycle limit, so the enumeration continues past it. The
81    /// callback gets each cycle once, in cycle order.
82    ///
83    /// A plain import that the importer never reads as a value is not a
84    /// runtime edge, because TypeScript removes it (issues #5262 and #5309).
85    /// `elision_of` gets the path of a TypeScript importer with such an
86    /// import, and returns the [`ImportElision`] of its compiler options.
87    /// The callback gets each importer at most once.
88    #[must_use]
89    pub fn find_cycles_accepting(
90        &self,
91        options: CycleOptions,
92        elision_of: &mut dyn FnMut(&Path) -> ImportElision,
93        accept: &mut dyn FnMut(&[FileId]) -> bool,
94    ) -> CycleSearch {
95        let n = self.modules.len();
96        if n == 0 {
97            return CycleSearch::default();
98        }
99
100        let (all_succs, succ_ranges) = self.build_runtime_successors(n, options, elision_of);
101
102        let mut state = SccState::new(n);
103        for start_node in 0..n {
104            if state.indices[start_node] != u32::MAX {
105                continue;
106            }
107            state.run_dfs_from(start_node, &all_succs, &succ_ranges);
108        }
109
110        self.enumerate_cycles_from_sccs(&state.sccs, &all_succs, &succ_ranges, accept)
111    }
112
113    /// Build the flattened runtime-successor adjacency (type-only edges,
114    /// imports that TypeScript removes, edges that do not load their target,
115    /// lazy edges when `options` asks for it, and duplicate targets excluded)
116    /// plus the per-node range index into it.
117    fn build_runtime_successors(
118        &self,
119        n: usize,
120        options: CycleOptions,
121        elision_of: &mut dyn FnMut(&Path) -> ImportElision,
122    ) -> (Vec<usize>, Vec<Range<usize>>) {
123        let mut all_succs: Vec<usize> = Vec::with_capacity(self.edges.len());
124        let mut succ_ranges: Vec<Range<usize>> = Vec::with_capacity(n);
125        let mut seen_set = FxHashSet::default();
126        for module in &self.modules {
127            let start = all_succs.len();
128            seen_set.clear();
129            let mut elision = ImporterElision::new(&module.path);
130            for edge in &self.edges[module.edge_range.clone()] {
131                let mut is_runtime = |s: &ImportedSymbol| {
132                    !s.is_type_only
133                        && s.loads_target()
134                        && !self.is_removed_import(
135                            edge.target,
136                            s,
137                            module,
138                            elision.get(&module.path, elision_of),
139                        )
140                };
141                if !edge.symbols.iter().any(&mut is_runtime) {
142                    continue;
143                }
144                if options.ignore_lazy_imports
145                    && !edge
146                        .symbols
147                        .iter()
148                        .any(|s| s.is_eager_value() && is_runtime(s))
149                {
150                    continue;
151                }
152                let target = edge.target.0 as usize;
153                if target < n && seen_set.insert(target) {
154                    all_succs.push(target);
155                }
156            }
157            let end = all_succs.len();
158            succ_ranges.push(start..end);
159        }
160        (all_succs, succ_ranges)
161    }
162
163    /// Enumerate individual elementary cycles from SCCs and return sorted results.
164    #[expect(
165        clippy::cast_possible_truncation,
166        reason = "file count is bounded by project size, well under u32::MAX"
167    )]
168    fn enumerate_cycles_from_sccs(
169        &self,
170        sccs: &[Vec<FileId>],
171        all_succs: &[usize],
172        succ_ranges: &[Range<usize>],
173        accept: &mut dyn FnMut(&[FileId]) -> bool,
174    ) -> CycleSearch {
175        let succs = SuccessorMap {
176            all_succs,
177            succ_ranges,
178            modules: &self.modules,
179        };
180
181        let mut result: Vec<Vec<FileId>> = Vec::new();
182        let mut capped_sccs: Vec<Vec<FileId>> = Vec::new();
183        let mut seen_cycles: FxHashSet<Vec<u32>> = FxHashSet::default();
184
185        for scc in sccs {
186            if scc.len() == 2 {
187                let mut cycle = vec![scc[0].0 as usize, scc[1].0 as usize];
188                if self.modules[cycle[1]].path < self.modules[cycle[0]].path {
189                    cycle.swap(0, 1);
190                }
191                let key: Vec<u32> = cycle.iter().map(|&n| n as u32).collect();
192                let files: Vec<FileId> = cycle.into_iter().map(|n| FileId(n as u32)).collect();
193                if seen_cycles.insert(key) && !accept(&files) {
194                    result.push(files);
195                }
196                continue;
197            }
198
199            let scc_nodes: Vec<usize> = scc.iter().map(|id| id.0 as usize).collect();
200            let (elementary, capped) =
201                enumerate_elementary_cycles(&scc_nodes, &succs, MAX_CYCLES_PER_SCC, accept);
202            if capped {
203                capped_sccs.push(scc.clone());
204            }
205
206            for cycle in elementary {
207                let key: Vec<u32> = cycle.iter().map(|&n| n as u32).collect();
208                if seen_cycles.insert(key) {
209                    result.push(cycle.into_iter().map(|n| FileId(n as u32)).collect());
210                }
211            }
212        }
213
214        result.sort_by(|a, b| {
215            a.len().cmp(&b.len()).then_with(|| {
216                self.modules[a[0].0 as usize]
217                    .path
218                    .cmp(&self.modules[b[0].0 as usize].path)
219            })
220        });
221
222        CycleSearch {
223            cycles: result,
224            capped_sccs,
225        }
226    }
227}
228
229/// One iterative-DFS frame for the Tarjan SCC pass over runtime successors.
230struct SccFrame {
231    node: usize,
232    succ_pos: usize,
233    succ_end: usize,
234}
235
236/// Mutable Tarjan SCC state for `find_cycles`, collecting SCCs of size >= 2.
237struct SccState {
238    index_counter: u32,
239    indices: Vec<u32>,
240    lowlinks: Vec<u32>,
241    on_stack: FixedBitSet,
242    stack: Vec<usize>,
243    sccs: Vec<Vec<FileId>>,
244}
245
246impl SccState {
247    fn new(n: usize) -> Self {
248        Self {
249            index_counter: 0,
250            indices: vec![u32::MAX; n],
251            lowlinks: vec![0; n],
252            on_stack: FixedBitSet::with_capacity(n),
253            stack: Vec::new(),
254            sccs: Vec::new(),
255        }
256    }
257
258    /// Assign the next DFS index to `node` and push it onto the SCC stack.
259    fn discover(&mut self, node: usize) {
260        self.indices[node] = self.index_counter;
261        self.lowlinks[node] = self.index_counter;
262        self.index_counter += 1;
263        self.on_stack.insert(node);
264        self.stack.push(node);
265    }
266
267    /// Build a frame spanning the successor range of `node`.
268    fn frame_for(node: usize, succ_ranges: &[Range<usize>]) -> SccFrame {
269        let range = &succ_ranges[node];
270        SccFrame {
271            node,
272            succ_pos: range.start,
273            succ_end: range.end,
274        }
275    }
276
277    /// Run the iterative Tarjan DFS rooted at `start`, appending discovered
278    /// SCCs of size >= 2 to `self.sccs`.
279    fn run_dfs_from(&mut self, start: usize, all_succs: &[usize], succ_ranges: &[Range<usize>]) {
280        self.discover(start);
281        let mut dfs_stack: Vec<SccFrame> = vec![Self::frame_for(start, succ_ranges)];
282
283        while let Some(frame) = dfs_stack.last_mut() {
284            if frame.succ_pos < frame.succ_end {
285                if let Some(child) = self.advance_frame(frame, all_succs) {
286                    dfs_stack.push(Self::frame_for(child, succ_ranges));
287                }
288            } else {
289                let v = frame.node;
290                let v_lowlink = self.lowlinks[v];
291                dfs_stack.pop();
292                if let Some(parent) = dfs_stack.last() {
293                    let pv = parent.node;
294                    self.lowlinks[pv] = self.lowlinks[pv].min(v_lowlink);
295                }
296                self.collect_root_scc(v);
297            }
298        }
299    }
300
301    /// Advance one successor of `frame`, discovering a new child (returned for
302    /// descent) or updating the lowlink for an on-stack back edge.
303    fn advance_frame(&mut self, frame: &mut SccFrame, all_succs: &[usize]) -> Option<usize> {
304        let w = all_succs[frame.succ_pos];
305        frame.succ_pos += 1;
306        if self.indices[w] == u32::MAX {
307            self.discover(w);
308            Some(w)
309        } else {
310            if self.on_stack.contains(w) {
311                let v = frame.node;
312                self.lowlinks[v] = self.lowlinks[v].min(self.indices[w]);
313            }
314            None
315        }
316    }
317
318    /// When `v` is an SCC root, pop its members off the stack and record the
319    /// SCC if it has at least two nodes.
320    #[expect(
321        clippy::cast_possible_truncation,
322        reason = "file count is bounded by project size, well under u32::MAX"
323    )]
324    #[expect(
325        clippy::expect_used,
326        reason = "Tarjan traversal only pops nodes that were pushed onto the SCC stack"
327    )]
328    fn collect_root_scc(&mut self, v: usize) {
329        if self.lowlinks[v] != self.indices[v] {
330            return;
331        }
332        let mut scc = Vec::new();
333        loop {
334            let w = self.stack.pop().expect("SCC stack should not be empty");
335            self.on_stack.set(w, false);
336            scc.push(FileId(w as u32));
337            if w == v {
338                break;
339            }
340        }
341        if scc.len() >= 2 {
342            self.sccs.push(scc);
343        }
344    }
345}
346
347/// Rotate a cycle so the node with the smallest path is first (canonical form for dedup).
348fn canonical_cycle(cycle: &[usize], modules: &[ModuleNode]) -> Vec<usize> {
349    if cycle.is_empty() {
350        return Vec::new();
351    }
352    let min_pos = cycle
353        .iter()
354        .enumerate()
355        .min_by(|(_, a), (_, b)| modules[**a].path.cmp(&modules[**b].path))
356        .map_or(0, |(i, _)| i);
357    let mut result = cycle[min_pos..].to_vec();
358    result.extend_from_slice(&cycle[..min_pos]);
359    result
360}
361
362struct CycleFrame {
363    succ_pos: usize,
364    succ_end: usize,
365}
366
367struct SuccessorMap<'a> {
368    all_succs: &'a [usize],
369    succ_ranges: &'a [Range<usize>],
370    modules: &'a [ModuleNode],
371}
372
373#[expect(
374    clippy::cast_possible_truncation,
375    reason = "file count is bounded by project size, well under u32::MAX"
376)]
377fn try_record_cycle(
378    path: &[usize],
379    modules: &[ModuleNode],
380    seen: &mut FxHashSet<Vec<u32>>,
381    cycles: &mut Vec<Vec<usize>>,
382    accept: &mut dyn FnMut(&[FileId]) -> bool,
383) {
384    let canonical = canonical_cycle(path, modules);
385    let key: Vec<u32> = canonical.iter().map(|&n| n as u32).collect();
386    if !seen.insert(key) {
387        return;
388    }
389    let files: Vec<FileId> = canonical.iter().map(|&n| FileId(n as u32)).collect();
390    if !accept(&files) {
391        cycles.push(canonical);
392    }
393}
394
395/// Run a bounded DFS from `start`, looking for elementary cycles of exactly `depth_limit` nodes.
396///
397/// Appends any newly found cycles to `cycles` (deduped via `seen`).
398/// Stops early once `cycles.len() >= max_cycles`.
399struct DfsCycleInput<'a> {
400    start: usize,
401    depth_limit: usize,
402    scc_set: &'a FxHashSet<usize>,
403    succs: &'a SuccessorMap<'a>,
404    max_cycles: usize,
405    seen: &'a mut FxHashSet<Vec<u32>>,
406    cycles: &'a mut Vec<Vec<usize>>,
407    accept: &'a mut dyn FnMut(&[FileId]) -> bool,
408}
409
410fn dfs_find_cycles_from(input: &mut DfsCycleInput<'_>) {
411    let mut path: Vec<usize> = vec![input.start];
412    let mut path_set = FixedBitSet::with_capacity(input.succs.modules.len());
413    path_set.insert(input.start);
414
415    let range = &input.succs.succ_ranges[input.start];
416    let mut dfs: Vec<CycleFrame> = vec![CycleFrame {
417        succ_pos: range.start,
418        succ_end: range.end,
419    }];
420
421    while let Some(frame) = dfs.last_mut() {
422        if input.cycles.len() >= input.max_cycles {
423            return;
424        }
425
426        if frame.succ_pos >= frame.succ_end {
427            dfs.pop();
428            if path.len() > 1 {
429                let Some(removed) = path.pop() else {
430                    continue;
431                };
432                path_set.set(removed, false);
433            }
434            continue;
435        }
436
437        let w = input.succs.all_succs[frame.succ_pos];
438        frame.succ_pos += 1;
439
440        if !input.scc_set.contains(&w) {
441            continue;
442        }
443
444        if w == input.start && path.len() >= 2 && path.len() == input.depth_limit {
445            try_record_cycle(
446                &path,
447                input.succs.modules,
448                input.seen,
449                input.cycles,
450                input.accept,
451            );
452            continue;
453        }
454
455        if path_set.contains(w) || path.len() >= input.depth_limit {
456            continue;
457        }
458
459        path.push(w);
460        path_set.insert(w);
461
462        let range = &input.succs.succ_ranges[w];
463        dfs.push(CycleFrame {
464            succ_pos: range.start,
465            succ_end: range.end,
466        });
467    }
468}
469
470/// Enumerate individual elementary cycles within an SCC using depth-limited DFS.
471///
472/// Uses iterative deepening: first finds all 2-node cycles, then 3-node, etc.
473/// This ensures the shortest, most actionable cycles are always found first.
474/// Stops after `max_cycles` total cycles to bound work on dense SCCs. A
475/// cycle that `accept` accepts does not count. The flag is `true` when the
476/// enumeration stopped at `max_cycles`.
477fn enumerate_elementary_cycles(
478    scc_nodes: &[usize],
479    succs: &SuccessorMap<'_>,
480    max_cycles: usize,
481    accept: &mut dyn FnMut(&[FileId]) -> bool,
482) -> (Vec<Vec<usize>>, bool) {
483    let scc_set: FxHashSet<usize> = scc_nodes.iter().copied().collect();
484    let mut cycles: Vec<Vec<usize>> = Vec::new();
485    let mut seen: FxHashSet<Vec<u32>> = FxHashSet::default();
486
487    let mut sorted_nodes: Vec<usize> = scc_nodes.to_vec();
488    sorted_nodes.sort_by(|a, b| succs.modules[*a].path.cmp(&succs.modules[*b].path));
489
490    let max_depth = scc_nodes.len().min(MAX_CYCLE_LENGTH);
491    for depth_limit in 2..=max_depth {
492        if cycles.len() >= max_cycles {
493            break;
494        }
495
496        for &start in &sorted_nodes {
497            if cycles.len() >= max_cycles {
498                break;
499            }
500
501            dfs_find_cycles_from(&mut DfsCycleInput {
502                start,
503                depth_limit,
504                scc_set: &scc_set,
505                succs,
506                max_cycles,
507                seen: &mut seen,
508                cycles: &mut cycles,
509                accept,
510            });
511        }
512    }
513
514    let capped = cycles.len() >= max_cycles;
515    (cycles, capped)
516}
517
518#[cfg(test)]
519mod tests {
520    use std::ops::Range;
521    use std::path::PathBuf;
522
523    use rustc_hash::FxHashSet;
524
525    use crate::graph::types::ModuleNode;
526    use crate::resolve::{ResolveResult, ResolvedImport, ResolvedModule};
527    use fallow_types::discover::{DiscoveredFile, EntryPoint, EntryPointSource, FileId};
528    use fallow_types::extract::{ExportName, ImportInfo, ImportedName, VisibilityTag};
529
530    use super::{
531        DfsCycleInput, ModuleGraph, SuccessorMap, canonical_cycle, dfs_find_cycles_from,
532        enumerate_elementary_cycles, try_record_cycle,
533    };
534
535    /// Helper: build a graph from files+edges, no entry points needed for cycle detection.
536    #[expect(
537        clippy::cast_possible_truncation,
538        reason = "test file counts are trivially small"
539    )]
540    fn build_cycle_graph(file_count: usize, edges_spec: &[(u32, u32)]) -> ModuleGraph {
541        let files: Vec<DiscoveredFile> = (0..file_count)
542            .map(|i| DiscoveredFile {
543                id: FileId(i as u32),
544                path: PathBuf::from(format!("/project/file{i}.ts")),
545                size_bytes: 100,
546            })
547            .collect();
548
549        let resolved_modules: Vec<ResolvedModule> = (0..file_count)
550            .map(|i| {
551                let imports: Vec<ResolvedImport> = edges_spec
552                    .iter()
553                    .filter(|(src, _)| *src == i as u32)
554                    .map(|(_, tgt)| ResolvedImport {
555                        info: ImportInfo {
556                            source: format!("./file{tgt}"),
557                            imported_name: ImportedName::Named("x".to_string()),
558                            local_name: "x".to_string(),
559                            is_type_only: false,
560                            is_type_only_star: false,
561                            from_style: false,
562                            span: oxc_span::Span::new(0, 10),
563                            source_span: oxc_span::Span::default(),
564                        },
565                        target: ResolveResult::InternalModule(FileId(*tgt)),
566                    })
567                    .collect();
568
569                ResolvedModule {
570                    file_id: FileId(i as u32),
571                    path: PathBuf::from(format!("/project/file{i}.ts")),
572                    exports: vec![fallow_types::extract::ExportInfo {
573                        name: ExportName::Named("x".to_string()),
574                        local_name: Some("x".to_string()),
575                        is_type_only: false,
576                        visibility: VisibilityTag::None,
577                        expected_unused_reason: None,
578                        span: oxc_span::Span::new(0, 20),
579                        members: vec![],
580                        is_side_effect_used: false,
581                        super_class: None,
582                        deprecated: false,
583                        deprecated_reason: None,
584                    }]
585                    .into(),
586                    re_exports: vec![],
587                    resolved_imports: imports,
588                    resolved_dynamic_imports: vec![],
589                    resolved_dynamic_patterns: vec![],
590                    member_accesses: vec![].into(),
591                    semantic_facts: std::sync::Arc::default(),
592                    whole_object_uses: std::sync::Arc::default(),
593                    has_cjs_exports: false,
594                    has_angular_component_template_url: false,
595                    unused_import_bindings: FxHashSet::default(),
596                    type_referenced_import_bindings: vec![],
597                    value_referenced_import_bindings: vec![],
598                    namespace_object_aliases: vec![],
599                    exported_factory_returns: std::sync::Arc::default(),
600                    exported_factory_return_object_shapes: std::sync::Arc::default(),
601                    type_member_types: std::sync::Arc::default(),
602                    missing_export_targets: vec![],
603                }
604            })
605            .collect();
606
607        let entry_points = vec![EntryPoint {
608            path: PathBuf::from("/project/file0.ts"),
609            source: EntryPointSource::PackageJsonMain,
610        }];
611
612        ModuleGraph::build(&resolved_modules, &entry_points, &files)
613    }
614
615    fn dfs_find_cycles_from_for_test(mut input: DfsCycleInput<'_>) {
616        dfs_find_cycles_from(&mut input);
617    }
618
619    #[test]
620    fn find_cycles_empty_graph() {
621        let graph = ModuleGraph::build(&[], &[], &[]);
622        assert!(graph.find_cycles().is_empty());
623    }
624
625    #[test]
626    fn find_cycles_no_cycles() {
627        let graph = build_cycle_graph(3, &[(0, 1), (1, 2)]);
628        assert!(graph.find_cycles().is_empty());
629    }
630
631    #[test]
632    fn find_cycles_simple_two_node_cycle() {
633        let graph = build_cycle_graph(2, &[(0, 1), (1, 0)]);
634        let cycles = graph.find_cycles();
635        assert_eq!(cycles.len(), 1);
636        assert_eq!(cycles[0].len(), 2);
637    }
638
639    #[test]
640    fn find_cycles_three_node_cycle() {
641        let graph = build_cycle_graph(3, &[(0, 1), (1, 2), (2, 0)]);
642        let cycles = graph.find_cycles();
643        assert_eq!(cycles.len(), 1);
644        assert_eq!(cycles[0].len(), 3);
645    }
646
647    #[test]
648    fn find_cycles_self_import_ignored() {
649        let graph = build_cycle_graph(1, &[(0, 0)]);
650        let cycles = graph.find_cycles();
651        assert!(
652            cycles.is_empty(),
653            "self-imports should not be reported as cycles"
654        );
655    }
656
657    #[test]
658    fn find_cycles_multiple_independent_cycles() {
659        let graph = build_cycle_graph(4, &[(0, 1), (1, 0), (2, 3), (3, 2)]);
660        let cycles = graph.find_cycles();
661        assert_eq!(cycles.len(), 2);
662        assert!(cycles.iter().all(|c| c.len() == 2));
663    }
664
665    #[test]
666    fn find_cycles_linear_chain_with_back_edge() {
667        let graph = build_cycle_graph(4, &[(0, 1), (1, 2), (2, 3), (3, 1)]);
668        let cycles = graph.find_cycles();
669        assert_eq!(cycles.len(), 1);
670        assert_eq!(cycles[0].len(), 3);
671        let ids: Vec<u32> = cycles[0].iter().map(|f| f.0).collect();
672        assert!(ids.contains(&1));
673        assert!(ids.contains(&2));
674        assert!(ids.contains(&3));
675        assert!(!ids.contains(&0));
676    }
677
678    #[test]
679    fn find_cycles_overlapping_cycles_enumerated() {
680        let graph = build_cycle_graph(3, &[(0, 1), (1, 0), (1, 2), (2, 1)]);
681        let cycles = graph.find_cycles();
682        assert_eq!(
683            cycles.len(),
684            2,
685            "should find 2 elementary cycles, not 1 SCC"
686        );
687        assert!(
688            cycles.iter().all(|c| c.len() == 2),
689            "both cycles should have length 2"
690        );
691    }
692
693    #[test]
694    fn find_cycles_deterministic_ordering() {
695        let graph1 = build_cycle_graph(3, &[(0, 1), (1, 2), (2, 0)]);
696        let graph2 = build_cycle_graph(3, &[(0, 1), (1, 2), (2, 0)]);
697        let cycles1 = graph1.find_cycles();
698        let cycles2 = graph2.find_cycles();
699        assert_eq!(cycles1.len(), cycles2.len());
700        for (c1, c2) in cycles1.iter().zip(cycles2.iter()) {
701            let paths1: Vec<&PathBuf> = c1
702                .iter()
703                .map(|f| &graph1.modules[f.0 as usize].path)
704                .collect();
705            let paths2: Vec<&PathBuf> = c2
706                .iter()
707                .map(|f| &graph2.modules[f.0 as usize].path)
708                .collect();
709            assert_eq!(paths1, paths2);
710        }
711    }
712
713    #[test]
714    fn find_cycles_sorted_by_length() {
715        let graph = build_cycle_graph(5, &[(0, 1), (1, 0), (2, 3), (3, 4), (4, 2)]);
716        let cycles = graph.find_cycles();
717        assert_eq!(cycles.len(), 2);
718        assert!(
719            cycles[0].len() <= cycles[1].len(),
720            "cycles should be sorted by length"
721        );
722    }
723
724    #[test]
725    fn find_cycles_large_cycle() {
726        let edges: Vec<(u32, u32)> = (0..10).map(|i| (i, (i + 1) % 10)).collect();
727        let graph = build_cycle_graph(10, &edges);
728        let cycles = graph.find_cycles();
729        assert_eq!(cycles.len(), 1);
730        assert_eq!(cycles[0].len(), 10);
731    }
732
733    #[test]
734    fn find_cycles_complex_scc_multiple_elementary() {
735        let graph = build_cycle_graph(4, &[(0, 1), (1, 2), (2, 3), (3, 0), (0, 2)]);
736        let cycles = graph.find_cycles();
737        assert!(
738            cycles.len() >= 2,
739            "should find at least 2 elementary cycles, got {}",
740            cycles.len()
741        );
742        assert!(cycles.iter().all(|c| c.len() <= 4));
743    }
744
745    #[test]
746    fn find_cycles_no_duplicate_cycles() {
747        let graph = build_cycle_graph(3, &[(0, 1), (1, 2), (2, 0)]);
748        let cycles = graph.find_cycles();
749        assert_eq!(cycles.len(), 1, "triangle should produce exactly 1 cycle");
750        assert_eq!(cycles[0].len(), 3);
751    }
752
753    /// Build lightweight `ModuleNode` stubs and successor data for unit tests.
754    ///
755    /// `edges_spec` is a list of (source, target) pairs (0-indexed).
756    /// Returns (modules, all_succs, succ_ranges) suitable for constructing a `SuccessorMap`.
757    #[expect(
758        clippy::cast_possible_truncation,
759        reason = "test file counts are trivially small"
760    )]
761    fn build_test_succs(
762        file_count: usize,
763        edges_spec: &[(usize, usize)],
764    ) -> (Vec<ModuleNode>, Vec<usize>, Vec<Range<usize>>) {
765        let modules: Vec<ModuleNode> = (0..file_count)
766            .map(|i| {
767                let mut node = ModuleNode {
768                    file_id: FileId(i as u32),
769                    path: PathBuf::from(format!("/project/file{i}.ts")),
770                    edge_range: 0..0,
771                    exports: vec![],
772                    re_exports: vec![],
773                    flags: ModuleNode::flags_from(i == 0, true, false),
774                };
775                node.set_reachable(true);
776                node
777            })
778            .collect();
779
780        let mut all_succs: Vec<usize> = Vec::new();
781        let mut succ_ranges: Vec<Range<usize>> = Vec::with_capacity(file_count);
782        for src in 0..file_count {
783            let start = all_succs.len();
784            let mut seen = FxHashSet::default();
785            for &(s, t) in edges_spec {
786                if s == src && t < file_count && seen.insert(t) {
787                    all_succs.push(t);
788                }
789            }
790            let end = all_succs.len();
791            succ_ranges.push(start..end);
792        }
793
794        (modules, all_succs, succ_ranges)
795    }
796
797    #[test]
798    fn canonical_cycle_empty() {
799        let modules: Vec<ModuleNode> = vec![];
800        assert!(canonical_cycle(&[], &modules).is_empty());
801    }
802
803    #[test]
804    fn canonical_cycle_rotates_to_smallest_path() {
805        let (modules, _, _) = build_test_succs(3, &[]);
806        let result = canonical_cycle(&[2, 0, 1], &modules);
807        assert_eq!(result, vec![0, 1, 2]);
808    }
809
810    #[test]
811    fn canonical_cycle_already_canonical() {
812        let (modules, _, _) = build_test_succs(3, &[]);
813        let result = canonical_cycle(&[0, 1, 2], &modules);
814        assert_eq!(result, vec![0, 1, 2]);
815    }
816
817    #[test]
818    fn canonical_cycle_single_node() {
819        let (modules, _, _) = build_test_succs(1, &[]);
820        let result = canonical_cycle(&[0], &modules);
821        assert_eq!(result, vec![0]);
822    }
823
824    #[test]
825    fn try_record_cycle_inserts_new_cycle() {
826        let (modules, _, _) = build_test_succs(3, &[]);
827        let mut seen = FxHashSet::default();
828        let mut cycles = Vec::new();
829
830        try_record_cycle(&[0, 1, 2], &modules, &mut seen, &mut cycles, &mut |_| false);
831        assert_eq!(cycles.len(), 1);
832        assert_eq!(cycles[0], vec![0, 1, 2]);
833    }
834
835    #[test]
836    fn try_record_cycle_deduplicates_rotated_cycle() {
837        let (modules, _, _) = build_test_succs(3, &[]);
838        let mut seen = FxHashSet::default();
839        let mut cycles = Vec::new();
840
841        try_record_cycle(&[0, 1, 2], &modules, &mut seen, &mut cycles, &mut |_| false);
842        try_record_cycle(&[1, 2, 0], &modules, &mut seen, &mut cycles, &mut |_| false);
843        try_record_cycle(&[2, 0, 1], &modules, &mut seen, &mut cycles, &mut |_| false);
844
845        assert_eq!(
846            cycles.len(),
847            1,
848            "rotations of the same cycle should be deduped"
849        );
850    }
851
852    #[test]
853    fn try_record_cycle_single_node_self_loop() {
854        let (modules, _, _) = build_test_succs(1, &[]);
855        let mut seen = FxHashSet::default();
856        let mut cycles = Vec::new();
857
858        try_record_cycle(&[0], &modules, &mut seen, &mut cycles, &mut |_| false);
859        assert_eq!(cycles.len(), 1);
860        assert_eq!(cycles[0], vec![0]);
861    }
862
863    #[test]
864    fn try_record_cycle_distinct_cycles_both_recorded() {
865        let (modules, _, _) = build_test_succs(4, &[]);
866        let mut seen = FxHashSet::default();
867        let mut cycles = Vec::new();
868
869        try_record_cycle(&[0, 1], &modules, &mut seen, &mut cycles, &mut |_| false);
870        try_record_cycle(&[2, 3], &modules, &mut seen, &mut cycles, &mut |_| false);
871
872        assert_eq!(cycles.len(), 2);
873    }
874
875    #[test]
876    fn successor_map_empty_graph() {
877        let (modules, all_succs, succ_ranges) = build_test_succs(0, &[]);
878        let succs = SuccessorMap {
879            all_succs: &all_succs,
880            succ_ranges: &succ_ranges,
881            modules: &modules,
882        };
883        assert!(succs.all_succs.is_empty());
884        assert!(succs.succ_ranges.is_empty());
885    }
886
887    #[test]
888    fn successor_map_single_node_self_edge() {
889        let (modules, all_succs, succ_ranges) = build_test_succs(1, &[(0, 0)]);
890        let succs = SuccessorMap {
891            all_succs: &all_succs,
892            succ_ranges: &succ_ranges,
893            modules: &modules,
894        };
895        assert_eq!(succs.all_succs.len(), 1);
896        assert_eq!(succs.all_succs[0], 0);
897        assert_eq!(succs.succ_ranges[0], 0..1);
898    }
899
900    #[test]
901    fn successor_map_deduplicates_edges() {
902        let (modules, all_succs, succ_ranges) = build_test_succs(2, &[(0, 1), (0, 1)]);
903        let succs = SuccessorMap {
904            all_succs: &all_succs,
905            succ_ranges: &succ_ranges,
906            modules: &modules,
907        };
908        let range = &succs.succ_ranges[0];
909        assert_eq!(
910            range.end - range.start,
911            1,
912            "duplicate edges should be deduped"
913        );
914    }
915
916    #[test]
917    fn successor_map_multiple_successors() {
918        let (modules, all_succs, succ_ranges) = build_test_succs(4, &[(0, 1), (0, 2), (0, 3)]);
919        let succs = SuccessorMap {
920            all_succs: &all_succs,
921            succ_ranges: &succ_ranges,
922            modules: &modules,
923        };
924        let range = &succs.succ_ranges[0];
925        assert_eq!(range.end - range.start, 3);
926        for r in &succs.succ_ranges[1..4] {
927            assert_eq!(r.end - r.start, 0);
928        }
929    }
930
931    #[test]
932    fn dfs_find_cycles_from_isolated_node() {
933        let (modules, all_succs, succ_ranges) = build_test_succs(1, &[]);
934        let succs = SuccessorMap {
935            all_succs: &all_succs,
936            succ_ranges: &succ_ranges,
937            modules: &modules,
938        };
939        let scc_set: FxHashSet<usize> = std::iter::once(0).collect();
940        let mut seen = FxHashSet::default();
941        let mut cycles = Vec::new();
942
943        dfs_find_cycles_from_for_test(DfsCycleInput {
944            start: 0,
945            depth_limit: 2,
946            scc_set: &scc_set,
947            succs: &succs,
948            max_cycles: 10,
949            accept: &mut |_| false,
950            seen: &mut seen,
951            cycles: &mut cycles,
952        });
953        assert!(cycles.is_empty(), "isolated node should have no cycles");
954    }
955
956    #[test]
957    fn dfs_find_cycles_from_simple_two_cycle() {
958        let (modules, all_succs, succ_ranges) = build_test_succs(2, &[(0, 1), (1, 0)]);
959        let succs = SuccessorMap {
960            all_succs: &all_succs,
961            succ_ranges: &succ_ranges,
962            modules: &modules,
963        };
964        let scc_set: FxHashSet<usize> = [0, 1].into_iter().collect();
965        let mut seen = FxHashSet::default();
966        let mut cycles = Vec::new();
967
968        dfs_find_cycles_from_for_test(DfsCycleInput {
969            start: 0,
970            depth_limit: 2,
971            scc_set: &scc_set,
972            succs: &succs,
973            max_cycles: 10,
974            accept: &mut |_| false,
975            seen: &mut seen,
976            cycles: &mut cycles,
977        });
978        assert_eq!(cycles.len(), 1);
979        assert_eq!(cycles[0].len(), 2);
980    }
981
982    #[test]
983    fn dfs_find_cycles_from_diamond_graph() {
984        let (modules, all_succs, succ_ranges) =
985            build_test_succs(4, &[(0, 1), (0, 2), (1, 3), (2, 3), (3, 0)]);
986        let succs = SuccessorMap {
987            all_succs: &all_succs,
988            succ_ranges: &succ_ranges,
989            modules: &modules,
990        };
991        let scc_set: FxHashSet<usize> = [0, 1, 2, 3].into_iter().collect();
992        let mut seen = FxHashSet::default();
993        let mut cycles = Vec::new();
994
995        dfs_find_cycles_from_for_test(DfsCycleInput {
996            start: 0,
997            depth_limit: 3,
998            scc_set: &scc_set,
999            succs: &succs,
1000            max_cycles: 10,
1001            accept: &mut |_| false,
1002            seen: &mut seen,
1003            cycles: &mut cycles,
1004        });
1005        assert_eq!(cycles.len(), 2, "diamond should have two 3-node cycles");
1006        assert!(cycles.iter().all(|c| c.len() == 3));
1007    }
1008
1009    #[test]
1010    fn dfs_find_cycles_from_depth_limit_prevents_longer_cycles() {
1011        let (modules, all_succs, succ_ranges) =
1012            build_test_succs(4, &[(0, 1), (1, 2), (2, 3), (3, 0)]);
1013        let succs = SuccessorMap {
1014            all_succs: &all_succs,
1015            succ_ranges: &succ_ranges,
1016            modules: &modules,
1017        };
1018        let scc_set: FxHashSet<usize> = [0, 1, 2, 3].into_iter().collect();
1019        let mut seen = FxHashSet::default();
1020        let mut cycles = Vec::new();
1021
1022        dfs_find_cycles_from_for_test(DfsCycleInput {
1023            start: 0,
1024            depth_limit: 3,
1025            scc_set: &scc_set,
1026            succs: &succs,
1027            max_cycles: 10,
1028            accept: &mut |_| false,
1029            seen: &mut seen,
1030            cycles: &mut cycles,
1031        });
1032        assert!(
1033            cycles.is_empty(),
1034            "depth_limit=3 should prevent finding a 4-node cycle"
1035        );
1036    }
1037
1038    #[test]
1039    fn dfs_find_cycles_from_depth_limit_exact_match() {
1040        let (modules, all_succs, succ_ranges) =
1041            build_test_succs(4, &[(0, 1), (1, 2), (2, 3), (3, 0)]);
1042        let succs = SuccessorMap {
1043            all_succs: &all_succs,
1044            succ_ranges: &succ_ranges,
1045            modules: &modules,
1046        };
1047        let scc_set: FxHashSet<usize> = [0, 1, 2, 3].into_iter().collect();
1048        let mut seen = FxHashSet::default();
1049        let mut cycles = Vec::new();
1050
1051        dfs_find_cycles_from_for_test(DfsCycleInput {
1052            start: 0,
1053            depth_limit: 4,
1054            scc_set: &scc_set,
1055            succs: &succs,
1056            max_cycles: 10,
1057            accept: &mut |_| false,
1058            seen: &mut seen,
1059            cycles: &mut cycles,
1060        });
1061        assert_eq!(
1062            cycles.len(),
1063            1,
1064            "depth_limit=4 should find the 4-node cycle"
1065        );
1066        assert_eq!(cycles[0].len(), 4);
1067    }
1068
1069    #[test]
1070    fn dfs_find_cycles_from_respects_max_cycles() {
1071        let edges: Vec<(usize, usize)> = (0..4)
1072            .flat_map(|i| (0..4).filter(move |&j| i != j).map(move |j| (i, j)))
1073            .collect();
1074        let (modules, all_succs, succ_ranges) = build_test_succs(4, &edges);
1075        let succs = SuccessorMap {
1076            all_succs: &all_succs,
1077            succ_ranges: &succ_ranges,
1078            modules: &modules,
1079        };
1080        let scc_set: FxHashSet<usize> = (0..4).collect();
1081        let mut seen = FxHashSet::default();
1082        let mut cycles = Vec::new();
1083
1084        dfs_find_cycles_from_for_test(DfsCycleInput {
1085            start: 0,
1086            depth_limit: 2,
1087            scc_set: &scc_set,
1088            succs: &succs,
1089            max_cycles: 2,
1090            accept: &mut |_| false,
1091            seen: &mut seen,
1092            cycles: &mut cycles,
1093        });
1094        assert!(
1095            cycles.len() <= 2,
1096            "should respect max_cycles limit, got {}",
1097            cycles.len()
1098        );
1099    }
1100
1101    #[test]
1102    fn dfs_find_cycles_from_ignores_nodes_outside_scc() {
1103        let (modules, all_succs, succ_ranges) = build_test_succs(3, &[(0, 1), (1, 2), (2, 0)]);
1104        let succs = SuccessorMap {
1105            all_succs: &all_succs,
1106            succ_ranges: &succ_ranges,
1107            modules: &modules,
1108        };
1109        let scc_set: FxHashSet<usize> = [0, 1].into_iter().collect();
1110        let mut seen = FxHashSet::default();
1111        let mut cycles = Vec::new();
1112
1113        for depth in 2..=3 {
1114            dfs_find_cycles_from_for_test(DfsCycleInput {
1115                start: 0,
1116                depth_limit: depth,
1117                scc_set: &scc_set,
1118                succs: &succs,
1119                max_cycles: 10,
1120                accept: &mut |_| false,
1121                seen: &mut seen,
1122                cycles: &mut cycles,
1123            });
1124        }
1125        assert!(
1126            cycles.is_empty(),
1127            "should not find cycles through nodes outside the SCC set"
1128        );
1129    }
1130
1131    #[test]
1132    fn enumerate_elementary_cycles_empty_scc() {
1133        let (modules, all_succs, succ_ranges) = build_test_succs(0, &[]);
1134        let succs = SuccessorMap {
1135            all_succs: &all_succs,
1136            succ_ranges: &succ_ranges,
1137            modules: &modules,
1138        };
1139        let cycles = enumerate_elementary_cycles(&[], &succs, 10, &mut |_| false).0;
1140        assert!(cycles.is_empty());
1141    }
1142
1143    #[test]
1144    fn enumerate_elementary_cycles_max_cycles_limit() {
1145        let edges: Vec<(usize, usize)> = (0..4)
1146            .flat_map(|i| (0..4).filter(move |&j| i != j).map(move |j| (i, j)))
1147            .collect();
1148        let (modules, all_succs, succ_ranges) = build_test_succs(4, &edges);
1149        let succs = SuccessorMap {
1150            all_succs: &all_succs,
1151            succ_ranges: &succ_ranges,
1152            modules: &modules,
1153        };
1154        let scc_nodes: Vec<usize> = (0..4).collect();
1155
1156        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 3, &mut |_| false).0;
1157        assert!(
1158            cycles.len() <= 3,
1159            "should respect max_cycles=3 limit, got {}",
1160            cycles.len()
1161        );
1162    }
1163
1164    #[test]
1165    fn enumerate_elementary_cycles_finds_all_in_triangle() {
1166        let (modules, all_succs, succ_ranges) = build_test_succs(3, &[(0, 1), (1, 2), (2, 0)]);
1167        let succs = SuccessorMap {
1168            all_succs: &all_succs,
1169            succ_ranges: &succ_ranges,
1170            modules: &modules,
1171        };
1172        let scc_nodes: Vec<usize> = vec![0, 1, 2];
1173
1174        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20, &mut |_| false).0;
1175        assert_eq!(cycles.len(), 1);
1176        assert_eq!(cycles[0].len(), 3);
1177    }
1178
1179    #[test]
1180    fn enumerate_elementary_cycles_iterative_deepening_order() {
1181        let (modules, all_succs, succ_ranges) =
1182            build_test_succs(3, &[(0, 1), (1, 0), (1, 2), (2, 0)]);
1183        let succs = SuccessorMap {
1184            all_succs: &all_succs,
1185            succ_ranges: &succ_ranges,
1186            modules: &modules,
1187        };
1188        let scc_nodes: Vec<usize> = vec![0, 1, 2];
1189
1190        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20, &mut |_| false).0;
1191        assert!(cycles.len() >= 2, "should find at least 2 cycles");
1192        assert!(
1193            cycles[0].len() <= cycles[cycles.len() - 1].len(),
1194            "shorter cycles should be found before longer ones"
1195        );
1196    }
1197
1198    #[test]
1199    fn find_cycles_max_cycles_per_scc_respected() {
1200        let edges: Vec<(u32, u32)> = (0..5)
1201            .flat_map(|i| (0..5).filter(move |&j| i != j).map(move |j| (i, j)))
1202            .collect();
1203        let graph = build_cycle_graph(5, &edges);
1204        let cycles = graph.find_cycles();
1205        assert!(
1206            cycles.len() <= 20,
1207            "should cap at MAX_CYCLES_PER_SCC, got {}",
1208            cycles.len()
1209        );
1210        assert!(
1211            !cycles.is_empty(),
1212            "dense graph should still find some cycles"
1213        );
1214    }
1215
1216    #[test]
1217    fn find_cycles_graph_with_no_cycles_returns_empty() {
1218        let graph = build_cycle_graph(5, &[(0, 1), (0, 2), (0, 3), (0, 4)]);
1219        assert!(graph.find_cycles().is_empty());
1220    }
1221
1222    #[test]
1223    fn find_cycles_diamond_no_cycle() {
1224        let graph = build_cycle_graph(4, &[(0, 1), (0, 2), (1, 3), (2, 3)]);
1225        assert!(graph.find_cycles().is_empty());
1226    }
1227
1228    #[test]
1229    fn find_cycles_diamond_with_back_edge() {
1230        let graph = build_cycle_graph(4, &[(0, 1), (0, 2), (1, 3), (2, 3), (3, 0)]);
1231        let cycles = graph.find_cycles();
1232        assert!(
1233            cycles.len() >= 2,
1234            "diamond with back-edge should have at least 2 elementary cycles, got {}",
1235            cycles.len()
1236        );
1237        assert_eq!(cycles[0].len(), 3);
1238    }
1239
1240    #[test]
1241    fn canonical_cycle_non_sequential_indices() {
1242        let (modules, _, _) = build_test_succs(5, &[]);
1243        let result = canonical_cycle(&[3, 1, 4], &modules);
1244        assert_eq!(result, vec![1, 4, 3]);
1245    }
1246
1247    #[test]
1248    fn canonical_cycle_different_starting_points_same_result() {
1249        let (modules, _, _) = build_test_succs(4, &[]);
1250        let r1 = canonical_cycle(&[0, 1, 2, 3], &modules);
1251        let r2 = canonical_cycle(&[1, 2, 3, 0], &modules);
1252        let r3 = canonical_cycle(&[2, 3, 0, 1], &modules);
1253        let r4 = canonical_cycle(&[3, 0, 1, 2], &modules);
1254        assert_eq!(r1, r2);
1255        assert_eq!(r2, r3);
1256        assert_eq!(r3, r4);
1257        assert_eq!(r1, vec![0, 1, 2, 3]);
1258    }
1259
1260    #[test]
1261    fn canonical_cycle_two_node_both_rotations() {
1262        let (modules, _, _) = build_test_succs(2, &[]);
1263        assert_eq!(canonical_cycle(&[0, 1], &modules), vec![0, 1]);
1264        assert_eq!(canonical_cycle(&[1, 0], &modules), vec![0, 1]);
1265    }
1266
1267    #[test]
1268    fn dfs_find_cycles_from_self_loop_not_found() {
1269        let (modules, all_succs, succ_ranges) = build_test_succs(1, &[(0, 0)]);
1270        let succs = SuccessorMap {
1271            all_succs: &all_succs,
1272            succ_ranges: &succ_ranges,
1273            modules: &modules,
1274        };
1275        let scc_set: FxHashSet<usize> = std::iter::once(0).collect();
1276        let mut seen = FxHashSet::default();
1277        let mut cycles = Vec::new();
1278
1279        for depth in 1..=3 {
1280            dfs_find_cycles_from_for_test(DfsCycleInput {
1281                start: 0,
1282                depth_limit: depth,
1283                scc_set: &scc_set,
1284                succs: &succs,
1285                max_cycles: 10,
1286                accept: &mut |_| false,
1287                seen: &mut seen,
1288                cycles: &mut cycles,
1289            });
1290        }
1291        assert!(
1292            cycles.is_empty(),
1293            "self-loop should not be detected as a cycle by dfs_find_cycles_from"
1294        );
1295    }
1296
1297    #[test]
1298    fn enumerate_elementary_cycles_self_loop_not_found() {
1299        let (modules, all_succs, succ_ranges) = build_test_succs(1, &[(0, 0)]);
1300        let succs = SuccessorMap {
1301            all_succs: &all_succs,
1302            succ_ranges: &succ_ranges,
1303            modules: &modules,
1304        };
1305        let cycles = enumerate_elementary_cycles(&[0], &succs, 20, &mut |_| false).0;
1306        assert!(
1307            cycles.is_empty(),
1308            "self-loop should not produce elementary cycles"
1309        );
1310    }
1311
1312    #[test]
1313    fn find_cycles_two_cycles_sharing_edge() {
1314        let graph = build_cycle_graph(4, &[(0, 1), (1, 2), (2, 0), (1, 3), (3, 0)]);
1315        let cycles = graph.find_cycles();
1316        assert_eq!(
1317            cycles.len(),
1318            2,
1319            "two cycles sharing edge A->B should both be found, got {}",
1320            cycles.len()
1321        );
1322        assert!(
1323            cycles.iter().all(|c| c.len() == 3),
1324            "both cycles should have length 3"
1325        );
1326    }
1327
1328    #[test]
1329    fn enumerate_elementary_cycles_shared_edge() {
1330        let (modules, all_succs, succ_ranges) =
1331            build_test_succs(4, &[(0, 1), (1, 2), (2, 0), (1, 3), (3, 0)]);
1332        let succs = SuccessorMap {
1333            all_succs: &all_succs,
1334            succ_ranges: &succ_ranges,
1335            modules: &modules,
1336        };
1337        let scc_nodes: Vec<usize> = vec![0, 1, 2, 3];
1338        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20, &mut |_| false).0;
1339        assert_eq!(
1340            cycles.len(),
1341            2,
1342            "should find exactly 2 elementary cycles sharing edge 0->1, got {}",
1343            cycles.len()
1344        );
1345    }
1346
1347    #[test]
1348    fn enumerate_elementary_cycles_pentagon_with_chords() {
1349        let (modules, all_succs, succ_ranges) =
1350            build_test_succs(5, &[(0, 1), (1, 2), (2, 3), (3, 4), (4, 0), (0, 2), (0, 3)]);
1351        let succs = SuccessorMap {
1352            all_succs: &all_succs,
1353            succ_ranges: &succ_ranges,
1354            modules: &modules,
1355        };
1356        let scc_nodes: Vec<usize> = vec![0, 1, 2, 3, 4];
1357        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20, &mut |_| false).0;
1358
1359        assert!(
1360            cycles.len() >= 3,
1361            "pentagon with chords should have at least 3 elementary cycles, got {}",
1362            cycles.len()
1363        );
1364        let unique: FxHashSet<Vec<usize>> = cycles.iter().cloned().collect();
1365        assert_eq!(
1366            unique.len(),
1367            cycles.len(),
1368            "all enumerated cycles should be unique"
1369        );
1370        assert_eq!(
1371            cycles[0].len(),
1372            3,
1373            "shortest cycle in pentagon with chords should be length 3"
1374        );
1375    }
1376
1377    #[test]
1378    fn find_cycles_large_scc_complete_graph_k6() {
1379        let edges: Vec<(u32, u32)> = (0..6)
1380            .flat_map(|i| (0..6).filter(move |&j| i != j).map(move |j| (i, j)))
1381            .collect();
1382        let graph = build_cycle_graph(6, &edges);
1383        let cycles = graph.find_cycles();
1384
1385        assert!(
1386            cycles.len() <= 20,
1387            "should cap at MAX_CYCLES_PER_SCC (20), got {}",
1388            cycles.len()
1389        );
1390        assert_eq!(
1391            cycles.len(),
1392            20,
1393            "K6 has far more than 20 elementary cycles, so we should hit the cap"
1394        );
1395        assert_eq!(cycles[0].len(), 2, "shortest cycles in K6 should be 2-node");
1396    }
1397
1398    #[test]
1399    fn enumerate_elementary_cycles_respects_depth_cap_of_12() {
1400        let edges: Vec<(usize, usize)> = (0..15).map(|i| (i, (i + 1) % 15)).collect();
1401        let (modules, all_succs, succ_ranges) = build_test_succs(15, &edges);
1402        let succs = SuccessorMap {
1403            all_succs: &all_succs,
1404            succ_ranges: &succ_ranges,
1405            modules: &modules,
1406        };
1407        let scc_nodes: Vec<usize> = (0..15).collect();
1408        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20, &mut |_| false).0;
1409
1410        assert!(
1411            cycles.is_empty(),
1412            "a pure 15-node cycle should not be found with depth cap of 12, got {} cycles",
1413            cycles.len()
1414        );
1415    }
1416
1417    #[test]
1418    fn enumerate_elementary_cycles_finds_cycle_at_depth_cap_boundary() {
1419        let edges: Vec<(usize, usize)> = (0..12).map(|i| (i, (i + 1) % 12)).collect();
1420        let (modules, all_succs, succ_ranges) = build_test_succs(12, &edges);
1421        let succs = SuccessorMap {
1422            all_succs: &all_succs,
1423            succ_ranges: &succ_ranges,
1424            modules: &modules,
1425        };
1426        let scc_nodes: Vec<usize> = (0..12).collect();
1427        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20, &mut |_| false).0;
1428
1429        assert_eq!(
1430            cycles.len(),
1431            1,
1432            "a pure 12-node cycle should be found at the depth cap boundary"
1433        );
1434        assert_eq!(cycles[0].len(), 12);
1435    }
1436
1437    #[test]
1438    fn enumerate_elementary_cycles_13_node_pure_cycle_not_found() {
1439        let edges: Vec<(usize, usize)> = (0..13).map(|i| (i, (i + 1) % 13)).collect();
1440        let (modules, all_succs, succ_ranges) = build_test_succs(13, &edges);
1441        let succs = SuccessorMap {
1442            all_succs: &all_succs,
1443            succ_ranges: &succ_ranges,
1444            modules: &modules,
1445        };
1446        let scc_nodes: Vec<usize> = (0..13).collect();
1447        let cycles = enumerate_elementary_cycles(&scc_nodes, &succs, 20, &mut |_| false).0;
1448
1449        assert!(
1450            cycles.is_empty(),
1451            "13-node pure cycle exceeds depth cap of 12"
1452        );
1453    }
1454
1455    #[test]
1456    fn find_cycles_max_cycles_per_scc_enforced_on_k7() {
1457        let edges: Vec<(u32, u32)> = (0..7)
1458            .flat_map(|i| (0..7).filter(move |&j| i != j).map(move |j| (i, j)))
1459            .collect();
1460        let graph = build_cycle_graph(7, &edges);
1461        let cycles = graph.find_cycles();
1462
1463        assert!(
1464            cycles.len() <= 20,
1465            "K7 should cap at MAX_CYCLES_PER_SCC (20), got {}",
1466            cycles.len()
1467        );
1468        assert_eq!(
1469            cycles.len(),
1470            20,
1471            "K7 has far more than 20 elementary cycles, should hit the cap exactly"
1472        );
1473    }
1474
1475    #[test]
1476    fn find_cycles_two_dense_sccs_each_capped() {
1477        let mut edges: Vec<(u32, u32)> = Vec::new();
1478        for i in 0..4 {
1479            for j in 0..4 {
1480                if i != j {
1481                    edges.push((i, j));
1482                }
1483            }
1484        }
1485        for i in 4..8 {
1486            for j in 4..8 {
1487                if i != j {
1488                    edges.push((i, j));
1489                }
1490            }
1491        }
1492        let graph = build_cycle_graph(8, &edges);
1493        let cycles = graph.find_cycles();
1494
1495        assert!(!cycles.is_empty(), "two dense SCCs should produce cycles");
1496        assert!(
1497            cycles.len() > 2,
1498            "should find multiple cycles across both SCCs, got {}",
1499            cycles.len()
1500        );
1501    }
1502
1503    mod proptests {
1504        use super::*;
1505        use proptest::prelude::*;
1506
1507        proptest! {
1508            /// A DAG (directed acyclic graph) should always have zero cycles.
1509            /// We construct a DAG by only allowing edges from lower to higher node indices.
1510            #[test]
1511            fn dag_has_no_cycles(
1512                file_count in 2..20usize,
1513                edge_pairs in prop::collection::vec((0..19u32, 0..19u32), 0..30),
1514            ) {
1515                let dag_edges: Vec<(u32, u32)> = edge_pairs
1516                    .into_iter()
1517                    .filter(|(a, b)| (*a as usize) < file_count && (*b as usize) < file_count && a < b)
1518                    .collect();
1519
1520                let graph = build_cycle_graph(file_count, &dag_edges);
1521                let cycles = graph.find_cycles();
1522                prop_assert!(
1523                    cycles.is_empty(),
1524                    "DAG should have no cycles, but found {}",
1525                    cycles.len()
1526                );
1527            }
1528
1529            /// Adding mutual edges A->B->A should always detect a cycle.
1530            #[test]
1531            fn mutual_edges_always_detect_cycle(extra_nodes in 0..10usize) {
1532                let file_count = 2 + extra_nodes;
1533                let graph = build_cycle_graph(file_count, &[(0, 1), (1, 0)]);
1534                let cycles = graph.find_cycles();
1535                prop_assert!(
1536                    !cycles.is_empty(),
1537                    "A->B->A should always produce at least one cycle"
1538                );
1539                let has_pair_cycle = cycles.iter().any(|c| {
1540                    c.contains(&FileId(0)) && c.contains(&FileId(1))
1541                });
1542                prop_assert!(has_pair_cycle, "Should find a cycle containing nodes 0 and 1");
1543            }
1544
1545            /// All cycle members should be valid FileId indices.
1546            #[test]
1547            fn cycle_members_are_valid_indices(
1548                file_count in 2..15usize,
1549                edge_pairs in prop::collection::vec((0..14u32, 0..14u32), 1..20),
1550            ) {
1551                let edges: Vec<(u32, u32)> = edge_pairs
1552                    .into_iter()
1553                    .filter(|(a, b)| (*a as usize) < file_count && (*b as usize) < file_count && a != b)
1554                    .collect();
1555
1556                let graph = build_cycle_graph(file_count, &edges);
1557                let cycles = graph.find_cycles();
1558                for cycle in &cycles {
1559                    prop_assert!(cycle.len() >= 2, "Cycles must have at least 2 nodes");
1560                    for file_id in cycle {
1561                        prop_assert!(
1562                            (file_id.0 as usize) < file_count,
1563                            "FileId {} exceeds file count {}",
1564                            file_id.0, file_count
1565                        );
1566                    }
1567                }
1568            }
1569
1570            /// Cycles should be sorted by length (shortest first).
1571            #[test]
1572            fn cycles_sorted_by_length(
1573                file_count in 3..12usize,
1574                edge_pairs in prop::collection::vec((0..11u32, 0..11u32), 2..25),
1575            ) {
1576                let edges: Vec<(u32, u32)> = edge_pairs
1577                    .into_iter()
1578                    .filter(|(a, b)| (*a as usize) < file_count && (*b as usize) < file_count && a != b)
1579                    .collect();
1580
1581                let graph = build_cycle_graph(file_count, &edges);
1582                let cycles = graph.find_cycles();
1583                for window in cycles.windows(2) {
1584                    prop_assert!(
1585                        window[0].len() <= window[1].len(),
1586                        "Cycles should be sorted by length: {} > {}",
1587                        window[0].len(), window[1].len()
1588                    );
1589                }
1590            }
1591        }
1592    }
1593
1594    /// Build a cycle graph where specific edges are type-only.
1595    fn build_cycle_graph_with_type_only(
1596        file_count: usize,
1597        edges_spec: &[(u32, u32, bool)], // (source, target, is_type_only)
1598    ) -> ModuleGraph {
1599        let files: Vec<DiscoveredFile> = (0..file_count)
1600            .map(|i| DiscoveredFile {
1601                id: FileId(i as u32),
1602                path: PathBuf::from(format!("/project/file{i}.ts")),
1603                size_bytes: 100,
1604            })
1605            .collect();
1606
1607        let resolved_modules: Vec<ResolvedModule> = (0..file_count)
1608            .map(|i| {
1609                let imports: Vec<ResolvedImport> = edges_spec
1610                    .iter()
1611                    .filter(|(src, _, _)| *src == i as u32)
1612                    .map(|(_, tgt, type_only)| ResolvedImport {
1613                        info: ImportInfo {
1614                            source: format!("./file{tgt}"),
1615                            imported_name: ImportedName::Named("x".to_string()),
1616                            local_name: "x".to_string(),
1617                            is_type_only: *type_only,
1618                            is_type_only_star: false,
1619                            from_style: false,
1620                            span: oxc_span::Span::new(0, 10),
1621                            source_span: oxc_span::Span::default(),
1622                        },
1623                        target: ResolveResult::InternalModule(FileId(*tgt)),
1624                    })
1625                    .collect();
1626
1627                ResolvedModule {
1628                    file_id: FileId(i as u32),
1629                    path: PathBuf::from(format!("/project/file{i}.ts")),
1630                    exports: vec![fallow_types::extract::ExportInfo {
1631                        name: ExportName::Named("x".to_string()),
1632                        local_name: Some("x".to_string()),
1633                        is_type_only: false,
1634                        visibility: VisibilityTag::None,
1635                        expected_unused_reason: None,
1636                        span: oxc_span::Span::new(0, 20),
1637                        members: vec![],
1638                        is_side_effect_used: false,
1639                        super_class: None,
1640                        deprecated: false,
1641                        deprecated_reason: None,
1642                    }]
1643                    .into(),
1644                    re_exports: vec![],
1645                    resolved_imports: imports,
1646                    resolved_dynamic_imports: vec![],
1647                    resolved_dynamic_patterns: vec![],
1648                    member_accesses: vec![].into(),
1649                    semantic_facts: std::sync::Arc::default(),
1650                    whole_object_uses: std::sync::Arc::default(),
1651                    has_cjs_exports: false,
1652                    has_angular_component_template_url: false,
1653                    unused_import_bindings: FxHashSet::default(),
1654                    type_referenced_import_bindings: vec![],
1655                    value_referenced_import_bindings: vec![],
1656                    namespace_object_aliases: vec![],
1657                    exported_factory_returns: std::sync::Arc::default(),
1658                    exported_factory_return_object_shapes: std::sync::Arc::default(),
1659                    type_member_types: std::sync::Arc::default(),
1660                    missing_export_targets: vec![],
1661                }
1662            })
1663            .collect();
1664
1665        let entry_points = vec![EntryPoint {
1666            path: PathBuf::from("/project/file0.ts"),
1667            source: EntryPointSource::PackageJsonMain,
1668        }];
1669
1670        ModuleGraph::build(&resolved_modules, &entry_points, &files)
1671    }
1672
1673    #[test]
1674    fn type_only_bidirectional_import_not_a_cycle() {
1675        let graph = build_cycle_graph_with_type_only(2, &[(0, 1, true), (1, 0, true)]);
1676        let cycles = graph.find_cycles();
1677        assert!(
1678            cycles.is_empty(),
1679            "type-only bidirectional imports should not be reported as cycles"
1680        );
1681    }
1682
1683    #[test]
1684    fn mixed_type_and_value_import_not_a_cycle() {
1685        let graph = build_cycle_graph_with_type_only(2, &[(0, 1, false), (1, 0, true)]);
1686        let cycles = graph.find_cycles();
1687        assert!(
1688            cycles.is_empty(),
1689            "A->B (value) + B->A (type-only) is not a runtime cycle"
1690        );
1691    }
1692
1693    #[test]
1694    fn both_value_imports_with_one_type_still_a_cycle() {
1695        let graph = build_cycle_graph_with_type_only(2, &[(0, 1, false), (1, 0, false)]);
1696        let cycles = graph.find_cycles();
1697        assert!(
1698            !cycles.is_empty(),
1699            "bidirectional value imports should be reported as a cycle"
1700        );
1701    }
1702
1703    #[test]
1704    fn all_value_imports_still_a_cycle() {
1705        let graph = build_cycle_graph_with_type_only(2, &[(0, 1, false), (1, 0, false)]);
1706        let cycles = graph.find_cycles();
1707        assert_eq!(cycles.len(), 1);
1708    }
1709
1710    #[test]
1711    fn three_node_type_only_cycle_not_reported() {
1712        let graph =
1713            build_cycle_graph_with_type_only(3, &[(0, 1, true), (1, 2, true), (2, 0, true)]);
1714        let cycles = graph.find_cycles();
1715        assert!(
1716            cycles.is_empty(),
1717            "three-node type-only cycle should not be reported"
1718        );
1719    }
1720
1721    #[test]
1722    fn three_node_cycle_one_value_edge_still_reported() {
1723        let graph =
1724            build_cycle_graph_with_type_only(3, &[(0, 1, false), (1, 2, true), (2, 0, true)]);
1725        let cycles = graph.find_cycles();
1726        assert!(
1727            cycles.is_empty(),
1728            "cycle broken by type-only edge in the middle should not be reported"
1729        );
1730    }
1731
1732    #[test]
1733    fn accepted_cycles_leave_their_slots_to_other_cycles() {
1734        let mut edges = Vec::new();
1735        for from in 0..5_u32 {
1736            for to in 0..5_u32 {
1737                if from != to {
1738                    edges.push((from, to));
1739                }
1740            }
1741        }
1742        let graph = build_cycle_graph(5, &edges);
1743        let all = graph.find_cycles_accepting(
1744            super::CycleOptions::default(),
1745            &mut |_| super::ImportElision::RemoveUnread(super::DecoratorMetadata::Off),
1746            &mut |_| false,
1747        );
1748        assert_eq!(all.cycles.len(), super::MAX_CYCLES_PER_SCC);
1749        assert_eq!(all.capped_sccs.len(), 1);
1750
1751        let mut offered = 0;
1752        let rest = graph.find_cycles_accepting(
1753            super::CycleOptions::default(),
1754            &mut |_| super::ImportElision::RemoveUnread(super::DecoratorMetadata::Off),
1755            &mut |cycle| {
1756                offered += 1;
1757                cycle.len() == 2
1758            },
1759        );
1760        assert_eq!(rest.cycles.len(), super::MAX_CYCLES_PER_SCC);
1761        assert!(rest.cycles.iter().all(|cycle| cycle.len() > 2));
1762        assert_eq!(offered, 10 + super::MAX_CYCLES_PER_SCC);
1763    }
1764}