1mod ambiguity;
7mod build;
8mod cycle_edge_span;
9mod cycles;
10mod effective_exports;
11mod effective_re_exports;
12mod entry_load;
13mod entry_marks;
14mod fan_io;
15mod impact_closure;
16mod namespace_aliases;
17mod namespace_escapes;
18mod namespace_indexes;
19mod namespace_re_exports;
20mod narrowing;
21pub mod package_entry;
22mod partition_order;
23mod public_exports;
24mod re_exports;
25mod reachability;
26mod shortest_import_path;
27mod support_reach;
28mod test_reach;
29pub mod types;
30
31use std::path::Path;
32
33use fixedbitset::FixedBitSet;
34use rustc_hash::{FxHashMap, FxHashSet};
35
36use crate::resolve::{ResolvedModule, ResolvedReplacedModuleTarget};
37use fallow_types::discover::{DiscoveredFile, EntryPoint, FileId};
38use fallow_types::extract::{ImportLoadKind, ImportedName, ModuleLoadMechanism};
39use types::{ReferencePathInterner, ReferencePathNode, ReferenceRouteNodeId, ReferenceRoutes};
40
41pub(super) fn relativize(path: &Path, root: &Path) -> String {
45 path.strip_prefix(root)
46 .unwrap_or(path)
47 .to_string_lossy()
48 .replace('\\', "/")
49}
50
51pub use ambiguity::{AmbiguityParticipants, AmbiguousStarExport};
52pub use cycles::{CycleOptions, CycleSearch, MAX_CYCLE_LENGTH, MAX_CYCLES_PER_SCC};
53pub use effective_exports::{EffectiveExportBinding, EffectiveExportResolution, ExportNamespace};
54pub use effective_re_exports::EffectiveReExportRoute;
55pub use entry_load::{DominatingImport, EntryLoadClosure};
56pub use entry_marks::untracked_load_targets;
57pub use fan_io::{FocusFileFacts, FocusFileFactsPaths};
58pub use impact_closure::{
59 CoordinationGap, CoordinationGapPaths, ImpactClosure, ImpactClosurePaths,
60};
61pub use namespace_escapes::{NamespaceEscape, NamespaceEscapeReason};
62pub use partition_order::{PartitionOrder, PartitionOrderPaths, ReviewUnit, ReviewUnitPaths};
63pub use public_exports::PublicExportOrigin;
64pub use re_exports::GraphReExportCycle;
65pub use shortest_import_path::ImportPathHop;
66pub use test_reach::{ExportTestReach, ExportTestReachResult, TestMaskingState};
67pub use types::{
68 ExportSymbol, ModuleNode, ReExportEdge, ReachabilityRoots, ReferenceKind, ReferencePathId,
69 SymbolReference,
70};
71
72#[derive(Debug, Clone, Copy)]
74pub struct EffectiveExportOrigin<'graph> {
75 file_id: FileId,
76 export: &'graph ExportSymbol,
77}
78
79#[derive(Debug, Clone, Copy)]
81pub struct EffectiveExportSurface<'graph> {
82 binding: EffectiveExportBinding,
83 namespace: ExportNamespace,
84 export: Option<&'graph ExportSymbol>,
85 origin: Option<EffectiveExportOrigin<'graph>>,
86 local_export: bool,
87}
88
89impl<'graph> EffectiveExportSurface<'graph> {
90 #[must_use]
92 pub const fn binding(self) -> EffectiveExportBinding {
93 self.binding
94 }
95
96 #[must_use]
98 pub const fn namespace(self) -> ExportNamespace {
99 self.namespace
100 }
101
102 #[must_use]
108 pub const fn export(self) -> Option<&'graph ExportSymbol> {
109 self.export
110 }
111
112 #[must_use]
114 pub const fn origin(self) -> Option<EffectiveExportOrigin<'graph>> {
115 self.origin
116 }
117}
118
119impl<'graph> EffectiveExportOrigin<'graph> {
120 #[must_use]
122 pub const fn file_id(self) -> FileId {
123 self.file_id
124 }
125
126 #[must_use]
128 pub const fn export(self) -> &'graph ExportSymbol {
129 self.export
130 }
131}
132
133#[must_use]
142pub fn is_declaration_file_path(path: &Path) -> bool {
143 path.file_name()
144 .and_then(|n| n.to_str())
145 .is_some_and(|name| {
146 name.ends_with(".d.ts") || name.ends_with(".d.mts") || name.ends_with(".d.cts")
147 })
148}
149
150#[derive(Debug, serde::Serialize, serde::Deserialize)]
158pub struct ModuleGraph {
159 pub modules: Vec<ModuleNode>,
169 edges: Vec<Edge>,
171 pub package_usage: FxHashMap<String, Vec<FileId>>,
174 pub type_only_package_usage: FxHashMap<String, Vec<FileId>>,
179 pub asset_package_usage: FxHashMap<String, Vec<FileId>>,
185 pub eager_package_imports: FxHashMap<FileId, Vec<EagerPackageImport>>,
189 pub entry_points: FxHashSet<FileId>,
191 pub runtime_entry_points: FxHashSet<FileId>,
193 pub test_entry_points: FxHashSet<FileId>,
195 support_entry_points: FxHashSet<FileId>,
197 test_reachability_index: TestReachabilityIndex,
202 reference_paths: Vec<ReferencePathNode>,
204 reference_routes: ReferenceRoutes,
206 pub reverse_deps: Vec<Vec<FileId>>,
208 #[serde(skip, default)]
216 namespace_imported: FixedBitSet,
217 pub re_export_cycles: Vec<GraphReExportCycle>,
224 pub namespace_escapes: Vec<NamespaceEscape>,
227 effective_exports: effective_exports::EffectiveExportIndex,
229}
230
231#[derive(Debug, serde::Serialize, serde::Deserialize)]
238pub struct Edge {
239 source: FileId,
241 target: FileId,
243 symbols: Vec<ImportedSymbol>,
245}
246
247impl Edge {
248 #[must_use]
253 fn runs_target_code(&self) -> bool {
254 self.symbols.is_empty()
255 || self
256 .symbols
257 .iter()
258 .any(|symbol| symbol.load_kind.runs_target_code())
259 }
260
261 #[must_use]
266 fn runs_target_code_in_tests(&self) -> bool {
267 self.symbols.is_empty()
268 || self
269 .symbols
270 .iter()
271 .any(|symbol| !symbol.is_type_only && symbol.load_kind.runs_target_code())
272 }
273}
274
275#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
277pub struct EagerPackageImport {
278 pub package: String,
280 pub specifier: String,
282}
283
284#[derive(Debug, serde::Serialize, serde::Deserialize)]
286pub struct ImportedSymbol {
287 pub imported_name: ImportedName,
290 pub local_name: String,
292 #[serde(with = "crate::cache::span_serde")]
294 pub import_span: oxc_span::Span,
295 pub is_type_only: bool,
298 pub(crate) is_type_only_star: bool,
301 mechanism: ModuleLoadMechanism,
303 load_kind: ImportLoadKind,
307}
308
309impl ImportedSymbol {
310 #[must_use]
312 pub const fn load_kind(&self) -> ImportLoadKind {
313 self.load_kind
314 }
315
316 #[must_use]
319 pub const fn is_eager_value(&self) -> bool {
320 self.load_kind.is_eager_value(self.is_type_only)
321 }
322
323 #[must_use]
327 pub const fn loads_target(&self) -> bool {
328 self.load_kind.loads_target()
329 }
330
331 #[must_use]
343 fn is_ambient_star(&self) -> bool {
344 self.is_type_only
345 && self.local_name.is_empty()
346 && matches!(
347 self.imported_name,
348 ImportedName::Namespace | ImportedName::Default
349 )
350 }
351
352 #[must_use]
360 fn is_value_bearing_ambient_star(&self) -> bool {
361 self.is_ambient_star() && !self.is_type_only_star
362 }
363}
364
365#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
373struct TestReachabilityIndex {
374 profile_count: usize,
375 words_per_file: usize,
376 reachable_profiles: Vec<u64>,
377 masked_profiles: Vec<MaskedTestProfiles>,
378 profile_roots: Vec<Vec<FileId>>,
381 masking_capped: bool,
385}
386
387#[derive(Debug, serde::Serialize, serde::Deserialize)]
389struct MaskedTestProfiles {
390 target: FileId,
391 profiles: Vec<u64>,
392}
393
394impl TestReachabilityIndex {
395 fn new(file_capacity: usize, profile_count: usize) -> Self {
396 let words_per_file = profile_count.div_ceil(u64::BITS as usize);
397 let storage_len = file_capacity.saturating_mul(words_per_file);
398 Self {
399 profile_count,
400 words_per_file,
401 reachable_profiles: vec![0; storage_len],
402 masked_profiles: Vec::new(),
403 profile_roots: Vec::new(),
404 masking_capped: false,
405 }
406 }
407
408 fn root_masks(&self) -> FxHashMap<FileId, Vec<FileId>> {
411 let mut masks: FxHashMap<FileId, Vec<FileId>> = FxHashMap::default();
412 for row in &self.masked_profiles {
413 for (profile, roots) in self.profile_roots.iter().enumerate() {
414 let masked = row
415 .profiles
416 .get(profile / u64::BITS as usize)
417 .is_some_and(|word| word & (1_u64 << (profile % u64::BITS as usize)) != 0);
418 if !masked {
419 continue;
420 }
421 for &root in roots {
422 masks.entry(root).or_default().push(row.target);
423 }
424 }
425 }
426 masks
427 }
428
429 fn set_sparse_masks(&mut self, masks: FxHashMap<FileId, Vec<u64>>) {
430 let mut rows: Vec<_> = masks
431 .into_iter()
432 .map(|(target, profiles)| MaskedTestProfiles { target, profiles })
433 .collect();
434 rows.sort_unstable_by_key(|row| row.target.0);
435 self.masked_profiles = rows;
436 }
437
438 fn profiles_for<'a>(&self, storage: &'a [u64], file_id: FileId) -> Option<&'a [u64]> {
439 let start = (file_id.0 as usize).checked_mul(self.words_per_file)?;
440 let end = start.checked_add(self.words_per_file)?;
441 storage.get(start..end)
442 }
443
444 fn masked_profiles_for(&self, file_id: FileId) -> Option<&[u64]> {
445 self.masked_profiles
446 .binary_search_by_key(&file_id.0, |row| row.target.0)
447 .ok()
448 .map(|index| self.masked_profiles[index].profiles.as_slice())
449 }
450
451 fn covers_reference_path(
452 &self,
453 source: FileId,
454 path: types::ReferencePathId,
455 paths: &[ReferencePathNode],
456 routes: &ReferenceRoutes,
457 ) -> bool {
458 let Some(source_profiles) = self.profiles_for(&self.reachable_profiles, source) else {
459 return false;
460 };
461
462 for (word_index, &source_word) in source_profiles.iter().enumerate() {
463 let mut active_profiles = source_word;
464 if active_profiles == 0 {
465 continue;
466 }
467
468 let mut next = Some(path);
469 while let Some(path_id) = next {
470 let Some(path_node) = paths.get(path_id.index()) else {
471 return false;
472 };
473 next = path_node.parent();
474 active_profiles = match *path_node {
475 ReferencePathNode::Hop {
476 target, mechanism, ..
477 } => self.active_hop_profiles(target, mechanism, word_index, active_profiles),
478 ReferencePathNode::Route {
479 graph,
480 start,
481 terminal,
482 start_mechanism,
483 ..
484 } => self.active_route_profiles(
485 routes,
486 graph,
487 start,
488 terminal,
489 start_mechanism,
490 word_index,
491 active_profiles,
492 ),
493 };
494 if active_profiles == 0 {
495 break;
496 }
497 }
498
499 if active_profiles != 0 {
500 return true;
501 }
502 }
503
504 false
505 }
506
507 fn active_hop_profiles(
508 &self,
509 target: FileId,
510 mechanism: ModuleLoadMechanism,
511 word_index: usize,
512 mut active_profiles: u64,
513 ) -> u64 {
514 let Some(target_word) = self
515 .profiles_for(&self.reachable_profiles, target)
516 .and_then(|profiles| profiles.get(word_index))
517 else {
518 return 0;
519 };
520 active_profiles &= target_word;
521 if matches!(mechanism, ModuleLoadMechanism::EsModule)
522 && let Some(masked_profiles) = self.masked_profiles_for(target)
523 {
524 let Some(masked_word) = masked_profiles.get(word_index) else {
525 return 0;
526 };
527 active_profiles &= !masked_word;
528 }
529 active_profiles
530 }
531
532 #[expect(
536 clippy::too_many_arguments,
537 reason = "the route identity and profile word form one evaluation contract"
538 )]
539 fn active_route_profiles(
540 &self,
541 routes: &ReferenceRoutes,
542 graph_id: types::ReferenceRouteGraphId,
543 start: ReferenceRouteNodeId,
544 terminal: ReferenceRouteNodeId,
545 start_mechanism: Option<ModuleLoadMechanism>,
546 word_index: usize,
547 candidate_profiles: u64,
548 ) -> u64 {
549 let Some(graph) = routes.graphs.get(graph_id.0 as usize) else {
550 return 0;
551 };
552 let node_count = graph.nodes.end.saturating_sub(graph.nodes.start) as usize;
553 let start_index = start.0 as usize;
554 let terminal_index = terminal.0 as usize;
555 if start_index >= node_count || terminal_index >= node_count {
556 return 0;
557 }
558
559 let mut attempted = vec![0_u64; node_count];
560 let mut pending = vec![0_u64; node_count];
561 let mut queued = vec![false; node_count];
562 let mut queue = std::collections::VecDeque::from([start_index]);
563 pending[start_index] = candidate_profiles;
564 queued[start_index] = true;
565 let mut successful_profiles = 0_u64;
566
567 while let Some(local_index) = queue.pop_front() {
568 queued[local_index] = false;
569 let incoming = pending[local_index] & !attempted[local_index];
570 pending[local_index] = 0;
571 attempted[local_index] |= incoming;
572 if incoming == 0 {
573 continue;
574 }
575
576 let Some(node) = routes.nodes.get(graph.nodes.start as usize + local_index) else {
577 return 0;
578 };
579 let active = if local_index == start_index {
580 start_mechanism.map_or(incoming, |mechanism| {
581 self.active_hop_profiles(node.target, mechanism, word_index, incoming)
582 })
583 } else {
584 self.active_hop_profiles(node.target, node.mechanism, word_index, incoming)
585 };
586 if active == 0 {
587 continue;
588 }
589 if local_index == terminal_index {
590 successful_profiles |= active;
591 continue;
592 }
593
594 let Some(successors) = routes
595 .edges
596 .get(node.successors.start as usize..node.successors.end as usize)
597 else {
598 return 0;
599 };
600 for successor in successors {
601 let successor_index = successor.0 as usize;
602 if successor_index >= node_count {
603 return 0;
604 }
605 let new_profiles = active & !attempted[successor_index] & !pending[successor_index];
606 if new_profiles == 0 {
607 continue;
608 }
609 pending[successor_index] |= new_profiles;
610 if !queued[successor_index] {
611 queued[successor_index] = true;
612 queue.push_back(successor_index);
613 }
614 }
615 }
616
617 successful_profiles
618 }
619
620 #[cfg(test)]
621 fn profile_contains(&self, storage: &[u64], file_id: FileId, profile: usize) -> bool {
622 self.profiles_for(storage, file_id)
623 .and_then(|words| words.get(profile / u64::BITS as usize))
624 .is_some_and(|word| word & (1_u64 << (profile % u64::BITS as usize)) != 0)
625 }
626
627 #[cfg(test)]
628 fn profile_reaches(&self, file_id: FileId, profile: usize) -> bool {
629 self.profile_contains(&self.reachable_profiles, file_id, profile)
630 }
631
632 #[cfg(test)]
633 fn profile_masks(&self, file_id: FileId, profile: usize) -> bool {
634 self.masked_profiles_for(file_id)
635 .and_then(|words| words.get(profile / u64::BITS as usize))
636 .is_some_and(|word| word & (1_u64 << (profile % u64::BITS as usize)) != 0)
637 }
638}
639
640#[derive(Debug, Clone, Copy)]
643pub struct OutgoingEdgeSummary<'a> {
644 pub target: FileId,
646 pub all_type_only: bool,
649 pub span_start: Option<u32>,
652 pub symbols: &'a [ImportedSymbol],
655}
656
657#[derive(Debug, Clone, PartialEq, Eq)]
659pub struct DirectImporterSummary {
660 pub source: FileId,
662 pub symbols: Vec<ImportedSymbolSummary>,
664}
665
666#[derive(Debug, Clone, PartialEq, Eq)]
668pub struct ImportedSymbolSummary {
669 pub imported: String,
672 pub local: String,
674 pub type_only: bool,
676}
677
678#[cfg(target_pointer_width = "64")]
679const _: () = assert!(std::mem::size_of::<Edge>() == 32);
680#[cfg(target_pointer_width = "64")]
681const _: () = assert!(std::mem::size_of::<ImportedSymbol>() == 64);
682
683#[cold]
684#[inline(never)]
685fn propagate_namespace_references(
686 graph: &mut ModuleGraph,
687 module_by_id: &FxHashMap<FileId, &ResolvedModule>,
688 features: build::NamespaceFeatures,
689 exposed_namespace_targets: &re_exports::ExposedNamespaceTargets,
690 reference_paths: &mut ReferencePathInterner,
691) {
692 let indexes = namespace_indexes::NamespacePropagationIndexes::new(graph, module_by_id);
693 if features.has_aliases {
694 namespace_aliases::propagate_cross_package_aliases(
695 graph,
696 module_by_id,
697 &indexes,
698 reference_paths,
699 );
700 }
701 if features.has_re_exports {
702 namespace_re_exports::propagate_namespace_re_exports(
703 graph,
704 &indexes,
705 exposed_namespace_targets,
706 reference_paths,
707 );
708 }
709}
710
711impl ModuleGraph {
712 fn resolve_entry_point_ids(
713 entry_points: &[EntryPoint],
714 path_to_id: &FxHashMap<&Path, FileId>,
715 ) -> FxHashSet<FileId> {
716 entry_points
717 .iter()
718 .filter_map(|ep| {
719 path_to_id.get(ep.path.as_path()).copied().or_else(|| {
720 dunce::canonicalize(&ep.path)
721 .ok()
722 .and_then(|path| path_to_id.get(path.as_path()).copied())
723 })
724 })
725 .collect()
726 }
727
728 pub fn build(
730 resolved_modules: &[ResolvedModule],
731 entry_points: &[EntryPoint],
732 files: &[DiscoveredFile],
733 ) -> Self {
734 Self::build_with_reachability_roots(
735 resolved_modules,
736 entry_points,
737 entry_points,
738 &[],
739 files,
740 )
741 }
742
743 fn build_with_reachability_roots(
745 resolved_modules: &[ResolvedModule],
746 entry_points: &[EntryPoint],
747 runtime_entry_points: &[EntryPoint],
748 test_entry_points: &[EntryPoint],
749 files: &[DiscoveredFile],
750 ) -> Self {
751 Self::build_with_reachability_roots_and_replacements(
752 resolved_modules,
753 &[],
754 entry_points,
755 runtime_entry_points,
756 test_entry_points,
757 files,
758 )
759 }
760
761 pub fn build_with_reachability_roots_and_replacements(
763 resolved_modules: &[ResolvedModule],
764 replaced_module_targets: &[ResolvedReplacedModuleTarget],
765 entry_points: &[EntryPoint],
766 runtime_entry_points: &[EntryPoint],
767 test_entry_points: &[EntryPoint],
768 files: &[DiscoveredFile],
769 ) -> Self {
770 Self::build_with_declaration_seeding(
771 resolved_modules,
772 replaced_module_targets,
773 &ReachabilityRoots {
774 all: entry_points,
775 runtime: runtime_entry_points,
776 test: test_entry_points,
777 consumer_checked: &FxHashSet::default(),
778 },
779 files,
780 &FxHashSet::default(),
781 )
782 }
783
784 pub fn build_with_declaration_seeding(
795 resolved_modules: &[ResolvedModule],
796 replaced_module_targets: &[ResolvedReplacedModuleTarget],
797 roots: &ReachabilityRoots<'_>,
798 files: &[DiscoveredFile],
799 unseeded_declaration_files: &FxHashSet<FileId>,
800 ) -> Self {
801 let ReachabilityRoots {
802 all: entry_points,
803 runtime: runtime_entry_points,
804 test: test_entry_points,
805 consumer_checked,
806 } = *roots;
807 let _span = tracing::info_span!("build_graph").entered();
808
809 let module_count = files.len();
810
811 let max_file_id = files
812 .iter()
813 .map(|f| f.id.0 as usize)
814 .max()
815 .map_or(0, |m| m + 1);
816 let total_capacity = max_file_id.max(module_count);
817
818 let path_to_id: FxHashMap<&Path, FileId> =
819 files.iter().map(|f| (f.path.as_path(), f.id)).collect();
820
821 let module_by_id: FxHashMap<FileId, &ResolvedModule> =
822 resolved_modules.iter().map(|m| (m.file_id, m)).collect();
823
824 let mut entry_point_ids = Self::resolve_entry_point_ids(entry_points, &path_to_id);
825 let runtime_entry_point_ids =
826 Self::resolve_entry_point_ids(runtime_entry_points, &path_to_id);
827 let test_entry_point_ids = Self::resolve_entry_point_ids(test_entry_points, &path_to_id);
828
829 for file in files {
830 if is_declaration_file_path(&file.path)
831 && !unseeded_declaration_files.contains(&file.id)
832 {
833 entry_point_ids.insert(file.id);
834 }
835 }
836
837 let (mut graph, namespace_features) = Self::populate_edges(&build::PopulateEdgesInput {
838 files,
839 module_by_id: &module_by_id,
840 entry_point_ids: &entry_point_ids,
841 runtime_entry_point_ids: &runtime_entry_point_ids,
842 test_entry_point_ids: &test_entry_point_ids,
843 module_count,
844 total_capacity,
845 });
846 graph.index_exports(resolved_modules, consumer_checked);
847
848 let test_reachability_plan = reachability::TestReachabilityPlan::new(
849 &test_entry_point_ids,
850 replaced_module_targets,
851 total_capacity,
852 );
853
854 let mut reference_paths =
855 ReferencePathInterner::new(test_reachability_plan.requires_reference_provenance());
856 let mut whole_module_targets =
857 graph.populate_references(&module_by_id, &entry_point_ids, &mut reference_paths);
858 graph.namespace_escapes = whole_module_targets.take_escapes();
859 let entry_reachable = graph.collect_reachable(&entry_point_ids, total_capacity);
864 let exposed_namespace_targets = graph.collect_exposed_namespace_targets(
865 &whole_module_targets,
866 &entry_reachable,
867 &module_by_id,
868 );
869
870 if namespace_features.has_aliases || namespace_features.has_re_exports {
871 propagate_namespace_references(
872 &mut graph,
873 &module_by_id,
874 namespace_features,
875 &exposed_namespace_targets,
876 &mut reference_paths,
877 );
878 }
879
880 graph.mark_reachable(
881 &entry_reachable,
882 &entry_point_ids,
883 &runtime_entry_point_ids,
884 test_reachability_plan,
885 total_capacity,
886 );
887
888 graph.re_export_cycles = graph.resolve_re_export_chains(
889 &module_by_id,
890 &exposed_namespace_targets,
891 consumer_checked,
892 &mut reference_paths,
893 );
894 namespace_escapes::normalize(&mut graph.namespace_escapes);
895 let finalized_paths = reference_paths.finalize(&mut graph.modules);
896 graph.reference_paths = finalized_paths.paths;
897 graph.reference_routes = finalized_paths.routes;
898
899 graph
900 }
901
902 #[must_use]
904 pub const fn module_count(&self) -> usize {
905 self.modules.len()
906 }
907
908 #[must_use]
910 pub const fn edge_count(&self) -> usize {
911 self.edges.len()
912 }
913
914 #[must_use]
916 pub fn is_test_reachable(&self, file_id: FileId) -> bool {
917 self.modules
918 .get(file_id.0 as usize)
919 .is_some_and(ModuleNode::is_test_reachable)
920 }
921
922 #[must_use]
934 fn is_test_reference_covered(&self, export: &ExportSymbol, reference_index: usize) -> bool {
935 let Some(reference) = export.references.get(reference_index) else {
936 return false;
937 };
938 if reference.namespace != ExportNamespace::Value {
939 return false;
940 }
941 if self.test_reachability_index.profile_count == 0 {
942 return self.is_test_reachable(reference.from_file);
943 }
944
945 let Some(path) = export.reference_path(reference_index) else {
946 return false;
947 };
948
949 self.test_reachability_index.covers_reference_path(
950 reference.from_file,
951 path,
952 &self.reference_paths,
953 &self.reference_routes,
954 )
955 }
956
957 #[must_use]
960 pub fn is_any_test_reference_covered(&self, export: &ExportSymbol) -> bool {
961 (0..export.references.len())
962 .any(|reference_index| self.is_test_reference_covered(export, reference_index))
963 }
964
965 #[cfg(test)]
966 fn reference_path_hops(
967 &self,
968 export: &ExportSymbol,
969 reference_index: usize,
970 ) -> Vec<(FileId, ModuleLoadMechanism)> {
971 let mut hops = Vec::new();
972 let mut next = export.reference_path(reference_index);
973 while let Some(path_id) = next {
974 let Some(node) = self.reference_paths.get(path_id.index()) else {
975 return Vec::new();
976 };
977 next = node.parent();
978 match *node {
979 ReferencePathNode::Hop {
980 target, mechanism, ..
981 } => hops.push((target, mechanism)),
982 ReferencePathNode::Route {
983 graph,
984 start,
985 terminal,
986 start_mechanism,
987 ..
988 } => hops.extend(self.reference_routes.canonical_hops(
989 graph,
990 start,
991 terminal,
992 start_mechanism,
993 )),
994 }
995 }
996 hops
997 }
998
999 pub(crate) fn reconstruct_namespace_imported(&mut self) {
1014 let capacity = self
1015 .edges
1016 .iter()
1017 .map(|edge| edge.target.0 as usize + 1)
1018 .max()
1019 .unwrap_or(0)
1020 .max(self.modules.len());
1021 let mut bitset = FixedBitSet::with_capacity(capacity);
1022 for edge in &self.edges {
1023 if edge
1024 .symbols
1025 .iter()
1026 .any(|sym| matches!(sym.imported_name, ImportedName::Namespace))
1027 {
1028 let idx = edge.target.0 as usize;
1029 if idx < capacity {
1030 bitset.insert(idx);
1031 }
1032 }
1033 }
1034 self.namespace_imported = bitset;
1035 }
1036
1037 #[must_use]
1043 pub fn resolve_export(
1044 &self,
1045 file_id: FileId,
1046 name: &str,
1047 namespace: ExportNamespace,
1048 ) -> EffectiveExportResolution {
1049 self.effective_exports.resolve(file_id, name, namespace)
1050 }
1051
1052 #[must_use]
1059 pub fn effective_bindings_share_declaration_group(
1060 &self,
1061 left: EffectiveExportBinding,
1062 right: EffectiveExportBinding,
1063 ) -> bool {
1064 if left == right || left.origin_file() != right.origin_file() {
1065 return left == right;
1066 }
1067 let Some(right_slot) = right.origin_slot() else {
1068 return false;
1069 };
1070 self.effective_exports
1071 .declaration_group_slots(left)
1072 .contains(&right_slot)
1073 }
1074
1075 #[must_use]
1081 pub fn resolve_export_origin(
1082 &self,
1083 file_id: FileId,
1084 name: &str,
1085 namespace: ExportNamespace,
1086 ) -> Option<EffectiveExportOrigin<'_>> {
1087 let EffectiveExportResolution::Unique(binding) =
1088 self.resolve_export(file_id, name, namespace)
1089 else {
1090 return None;
1091 };
1092 self.export_binding_origin(binding)
1093 }
1094
1095 #[must_use]
1098 pub fn effective_export_surface(
1099 &self,
1100 file_id: FileId,
1101 name: &str,
1102 namespace: ExportNamespace,
1103 ) -> Option<EffectiveExportSurface<'_>> {
1104 let EffectiveExportResolution::Unique(binding) =
1105 self.resolve_export(file_id, name, namespace)
1106 else {
1107 return None;
1108 };
1109 let module = self.modules.get(file_id.0 as usize)?;
1110 let exact_surface = module.exports.iter().find(|export| {
1111 export.name.matches_str(name)
1112 && match namespace {
1113 ExportNamespace::Type => export.is_type_only,
1114 ExportNamespace::Value => !export.is_type_only,
1115 }
1116 });
1117 let surface_export = exact_surface.or_else(|| {
1118 module
1119 .exports
1120 .iter()
1121 .find(|export| export.name.matches_str(name))
1122 });
1123 let origin = self.export_binding_origin(binding);
1124 let export = surface_export.or_else(|| origin.map(|o| o.export));
1125 Some(EffectiveExportSurface {
1126 binding,
1127 namespace,
1128 export,
1129 origin,
1130 local_export: surface_export.is_some(),
1131 })
1132 }
1133
1134 #[must_use]
1140 pub fn effective_export_surface_re_export(
1141 &self,
1142 file_id: FileId,
1143 name: &str,
1144 namespace: ExportNamespace,
1145 ) -> Option<&ReExportEdge> {
1146 let EffectiveExportResolution::Unique(binding) =
1147 self.resolve_export(file_id, name, namespace)
1148 else {
1149 return None;
1150 };
1151 self.modules
1152 .get(file_id.0 as usize)?
1153 .re_exports
1154 .iter()
1155 .find(|re_export| {
1156 re_export.exported_name == name
1157 && (namespace == ExportNamespace::Type || !re_export.is_type_only)
1158 && if re_export.imported_name == "*" {
1159 binding.namespace_source() == Some(re_export.source_file)
1160 } else {
1161 self.resolve_export(
1162 re_export.source_file,
1163 &re_export.imported_name,
1164 namespace,
1165 ) == EffectiveExportResolution::Unique(binding)
1166 }
1167 })
1168 }
1169
1170 #[must_use]
1176 pub fn effective_export_surface_references(
1177 &self,
1178 file_id: FileId,
1179 name: &str,
1180 namespace: ExportNamespace,
1181 ) -> Vec<&SymbolReference> {
1182 let Some(surface) = self.effective_export_surface(file_id, name, namespace) else {
1183 return Vec::new();
1184 };
1185 let Some(export) = surface.export() else {
1186 return Vec::new();
1187 };
1188 if surface.local_export
1189 || surface
1190 .origin()
1191 .is_none_or(|origin| origin.file_id() == file_id)
1192 {
1193 return export.references_in(namespace).collect();
1194 }
1195 let mut exposed: FxHashMap<FileId, FxHashSet<String>> = FxHashMap::default();
1196 exposed.entry(file_id).or_default().insert(name.to_string());
1197 for route in self.effective_re_export_routes(file_id, name, namespace) {
1198 exposed
1199 .entry(route.barrel_file())
1200 .or_default()
1201 .insert(route.exported_name().to_string());
1202 }
1203 export
1204 .references
1205 .iter()
1206 .filter(|reference| {
1207 reference.namespace == namespace
1208 && self.reference_reaches_surface(reference, &exposed, namespace)
1209 })
1210 .collect()
1211 }
1212
1213 fn reference_reaches_surface(
1214 &self,
1215 reference: &SymbolReference,
1216 exposed: &FxHashMap<FileId, FxHashSet<String>>,
1217 namespace: ExportNamespace,
1218 ) -> bool {
1219 if reference.kind == ReferenceKind::ReExport && exposed.contains_key(&reference.from_file) {
1220 return true;
1221 }
1222 self.outgoing_symbol_edges(reference.from_file)
1223 .any(|(target, symbols)| {
1224 let Some(names) = exposed.get(&target) else {
1225 return false;
1226 };
1227 symbols.iter().any(|symbol| {
1228 symbol.import_span == reference.import_span
1229 && (namespace == ExportNamespace::Type
1230 || !symbol.is_type_only
1231 || symbol.is_value_bearing_ambient_star())
1232 && match &symbol.imported_name {
1233 ImportedName::Named(imported) => names.contains(imported.as_str()),
1234 ImportedName::Default => names.contains("default"),
1235 ImportedName::Namespace => true,
1236 ImportedName::SideEffect => false,
1237 }
1238 })
1239 })
1240 }
1241
1242 #[must_use]
1244 pub fn export_binding_origin(
1245 &self,
1246 binding: EffectiveExportBinding,
1247 ) -> Option<EffectiveExportOrigin<'_>> {
1248 let origin_file = binding.origin_file();
1249 let export = self
1250 .modules
1251 .get(origin_file.0 as usize)?
1252 .exports
1253 .get(binding.origin_slot()?)?;
1254 Some(EffectiveExportOrigin {
1255 file_id: origin_file,
1256 export,
1257 })
1258 }
1259
1260 #[must_use]
1265 pub fn unique_export_bindings(
1266 &self,
1267 file_id: FileId,
1268 namespace: ExportNamespace,
1269 ) -> FxHashSet<EffectiveExportBinding> {
1270 self.effective_exports.unique_bindings(file_id, namespace)
1271 }
1272
1273 #[must_use]
1281 pub fn importer_connects_export_origin(
1282 &self,
1283 importer: FileId,
1284 source: FileId,
1285 name: &str,
1286 namespace: ExportNamespace,
1287 ) -> bool {
1288 let Some(importer_module) = self.modules.get(importer.0 as usize) else {
1289 return false;
1290 };
1291 let re_export_count = importer_module
1292 .re_exports
1293 .iter()
1294 .filter(|re_export| re_export.source_file == source)
1295 .count();
1296 if self.edges[importer_module.edge_range.clone()]
1297 .iter()
1298 .any(|edge| edge.target == source && edge.symbols.len() > re_export_count)
1299 {
1300 return true;
1301 }
1302
1303 importer_module.re_exports.iter().any(|re_export| {
1304 if re_export.source_file != source
1305 || (namespace == ExportNamespace::Value && re_export.is_type_only)
1306 {
1307 return false;
1308 }
1309 let exported_name = if re_export.imported_name == "*" {
1310 if re_export.exported_name != "*" || name == "default" {
1311 return false;
1312 }
1313 name
1314 } else {
1315 if re_export.imported_name != name {
1316 return false;
1317 }
1318 &re_export.exported_name
1319 };
1320 self.effective_exports.contributes_through(
1321 importer,
1322 exported_name,
1323 source,
1324 name,
1325 namespace,
1326 )
1327 })
1328 }
1329
1330 #[must_use]
1333 pub fn has_namespace_import(&self, file_id: FileId) -> bool {
1334 self.namespace_imported.contains(file_id.0 as usize)
1336 }
1337
1338 #[must_use]
1340 pub fn edges_for(&self, file_id: FileId) -> Vec<FileId> {
1341 let idx = file_id.0 as usize;
1342 if idx >= self.modules.len() {
1343 return Vec::new();
1344 }
1345 let range = &self.modules[idx].edge_range;
1346 self.edges[range.clone()].iter().map(|e| e.target).collect()
1347 }
1348
1349 pub fn outgoing_symbol_edges(
1355 &self,
1356 file_id: FileId,
1357 ) -> impl Iterator<Item = (FileId, &[ImportedSymbol])> + '_ {
1358 let idx = file_id.0 as usize;
1359 let range = if idx < self.modules.len() {
1360 self.modules[idx].edge_range.clone()
1361 } else {
1362 0..0
1363 };
1364 self.edges[range]
1365 .iter()
1366 .map(|edge| (edge.target, edge.symbols.as_slice()))
1367 }
1368
1369 #[must_use]
1373 pub fn importers_of(&self, target: FileId) -> &[FileId] {
1374 self.reverse_deps
1375 .get(target.0 as usize)
1376 .map_or(&[], Vec::as_slice)
1377 }
1378
1379 #[must_use]
1384 pub fn direct_importer_summaries(&self, target: FileId) -> Vec<DirectImporterSummary> {
1385 let Some(importers) = self.reverse_deps.get(target.0 as usize) else {
1386 return Vec::new();
1387 };
1388
1389 let mut summaries = Vec::new();
1390 for &source in importers {
1391 let idx = source.0 as usize;
1392 let Some(source_node) = self.modules.get(idx) else {
1393 continue;
1394 };
1395 let mut symbols = Vec::new();
1396 for edge in &self.edges[source_node.edge_range.clone()] {
1397 if edge.target != target {
1398 continue;
1399 }
1400 symbols.extend(edge.symbols.iter().map(|symbol| ImportedSymbolSummary {
1401 imported: imported_name_label(&symbol.imported_name),
1402 local: symbol.local_name.clone(),
1403 type_only: symbol.is_type_only,
1404 }));
1405 }
1406 symbols.sort_by(|a, b| {
1407 a.imported
1408 .cmp(&b.imported)
1409 .then_with(|| a.local.cmp(&b.local))
1410 .then_with(|| a.type_only.cmp(&b.type_only))
1411 });
1412 symbols.dedup();
1413 summaries.push(DirectImporterSummary { source, symbols });
1414 }
1415 summaries.sort_by_key(|summary| summary.source.0);
1416 summaries
1417 }
1418
1419 pub fn outgoing_edge_summaries(
1439 &self,
1440 file_id: FileId,
1441 ) -> impl Iterator<Item = OutgoingEdgeSummary<'_>> + '_ {
1442 self.outgoing_symbol_edges(file_id)
1443 .filter_map(|(target, symbols)| {
1444 let mut loading = symbols.iter().filter(|s| s.loads_target()).peekable();
1445 let first = loading.peek().copied()?;
1446 let value = loading.find(|s| !s.is_type_only);
1447 Some(OutgoingEdgeSummary {
1448 target,
1449 all_type_only: value.is_none(),
1450 span_start: Some(value.unwrap_or(first).import_span.start),
1451 symbols,
1452 })
1453 })
1454 }
1455
1456 pub fn outgoing_edge_symbols(
1467 &self,
1468 file_id: FileId,
1469 ) -> impl Iterator<Item = (FileId, &[ImportedSymbol])> + '_ {
1470 let idx = file_id.0 as usize;
1471 let range = if idx < self.modules.len() {
1472 self.modules[idx].edge_range.clone()
1473 } else {
1474 0..0
1475 };
1476 self.edges[range]
1477 .iter()
1478 .map(|edge| (edge.target, edge.symbols.as_slice()))
1479 }
1480
1481 pub fn outgoing_edge_summaries_with_exclusions<'a>(
1500 &'a self,
1501 file_id: FileId,
1502 excluded_span_starts: &'a FxHashSet<u32>,
1503 ) -> impl Iterator<Item = (FileId, bool, Option<u32>, bool)> + 'a {
1504 let idx = file_id.0 as usize;
1505 let range = if idx < self.modules.len() {
1506 self.modules[idx].edge_range.clone()
1507 } else {
1508 0..0
1509 };
1510 self.edges[range].iter().filter_map(move |edge| {
1511 let loading = || edge.symbols.iter().filter(|s| s.loads_target());
1512 let first = loading().next()?;
1513 let erased = |s: &&ImportedSymbol| {
1514 s.is_type_only || self.names_only_type_exports(edge.target, &s.imported_name)
1515 };
1516 let all_type_only = loading().all(|s| erased(&s));
1517 let span = loading()
1518 .find(|s| !erased(s))
1519 .unwrap_or(first)
1520 .import_span
1521 .start;
1522 let mut value_symbols = loading().filter(|s| !erased(s)).peekable();
1526 let all_client_only = value_symbols.peek().is_some()
1527 && value_symbols.all(|s| excluded_span_starts.contains(&s.import_span.start));
1528 Some((edge.target, all_type_only, Some(span), all_client_only))
1529 })
1530 }
1531}
1532
1533impl ModuleGraph {
1534 fn names_only_type_exports(&self, target: FileId, name: &ImportedName) -> bool {
1539 let ImportedName::Named(name) = name else {
1540 return false;
1541 };
1542 matches!(
1543 self.resolve_export(target, name, ExportNamespace::Value),
1544 EffectiveExportResolution::Missing
1545 ) && matches!(
1546 self.resolve_export(target, name, ExportNamespace::Type),
1547 EffectiveExportResolution::Unique(_)
1548 )
1549 }
1550}
1551
1552fn imported_name_label(name: &ImportedName) -> String {
1553 match name {
1554 ImportedName::Named(name) => name.clone(),
1555 ImportedName::Default => "default".to_string(),
1556 ImportedName::Namespace => "*".to_string(),
1557 ImportedName::SideEffect => "side-effect".to_string(),
1558 }
1559}
1560
1561#[cfg(test)]
1562#[path = "graph_tests.rs"]
1563mod tests;