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