1mod 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#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
80pub struct GraphReExportCycle {
81 pub files: Vec<PathBuf>,
85 pub file_ids: Vec<FileId>,
90 pub is_self_loop: bool,
93 #[serde(default)]
97 pub anchor_span_start: Option<u32>,
98}
99
100struct ReExportTuple {
106 barrel: FileId,
107 source: FileId,
108 imported_name: String,
109 exported_name: String,
110 is_type_only: bool,
115}
116
117impl ReExportTuple {
118 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#[derive(Clone, Copy, PartialEq, Eq, Debug)]
142enum Exposure {
143 StarSurface,
145 NamespaceObject,
148}
149
150#[derive(Default)]
158pub(in crate::graph) struct WholeModuleObservations {
159 ambient: FxHashMap<FileId, Exposure>,
161 observed: FxHashSet<FileId>,
163 escapes: Vec<super::namespace_escapes::NamespaceEscape>,
165}
166
167impl WholeModuleObservations {
168 pub(in crate::graph) fn observe(&mut self, target: FileId) {
170 self.observed.insert(target);
171 }
172
173 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 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 pub(in crate::graph) fn observe_ambient_star(&mut self, target: FileId) {
190 self.ambient.entry(target).or_insert(Exposure::StarSurface);
191 }
192
193 pub(in crate::graph) fn observe_ambient_namespace(&mut self, target: FileId) {
195 self.ambient.insert(target, Exposure::NamespaceObject);
196 }
197
198 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
217pub(in crate::graph) struct ExposedNamespaceTargets {
224 members: FxHashMap<FileId, Exposure>,
225}
226
227impl ExposedNamespaceTargets {
228 pub(in crate::graph) fn is_empty(&self) -> bool {
230 self.members.is_empty()
231 }
232
233 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 fn files(&self) -> impl Iterator<Item = FileId> + '_ {
253 self.members.keys().copied()
254 }
255
256 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
274fn is_namespace_re_export(re: &super::types::ReExportEdge) -> bool {
277 re.imported_name == "*" && re.exported_name != "*"
278}
279
280struct NameForwarders<'a> {
286 named: FxHashMap<(FileId, &'a str), Vec<(FileId, &'a str)>>,
289 stars: FxHashMap<FileId, Vec<FileId>>,
291}
292
293#[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
332fn 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
362struct ExposedNameSearch<'a> {
372 forwarders: NameForwarders<'a>,
373 whole_object_names: FxHashMap<FileId, Vec<String>>,
378 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 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 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(¤t) {
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
527fn 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
568struct 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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
1168fn 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
1203fn 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
1222fn 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
1240fn 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
1273fn 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
1294fn 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
1338fn 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
1360struct 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 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 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 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
1437fn 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}