Skip to main content

fallow_graph/graph/re_exports/
mod.rs

1//! Phase 4: Re-export chain resolution, propagate references through barrel files.
2
3mod propagate;
4#[cfg(test)]
5mod test_support;
6#[cfg(test)]
7mod tests;
8#[cfg(test)]
9mod tests_exposure_walk;
10#[cfg(test)]
11mod tests_name_search;
12#[cfg(test)]
13mod tests_namespace_targets;
14#[cfg(test)]
15mod tests_star_propagate;
16
17use std::collections::VecDeque;
18use std::path::PathBuf;
19
20use fixedbitset::FixedBitSet;
21use rustc_hash::{FxHashMap, FxHashSet};
22
23#[cfg(test)]
24use std::cell::{Cell, RefCell};
25
26use crate::resolve::ResolvedModule;
27use fallow_types::discover::FileId;
28
29use super::types::{ReferencePathInterner, RoutedReferenceKey};
30use super::{Edge, ModuleGraph};
31
32use propagate::{
33    EffectiveDeclarationRouteCache, ImportBindingUsageIndex, NamedPropagationScratch,
34    NamedReExportPropagation, NamedStarRefCache, StarReExportPropagation,
35    propagate_named_re_export, propagate_star_re_export,
36};
37
38#[cfg(test)]
39thread_local! {
40    static PROPAGATION_VISITS: RefCell<Option<Vec<(FileId, FileId)>>> =
41        const { RefCell::new(None) };
42    static DIFFERENTIAL_CHECK_ENABLED: Cell<bool> = const { Cell::new(false) };
43}
44
45#[cfg(test)]
46fn record_propagation_visit(entry: &ReExportTuple) {
47    PROPAGATION_VISITS.with(|visits| {
48        if let Some(visits) = visits.borrow_mut().as_mut() {
49            visits.push((entry.barrel, entry.source));
50        }
51    });
52}
53
54#[cfg(test)]
55fn capture_propagation_visits<T>(run: impl FnOnce() -> T) -> (T, Vec<(FileId, FileId)>) {
56    PROPAGATION_VISITS.with(|visits| *visits.borrow_mut() = Some(Vec::new()));
57    let result = run();
58    let visits = PROPAGATION_VISITS.with(|visits| visits.borrow_mut().take().unwrap_or_default());
59    (result, visits)
60}
61
62#[cfg(test)]
63fn with_re_export_differential_check<T>(run: impl FnOnce() -> T) -> T {
64    DIFFERENTIAL_CHECK_ENABLED.with(|enabled| {
65        let previous = enabled.replace(true);
66        let result = run();
67        enabled.set(previous);
68        result
69    })
70}
71
72/// A re-export cycle or self-loop detected during Phase 4 chain resolution.
73///
74/// The graph-layer mirror of `fallow_types::results::ReExportCycle`. Kept in
75/// the graph crate so the types crate does not need a dependency arrow back
76/// into graph for the conversion. The analysis backend performs the
77/// `GraphReExportCycle` to `ReExportCycle` mapping by reading `is_self_loop`
78/// and routing to the matching `ReExportCycleKind` variant.
79#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
80pub struct GraphReExportCycle {
81    /// Member files participating in the cycle, sorted lexicographically by
82    /// the `Path::display()` form (matches the existing diagnostic-output
83    /// sort). For a self-loop, exactly one entry.
84    pub files: Vec<PathBuf>,
85    /// Parallel array to `files`: the FileId for each member. Kept alongside
86    /// the paths so the core-layer detector can call
87    /// `suppressions.is_file_suppressed(id, IssueKind::ReExportCycle)`
88    /// without an extra path-to-FileId lookup.
89    pub file_ids: Vec<FileId>,
90    /// `true` for single-file self-re-exports (`export * from './'`), `false`
91    /// for multi-node strongly connected components.
92    pub is_self_loop: bool,
93    /// Byte offset of the `export ... from` statement in `files[0]` that
94    /// re-exports from a member of the cycle. `None` when every such
95    /// statement was synthesized inside the graph layer and has no span.
96    #[serde(default)]
97    pub anchor_span_start: Option<u32>,
98}
99
100/// A single re-export edge collected from the module graph.
101///
102/// Replaces an earlier ad-hoc 5-tuple so the propagation loop is more
103/// readable and the new `is_type_only` field carried into
104/// [`propagate_star_re_export`] does not get lost in tuple-index plumbing.
105struct ReExportTuple {
106    barrel: FileId,
107    source: FileId,
108    imported_name: String,
109    exported_name: String,
110    /// `true` when the triggering re-export edge is `export type * from ...`
111    /// or `export type { foo } from ...`. Threaded into star propagation so
112    /// any synthetic stub created on the source module reflects the chain's
113    /// type-only-ness instead of defaulting to `false`.
114    is_type_only: bool,
115}
116
117impl ReExportTuple {
118    /// `export * as ns from './x'`, see [`is_namespace_re_export`].
119    fn is_namespace(&self) -> bool {
120        self.imported_name == "*" && self.exported_name != "*"
121    }
122}
123
124struct ReExportContext<'a> {
125    open_star_barrels: &'a FxHashSet<FileId>,
126    edges_by_target: &'a FxHashMap<FileId, Vec<usize>>,
127    binding_usage: &'a ImportBindingUsageIndex,
128    effective_exports: &'a super::effective_exports::EffectiveExportIndex,
129    existing_refs: &'a mut FxHashSet<RoutedReferenceKey>,
130    synthetic_stubs: &'a mut FxHashSet<(FileId, String, bool)>,
131    declaration_routes: &'a mut EffectiveDeclarationRouteCache,
132    scratch: &'a mut NamedPropagationScratch,
133    reference_paths: &'a mut ReferencePathInterner,
134    named_star_refs: &'a mut NamedStarRefCache,
135}
136
137/// How much of a closure member the consumers that cannot be enumerated see.
138///
139/// The two differ on `default` alone, because a plain `export *` forwards
140/// every named export of its source and never the source's `default`.
141#[derive(Clone, Copy, PartialEq, Eq, Debug)]
142enum Exposure {
143    /// Reached through a plain `export *`: every export except `default`.
144    StarSurface,
145    /// The whole namespace object is observed: every export, `default`
146    /// included.
147    NamespaceObject,
148}
149
150/// The targets whose module surface Phase 2 saw observed, split by whether
151/// the observation survives the target being unreachable.
152///
153/// Ambient module declarations expose an external module id, so their
154/// observation stands at any reachability. Every other observer is a real
155/// consumer in this graph and is retained only while an entry point reaches
156/// its target.
157#[derive(Default)]
158pub(in crate::graph) struct WholeModuleObservations {
159    /// Targets an ambient module body re-exports from, at any reachability.
160    ambient: FxHashMap<FileId, Exposure>,
161    /// Targets a consumer in this graph observes as a whole object.
162    observed: FxHashSet<FileId>,
163    /// The namespace bindings that got the full credit in this pass.
164    escapes: Vec<super::namespace_escapes::NamespaceEscape>,
165}
166
167impl WholeModuleObservations {
168    /// Record a whole-object observation made by a consumer in this graph.
169    pub(in crate::graph) fn observe(&mut self, target: FileId) {
170        self.observed.insert(target);
171    }
172
173    /// Record a namespace binding that got the full credit of its target.
174    pub(in crate::graph) fn record_escape(
175        &mut self,
176        escape: super::namespace_escapes::NamespaceEscape,
177    ) {
178        self.escapes.push(escape);
179    }
180
181    /// Move the recorded escapes out.
182    pub(in crate::graph) fn take_escapes(
183        &mut self,
184    ) -> Vec<super::namespace_escapes::NamespaceEscape> {
185        std::mem::take(&mut self.escapes)
186    }
187
188    /// Record the target of an ambient plain `export *`.
189    pub(in crate::graph) fn observe_ambient_star(&mut self, target: FileId) {
190        self.ambient.entry(target).or_insert(Exposure::StarSurface);
191    }
192
193    /// Record the target of an ambient `export * as ns`.
194    pub(in crate::graph) fn observe_ambient_namespace(&mut self, target: FileId) {
195        self.ambient.insert(target, Exposure::NamespaceObject);
196    }
197
198    /// The closure seeds: every ambient target, plus the observed targets an
199    /// entry point reaches.
200    fn seeds<'a>(
201        &'a self,
202        entry_reachable: &'a FixedBitSet,
203    ) -> impl Iterator<Item = (FileId, Exposure)> + 'a {
204        self.ambient
205            .iter()
206            .map(|(&target, &exposure)| (target, exposure))
207            .chain(
208                self.observed
209                    .iter()
210                    .copied()
211                    .filter(|target| entry_reachable.contains(target.0 as usize))
212                    .map(|target| (target, Exposure::NamespaceObject)),
213            )
214    }
215}
216
217/// The exposed namespace closure: every module whose names reach consumers
218/// the graph cannot enumerate, with the part of its export surface they see.
219///
220/// Built by [`ModuleGraph::collect_exposed_namespace_targets`], computed once
221/// per graph build and read by Phase 2c (namespace re-export propagation) and
222/// Phase 4 (the entry-star seed).
223pub(in crate::graph) struct ExposedNamespaceTargets {
224    members: FxHashMap<FileId, Exposure>,
225}
226
227impl ExposedNamespaceTargets {
228    /// Whether the closure has no members at all.
229    pub(in crate::graph) fn is_empty(&self) -> bool {
230        self.members.is_empty()
231    }
232
233    /// Whether the member exposes `exported_name`.
234    ///
235    /// A member reached through a plain `export *` does not expose `default`:
236    /// the star that carried its names onward never forwards it, so an
237    /// `export * as default` declared on such a member hands its target's
238    /// namespace object to nobody.
239    pub(in crate::graph) fn exposes_name(&self, file_id: FileId, exported_name: &str) -> bool {
240        match self.members.get(&file_id) {
241            Some(Exposure::NamespaceObject) => true,
242            Some(Exposure::StarSurface) => exported_name != "default",
243            None => false,
244        }
245    }
246
247    /// Every member, at either exposure.
248    ///
249    /// Phase 4 star propagation credits the named exports of a member's
250    /// `export *` sources and never their `default`, which both exposures
251    /// forward alike, so it reads the membership alone.
252    fn files(&self) -> impl Iterator<Item = FileId> + '_ {
253        self.members.keys().copied()
254    }
255
256    /// Record a member, re-walking it when a wider exposure than a previous
257    /// visit arrives. Each member is walked at most twice.
258    fn record(&mut self, stack: &mut Vec<(FileId, Exposure)>, file_id: FileId, exposure: Exposure) {
259        match self.members.entry(file_id) {
260            std::collections::hash_map::Entry::Occupied(mut slot) => {
261                if *slot.get() == Exposure::StarSurface && exposure == Exposure::NamespaceObject {
262                    slot.insert(exposure);
263                    stack.push((file_id, exposure));
264                }
265            }
266            std::collections::hash_map::Entry::Vacant(slot) => {
267                slot.insert(exposure);
268                stack.push((file_id, exposure));
269            }
270        }
271    }
272}
273
274/// `export * as ns from './x'`: the barrel exposes x's namespace object under
275/// a single name instead of forwarding x's names.
276fn is_namespace_re_export(re: &super::types::ReExportEdge) -> bool {
277    re.imported_name == "*" && re.exported_name != "*"
278}
279
280/// Reverse index of the re-export edges that carry one exported name outward,
281/// from the module that declares it toward the barrels that forward it.
282///
283/// A namespace re-export (`export * as ns`) is not a forwarder: it bundles the
284/// source's names into one object instead of passing them along.
285struct NameForwarders<'a> {
286    /// `(source, imported name)` to the barrels re-exporting it, each with the
287    /// name it exports it under, so renames are followed exactly.
288    named: FxHashMap<(FileId, &'a str), Vec<(FileId, &'a str)>>,
289    /// Source file to the barrels that re-export all of its names.
290    stars: FxHashMap<FileId, Vec<FileId>>,
291}
292
293/// Reusable state for [`ExposedNameSearch::reaches_exposure`].
294///
295/// `failed` outlives a single search within one round: an exhausted search
296/// proves that every state it visited fails too, so a forwarding chain shared
297/// by many namespace edges is walked once instead of once per edge. A round
298/// that widens the closure clears it, because a state that failed against the
299/// smaller closure can succeed against the wider one.
300#[derive(Default)]
301struct NameSearchScratch<'a> {
302    visited: FxHashSet<(FileId, &'a str)>,
303    frontier: Vec<(FileId, &'a str)>,
304    failed: FxHashSet<(FileId, &'a str)>,
305}
306
307impl<'a> NameForwarders<'a> {
308    fn build(modules: &'a [super::types::ModuleNode]) -> Self {
309        let mut named: FxHashMap<(FileId, &'a str), Vec<(FileId, &'a str)>> = FxHashMap::default();
310        let mut stars: FxHashMap<FileId, Vec<FileId>> = FxHashMap::default();
311        for module in modules {
312            for re in &module.re_exports {
313                if re.imported_name == "*" {
314                    if re.exported_name == "*" {
315                        stars
316                            .entry(re.source_file)
317                            .or_default()
318                            .push(module.file_id);
319                    }
320                } else {
321                    named
322                        .entry((re.source_file, re.imported_name.as_str()))
323                        .or_default()
324                        .push((module.file_id, re.exported_name.as_str()));
325                }
326            }
327        }
328        Self { named, stars }
329    }
330}
331
332/// Extend `may_reach` with every module `seeds` re-exports from, transitively,
333/// following named and plain-star edges and ignoring names.
334///
335/// `export * as ns` is left out: it bundles its source's names into one object
336/// instead of forwarding them, so it never carries a name outward.
337///
338/// A seed already in `may_reach` is skipped with its whole subtree, which is
339/// what lets the closure fixpoint widen the prune round by round instead of
340/// rebuilding it from scratch.
341fn extend_forwarding_sources(
342    modules: &[super::types::ModuleNode],
343    may_reach: &mut FxHashSet<FileId>,
344    seeds: impl IntoIterator<Item = FileId>,
345) {
346    let mut stack: Vec<FileId> = seeds
347        .into_iter()
348        .filter(|seed| may_reach.insert(*seed))
349        .collect();
350    while let Some(barrel) = stack.pop() {
351        let Some(module) = modules.get(barrel.0 as usize) else {
352            continue;
353        };
354        for re in &module.re_exports {
355            if !is_namespace_re_export(re) && may_reach.insert(re.source_file) {
356                stack.push(re.source_file);
357            }
358        }
359    }
360}
361
362/// The outward search that decides whether one `export * as ns` edge hands its
363/// target's namespace object to consumers the graph cannot enumerate.
364///
365/// A name reaches such a consumer when it arrives, through named and plain-star
366/// re-exports, at an entry point's own export surface, at a module already in
367/// the exposed namespace closure, or at a name some importer uses as a whole
368/// object. The three are the same three decisions Phase 2c makes for the
369/// namespace edges it credits, so seeding from them keeps the closure and
370/// Phase 2c from disagreeing about which objects are observed.
371struct ExposedNameSearch<'a> {
372    forwarders: NameForwarders<'a>,
373    /// Per target file, the imported names whose local binding some importer
374    /// uses as a whole object (`Object.values(ns)`, a spread, a
375    /// destructure-with-rest). Named imports only: a namespace import is
376    /// already a `whole_module_targets` seed.
377    whole_object_names: FxHashMap<FileId, Vec<String>>,
378    /// Every module some acceptance point re-exports from, transitively, names
379    /// ignored.
380    ///
381    /// A name can only travel from a module to an acceptance point along
382    /// forwarding edges, so a module outside this set answers the search in
383    /// constant time however deep its own chains run. Recomputed per round,
384    /// because a round that widens the closure adds acceptance points.
385    may_reach: FxHashSet<FileId>,
386    scratch: NameSearchScratch<'a>,
387}
388
389impl<'a> ExposedNameSearch<'a> {
390    fn build(
391        modules: &'a [super::types::ModuleNode],
392        module_by_id: &FxHashMap<FileId, &ResolvedModule>,
393    ) -> Self {
394        let mut whole_object_names: FxHashMap<FileId, Vec<String>> = FxHashMap::default();
395        for consumer in module_by_id.values() {
396            if consumer.whole_object_uses.is_empty() {
397                continue;
398            }
399            for import in &consumer.resolved_imports {
400                let Some(target) = import.target.internal_file_id() else {
401                    continue;
402                };
403                let imported_name = match &import.info.imported_name {
404                    fallow_types::extract::ImportedName::Named(name) => name.as_str(),
405                    fallow_types::extract::ImportedName::Default => "default",
406                    _ => continue,
407                };
408                let local_name = import.info.local_name.as_str();
409                if local_name.is_empty()
410                    || !consumer
411                        .whole_object_uses
412                        .iter()
413                        .any(|used| used == local_name)
414                {
415                    continue;
416                }
417                let names = whole_object_names.entry(target).or_default();
418                if !names.iter().any(|name| name == imported_name) {
419                    names.push(imported_name.to_string());
420                }
421            }
422        }
423
424        let mut may_reach = FxHashSet::default();
425        extend_forwarding_sources(
426            modules,
427            &mut may_reach,
428            modules
429                .iter()
430                .filter(|m| m.exposes_entry_surface())
431                .map(|m| m.file_id)
432                .chain(whole_object_names.keys().copied()),
433        );
434
435        Self {
436            forwarders: NameForwarders::build(modules),
437            whole_object_names,
438            may_reach,
439            scratch: NameSearchScratch::default(),
440        }
441    }
442
443    /// Widen the reachability prune with the members the last round added and
444    /// drop the memoised failures for a round against the wider closure.
445    ///
446    /// The prune only ever grows, so the members already walked keep their
447    /// subtree and each re-export edge is visited at most once across every
448    /// round instead of once per round.
449    fn refresh(
450        &mut self,
451        modules: &'a [super::types::ModuleNode],
452        closure: &ExposedNamespaceTargets,
453    ) {
454        extend_forwarding_sources(
455            modules,
456            &mut self.may_reach,
457            closure.members.keys().copied(),
458        );
459        self.scratch.failed.clear();
460    }
461
462    /// Whether `name`, as exported by `file`, reaches an acceptance point
463    /// through named and plain-star re-exports.
464    ///
465    /// Each hop must really forward the binding: a barrel that declares its
466    /// own `name`, or that receives it from two stars at once, exports a
467    /// different binding under that name and the chain stops there. Being on
468    /// an entry point's plain-`export *` closure is not on its own proof that
469    /// the name survives to the entry, so no hop is skipped for it. A plain
470    /// `export *` also never carries `default`, so a `default`-named state
471    /// takes named hops only.
472    fn reaches_exposure(
473        &mut self,
474        graph: &ModuleGraph,
475        closure: &ExposedNamespaceTargets,
476        file: FileId,
477        name: &'a str,
478    ) -> bool {
479        if !self.may_reach.contains(&file) || self.scratch.failed.contains(&(file, name)) {
480            return false;
481        }
482        let Self {
483            forwarders,
484            whole_object_names,
485            may_reach,
486            scratch,
487        } = self;
488        scratch.visited.clear();
489        scratch.frontier.clear();
490        scratch.visited.insert((file, name));
491        scratch.frontier.push((file, name));
492        while let Some((current, current_name)) = scratch.frontier.pop() {
493            if exposes_here(graph, closure, whole_object_names, current, current_name) {
494                return true;
495            }
496            if let Some(barrels) = forwarders.named.get(&(current, current_name)) {
497                for &(barrel, exported_name) in barrels {
498                    if may_reach.contains(&barrel)
499                        && graph.forwards_binding(current, current_name, barrel, exported_name)
500                        && !scratch.failed.contains(&(barrel, exported_name))
501                        && scratch.visited.insert((barrel, exported_name))
502                    {
503                        scratch.frontier.push((barrel, exported_name));
504                    }
505                }
506            }
507            if current_name == "default" {
508                continue;
509            }
510            if let Some(barrels) = forwarders.stars.get(&current) {
511                for &barrel in barrels {
512                    if may_reach.contains(&barrel)
513                        && graph.forwards_binding(current, current_name, barrel, current_name)
514                        && !scratch.failed.contains(&(barrel, current_name))
515                        && scratch.visited.insert((barrel, current_name))
516                    {
517                        scratch.frontier.push((barrel, current_name));
518                    }
519                }
520            }
521        }
522        scratch.failed.extend(scratch.visited.iter().copied());
523        false
524    }
525}
526
527/// Whether the module that exports `name` already hands it to a consumer the
528/// graph cannot enumerate, with no further re-export hop needed.
529///
530/// An entry point exposes every name it exports, `default` included: it is the
531/// public API. An entry point that `includeEntryExports` covers exposes
532/// nothing here, because its exports need an importer in the project. A closure member exposes what its own exposure allows. A name
533/// some importer uses as a whole object is observed in full by that importer.
534fn exposes_here(
535    graph: &ModuleGraph,
536    closure: &ExposedNamespaceTargets,
537    whole_object_names: &FxHashMap<FileId, Vec<String>>,
538    file: FileId,
539    name: &str,
540) -> bool {
541    graph.exposes_entry_surface_file(file)
542        || closure.exposes_name(file, name)
543        || whole_object_names
544            .get(&file)
545            .is_some_and(|names| names.iter().any(|candidate| candidate == name))
546}
547
548struct ReExportFixpointInput<'a> {
549    re_export_info: &'a [ReExportTuple],
550    open_star_barrels: &'a FxHashSet<FileId>,
551    edges_by_target: &'a FxHashMap<FileId, Vec<usize>>,
552    module_by_id: &'a FxHashMap<FileId, &'a ResolvedModule>,
553    reference_paths: &'a mut ReferencePathInterner,
554}
555
556#[cfg(test)]
557struct LegacyReExportFullScan<'a> {
558    modules: &'a mut [super::types::ModuleNode],
559    edges: &'a [Edge],
560    re_export_info: &'a [ReExportTuple],
561    open_star_barrels: &'a FxHashSet<FileId>,
562    edges_by_target: &'a FxHashMap<FileId, Vec<usize>>,
563    module_by_id: &'a FxHashMap<FileId, &'a ResolvedModule>,
564    effective_exports: &'a super::effective_exports::EffectiveExportIndex,
565    reference_paths: &'a mut ReferencePathInterner,
566}
567
568/// Deterministic scheduler for monotone re-export propagation.
569///
570/// Each tuple reads export state from `barrel` and may add references or
571/// synthetic exports to `source`. When `source` changes, only tuples whose
572/// `barrel` is that module can observe the new state, so those tuple indices
573/// are re-enqueued in their original stable order.
574struct ReExportPropagationPlan {
575    observers_by_module: FxHashMap<FileId, Vec<usize>>,
576    queue: VecDeque<usize>,
577    enqueued: Vec<bool>,
578}
579
580impl ReExportPropagationPlan {
581    fn new(re_export_info: &[ReExportTuple]) -> Self {
582        let mut observers_by_module: FxHashMap<FileId, Vec<usize>> = FxHashMap::default();
583        for (idx, entry) in re_export_info.iter().enumerate() {
584            observers_by_module
585                .entry(entry.barrel)
586                .or_default()
587                .push(idx);
588        }
589
590        Self {
591            observers_by_module,
592            queue: (0..re_export_info.len()).collect(),
593            enqueued: vec![true; re_export_info.len()],
594        }
595    }
596
597    fn pop_front(&mut self) -> Option<usize> {
598        let idx = self.queue.pop_front()?;
599        self.enqueued[idx] = false;
600        Some(idx)
601    }
602
603    fn enqueue_observers(&mut self, changed_module: FileId) {
604        let Some(observers) = self.observers_by_module.get(&changed_module) else {
605            return;
606        };
607        for &idx in observers {
608            if !self.enqueued[idx] {
609                self.enqueued[idx] = true;
610                self.queue.push_back(idx);
611            }
612        }
613    }
614}
615
616impl ModuleGraph {
617    /// Resolve re-export chains: when module A re-exports from B,
618    /// any reference to A's re-exported symbol should also count as a reference
619    /// to B's original export (and transitively through the chain).
620    ///
621    /// Returns the list of re-export cycles and self-loops detected during
622    /// the upfront Tarjan SCC pass. The caller stores this on the
623    /// `ModuleGraph` so the `re-export-cycle` finding type can surface them
624    /// to users instead of relying on `RUST_LOG=warn` (see issue #515).
625    pub(super) fn resolve_re_export_chains(
626        &mut self,
627        module_by_id: &FxHashMap<FileId, &ResolvedModule>,
628        exposed_namespace_targets: &ExposedNamespaceTargets,
629        consumer_checked: &FxHashSet<FileId>,
630        reference_paths: &mut ReferencePathInterner,
631    ) -> Vec<GraphReExportCycle> {
632        let re_export_info = self.collect_re_export_tuples();
633
634        if re_export_info.is_empty() {
635            return Vec::new();
636        }
637
638        let cycles = find_re_export_cycles(&self.modules, &re_export_info);
639
640        let open_star_barrels =
641            self.collect_open_star_barrels(exposed_namespace_targets, consumer_checked);
642        let edges_by_target = self.build_edges_by_target();
643
644        self.run_re_export_fixpoint(ReExportFixpointInput {
645            re_export_info: &re_export_info,
646            open_star_barrels: &open_star_barrels,
647            edges_by_target: &edges_by_target,
648            module_by_id,
649            reference_paths,
650        });
651
652        cycles
653    }
654
655    /// Flatten every module's re-export edges into a single tuple list.
656    ///
657    /// A module that only asset references load (a `raw-loader!` resource)
658    /// never runs, so its re-exports forward nothing. The edge that loads it
659    /// already credits its own exports, and its sources stay out of reach,
660    /// the same as its imports.
661    fn collect_re_export_tuples(&self) -> Vec<ReExportTuple> {
662        let asset_only = self.asset_only_modules();
663        self.modules
664            .iter()
665            .filter(|m| !asset_only.contains(m.file_id.0 as usize))
666            .flat_map(|m| {
667                m.re_exports.iter().map(move |re| ReExportTuple {
668                    barrel: m.file_id,
669                    source: re.source_file,
670                    imported_name: re.imported_name.clone(),
671                    exported_name: re.exported_name.clone(),
672                    is_type_only: re.is_type_only,
673                })
674            })
675            .collect()
676    }
677
678    /// The modules that are not entry points and that only edges which do not
679    /// run their target load.
680    fn asset_only_modules(&self) -> FixedBitSet {
681        let total = self.modules.len();
682        let mut asset_loaded = FixedBitSet::with_capacity(total);
683        let mut run_loaded = FixedBitSet::with_capacity(total);
684        for edge in &self.edges {
685            let target = edge.target.0 as usize;
686            if target >= total {
687                continue;
688            }
689            if edge.runs_target_code() {
690                run_loaded.insert(target);
691            } else {
692                asset_loaded.insert(target);
693            }
694        }
695        asset_loaded.difference_with(&run_loaded);
696        for module in &self.modules {
697            if module.is_entry_point() {
698                asset_loaded.set(module.file_id.0 as usize, false);
699            }
700        }
701        asset_loaded
702    }
703
704    /// The modules whose plain `export *` credits every named export of its
705    /// source, because a consumer that the graph cannot list reads the names.
706    ///
707    /// The members are the entry points, their star sources closed over plain
708    /// `export *` chains, and every member of the exposed namespace closure
709    /// (`collect_exposed_namespace_targets`, computed once per build and
710    /// threaded in). An entry point in `consumer_checked` is not a member on
711    /// its own: its `export *` credits only the names that an importer uses.
712    fn collect_open_star_barrels(
713        &self,
714        exposed_namespace_targets: &ExposedNamespaceTargets,
715        consumer_checked: &FxHashSet<FileId>,
716    ) -> FxHashSet<FileId> {
717        let mut open_star_barrels: FxHashSet<FileId> = exposed_namespace_targets.files().collect();
718        open_star_barrels.extend(
719            self.modules
720                .iter()
721                .filter(|m| m.is_entry_point() && !consumer_checked.contains(&m.file_id))
722                .map(|m| m.file_id),
723        );
724        self.extend_plain_star_closure(&mut open_star_barrels);
725        open_star_barrels
726    }
727
728    /// Every module whose full namespace object is handed to consumers the
729    /// graph cannot enumerate per name (issues #2357, #2372, #2373).
730    ///
731    /// The seeds are the targets whose whole namespace object Phase 2
732    /// observed (`whole_module_targets`: an ambient-module star, a
733    /// dynamic-import pattern match, a bindingless side-effect `require()`, or
734    /// a namespace import the graph could not narrow because it is used as a
735    /// whole object, handed on without member access, or re-exported from a
736    /// non-entry module) plus every `export * as ns` source whose name reaches
737    /// an entry point's own export surface, an existing closure member, or an
738    /// importer that uses the binding as a whole object. Every such consumer
739    /// sees every name on the namespace object, including the names that only
740    /// arrive through the target's own `export *` and `export * as ns` chains,
741    /// and per-name propagation cannot credit those because no name is ever
742    /// imported. The closure therefore follows both chain forms: star
743    /// propagation treats each member like an entry barrel for its `export *`
744    /// sources (named exports, never `default`), and namespace re-export
745    /// propagation credits every export of each member's `export * as ns`
746    /// sources (`default` included, because the namespace object exposes it).
747    ///
748    /// A member reached through a plain `export *` carries the weaker
749    /// [`Exposure::StarSurface`]: the star forwarded its named exports and not
750    /// its `default`, so an `export * as default` declared on it exposes
751    /// nothing and stops the walk.
752    ///
753    /// The namespace-edge seeds and the closure walk run to a fixpoint against
754    /// each other: a target that joins the closure can itself expose a name a
755    /// further `export * as ns` edge forwards to it, and that edge only
756    /// qualifies once the target is a member. The rounds are the same
757    /// exposure decision Phase 2c makes per namespace edge, so the closure
758    /// Phase 2c reads already contains every target Phase 2c would credit in
759    /// full, instead of stopping one namespace level short of it.
760    ///
761    /// `entry_reachable` is the entry-point reachability bitset. It gates the
762    /// two seed kinds issues #2372 and #2373 add (an observed whole-object
763    /// target and an `export * as ns` source), and nothing else: withholding
764    /// those can only withhold credit the pre-existing closure never gave.
765    /// The ambient seeds and the walk stay ungated, because a chain that
766    /// starts at an unreachable shim routinely re-enters a module an entry
767    /// point imports directly, and gating it would report exports on files
768    /// the report calls reachable.
769    ///
770    /// Computed once per graph build and threaded into both phases that read
771    /// it; it depends only on `re_exports`, the entry-point flags, the
772    /// consumers' whole-object uses, and reachability, none of which any later
773    /// phase mutates.
774    pub(in crate::graph) fn collect_exposed_namespace_targets(
775        &self,
776        whole_module_targets: &WholeModuleObservations,
777        entry_reachable: &FixedBitSet,
778        module_by_id: &FxHashMap<FileId, &ResolvedModule>,
779    ) -> ExposedNamespaceTargets {
780        let mut closure = ExposedNamespaceTargets {
781            members: FxHashMap::default(),
782        };
783        let mut stack: Vec<(FileId, Exposure)> = Vec::new();
784        for (seed, exposure) in whole_module_targets.seeds(entry_reachable) {
785            closure.record(&mut stack, seed, exposure);
786        }
787
788        let mut pending: Vec<(FileId, &str, FileId)> = self
789            .modules
790            .iter()
791            .flat_map(|m| {
792                m.re_exports
793                    .iter()
794                    .filter(|re| is_namespace_re_export(re))
795                    .map(move |re| (m.file_id, re.exported_name.as_str(), re.source_file))
796            })
797            .filter(|(_, _, source)| entry_reachable.contains(source.0 as usize))
798            .collect();
799        let mut search =
800            (!pending.is_empty()).then(|| ExposedNameSearch::build(&self.modules, module_by_id));
801
802        loop {
803            self.extend_exposure_walk(&mut closure, &mut stack);
804            let Some(search) = search.as_mut() else { break };
805            if pending.is_empty() {
806                break;
807            }
808            search.refresh(&self.modules, &closure);
809            let mut widened = false;
810            let mut still_pending = Vec::with_capacity(pending.len());
811            for (barrel, exported_name, source) in std::mem::take(&mut pending) {
812                if closure.members.get(&source) == Some(&Exposure::NamespaceObject) {
813                    continue;
814                }
815                if search.reaches_exposure(self, &closure, barrel, exported_name) {
816                    closure.record(&mut stack, source, Exposure::NamespaceObject);
817                    widened = true;
818                } else {
819                    still_pending.push((barrel, exported_name, source));
820                }
821            }
822            pending = still_pending;
823            if !widened {
824                break;
825            }
826        }
827        closure
828    }
829
830    /// Drain the closure's work stack, carrying each member's exposure along
831    /// its own `export *` and `export * as ns` edges.
832    ///
833    /// No hop is dropped for reachability. A re-export edge makes its source
834    /// reachable whenever the barrel is, so only the ambient seeds can ever
835    /// walk from an unreachable member, and their chains routinely re-enter
836    /// modules an entry point imports directly.
837    fn extend_exposure_walk(
838        &self,
839        closure: &mut ExposedNamespaceTargets,
840        stack: &mut Vec<(FileId, Exposure)>,
841    ) {
842        while let Some((file_id, exposure)) = stack.pop() {
843            let Some(module) = self.modules.get(file_id.0 as usize) else {
844                continue;
845            };
846            for re in &module.re_exports {
847                if re.imported_name != "*" {
848                    continue;
849                }
850                let next = if re.exported_name == "*" {
851                    Exposure::StarSurface
852                } else if exposure == Exposure::NamespaceObject || re.exported_name != "default" {
853                    Exposure::NamespaceObject
854                } else {
855                    continue;
856                };
857                closure.record(stack, re.source_file, next);
858            }
859        }
860    }
861
862    /// Whether `barrel` re-exports under `barrel_name` the very binding
863    /// `source` exports under `source_name`.
864    ///
865    /// Only the namespace choice lives here: the value namespace decides
866    /// whenever the source exports the name there (a namespace object is a
867    /// value binding), and a type-only surface falls back to the type
868    /// namespace. The per-namespace comparison itself is Phase 2c's own
869    /// `uniquely_forwards_binding`, so the closure's outward search and the
870    /// phase it pre-computes for cannot drift apart on what a hop forwards.
871    fn forwards_binding(
872        &self,
873        source: FileId,
874        source_name: &str,
875        barrel: FileId,
876        barrel_name: &str,
877    ) -> bool {
878        for namespace in [super::ExportNamespace::Value, super::ExportNamespace::Type] {
879            if !matches!(
880                self.resolve_export(source, source_name, namespace),
881                super::EffectiveExportResolution::Unique(_)
882            ) {
883                continue;
884            }
885            return super::namespace_indexes::uniquely_forwards_binding(
886                self,
887                source,
888                source_name,
889                barrel,
890                barrel_name,
891                namespace,
892            );
893        }
894        false
895    }
896
897    /// Whether the file is an entry point whose exports reach consumers that
898    /// the graph cannot list.
899    fn exposes_entry_surface_file(&self, file_id: FileId) -> bool {
900        self.modules
901            .get(file_id.0 as usize)
902            .is_some_and(super::types::ModuleNode::exposes_entry_surface)
903    }
904
905    /// Extend `targets` with every module its members reach through plain
906    /// `export *` chains, transitively.
907    fn extend_plain_star_closure(&self, targets: &mut FxHashSet<FileId>) {
908        let mut stack: Vec<FileId> = targets.iter().copied().collect();
909        while let Some(file_id) = stack.pop() {
910            let Some(module) = self.modules.get(file_id.0 as usize) else {
911                continue;
912            };
913            for re in module
914                .re_exports
915                .iter()
916                .filter(|re| re.imported_name == "*" && re.exported_name == "*")
917            {
918                if targets.insert(re.source_file) {
919                    stack.push(re.source_file);
920                }
921            }
922        }
923    }
924
925    /// Index every edge by its target file for fast star-propagation lookups.
926    fn build_edges_by_target(&self) -> FxHashMap<FileId, Vec<usize>> {
927        let mut edges_by_target: FxHashMap<FileId, Vec<usize>> = FxHashMap::default();
928        for (idx, edge) in self.edges.iter().enumerate() {
929            edges_by_target.entry(edge.target).or_default().push(idx);
930        }
931        edges_by_target
932    }
933
934    /// Run monotone propagation, revisiting only tuples affected by new state.
935    fn run_re_export_fixpoint(&mut self, input: ReExportFixpointInput<'_>) {
936        let ReExportFixpointInput {
937            re_export_info,
938            open_star_barrels,
939            edges_by_target,
940            module_by_id,
941            reference_paths,
942        } = input;
943        #[cfg(test)]
944        let mut legacy_modules: Option<Vec<super::types::ModuleNode>> = DIFFERENTIAL_CHECK_ENABLED
945            .with(|enabled| {
946                enabled.get().then(|| {
947                    serde_json::from_value(
948                        serde_json::to_value(&self.modules)
949                            .expect("module graph should serialize for differential testing"),
950                    )
951                    .expect("module graph should deserialize for differential testing")
952                })
953            });
954
955        let safety_cap = self.re_export_transition_safety_cap(re_export_info);
956        let mut processed = 0usize;
957        let mut plan = ReExportPropagationPlan::new(re_export_info);
958        let mut existing_refs: FxHashSet<RoutedReferenceKey> = FxHashSet::default();
959        let mut synthetic_stubs: FxHashSet<(FileId, String, bool)> = FxHashSet::default();
960        let binding_usage = ImportBindingUsageIndex::build(module_by_id);
961        let mut declaration_routes = EffectiveDeclarationRouteCache::default();
962        let mut scratch = NamedPropagationScratch::default();
963        let mut named_star_refs = NamedStarRefCache::default();
964
965        while let Some(entry_idx) = plan.pop_front() {
966            if processed >= safety_cap {
967                tracing::error!(
968                    processed,
969                    safety_cap,
970                    re_export_edges = re_export_info.len(),
971                    "Re-export propagation exceeded its finite-state safety cap; \
972                     propagation may be non-monotonic. Please file a bug at \
973                     https://github.com/fallow-rs/fallow/issues with the repro."
974                );
975                break;
976            }
977            processed += 1;
978
979            let mut context = ReExportContext {
980                open_star_barrels,
981                edges_by_target,
982                binding_usage: &binding_usage,
983                effective_exports: &self.effective_exports,
984                existing_refs: &mut existing_refs,
985                synthetic_stubs: &mut synthetic_stubs,
986                declaration_routes: &mut declaration_routes,
987                scratch: &mut scratch,
988                reference_paths,
989                named_star_refs: &mut named_star_refs,
990            };
991
992            let entry = &re_export_info[entry_idx];
993            #[cfg(test)]
994            record_propagation_visit(entry);
995            if Self::propagate_re_export_entry(&mut self.modules, &self.edges, entry, &mut context)
996            {
997                plan.enqueue_observers(entry.source);
998            }
999        }
1000
1001        #[cfg(test)]
1002        if let Some(legacy_modules) = legacy_modules.as_mut() {
1003            // The oracle checks every name against every star source, so it
1004            // also proves that the source-name filter drops nothing.
1005            propagate::without_star_source_filter(|| {
1006                Self::run_re_export_full_scan(LegacyReExportFullScan {
1007                    modules: legacy_modules,
1008                    edges: &self.edges,
1009                    re_export_info,
1010                    open_star_barrels,
1011                    edges_by_target,
1012                    module_by_id,
1013                    effective_exports: &self.effective_exports,
1014                    reference_paths,
1015                });
1016            });
1017            assert_eq!(
1018                serde_json::to_value(legacy_modules)
1019                    .expect("legacy module graph should serialize for comparison"),
1020                serde_json::to_value(&self.modules)
1021                    .expect("queue module graph should serialize for comparison"),
1022                "work-queue propagation must match the legacy full-scan fixpoint"
1023            );
1024        }
1025    }
1026
1027    /// Bound scheduler work by the finite set of exports, synthetic names, and
1028    /// interned reference paths that monotone propagation can add.
1029    fn re_export_transition_safety_cap(&self, re_export_info: &[ReExportTuple]) -> usize {
1030        let initial_exports = self
1031            .modules
1032            .iter()
1033            .map(|module| module.exports.len())
1034            .sum::<usize>();
1035        let named_inputs = self
1036            .edges
1037            .iter()
1038            .flat_map(|edge| &edge.symbols)
1039            .filter(|symbol| {
1040                matches!(
1041                    &symbol.imported_name,
1042                    fallow_types::extract::ImportedName::Named(_)
1043                )
1044            })
1045            .count()
1046            .saturating_add(initial_exports)
1047            .saturating_add(re_export_info.len());
1048
1049        let module_count = self.modules.len();
1050        let synthetic_export_hosts = self
1051            .modules
1052            .iter()
1053            .filter(|module| {
1054                module
1055                    .re_exports
1056                    .iter()
1057                    .any(|re_export| re_export.exported_name == "*")
1058            })
1059            .count();
1060        let synthetic_exports = synthetic_export_hosts
1061            .saturating_mul(named_inputs)
1062            .saturating_mul(2);
1063        let max_exports = initial_exports.saturating_add(synthetic_exports);
1064        let reference_additions = max_exports.saturating_mul(module_count).saturating_mul(2);
1065        let state_changes = synthetic_exports.saturating_add(reference_additions);
1066
1067        re_export_info
1068            .len()
1069            .saturating_add(state_changes.saturating_mul(re_export_info.len()))
1070            .max(re_export_info.len())
1071    }
1072
1073    /// Propagate references for one re-export edge, dispatching star vs named.
1074    fn propagate_re_export_entry(
1075        modules: &mut [super::types::ModuleNode],
1076        edges: &[Edge],
1077        entry: &ReExportTuple,
1078        context: &mut ReExportContext<'_>,
1079    ) -> bool {
1080        let barrel_idx = entry.barrel.0 as usize;
1081        let source_idx = entry.source.0 as usize;
1082
1083        if barrel_idx >= modules.len() || source_idx >= modules.len() {
1084            return false;
1085        }
1086
1087        if entry.exported_name == "*" {
1088            propagate_star_re_export(StarReExportPropagation {
1089                modules,
1090                edges,
1091                edges_by_target: context.edges_by_target,
1092                binding_usage: context.binding_usage,
1093                effective_exports: context.effective_exports,
1094                barrel_id: entry.barrel,
1095                barrel_idx,
1096                source_id: entry.source,
1097                source_idx,
1098                open_star_barrels: context.open_star_barrels,
1099                triggering_is_type_only: entry.is_type_only,
1100                synthetic_stubs: context.synthetic_stubs,
1101                reference_paths: context.reference_paths,
1102                named_star_refs: context.named_star_refs,
1103            })
1104        } else {
1105            propagate_named_re_export(NamedReExportPropagation {
1106                modules,
1107                effective_exports: context.effective_exports,
1108                barrel_id: entry.barrel,
1109                barrel_idx,
1110                source_id: entry.source,
1111                source_idx,
1112                imported_name: &entry.imported_name,
1113                exported_name: &entry.exported_name,
1114                is_type_only: entry.is_type_only,
1115                existing_refs: context.existing_refs,
1116                declaration_routes: context.declaration_routes,
1117                scratch: context.scratch,
1118                reference_paths: context.reference_paths,
1119            })
1120        }
1121    }
1122
1123    #[cfg(test)]
1124    fn run_re_export_full_scan(input: LegacyReExportFullScan<'_>) {
1125        let LegacyReExportFullScan {
1126            modules,
1127            edges,
1128            re_export_info,
1129            open_star_barrels,
1130            edges_by_target,
1131            module_by_id,
1132            effective_exports,
1133            reference_paths,
1134        } = input;
1135        let max_iterations = re_export_info.len().saturating_add(1);
1136        let mut existing_refs: FxHashSet<RoutedReferenceKey> = FxHashSet::default();
1137        let mut synthetic_stubs: FxHashSet<(FileId, String, bool)> = FxHashSet::default();
1138        let binding_usage = ImportBindingUsageIndex::build(module_by_id);
1139        let mut declaration_routes = EffectiveDeclarationRouteCache::default();
1140        let mut scratch = NamedPropagationScratch::default();
1141
1142        for _ in 0..max_iterations {
1143            let mut changed = false;
1144            for entry in re_export_info {
1145                let mut context = ReExportContext {
1146                    open_star_barrels,
1147                    edges_by_target,
1148                    binding_usage: &binding_usage,
1149                    effective_exports,
1150                    existing_refs: &mut existing_refs,
1151                    synthetic_stubs: &mut synthetic_stubs,
1152                    declaration_routes: &mut declaration_routes,
1153                    scratch: &mut scratch,
1154                    reference_paths,
1155                    // A fresh cache per entry keeps the reference scan
1156                    // independent of the per-barrel cache it checks.
1157                    named_star_refs: &mut NamedStarRefCache::default(),
1158                };
1159                changed |= Self::propagate_re_export_entry(modules, edges, entry, &mut context);
1160            }
1161            if !changed {
1162                break;
1163            }
1164        }
1165    }
1166}
1167
1168/// Find SCCs of size >= 2 in the re-export subgraph and self-re-export
1169/// edges, emit one `tracing::warn!` per cycle, AND return structured cycle
1170/// data for the user-visible `re-export-cycle` finding type.
1171///
1172/// The `tracing::warn!` emissions remain unchanged from #442 (RUST_LOG=warn
1173/// operators still see them). The returned `Vec<GraphReExportCycle>` is the
1174/// structured surface that the analysis backend consumes and wraps in typed
1175/// `ReExportCycleFinding`s for end-user output. See issue #515.
1176fn find_re_export_cycles(
1177    modules: &[super::types::ModuleNode],
1178    re_export_info: &[ReExportTuple],
1179) -> Vec<GraphReExportCycle> {
1180    let mut cycles: Vec<GraphReExportCycle> = Vec::new();
1181
1182    let (node_index, nodes) = build_re_export_node_index(re_export_info);
1183    let n = nodes.len();
1184    if n == 0 {
1185        return cycles;
1186    }
1187
1188    let adj = build_re_export_adjacency(re_export_info, &node_index, modules, &mut cycles);
1189
1190    let sccs = tarjan_scc(n, &adj);
1191
1192    for scc in &sccs {
1193        cycles.push(build_multi_node_cycle(scc, &nodes, modules));
1194    }
1195
1196    for cycle in &mut cycles {
1197        cycle.anchor_span_start = cycle_anchor_span_start(&cycle.file_ids, modules);
1198    }
1199
1200    cycles
1201}
1202
1203/// The byte offset of the first `export ... from` statement in the first
1204/// member that re-exports from a member of the cycle. A namespace re-export
1205/// (`export * as ns`) is not part of the cycle, and a re-export without a
1206/// source span cannot anchor a line.
1207fn cycle_anchor_span_start(
1208    file_ids: &[FileId],
1209    modules: &[super::types::ModuleNode],
1210) -> Option<u32> {
1211    let anchor = modules.get(file_ids.first()?.0 as usize)?;
1212    anchor
1213        .re_exports
1214        .iter()
1215        .filter(|re| file_ids.contains(&re.source_file))
1216        .filter(|re| !is_namespace_re_export(re))
1217        .filter(|re| re.span.end > re.span.start)
1218        .map(|re| re.span.start)
1219        .min()
1220}
1221
1222/// Assign a dense node index to every distinct barrel / source file id.
1223fn build_re_export_node_index(
1224    re_export_info: &[ReExportTuple],
1225) -> (FxHashMap<FileId, usize>, Vec<FileId>) {
1226    let mut node_index: FxHashMap<FileId, usize> = FxHashMap::default();
1227    let mut nodes: Vec<FileId> = Vec::new();
1228    for entry in re_export_info {
1229        for &id in &[entry.barrel, entry.source] {
1230            node_index.entry(id).or_insert_with(|| {
1231                let idx = nodes.len();
1232                nodes.push(id);
1233                idx
1234            });
1235        }
1236    }
1237    (node_index, nodes)
1238}
1239
1240/// Build the adjacency list for the re-export subgraph, emitting a self-loop
1241/// `GraphReExportCycle` for any barrel that re-exports from itself.
1242///
1243/// `export * as ns` edges stay out of the subgraph. They expose one namespace
1244/// object and forward no names, so chain propagation cannot loop through them.
1245fn build_re_export_adjacency(
1246    re_export_info: &[ReExportTuple],
1247    node_index: &FxHashMap<FileId, usize>,
1248    modules: &[super::types::ModuleNode],
1249    cycles: &mut Vec<GraphReExportCycle>,
1250) -> Vec<Vec<usize>> {
1251    let mut adj: Vec<Vec<usize>> = vec![Vec::new(); node_index.len()];
1252    let mut seen_edge: FxHashSet<(usize, usize)> = FxHashSet::default();
1253    let mut seen_self_loop: FxHashSet<FileId> = FxHashSet::default();
1254    for entry in re_export_info {
1255        if entry.is_namespace() {
1256            continue;
1257        }
1258        let from = node_index[&entry.barrel];
1259        let to = node_index[&entry.source];
1260        if from == to {
1261            if seen_self_loop.insert(entry.barrel) {
1262                cycles.push(build_self_loop_cycle(entry.barrel, modules));
1263            }
1264            continue;
1265        }
1266        if seen_edge.insert((from, to)) {
1267            adj[from].push(to);
1268        }
1269    }
1270    adj
1271}
1272
1273/// Emit the `tracing::warn!` and structured cycle for a self-re-export edge.
1274fn build_self_loop_cycle(
1275    barrel: FileId,
1276    modules: &[super::types::ModuleNode],
1277) -> GraphReExportCycle {
1278    let (path_buf, path_display) = module_path_and_display(barrel, modules);
1279    tracing::warn!(
1280        file = path_display.as_str(),
1281        "Re-export self-loop detected: this file re-exports from \
1282         itself. Chain propagation is structurally a no-op for \
1283         these edges. Inspect the barrel for an accidental \
1284         `export * from './<this-file>'` after a rename or move."
1285    );
1286    GraphReExportCycle {
1287        files: vec![path_buf],
1288        file_ids: vec![barrel],
1289        is_self_loop: true,
1290        anchor_span_start: None,
1291    }
1292}
1293
1294/// Emit the `tracing::warn!` and structured cycle for a multi-node SCC.
1295fn build_multi_node_cycle(
1296    scc: &[usize],
1297    nodes: &[FileId],
1298    modules: &[super::types::ModuleNode],
1299) -> GraphReExportCycle {
1300    let mut triples: Vec<(PathBuf, String, FileId)> = scc
1301        .iter()
1302        .map(|&idx| {
1303            let file_id = nodes[idx];
1304            let (path, display) = module_path_and_display(file_id, modules);
1305            (path, display, file_id)
1306        })
1307        .collect();
1308    triples.sort_by(|a, b| a.1.cmp(&b.1));
1309    let members = triples
1310        .iter()
1311        .map(|(_, d, _)| d.as_str())
1312        .collect::<Vec<_>>()
1313        .join(" <-> ");
1314    tracing::warn!(
1315        target: fallow_types::ANALYSIS_DIAGNOSTIC_LOG_TARGET,
1316        cycle_size = scc.len(),
1317        members = members.as_str(),
1318        "Re-export cycle detected: chain propagation may be incomplete \
1319         for symbols on this barrel loop. Break the cycle to restore \
1320         full reachability analysis."
1321    );
1322    let (files, file_ids) = triples.into_iter().fold(
1323        (Vec::new(), Vec::new()),
1324        |(mut paths, mut ids), (p, _, id)| {
1325            paths.push(p);
1326            ids.push(id);
1327            (paths, ids)
1328        },
1329    );
1330    GraphReExportCycle {
1331        files,
1332        file_ids,
1333        is_self_loop: false,
1334        anchor_span_start: None,
1335    }
1336}
1337
1338/// Resolve a `FileId` to its `(PathBuf, display string)`, falling back to a
1339/// placeholder when the id is outside the module list.
1340fn module_path_and_display(
1341    file_id: FileId,
1342    modules: &[super::types::ModuleNode],
1343) -> (PathBuf, String) {
1344    let i = file_id.0 as usize;
1345    if i < modules.len() {
1346        let p = modules[i].path.clone();
1347        let d = p.display().to_string();
1348        (p, d)
1349    } else {
1350        let placeholder = format!("<file id {i}>");
1351        (PathBuf::from(&placeholder), placeholder)
1352    }
1353}
1354
1355struct TarjanFrame {
1356    node: usize,
1357    next_succ: usize,
1358}
1359
1360/// Mutable Tarjan SCC state shared across the iterative DFS.
1361struct TarjanState {
1362    index_counter: u32,
1363    indices: Vec<u32>,
1364    lowlinks: Vec<u32>,
1365    on_stack: fixedbitset::FixedBitSet,
1366    stack: Vec<usize>,
1367    sccs: Vec<Vec<usize>>,
1368}
1369
1370impl TarjanState {
1371    fn new(n: usize) -> Self {
1372        Self {
1373            index_counter: 0,
1374            indices: vec![u32::MAX; n],
1375            lowlinks: vec![0; n],
1376            on_stack: fixedbitset::FixedBitSet::with_capacity(n),
1377            stack: Vec::new(),
1378            sccs: Vec::new(),
1379        }
1380    }
1381
1382    /// Assign the next DFS index to `node` and push it onto the SCC stack.
1383    fn discover(&mut self, node: usize) {
1384        self.indices[node] = self.index_counter;
1385        self.lowlinks[node] = self.index_counter;
1386        self.index_counter = self.index_counter.saturating_add(1);
1387        self.stack.push(node);
1388        self.on_stack.insert(node);
1389    }
1390
1391    /// Advance one successor of the current frame, pushing a child frame when a
1392    /// new node is discovered. Returns the child node to descend into, if any.
1393    fn step_successor(&mut self, frame: &mut TarjanFrame, adj: &[Vec<usize>]) -> Option<usize> {
1394        let v = frame.node;
1395        let w = adj[v][frame.next_succ];
1396        frame.next_succ = frame.next_succ.saturating_add(1);
1397        if self.indices[w] == u32::MAX {
1398            self.discover(w);
1399            Some(w)
1400        } else {
1401            if self.on_stack.contains(w) {
1402                self.lowlinks[v] = self.lowlinks[v].min(self.indices[w]);
1403            }
1404            None
1405        }
1406    }
1407
1408    /// Finish the current frame: emit its SCC if it is a multi-node root, then
1409    /// propagate its lowlink to the parent frame.
1410    ///
1411    /// Single-node components are popped without an allocation. An acyclic
1412    /// barrel chain has one component per node, and callers only report
1413    /// components with two or more nodes.
1414    fn finish_frame(&mut self, v: usize, parent: Option<usize>) {
1415        if self.lowlinks[v] == self.indices[v] {
1416            if self.stack.last() == Some(&v) {
1417                self.stack.pop();
1418                self.on_stack.remove(v);
1419            } else {
1420                let mut scc = Vec::new();
1421                while let Some(w) = self.stack.pop() {
1422                    self.on_stack.remove(w);
1423                    scc.push(w);
1424                    if w == v {
1425                        break;
1426                    }
1427                }
1428                self.sccs.push(scc);
1429            }
1430        }
1431        if let Some(pv) = parent {
1432            self.lowlinks[pv] = self.lowlinks[pv].min(self.lowlinks[v]);
1433        }
1434    }
1435}
1436
1437/// Iterative Tarjan's strongly connected components, returns the SCCs that
1438/// contain two or more nodes. The graph is given as adjacency-by-index;
1439/// the caller maps node indices back to FileIds.
1440fn tarjan_scc(n: usize, adj: &[Vec<usize>]) -> Vec<Vec<usize>> {
1441    let mut state = TarjanState::new(n);
1442
1443    for start in 0..n {
1444        if state.indices[start] != u32::MAX {
1445            continue;
1446        }
1447        state.discover(start);
1448        let mut dfs: Vec<TarjanFrame> = vec![TarjanFrame {
1449            node: start,
1450            next_succ: 0,
1451        }];
1452
1453        while let Some(frame) = dfs.last_mut() {
1454            let v = frame.node;
1455            if frame.next_succ < adj[v].len() {
1456                if let Some(child) = state.step_successor(frame, adj) {
1457                    dfs.push(TarjanFrame {
1458                        node: child,
1459                        next_succ: 0,
1460                    });
1461                }
1462            } else {
1463                dfs.pop();
1464                state.finish_frame(v, dfs.last().map(|parent| parent.node));
1465            }
1466        }
1467    }
1468
1469    state.sccs
1470}