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 platform_family_credit;
24mod public_exports;
25mod re_exports;
26mod reachability;
27mod shortest_import_path;
28mod support_reach;
29mod test_reach;
30pub mod types;
31
32use std::path::Path;
33
34use fixedbitset::FixedBitSet;
35use rustc_hash::{FxHashMap, FxHashSet};
36
37use crate::resolve::{ResolvedModule, ResolvedReplacedModuleTarget};
38use fallow_types::discover::{DiscoveredFile, EntryPoint, FileId};
39use fallow_types::extract::{ImportLoadKind, ImportedName, ModuleLoadMechanism};
40use types::{ReferencePathInterner, ReferencePathNode, ReferenceRouteNodeId, ReferenceRoutes};
41
42pub(super) fn relativize(path: &Path, root: &Path) -> String {
46 path.strip_prefix(root)
47 .unwrap_or(path)
48 .to_string_lossy()
49 .replace('\\', "/")
50}
51
52pub use ambiguity::{AmbiguityParticipants, AmbiguousStarExport};
53pub use cycles::{CycleOptions, CycleSearch, MAX_CYCLE_LENGTH, MAX_CYCLES_PER_SCC};
54pub use effective_exports::{EffectiveExportBinding, EffectiveExportResolution, ExportNamespace};
55pub use effective_re_exports::EffectiveReExportRoute;
56pub use entry_load::{DominatingImport, EntryLoadClosure};
57pub use entry_marks::untracked_load_targets;
58pub use fan_io::{FocusFileFacts, FocusFileFactsPaths};
59pub use impact_closure::{
60 CoordinationGap, CoordinationGapPaths, ImpactClosure, ImpactClosurePaths,
61};
62pub use namespace_escapes::{NamespaceEscape, NamespaceEscapeReason};
63pub use partition_order::{PartitionOrder, PartitionOrderPaths, ReviewUnit, ReviewUnitPaths};
64pub use public_exports::PublicExportOrigin;
65pub use re_exports::GraphReExportCycle;
66pub use shortest_import_path::ImportPathHop;
67pub use test_reach::{ExportTestReach, ExportTestReachResult, TestMaskingState};
68pub use types::{
69 ExportSymbol, ModuleNode, ReExportEdge, ReachabilityRoots, ReferenceKind, ReferencePathId,
70 SymbolReference,
71};
72
73#[derive(Debug, Clone, Copy)]
75pub struct EffectiveExportOrigin<'graph> {
76 file_id: FileId,
77 export: &'graph ExportSymbol,
78}
79
80#[derive(Debug, Clone, Copy)]
82pub struct EffectiveExportSurface<'graph> {
83 binding: EffectiveExportBinding,
84 namespace: ExportNamespace,
85 export: Option<&'graph ExportSymbol>,
86 origin: Option<EffectiveExportOrigin<'graph>>,
87 local_export: bool,
88}
89
90impl<'graph> EffectiveExportSurface<'graph> {
91 #[must_use]
93 pub const fn binding(self) -> EffectiveExportBinding {
94 self.binding
95 }
96
97 #[must_use]
99 pub const fn namespace(self) -> ExportNamespace {
100 self.namespace
101 }
102
103 #[must_use]
109 pub const fn export(self) -> Option<&'graph ExportSymbol> {
110 self.export
111 }
112
113 #[must_use]
115 pub const fn origin(self) -> Option<EffectiveExportOrigin<'graph>> {
116 self.origin
117 }
118}
119
120impl<'graph> EffectiveExportOrigin<'graph> {
121 #[must_use]
123 pub const fn file_id(self) -> FileId {
124 self.file_id
125 }
126
127 #[must_use]
129 pub const fn export(self) -> &'graph ExportSymbol {
130 self.export
131 }
132}
133
134#[must_use]
143pub fn is_declaration_file_path(path: &Path) -> bool {
144 path.file_name()
145 .and_then(|n| n.to_str())
146 .is_some_and(|name| {
147 name.ends_with(".d.ts") || name.ends_with(".d.mts") || name.ends_with(".d.cts")
148 })
149}
150
151#[derive(Debug, serde::Serialize, serde::Deserialize)]
159pub struct ModuleGraph {
160 modules: Vec<ModuleNode>,
170 edges: Vec<Edge>,
172 pub package_usage: FxHashMap<String, Vec<FileId>>,
175 pub type_only_package_usage: FxHashMap<String, Vec<FileId>>,
180 pub asset_package_usage: FxHashMap<String, Vec<FileId>>,
188 pub eager_package_imports: FxHashMap<FileId, Vec<EagerPackageImport>>,
192 pub entry_points: FxHashSet<FileId>,
194 pub runtime_entry_points: FxHashSet<FileId>,
196 pub test_entry_points: FxHashSet<FileId>,
198 support_entry_points: FxHashSet<FileId>,
200 test_reachability_index: TestReachabilityIndex,
205 reference_paths: Vec<ReferencePathNode>,
207 reference_routes: ReferenceRoutes,
209 pub reverse_deps: Vec<Vec<FileId>>,
211 #[serde(skip, default)]
219 namespace_imported: FixedBitSet,
220 pub re_export_cycles: Vec<GraphReExportCycle>,
227 pub namespace_escapes: Vec<NamespaceEscape>,
230 effective_exports: effective_exports::EffectiveExportIndex,
232}
233
234#[derive(Debug, serde::Serialize, serde::Deserialize)]
241pub struct Edge {
242 source: FileId,
244 target: FileId,
246 symbols: Vec<ImportedSymbol>,
248}
249
250impl Edge {
251 #[must_use]
256 fn runs_target_code(&self) -> bool {
257 self.symbols.is_empty()
258 || self
259 .symbols
260 .iter()
261 .any(|symbol| symbol.load_kind.runs_target_code())
262 }
263
264 #[must_use]
269 fn runs_target_code_at_runtime(&self) -> bool {
270 self.symbols.is_empty()
271 || self
272 .symbols
273 .iter()
274 .any(|symbol| symbol.load_kind.runs_at_runtime())
275 }
276
277 #[must_use]
282 fn runs_target_code_in_tests(&self) -> bool {
283 self.symbols.is_empty()
284 || self
285 .symbols
286 .iter()
287 .any(|symbol| !symbol.is_type_only && symbol.load_kind.runs_target_code())
288 }
289}
290
291#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
293pub struct EagerPackageImport {
294 pub package: String,
296 pub specifier: String,
298}
299
300#[derive(Debug, serde::Serialize, serde::Deserialize)]
302pub struct ImportedSymbol {
303 pub imported_name: ImportedName,
306 pub local_name: String,
308 #[serde(with = "crate::cache::span_serde")]
310 pub import_span: oxc_span::Span,
311 pub is_type_only: bool,
314 pub(crate) is_type_only_star: bool,
317 mechanism: ModuleLoadMechanism,
319 load_kind: ImportLoadKind,
323}
324
325impl ImportedSymbol {
326 #[must_use]
328 pub const fn load_kind(&self) -> ImportLoadKind {
329 self.load_kind
330 }
331
332 #[must_use]
335 pub const fn is_eager_value(&self) -> bool {
336 self.load_kind.is_eager_value(self.is_type_only)
337 }
338
339 #[must_use]
343 pub const fn loads_target(&self) -> bool {
344 self.load_kind.loads_target()
345 }
346
347 #[must_use]
359 fn is_ambient_star(&self) -> bool {
360 self.is_type_only
361 && self.local_name.is_empty()
362 && matches!(
363 self.imported_name,
364 ImportedName::Namespace | ImportedName::Default
365 )
366 }
367
368 #[must_use]
376 fn is_value_bearing_ambient_star(&self) -> bool {
377 self.is_ambient_star() && !self.is_type_only_star
378 }
379}
380
381#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
389struct TestReachabilityIndex {
390 profile_count: usize,
391 words_per_file: usize,
392 reachable_profiles: Vec<u64>,
393 masked_profiles: Vec<MaskedTestProfiles>,
394 profile_roots: Vec<Vec<FileId>>,
397 masking_capped: bool,
401}
402
403#[derive(Debug, serde::Serialize, serde::Deserialize)]
405struct MaskedTestProfiles {
406 target: FileId,
407 profiles: Vec<u64>,
408}
409
410impl TestReachabilityIndex {
411 fn new(file_capacity: usize, profile_count: usize) -> Self {
412 let words_per_file = profile_count.div_ceil(u64::BITS as usize);
413 let storage_len = file_capacity.saturating_mul(words_per_file);
414 Self {
415 profile_count,
416 words_per_file,
417 reachable_profiles: vec![0; storage_len],
418 masked_profiles: Vec::new(),
419 profile_roots: Vec::new(),
420 masking_capped: false,
421 }
422 }
423
424 fn root_masks(&self) -> FxHashMap<FileId, Vec<FileId>> {
427 let mut masks: FxHashMap<FileId, Vec<FileId>> = FxHashMap::default();
428 for row in &self.masked_profiles {
429 for (profile, roots) in self.profile_roots.iter().enumerate() {
430 let masked = row
431 .profiles
432 .get(profile / u64::BITS as usize)
433 .is_some_and(|word| word & (1_u64 << (profile % u64::BITS as usize)) != 0);
434 if !masked {
435 continue;
436 }
437 for &root in roots {
438 masks.entry(root).or_default().push(row.target);
439 }
440 }
441 }
442 masks
443 }
444
445 fn set_sparse_masks(&mut self, masks: FxHashMap<FileId, Vec<u64>>) {
446 let mut rows: Vec<_> = masks
447 .into_iter()
448 .map(|(target, profiles)| MaskedTestProfiles { target, profiles })
449 .collect();
450 rows.sort_unstable_by_key(|row| row.target.0);
451 self.masked_profiles = rows;
452 }
453
454 fn profiles_for<'a>(&self, storage: &'a [u64], file_id: FileId) -> Option<&'a [u64]> {
455 let start = (file_id.0 as usize).checked_mul(self.words_per_file)?;
456 let end = start.checked_add(self.words_per_file)?;
457 storage.get(start..end)
458 }
459
460 fn masked_profiles_for(&self, file_id: FileId) -> Option<&[u64]> {
461 self.masked_profiles
462 .binary_search_by_key(&file_id.0, |row| row.target.0)
463 .ok()
464 .map(|index| self.masked_profiles[index].profiles.as_slice())
465 }
466
467 fn covers_reference_path(
468 &self,
469 source: FileId,
470 path: types::ReferencePathId,
471 paths: &[ReferencePathNode],
472 routes: &ReferenceRoutes,
473 ) -> bool {
474 let Some(source_profiles) = self.profiles_for(&self.reachable_profiles, source) else {
475 return false;
476 };
477
478 for (word_index, &source_word) in source_profiles.iter().enumerate() {
479 let mut active_profiles = source_word;
480 if active_profiles == 0 {
481 continue;
482 }
483
484 let mut next = Some(path);
485 while let Some(path_id) = next {
486 let Some(path_node) = paths.get(path_id.index()) else {
487 return false;
488 };
489 next = path_node.parent();
490 active_profiles = match *path_node {
491 ReferencePathNode::Hop {
492 target, mechanism, ..
493 } => self.active_hop_profiles(target, mechanism, word_index, active_profiles),
494 ReferencePathNode::Route {
495 graph,
496 start,
497 terminal,
498 start_mechanism,
499 ..
500 } => self.active_route_profiles(
501 routes,
502 graph,
503 start,
504 terminal,
505 start_mechanism,
506 word_index,
507 active_profiles,
508 ),
509 };
510 if active_profiles == 0 {
511 break;
512 }
513 }
514
515 if active_profiles != 0 {
516 return true;
517 }
518 }
519
520 false
521 }
522
523 fn active_hop_profiles(
524 &self,
525 target: FileId,
526 mechanism: ModuleLoadMechanism,
527 word_index: usize,
528 mut active_profiles: u64,
529 ) -> u64 {
530 let Some(target_word) = self
531 .profiles_for(&self.reachable_profiles, target)
532 .and_then(|profiles| profiles.get(word_index))
533 else {
534 return 0;
535 };
536 active_profiles &= target_word;
537 if matches!(mechanism, ModuleLoadMechanism::EsModule)
538 && let Some(masked_profiles) = self.masked_profiles_for(target)
539 {
540 let Some(masked_word) = masked_profiles.get(word_index) else {
541 return 0;
542 };
543 active_profiles &= !masked_word;
544 }
545 active_profiles
546 }
547
548 #[expect(
552 clippy::too_many_arguments,
553 reason = "the route identity and profile word form one evaluation contract"
554 )]
555 fn active_route_profiles(
556 &self,
557 routes: &ReferenceRoutes,
558 graph_id: types::ReferenceRouteGraphId,
559 start: ReferenceRouteNodeId,
560 terminal: ReferenceRouteNodeId,
561 start_mechanism: Option<ModuleLoadMechanism>,
562 word_index: usize,
563 candidate_profiles: u64,
564 ) -> u64 {
565 let Some(graph) = routes.graphs.get(graph_id.0 as usize) else {
566 return 0;
567 };
568 let node_count = graph.nodes.end.saturating_sub(graph.nodes.start) as usize;
569 let start_index = start.0 as usize;
570 let terminal_index = terminal.0 as usize;
571 if start_index >= node_count || terminal_index >= node_count {
572 return 0;
573 }
574
575 let mut attempted = vec![0_u64; node_count];
576 let mut pending = vec![0_u64; node_count];
577 let mut queued = vec![false; node_count];
578 let mut queue = std::collections::VecDeque::from([start_index]);
579 pending[start_index] = candidate_profiles;
580 queued[start_index] = true;
581 let mut successful_profiles = 0_u64;
582
583 while let Some(local_index) = queue.pop_front() {
584 queued[local_index] = false;
585 let incoming = pending[local_index] & !attempted[local_index];
586 pending[local_index] = 0;
587 attempted[local_index] |= incoming;
588 if incoming == 0 {
589 continue;
590 }
591
592 let Some(node) = routes.nodes.get(graph.nodes.start as usize + local_index) else {
593 return 0;
594 };
595 let active = if local_index == start_index {
596 start_mechanism.map_or(incoming, |mechanism| {
597 self.active_hop_profiles(node.target, mechanism, word_index, incoming)
598 })
599 } else {
600 self.active_hop_profiles(node.target, node.mechanism, word_index, incoming)
601 };
602 if active == 0 {
603 continue;
604 }
605 if local_index == terminal_index {
606 successful_profiles |= active;
607 continue;
608 }
609
610 let Some(successors) = routes
611 .edges
612 .get(node.successors.start as usize..node.successors.end as usize)
613 else {
614 return 0;
615 };
616 for successor in successors {
617 let successor_index = successor.0 as usize;
618 if successor_index >= node_count {
619 return 0;
620 }
621 let new_profiles = active & !attempted[successor_index] & !pending[successor_index];
622 if new_profiles == 0 {
623 continue;
624 }
625 pending[successor_index] |= new_profiles;
626 if !queued[successor_index] {
627 queued[successor_index] = true;
628 queue.push_back(successor_index);
629 }
630 }
631 }
632
633 successful_profiles
634 }
635
636 #[cfg(test)]
637 fn profile_contains(&self, storage: &[u64], file_id: FileId, profile: usize) -> bool {
638 self.profiles_for(storage, file_id)
639 .and_then(|words| words.get(profile / u64::BITS as usize))
640 .is_some_and(|word| word & (1_u64 << (profile % u64::BITS as usize)) != 0)
641 }
642
643 #[cfg(test)]
644 fn profile_reaches(&self, file_id: FileId, profile: usize) -> bool {
645 self.profile_contains(&self.reachable_profiles, file_id, profile)
646 }
647
648 #[cfg(test)]
649 fn profile_masks(&self, file_id: FileId, profile: usize) -> bool {
650 self.masked_profiles_for(file_id)
651 .and_then(|words| words.get(profile / u64::BITS as usize))
652 .is_some_and(|word| word & (1_u64 << (profile % u64::BITS as usize)) != 0)
653 }
654}
655
656#[derive(Debug, Clone, Copy)]
659pub struct OutgoingEdgeSummary<'a> {
660 pub target: FileId,
662 pub all_type_only: bool,
665 pub span_start: Option<u32>,
668 pub symbols: &'a [ImportedSymbol],
671}
672
673#[derive(Debug, Clone, PartialEq, Eq)]
675pub struct DirectImporterSummary {
676 pub source: FileId,
678 pub symbols: Vec<ImportedSymbolSummary>,
680}
681
682#[derive(Debug, Clone, PartialEq, Eq)]
684pub struct ImportedSymbolSummary {
685 pub imported: String,
688 pub local: String,
690 pub type_only: bool,
692}
693
694#[cfg(target_pointer_width = "64")]
695const _: () = assert!(std::mem::size_of::<Edge>() == 32);
696#[cfg(target_pointer_width = "64")]
697const _: () = assert!(std::mem::size_of::<ImportedSymbol>() == 64);
698
699#[cold]
700#[inline(never)]
701fn propagate_namespace_references(
702 graph: &mut ModuleGraph,
703 module_by_id: &FxHashMap<FileId, &ResolvedModule>,
704 features: build::NamespaceFeatures,
705 exposed_namespace_targets: &re_exports::ExposedNamespaceTargets,
706 reference_paths: &mut ReferencePathInterner,
707) {
708 let indexes = namespace_indexes::NamespacePropagationIndexes::new(graph, module_by_id);
709 if features.has_aliases {
710 namespace_aliases::propagate_cross_package_aliases(
711 graph,
712 module_by_id,
713 &indexes,
714 reference_paths,
715 );
716 }
717 if features.has_re_exports {
718 namespace_re_exports::propagate_namespace_re_exports(
719 graph,
720 &indexes,
721 exposed_namespace_targets,
722 reference_paths,
723 );
724 }
725}
726
727impl ModuleGraph {
728 fn resolve_entry_point_ids(
729 entry_points: &[EntryPoint],
730 path_to_id: &FxHashMap<&Path, FileId>,
731 ) -> FxHashSet<FileId> {
732 entry_points
733 .iter()
734 .filter_map(|ep| {
735 path_to_id.get(ep.path.as_path()).copied().or_else(|| {
736 dunce::canonicalize(&ep.path)
737 .ok()
738 .and_then(|path| path_to_id.get(path.as_path()).copied())
739 })
740 })
741 .collect()
742 }
743
744 pub fn build(
746 resolved_modules: &[ResolvedModule],
747 entry_points: &[EntryPoint],
748 files: &[DiscoveredFile],
749 ) -> Self {
750 Self::build_with_reachability_roots(
751 resolved_modules,
752 entry_points,
753 entry_points,
754 &[],
755 files,
756 )
757 }
758
759 fn build_with_reachability_roots(
761 resolved_modules: &[ResolvedModule],
762 entry_points: &[EntryPoint],
763 runtime_entry_points: &[EntryPoint],
764 test_entry_points: &[EntryPoint],
765 files: &[DiscoveredFile],
766 ) -> Self {
767 Self::build_with_reachability_roots_and_replacements(
768 resolved_modules,
769 &[],
770 entry_points,
771 runtime_entry_points,
772 test_entry_points,
773 files,
774 )
775 }
776
777 pub fn build_with_reachability_roots_and_replacements(
779 resolved_modules: &[ResolvedModule],
780 replaced_module_targets: &[ResolvedReplacedModuleTarget],
781 entry_points: &[EntryPoint],
782 runtime_entry_points: &[EntryPoint],
783 test_entry_points: &[EntryPoint],
784 files: &[DiscoveredFile],
785 ) -> Self {
786 Self::build_with_declaration_seeding(
787 resolved_modules,
788 replaced_module_targets,
789 &ReachabilityRoots {
790 all: entry_points,
791 runtime: runtime_entry_points,
792 test: test_entry_points,
793 consumer_checked: &FxHashSet::default(),
794 },
795 files,
796 &FxHashSet::default(),
797 )
798 }
799
800 pub fn build_with_declaration_seeding(
811 resolved_modules: &[ResolvedModule],
812 replaced_module_targets: &[ResolvedReplacedModuleTarget],
813 roots: &ReachabilityRoots<'_>,
814 files: &[DiscoveredFile],
815 unseeded_declaration_files: &FxHashSet<FileId>,
816 ) -> Self {
817 let ReachabilityRoots {
818 all: entry_points,
819 runtime: runtime_entry_points,
820 test: test_entry_points,
821 consumer_checked,
822 } = *roots;
823 let _span = tracing::info_span!("build_graph").entered();
824
825 let module_count = files.len();
826
827 let max_file_id = files
828 .iter()
829 .map(|f| f.id.0 as usize)
830 .max()
831 .map_or(0, |m| m + 1);
832 let total_capacity = max_file_id.max(module_count);
833
834 let path_to_id: FxHashMap<&Path, FileId> =
835 files.iter().map(|f| (f.path.as_path(), f.id)).collect();
836
837 let module_by_id: FxHashMap<FileId, &ResolvedModule> =
838 resolved_modules.iter().map(|m| (m.file_id, m)).collect();
839
840 let mut entry_point_ids = Self::resolve_entry_point_ids(entry_points, &path_to_id);
841 let runtime_entry_point_ids =
842 Self::resolve_entry_point_ids(runtime_entry_points, &path_to_id);
843 let test_entry_point_ids = Self::resolve_entry_point_ids(test_entry_points, &path_to_id);
844
845 for file in files {
846 if is_declaration_file_path(&file.path)
847 && !unseeded_declaration_files.contains(&file.id)
848 {
849 entry_point_ids.insert(file.id);
850 }
851 }
852
853 let (mut graph, namespace_features) = Self::populate_edges(&build::PopulateEdgesInput {
854 files,
855 module_by_id: &module_by_id,
856 entry_point_ids: &entry_point_ids,
857 runtime_entry_point_ids: &runtime_entry_point_ids,
858 test_entry_point_ids: &test_entry_point_ids,
859 module_count,
860 total_capacity,
861 });
862 graph.index_exports(resolved_modules, consumer_checked);
863
864 let test_reachability_plan = reachability::TestReachabilityPlan::new(
865 &test_entry_point_ids,
866 replaced_module_targets,
867 total_capacity,
868 );
869
870 let mut reference_paths =
871 ReferencePathInterner::new(test_reachability_plan.requires_reference_provenance());
872 let mut whole_module_targets =
873 graph.populate_references(&module_by_id, &entry_point_ids, &mut reference_paths);
874 graph.namespace_escapes = whole_module_targets.take_escapes();
875 let entry_reachable = graph.collect_reachable(&entry_point_ids, total_capacity);
880 let exposed_namespace_targets = graph.collect_exposed_namespace_targets(
881 &whole_module_targets,
882 &entry_reachable,
883 &module_by_id,
884 );
885
886 if namespace_features.has_aliases || namespace_features.has_re_exports {
887 propagate_namespace_references(
888 &mut graph,
889 &module_by_id,
890 namespace_features,
891 &exposed_namespace_targets,
892 &mut reference_paths,
893 );
894 }
895
896 graph.mark_reachable(
897 &entry_reachable,
898 &entry_point_ids,
899 &runtime_entry_point_ids,
900 test_reachability_plan,
901 total_capacity,
902 );
903
904 graph.re_export_cycles = graph.resolve_re_export_chains(
905 &module_by_id,
906 &exposed_namespace_targets,
907 consumer_checked,
908 &mut reference_paths,
909 );
910 graph.credit_platform_family_re_exports(&module_by_id);
911 namespace_escapes::normalize(&mut graph.namespace_escapes);
912 let finalized_paths = reference_paths.finalize(&mut graph.modules);
913 graph.reference_paths = finalized_paths.paths;
914 graph.reference_routes = finalized_paths.routes;
915
916 graph
917 }
918
919 #[must_use]
921 pub const fn module_count(&self) -> usize {
922 self.modules.len()
923 }
924
925 #[inline]
928 #[must_use]
929 pub fn modules(&self) -> &[ModuleNode] {
930 &self.modules
931 }
932
933 #[inline]
935 #[must_use]
936 pub fn module(&self, file_id: FileId) -> Option<&ModuleNode> {
937 self.modules.get(file_id.0 as usize)
938 }
939
940 #[cfg(any(test, feature = "testing"))]
943 #[must_use]
944 pub fn modules_mut(&mut self) -> &mut Vec<ModuleNode> {
945 &mut self.modules
946 }
947
948 #[must_use]
950 pub const fn edge_count(&self) -> usize {
951 self.edges.len()
952 }
953
954 #[must_use]
956 pub fn is_test_reachable(&self, file_id: FileId) -> bool {
957 self.modules
958 .get(file_id.0 as usize)
959 .is_some_and(ModuleNode::is_test_reachable)
960 }
961
962 #[must_use]
974 fn is_test_reference_covered(&self, export: &ExportSymbol, reference_index: usize) -> bool {
975 let Some(reference) = export.references.get(reference_index) else {
976 return false;
977 };
978 if reference.namespace != ExportNamespace::Value {
979 return false;
980 }
981 if self.test_reachability_index.profile_count == 0 {
982 return self.is_test_reachable(reference.from_file);
983 }
984
985 let Some(path) = export.reference_path(reference_index) else {
986 return false;
987 };
988
989 self.test_reachability_index.covers_reference_path(
990 reference.from_file,
991 path,
992 &self.reference_paths,
993 &self.reference_routes,
994 )
995 }
996
997 #[must_use]
1000 pub fn is_any_test_reference_covered(&self, export: &ExportSymbol) -> bool {
1001 (0..export.references.len())
1002 .any(|reference_index| self.is_test_reference_covered(export, reference_index))
1003 }
1004
1005 #[cfg(test)]
1006 fn reference_path_hops(
1007 &self,
1008 export: &ExportSymbol,
1009 reference_index: usize,
1010 ) -> Vec<(FileId, ModuleLoadMechanism)> {
1011 let mut hops = Vec::new();
1012 let mut next = export.reference_path(reference_index);
1013 while let Some(path_id) = next {
1014 let Some(node) = self.reference_paths.get(path_id.index()) else {
1015 return Vec::new();
1016 };
1017 next = node.parent();
1018 match *node {
1019 ReferencePathNode::Hop {
1020 target, mechanism, ..
1021 } => hops.push((target, mechanism)),
1022 ReferencePathNode::Route {
1023 graph,
1024 start,
1025 terminal,
1026 start_mechanism,
1027 ..
1028 } => hops.extend(self.reference_routes.canonical_hops(
1029 graph,
1030 start,
1031 terminal,
1032 start_mechanism,
1033 )),
1034 }
1035 }
1036 hops
1037 }
1038
1039 pub(crate) fn reconstruct_namespace_imported(&mut self) {
1054 let capacity = self
1055 .edges
1056 .iter()
1057 .map(|edge| edge.target.0 as usize + 1)
1058 .max()
1059 .unwrap_or(0)
1060 .max(self.modules.len());
1061 let mut bitset = FixedBitSet::with_capacity(capacity);
1062 for edge in &self.edges {
1063 if edge
1064 .symbols
1065 .iter()
1066 .any(|sym| matches!(sym.imported_name, ImportedName::Namespace))
1067 {
1068 let idx = edge.target.0 as usize;
1069 if idx < capacity {
1070 bitset.insert(idx);
1071 }
1072 }
1073 }
1074 self.namespace_imported = bitset;
1075 }
1076
1077 #[must_use]
1083 pub fn resolve_export(
1084 &self,
1085 file_id: FileId,
1086 name: &str,
1087 namespace: ExportNamespace,
1088 ) -> EffectiveExportResolution {
1089 self.effective_exports.resolve(file_id, name, namespace)
1090 }
1091
1092 #[must_use]
1099 pub fn effective_bindings_share_declaration_group(
1100 &self,
1101 left: EffectiveExportBinding,
1102 right: EffectiveExportBinding,
1103 ) -> bool {
1104 if left == right || left.origin_file() != right.origin_file() {
1105 return left == right;
1106 }
1107 let Some(right_slot) = right.origin_slot() else {
1108 return false;
1109 };
1110 self.effective_exports
1111 .declaration_group_slots(left)
1112 .contains(&right_slot)
1113 }
1114
1115 #[must_use]
1121 pub fn resolve_export_origin(
1122 &self,
1123 file_id: FileId,
1124 name: &str,
1125 namespace: ExportNamespace,
1126 ) -> Option<EffectiveExportOrigin<'_>> {
1127 let EffectiveExportResolution::Unique(binding) =
1128 self.resolve_export(file_id, name, namespace)
1129 else {
1130 return None;
1131 };
1132 self.export_binding_origin(binding)
1133 }
1134
1135 #[must_use]
1138 pub fn effective_export_surface(
1139 &self,
1140 file_id: FileId,
1141 name: &str,
1142 namespace: ExportNamespace,
1143 ) -> Option<EffectiveExportSurface<'_>> {
1144 let EffectiveExportResolution::Unique(binding) =
1145 self.resolve_export(file_id, name, namespace)
1146 else {
1147 return None;
1148 };
1149 let module = self.modules.get(file_id.0 as usize)?;
1150 let exact_surface = module.exports.iter().find(|export| {
1151 export.name.matches_str(name)
1152 && match namespace {
1153 ExportNamespace::Type => export.is_type_only,
1154 ExportNamespace::Value => !export.is_type_only,
1155 }
1156 });
1157 let surface_export = exact_surface.or_else(|| {
1158 module
1159 .exports
1160 .iter()
1161 .find(|export| export.name.matches_str(name))
1162 });
1163 let origin = self.export_binding_origin(binding);
1164 let export = surface_export.or_else(|| origin.map(|o| o.export));
1165 Some(EffectiveExportSurface {
1166 binding,
1167 namespace,
1168 export,
1169 origin,
1170 local_export: surface_export.is_some(),
1171 })
1172 }
1173
1174 #[must_use]
1180 pub fn effective_export_surface_re_export(
1181 &self,
1182 file_id: FileId,
1183 name: &str,
1184 namespace: ExportNamespace,
1185 ) -> Option<&ReExportEdge> {
1186 let EffectiveExportResolution::Unique(binding) =
1187 self.resolve_export(file_id, name, namespace)
1188 else {
1189 return None;
1190 };
1191 self.modules
1192 .get(file_id.0 as usize)?
1193 .re_exports
1194 .iter()
1195 .find(|re_export| {
1196 re_export.exported_name == name
1197 && (namespace == ExportNamespace::Type || !re_export.is_type_only)
1198 && if re_export.imported_name == "*" {
1199 binding.namespace_source() == Some(re_export.source_file)
1200 } else {
1201 self.resolve_export(
1202 re_export.source_file,
1203 &re_export.imported_name,
1204 namespace,
1205 ) == EffectiveExportResolution::Unique(binding)
1206 }
1207 })
1208 }
1209
1210 #[must_use]
1216 pub fn effective_export_surface_references(
1217 &self,
1218 file_id: FileId,
1219 name: &str,
1220 namespace: ExportNamespace,
1221 ) -> Vec<&SymbolReference> {
1222 let Some(surface) = self.effective_export_surface(file_id, name, namespace) else {
1223 return Vec::new();
1224 };
1225 let Some(export) = surface.export() else {
1226 return Vec::new();
1227 };
1228 if surface.local_export
1229 || surface
1230 .origin()
1231 .is_none_or(|origin| origin.file_id() == file_id)
1232 {
1233 return export.references_in(namespace).collect();
1234 }
1235 let mut exposed: FxHashMap<FileId, FxHashSet<String>> = FxHashMap::default();
1236 exposed.entry(file_id).or_default().insert(name.to_string());
1237 for route in self.effective_re_export_routes(file_id, name, namespace) {
1238 exposed
1239 .entry(route.barrel_file())
1240 .or_default()
1241 .insert(route.exported_name().to_string());
1242 }
1243 export
1244 .references
1245 .iter()
1246 .filter(|reference| {
1247 reference.namespace == namespace
1248 && self.reference_reaches_surface(reference, &exposed, namespace)
1249 })
1250 .collect()
1251 }
1252
1253 fn reference_reaches_surface(
1254 &self,
1255 reference: &SymbolReference,
1256 exposed: &FxHashMap<FileId, FxHashSet<String>>,
1257 namespace: ExportNamespace,
1258 ) -> bool {
1259 if reference.kind == ReferenceKind::ReExport && exposed.contains_key(&reference.from_file) {
1260 return true;
1261 }
1262 self.outgoing_symbol_edges(reference.from_file)
1263 .any(|(target, symbols)| {
1264 let Some(names) = exposed.get(&target) else {
1265 return false;
1266 };
1267 symbols.iter().any(|symbol| {
1268 symbol.import_span == reference.import_span
1269 && (namespace == ExportNamespace::Type
1270 || !symbol.is_type_only
1271 || symbol.is_value_bearing_ambient_star())
1272 && match &symbol.imported_name {
1273 ImportedName::Named(imported) => names.contains(imported.as_str()),
1274 ImportedName::Default => names.contains("default"),
1275 ImportedName::Namespace => true,
1276 ImportedName::SideEffect => false,
1277 }
1278 })
1279 })
1280 }
1281
1282 #[must_use]
1284 pub fn export_binding_origin(
1285 &self,
1286 binding: EffectiveExportBinding,
1287 ) -> Option<EffectiveExportOrigin<'_>> {
1288 let origin_file = binding.origin_file();
1289 let export = self
1290 .modules
1291 .get(origin_file.0 as usize)?
1292 .exports
1293 .get(binding.origin_slot()?)?;
1294 Some(EffectiveExportOrigin {
1295 file_id: origin_file,
1296 export,
1297 })
1298 }
1299
1300 #[must_use]
1305 pub fn unique_export_bindings(
1306 &self,
1307 file_id: FileId,
1308 namespace: ExportNamespace,
1309 ) -> FxHashSet<EffectiveExportBinding> {
1310 self.effective_exports.unique_bindings(file_id, namespace)
1311 }
1312
1313 #[must_use]
1321 pub fn importer_connects_export_origin(
1322 &self,
1323 importer: FileId,
1324 source: FileId,
1325 name: &str,
1326 namespace: ExportNamespace,
1327 ) -> bool {
1328 let Some(importer_module) = self.modules.get(importer.0 as usize) else {
1329 return false;
1330 };
1331 let re_export_count = importer_module
1332 .re_exports
1333 .iter()
1334 .filter(|re_export| re_export.source_file == source)
1335 .count();
1336 if self.edges[importer_module.edge_range.clone()]
1337 .iter()
1338 .any(|edge| edge.target == source && edge.symbols.len() > re_export_count)
1339 {
1340 return true;
1341 }
1342
1343 importer_module.re_exports.iter().any(|re_export| {
1344 if re_export.source_file != source
1345 || (namespace == ExportNamespace::Value && re_export.is_type_only)
1346 {
1347 return false;
1348 }
1349 let exported_name = if re_export.imported_name == "*" {
1350 if re_export.exported_name != "*" || name == "default" {
1351 return false;
1352 }
1353 name
1354 } else {
1355 if re_export.imported_name != name {
1356 return false;
1357 }
1358 &re_export.exported_name
1359 };
1360 self.effective_exports.contributes_through(
1361 importer,
1362 exported_name,
1363 source,
1364 name,
1365 namespace,
1366 )
1367 })
1368 }
1369
1370 #[must_use]
1373 pub fn has_namespace_import(&self, file_id: FileId) -> bool {
1374 self.namespace_imported.contains(file_id.0 as usize)
1376 }
1377
1378 #[must_use]
1380 pub fn edges_for(&self, file_id: FileId) -> Vec<FileId> {
1381 let idx = file_id.0 as usize;
1382 if idx >= self.modules.len() {
1383 return Vec::new();
1384 }
1385 let range = &self.modules[idx].edge_range;
1386 self.edges[range.clone()].iter().map(|e| e.target).collect()
1387 }
1388
1389 pub fn outgoing_symbol_edges(
1395 &self,
1396 file_id: FileId,
1397 ) -> impl Iterator<Item = (FileId, &[ImportedSymbol])> + '_ {
1398 let idx = file_id.0 as usize;
1399 let range = if idx < self.modules.len() {
1400 self.modules[idx].edge_range.clone()
1401 } else {
1402 0..0
1403 };
1404 self.edges[range]
1405 .iter()
1406 .map(|edge| (edge.target, edge.symbols.as_slice()))
1407 }
1408
1409 #[must_use]
1413 pub fn importers_of(&self, target: FileId) -> &[FileId] {
1414 self.reverse_deps
1415 .get(target.0 as usize)
1416 .map_or(&[], Vec::as_slice)
1417 }
1418
1419 #[must_use]
1424 pub fn direct_importer_summaries(&self, target: FileId) -> Vec<DirectImporterSummary> {
1425 let Some(importers) = self.reverse_deps.get(target.0 as usize) else {
1426 return Vec::new();
1427 };
1428
1429 let mut summaries = Vec::new();
1430 for &source in importers {
1431 let idx = source.0 as usize;
1432 let Some(source_node) = self.modules.get(idx) else {
1433 continue;
1434 };
1435 let mut symbols = Vec::new();
1436 for edge in &self.edges[source_node.edge_range.clone()] {
1437 if edge.target != target {
1438 continue;
1439 }
1440 symbols.extend(edge.symbols.iter().map(|symbol| ImportedSymbolSummary {
1441 imported: imported_name_label(&symbol.imported_name),
1442 local: symbol.local_name.clone(),
1443 type_only: symbol.is_type_only,
1444 }));
1445 }
1446 symbols.sort_by(|a, b| {
1447 a.imported
1448 .cmp(&b.imported)
1449 .then_with(|| a.local.cmp(&b.local))
1450 .then_with(|| a.type_only.cmp(&b.type_only))
1451 });
1452 symbols.dedup();
1453 summaries.push(DirectImporterSummary { source, symbols });
1454 }
1455 summaries.sort_by_key(|summary| summary.source.0);
1456 summaries
1457 }
1458
1459 pub fn outgoing_edge_summaries(
1479 &self,
1480 file_id: FileId,
1481 ) -> impl Iterator<Item = OutgoingEdgeSummary<'_>> + '_ {
1482 self.outgoing_symbol_edges(file_id)
1483 .filter_map(|(target, symbols)| {
1484 let mut loading = symbols.iter().filter(|s| s.loads_target()).peekable();
1485 let first = loading.peek().copied()?;
1486 let value = loading.find(|s| !s.is_type_only);
1487 Some(OutgoingEdgeSummary {
1488 target,
1489 all_type_only: value.is_none(),
1490 span_start: Some(value.unwrap_or(first).import_span.start),
1491 symbols,
1492 })
1493 })
1494 }
1495
1496 pub fn outgoing_edge_symbols(
1507 &self,
1508 file_id: FileId,
1509 ) -> impl Iterator<Item = (FileId, &[ImportedSymbol])> + '_ {
1510 let idx = file_id.0 as usize;
1511 let range = if idx < self.modules.len() {
1512 self.modules[idx].edge_range.clone()
1513 } else {
1514 0..0
1515 };
1516 self.edges[range]
1517 .iter()
1518 .map(|edge| (edge.target, edge.symbols.as_slice()))
1519 }
1520
1521 pub fn outgoing_edge_summaries_with_exclusions<'a>(
1540 &'a self,
1541 file_id: FileId,
1542 excluded_span_starts: &'a FxHashSet<u32>,
1543 ) -> impl Iterator<Item = (FileId, bool, Option<u32>, bool)> + 'a {
1544 let idx = file_id.0 as usize;
1545 let range = if idx < self.modules.len() {
1546 self.modules[idx].edge_range.clone()
1547 } else {
1548 0..0
1549 };
1550 self.edges[range].iter().filter_map(move |edge| {
1551 let loading = || edge.symbols.iter().filter(|s| s.loads_target());
1552 let first = loading().next()?;
1553 let erased = |s: &&ImportedSymbol| {
1554 s.is_type_only || self.names_only_type_exports(edge.target, &s.imported_name)
1555 };
1556 let all_type_only = loading().all(|s| erased(&s));
1557 let span = loading()
1558 .find(|s| !erased(s))
1559 .unwrap_or(first)
1560 .import_span
1561 .start;
1562 let mut value_symbols = loading().filter(|s| !erased(s)).peekable();
1566 let all_client_only = value_symbols.peek().is_some()
1567 && value_symbols.all(|s| excluded_span_starts.contains(&s.import_span.start));
1568 Some((edge.target, all_type_only, Some(span), all_client_only))
1569 })
1570 }
1571}
1572
1573impl ModuleGraph {
1574 fn names_only_type_exports(&self, target: FileId, name: &ImportedName) -> bool {
1579 let ImportedName::Named(name) = name else {
1580 return false;
1581 };
1582 matches!(
1583 self.resolve_export(target, name, ExportNamespace::Value),
1584 EffectiveExportResolution::Missing
1585 ) && matches!(
1586 self.resolve_export(target, name, ExportNamespace::Type),
1587 EffectiveExportResolution::Unique(_)
1588 )
1589 }
1590
1591 fn has_build_time_edge(&self) -> bool {
1595 self.edges.iter().any(|edge| {
1596 edge.symbols
1597 .iter()
1598 .any(|symbol| symbol.load_kind == ImportLoadKind::BuildTime)
1599 })
1600 }
1601
1602 fn collect_runtime_reachable(
1605 &self,
1606 entry_points: &FxHashSet<FileId>,
1607 total_capacity: usize,
1608 ) -> FixedBitSet {
1609 self.collect_reachable_along(
1610 entry_points,
1611 total_capacity,
1612 Edge::runs_target_code_at_runtime,
1613 )
1614 }
1615}
1616
1617fn imported_name_label(name: &ImportedName) -> String {
1618 match name {
1619 ImportedName::Named(name) => name.clone(),
1620 ImportedName::Default => "default".to_string(),
1621 ImportedName::Namespace => "*".to_string(),
1622 ImportedName::SideEffect => "side-effect".to_string(),
1623 }
1624}
1625
1626#[cfg(test)]
1627#[path = "graph_tests.rs"]
1628mod tests;