1mod ambiguity;
7mod build;
8mod cache_check;
9mod cycle_edge_span;
10mod cycles;
11mod effective_exports;
12mod effective_re_exports;
13mod entry_load;
14mod entry_marks;
15mod fan_io;
16mod impact_closure;
17mod import_elision;
18mod namespace_aliases;
19mod namespace_escapes;
20mod namespace_indexes;
21mod namespace_re_exports;
22mod narrowing;
23pub mod package_entry;
24mod partition_order;
25mod platform_family_credit;
26mod public_exports;
27mod re_exports;
28mod reachability;
29mod shortest_import_path;
30mod support_reach;
31mod test_reach;
32pub mod types;
33
34use std::path::Path;
35
36use fixedbitset::FixedBitSet;
37use rustc_hash::{FxHashMap, FxHashSet};
38
39use crate::resolve::{ResolvedModule, ResolvedReplacedModuleTarget};
40use fallow_types::discover::{DiscoveredFile, EntryPoint, FileId};
41use fallow_types::extract::{ImportLoadKind, ImportedName, ModuleLoadMechanism};
42use types::{ReferencePathInterner, ReferencePathNode, ReferenceRouteNodeId, ReferenceRoutes};
43
44pub(super) fn relativize(path: &Path, root: &Path) -> String {
48 path.strip_prefix(root)
49 .unwrap_or(path)
50 .to_string_lossy()
51 .replace('\\', "/")
52}
53
54pub use ambiguity::{AmbiguityParticipants, AmbiguousStarExport};
55pub use cycles::{CycleOptions, CycleSearch, MAX_CYCLE_LENGTH, MAX_CYCLES_PER_SCC};
56pub use effective_exports::{EffectiveExportBinding, EffectiveExportResolution, ExportNamespace};
57pub use effective_re_exports::EffectiveReExportRoute;
58pub use entry_load::{DominatingImport, EntryLoadClosure};
59pub use entry_marks::untracked_load_targets;
60pub use fan_io::{FocusFileFacts, FocusFileFactsPaths};
61pub use impact_closure::{
62 CoordinationGap, CoordinationGapPaths, ImpactClosure, ImpactClosurePaths,
63};
64pub use import_elision::{DecoratorMetadata, ImportElision, MetadataEmit};
65pub use namespace_escapes::{NamespaceEscape, NamespaceEscapeReason};
66pub use partition_order::{PartitionOrder, PartitionOrderPaths, ReviewUnit, ReviewUnitPaths};
67pub use public_exports::PublicExportOrigin;
68pub use re_exports::GraphReExportCycle;
69pub use shortest_import_path::ImportPathHop;
70pub use test_reach::{ExportTestReach, ExportTestReachResult, TestMaskingState};
71pub use types::{
72 ExportSymbol, ModuleNode, ReExportEdge, ReachabilityRoots, ReferenceKind, ReferencePathId,
73 SymbolReference,
74};
75
76#[derive(Debug, Clone, Copy)]
78pub struct EffectiveExportOrigin<'graph> {
79 file_id: FileId,
80 export: &'graph ExportSymbol,
81}
82
83#[derive(Debug, Clone, Copy)]
85pub struct EffectiveExportSurface<'graph> {
86 binding: EffectiveExportBinding,
87 namespace: ExportNamespace,
88 export: Option<&'graph ExportSymbol>,
89 origin: Option<EffectiveExportOrigin<'graph>>,
90 local_export: bool,
91}
92
93impl<'graph> EffectiveExportSurface<'graph> {
94 #[must_use]
96 pub const fn binding(self) -> EffectiveExportBinding {
97 self.binding
98 }
99
100 #[must_use]
102 pub const fn namespace(self) -> ExportNamespace {
103 self.namespace
104 }
105
106 #[must_use]
112 pub const fn export(self) -> Option<&'graph ExportSymbol> {
113 self.export
114 }
115
116 #[must_use]
118 pub const fn origin(self) -> Option<EffectiveExportOrigin<'graph>> {
119 self.origin
120 }
121}
122
123impl<'graph> EffectiveExportOrigin<'graph> {
124 #[must_use]
126 pub const fn file_id(self) -> FileId {
127 self.file_id
128 }
129
130 #[must_use]
132 pub const fn export(self) -> &'graph ExportSymbol {
133 self.export
134 }
135}
136
137#[must_use]
146pub fn is_declaration_file_path(path: &Path) -> bool {
147 path.file_name()
148 .and_then(|n| n.to_str())
149 .is_some_and(|name| {
150 name.ends_with(".d.ts") || name.ends_with(".d.mts") || name.ends_with(".d.cts")
151 })
152}
153
154#[derive(Debug, serde::Serialize, serde::Deserialize)]
162pub struct ModuleGraph {
163 modules: Vec<ModuleNode>,
173 edges: Vec<Edge>,
175 pub package_usage: FxHashMap<String, Vec<FileId>>,
178 pub type_only_package_usage: FxHashMap<String, Vec<FileId>>,
183 pub asset_package_usage: FxHashMap<String, Vec<FileId>>,
191 pub eager_package_imports: FxHashMap<FileId, Vec<EagerPackageImport>>,
195 pub entry_points: FxHashSet<FileId>,
197 pub runtime_entry_points: FxHashSet<FileId>,
199 pub test_entry_points: FxHashSet<FileId>,
201 support_entry_points: FxHashSet<FileId>,
203 test_reachability_index: TestReachabilityIndex,
208 reference_paths: Vec<ReferencePathNode>,
210 reference_routes: ReferenceRoutes,
212 pub reverse_deps: Vec<Vec<FileId>>,
214 #[serde(skip, default)]
222 namespace_imported: FixedBitSet,
223 pub re_export_cycles: Vec<GraphReExportCycle>,
230 pub namespace_escapes: Vec<NamespaceEscape>,
233 effective_exports: effective_exports::EffectiveExportIndex,
235 #[serde(skip, default)]
240 decorator_metadata_elision: FxHashMap<FileId, ImportElision>,
241}
242
243#[derive(Debug, serde::Serialize, serde::Deserialize)]
250pub struct Edge {
251 source: FileId,
253 target: FileId,
255 symbols: Vec<ImportedSymbol>,
257}
258
259impl Edge {
260 #[must_use]
265 fn runs_target_code(&self) -> bool {
266 self.symbols.is_empty()
267 || self
268 .symbols
269 .iter()
270 .any(|symbol| symbol.load_kind.runs_target_code())
271 }
272
273 #[must_use]
278 fn runs_target_code_at_runtime(&self) -> bool {
279 self.symbols.is_empty()
280 || self
281 .symbols
282 .iter()
283 .any(|symbol| symbol.load_kind.runs_at_runtime())
284 }
285
286 #[must_use]
291 fn runs_target_code_in_tests(&self) -> bool {
292 self.symbols.is_empty()
293 || self
294 .symbols
295 .iter()
296 .any(|symbol| !symbol.is_type_only && symbol.load_kind.runs_target_code())
297 }
298}
299
300#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
302pub struct EagerPackageImport {
303 pub package: String,
305 pub specifier: String,
307}
308
309#[derive(Debug, serde::Serialize, serde::Deserialize)]
311pub struct ImportedSymbol {
312 pub imported_name: ImportedName,
315 pub local_name: String,
317 #[serde(with = "crate::cache::span_serde")]
319 pub import_span: oxc_span::Span,
320 pub is_type_only: bool,
323 pub(crate) is_type_only_star: bool,
326 mechanism: ModuleLoadMechanism,
328 binding_use: import_elision::BindingUse,
333 load_kind: ImportLoadKind,
337}
338
339impl ImportedSymbol {
340 pub(crate) const fn decorator_metadata(&self) -> Option<MetadataEmit> {
344 match self.binding_use {
345 import_elision::BindingUse::DecoratorMetadata(emit) if !self.is_type_only => Some(emit),
346 _ => None,
347 }
348 }
349
350 #[must_use]
352 pub const fn load_kind(&self) -> ImportLoadKind {
353 self.load_kind
354 }
355
356 #[must_use]
359 pub const fn is_eager_value(&self) -> bool {
360 self.load_kind.is_eager_value(self.is_type_only)
361 }
362
363 #[must_use]
367 pub const fn loads_target(&self) -> bool {
368 self.load_kind.loads_target()
369 }
370
371 #[must_use]
383 fn is_ambient_star(&self) -> bool {
384 self.is_type_only
385 && self.local_name.is_empty()
386 && matches!(
387 self.imported_name,
388 ImportedName::Namespace | ImportedName::Default
389 )
390 }
391
392 #[must_use]
400 fn is_value_bearing_ambient_star(&self) -> bool {
401 self.is_ambient_star() && !self.is_type_only_star
402 }
403}
404
405#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
413struct TestReachabilityIndex {
414 profile_count: usize,
415 words_per_file: usize,
416 reachable_profiles: Vec<u64>,
417 masked_profiles: Vec<MaskedTestProfiles>,
418 profile_roots: Vec<Vec<FileId>>,
421 masking_capped: bool,
425}
426
427#[derive(Debug, serde::Serialize, serde::Deserialize)]
429struct MaskedTestProfiles {
430 target: FileId,
431 profiles: Vec<u64>,
432}
433
434impl TestReachabilityIndex {
435 fn new(file_capacity: usize, profile_count: usize) -> Self {
436 let words_per_file = profile_count.div_ceil(u64::BITS as usize);
437 let storage_len = file_capacity.saturating_mul(words_per_file);
438 Self {
439 profile_count,
440 words_per_file,
441 reachable_profiles: vec![0; storage_len],
442 masked_profiles: Vec::new(),
443 profile_roots: Vec::new(),
444 masking_capped: false,
445 }
446 }
447
448 fn root_masks(&self) -> FxHashMap<FileId, Vec<FileId>> {
451 let mut masks: FxHashMap<FileId, Vec<FileId>> = FxHashMap::default();
452 for row in &self.masked_profiles {
453 for (profile, roots) in self.profile_roots.iter().enumerate() {
454 let masked = row
455 .profiles
456 .get(profile / u64::BITS as usize)
457 .is_some_and(|word| word & (1_u64 << (profile % u64::BITS as usize)) != 0);
458 if !masked {
459 continue;
460 }
461 for &root in roots {
462 masks.entry(root).or_default().push(row.target);
463 }
464 }
465 }
466 masks
467 }
468
469 fn set_sparse_masks(&mut self, masks: FxHashMap<FileId, Vec<u64>>) {
470 let mut rows: Vec<_> = masks
471 .into_iter()
472 .map(|(target, profiles)| MaskedTestProfiles { target, profiles })
473 .collect();
474 rows.sort_unstable_by_key(|row| row.target.0);
475 self.masked_profiles = rows;
476 }
477
478 fn profiles_for<'a>(&self, storage: &'a [u64], file_id: FileId) -> Option<&'a [u64]> {
479 let start = (file_id.0 as usize).checked_mul(self.words_per_file)?;
480 let end = start.checked_add(self.words_per_file)?;
481 storage.get(start..end)
482 }
483
484 fn masked_profiles_for(&self, file_id: FileId) -> Option<&[u64]> {
485 self.masked_profiles
486 .binary_search_by_key(&file_id.0, |row| row.target.0)
487 .ok()
488 .map(|index| self.masked_profiles[index].profiles.as_slice())
489 }
490
491 fn covers_reference_path(
492 &self,
493 source: FileId,
494 path: types::ReferencePathId,
495 paths: &[ReferencePathNode],
496 routes: &ReferenceRoutes,
497 ) -> bool {
498 let Some(source_profiles) = self.profiles_for(&self.reachable_profiles, source) else {
499 return false;
500 };
501
502 for (word_index, &source_word) in source_profiles.iter().enumerate() {
503 let mut active_profiles = source_word;
504 if active_profiles == 0 {
505 continue;
506 }
507
508 let mut next = Some(path);
509 while let Some(path_id) = next {
510 let Some(path_node) = paths.get(path_id.index()) else {
511 return false;
512 };
513 next = path_node.parent();
514 active_profiles = match *path_node {
515 ReferencePathNode::Hop {
516 target, mechanism, ..
517 } => self.active_hop_profiles(target, mechanism, word_index, active_profiles),
518 ReferencePathNode::Route {
519 graph,
520 start,
521 terminal,
522 start_mechanism,
523 ..
524 } => self.active_route_profiles(
525 routes,
526 graph,
527 start,
528 terminal,
529 start_mechanism,
530 word_index,
531 active_profiles,
532 ),
533 };
534 if active_profiles == 0 {
535 break;
536 }
537 }
538
539 if active_profiles != 0 {
540 return true;
541 }
542 }
543
544 false
545 }
546
547 fn active_hop_profiles(
548 &self,
549 target: FileId,
550 mechanism: ModuleLoadMechanism,
551 word_index: usize,
552 mut active_profiles: u64,
553 ) -> u64 {
554 let Some(target_word) = self
555 .profiles_for(&self.reachable_profiles, target)
556 .and_then(|profiles| profiles.get(word_index))
557 else {
558 return 0;
559 };
560 active_profiles &= target_word;
561 if matches!(mechanism, ModuleLoadMechanism::EsModule)
562 && let Some(masked_profiles) = self.masked_profiles_for(target)
563 {
564 let Some(masked_word) = masked_profiles.get(word_index) else {
565 return 0;
566 };
567 active_profiles &= !masked_word;
568 }
569 active_profiles
570 }
571
572 #[expect(
576 clippy::too_many_arguments,
577 reason = "the route identity and profile word form one evaluation contract"
578 )]
579 fn active_route_profiles(
580 &self,
581 routes: &ReferenceRoutes,
582 graph_id: types::ReferenceRouteGraphId,
583 start: ReferenceRouteNodeId,
584 terminal: ReferenceRouteNodeId,
585 start_mechanism: Option<ModuleLoadMechanism>,
586 word_index: usize,
587 candidate_profiles: u64,
588 ) -> u64 {
589 let Some(graph) = routes.graphs.get(graph_id.0 as usize) else {
590 return 0;
591 };
592 let node_count = graph.nodes.end.saturating_sub(graph.nodes.start) as usize;
593 let start_index = start.0 as usize;
594 let terminal_index = terminal.0 as usize;
595 if start_index >= node_count || terminal_index >= node_count {
596 return 0;
597 }
598
599 let mut attempted = vec![0_u64; node_count];
600 let mut pending = vec![0_u64; node_count];
601 let mut queued = vec![false; node_count];
602 let mut queue = std::collections::VecDeque::from([start_index]);
603 pending[start_index] = candidate_profiles;
604 queued[start_index] = true;
605 let mut successful_profiles = 0_u64;
606
607 while let Some(local_index) = queue.pop_front() {
608 queued[local_index] = false;
609 let incoming = pending[local_index] & !attempted[local_index];
610 pending[local_index] = 0;
611 attempted[local_index] |= incoming;
612 if incoming == 0 {
613 continue;
614 }
615
616 let Some(node) = routes.nodes.get(graph.nodes.start as usize + local_index) else {
617 return 0;
618 };
619 let active = if local_index == start_index {
620 start_mechanism.map_or(incoming, |mechanism| {
621 self.active_hop_profiles(node.target, mechanism, word_index, incoming)
622 })
623 } else {
624 self.active_hop_profiles(node.target, node.mechanism, word_index, incoming)
625 };
626 if active == 0 {
627 continue;
628 }
629 if local_index == terminal_index {
630 successful_profiles |= active;
631 continue;
632 }
633
634 let Some(successors) = routes
635 .edges
636 .get(node.successors.start as usize..node.successors.end as usize)
637 else {
638 return 0;
639 };
640 for successor in successors {
641 let successor_index = successor.0 as usize;
642 if successor_index >= node_count {
643 return 0;
644 }
645 let new_profiles = active & !attempted[successor_index] & !pending[successor_index];
646 if new_profiles == 0 {
647 continue;
648 }
649 pending[successor_index] |= new_profiles;
650 if !queued[successor_index] {
651 queued[successor_index] = true;
652 queue.push_back(successor_index);
653 }
654 }
655 }
656
657 successful_profiles
658 }
659
660 #[cfg(test)]
661 fn profile_contains(&self, storage: &[u64], file_id: FileId, profile: usize) -> bool {
662 self.profiles_for(storage, file_id)
663 .and_then(|words| words.get(profile / u64::BITS as usize))
664 .is_some_and(|word| word & (1_u64 << (profile % u64::BITS as usize)) != 0)
665 }
666
667 #[cfg(test)]
668 fn profile_reaches(&self, file_id: FileId, profile: usize) -> bool {
669 self.profile_contains(&self.reachable_profiles, file_id, profile)
670 }
671
672 #[cfg(test)]
673 fn profile_masks(&self, file_id: FileId, profile: usize) -> bool {
674 self.masked_profiles_for(file_id)
675 .and_then(|words| words.get(profile / u64::BITS as usize))
676 .is_some_and(|word| word & (1_u64 << (profile % u64::BITS as usize)) != 0)
677 }
678}
679
680#[derive(Debug, Clone, Copy)]
683pub struct OutgoingEdgeSummary<'a> {
684 pub target: FileId,
686 pub all_type_only: bool,
689 pub span_start: Option<u32>,
692 pub symbols: &'a [ImportedSymbol],
695}
696
697#[derive(Debug, Clone, PartialEq, Eq)]
699pub struct DirectImporterSummary {
700 pub source: FileId,
702 pub symbols: Vec<ImportedSymbolSummary>,
704}
705
706#[derive(Debug, Clone, PartialEq, Eq)]
708pub struct ImportedSymbolSummary {
709 pub imported: String,
712 pub local: String,
714 pub type_only: bool,
716}
717
718#[cfg(target_pointer_width = "64")]
719const _: () = assert!(std::mem::size_of::<Edge>() == 32);
720#[cfg(target_pointer_width = "64")]
721const _: () = assert!(std::mem::size_of::<ImportedSymbol>() == 64);
722
723#[cold]
724#[inline(never)]
725fn propagate_namespace_references(
726 graph: &mut ModuleGraph,
727 module_by_id: &FxHashMap<FileId, &ResolvedModule>,
728 features: build::NamespaceFeatures,
729 exposed_namespace_targets: &re_exports::ExposedNamespaceTargets,
730 reference_paths: &mut ReferencePathInterner,
731) {
732 let indexes = namespace_indexes::NamespacePropagationIndexes::new(graph, module_by_id);
733 if features.has_aliases {
734 namespace_aliases::propagate_cross_package_aliases(
735 graph,
736 module_by_id,
737 &indexes,
738 reference_paths,
739 );
740 }
741 if features.has_re_exports {
742 namespace_re_exports::propagate_namespace_re_exports(
743 graph,
744 &indexes,
745 exposed_namespace_targets,
746 reference_paths,
747 );
748 }
749}
750
751impl ModuleGraph {
752 #[must_use]
758 pub fn describes_files(&self, files: &[DiscoveredFile]) -> bool {
759 self.modules.len() == files.len()
760 && self.has_valid_structure()
761 && self
762 .modules
763 .iter()
764 .zip(files)
765 .all(|(module, file)| (module.file_id, &module.path) == (file.id, &file.path))
766 }
767
768 fn resolve_entry_point_ids(
769 entry_points: &[EntryPoint],
770 path_to_id: &FxHashMap<&Path, FileId>,
771 ) -> FxHashSet<FileId> {
772 entry_points
773 .iter()
774 .filter_map(|ep| {
775 path_to_id.get(ep.path.as_path()).copied().or_else(|| {
776 dunce::canonicalize(&ep.path)
777 .ok()
778 .and_then(|path| path_to_id.get(path.as_path()).copied())
779 })
780 })
781 .collect()
782 }
783
784 pub fn build(
786 resolved_modules: &[ResolvedModule],
787 entry_points: &[EntryPoint],
788 files: &[DiscoveredFile],
789 ) -> Self {
790 Self::build_with_reachability_roots(
791 resolved_modules,
792 entry_points,
793 entry_points,
794 &[],
795 files,
796 )
797 }
798
799 fn build_with_reachability_roots(
801 resolved_modules: &[ResolvedModule],
802 entry_points: &[EntryPoint],
803 runtime_entry_points: &[EntryPoint],
804 test_entry_points: &[EntryPoint],
805 files: &[DiscoveredFile],
806 ) -> Self {
807 Self::build_with_reachability_roots_and_replacements(
808 resolved_modules,
809 &[],
810 entry_points,
811 runtime_entry_points,
812 test_entry_points,
813 files,
814 )
815 }
816
817 pub fn build_with_reachability_roots_and_replacements(
819 resolved_modules: &[ResolvedModule],
820 replaced_module_targets: &[ResolvedReplacedModuleTarget],
821 entry_points: &[EntryPoint],
822 runtime_entry_points: &[EntryPoint],
823 test_entry_points: &[EntryPoint],
824 files: &[DiscoveredFile],
825 ) -> Self {
826 Self::build_with_declaration_seeding(
827 resolved_modules,
828 replaced_module_targets,
829 &ReachabilityRoots {
830 all: entry_points,
831 runtime: runtime_entry_points,
832 test: test_entry_points,
833 consumer_checked: &FxHashSet::default(),
834 },
835 files,
836 &FxHashSet::default(),
837 )
838 }
839
840 pub fn build_with_declaration_seeding(
851 resolved_modules: &[ResolvedModule],
852 replaced_module_targets: &[ResolvedReplacedModuleTarget],
853 roots: &ReachabilityRoots<'_>,
854 files: &[DiscoveredFile],
855 unseeded_declaration_files: &FxHashSet<FileId>,
856 ) -> Self {
857 let ReachabilityRoots {
858 all: entry_points,
859 runtime: runtime_entry_points,
860 test: test_entry_points,
861 consumer_checked,
862 } = *roots;
863 let _span = tracing::info_span!("build_graph").entered();
864
865 let module_count = files.len();
866
867 let max_file_id = files
868 .iter()
869 .map(|f| f.id.0 as usize)
870 .max()
871 .map_or(0, |m| m + 1);
872 let total_capacity = max_file_id.max(module_count);
873
874 let path_to_id: FxHashMap<&Path, FileId> =
875 files.iter().map(|f| (f.path.as_path(), f.id)).collect();
876
877 let module_by_id: FxHashMap<FileId, &ResolvedModule> =
878 resolved_modules.iter().map(|m| (m.file_id, m)).collect();
879
880 let mut entry_point_ids = Self::resolve_entry_point_ids(entry_points, &path_to_id);
881 let runtime_entry_point_ids =
882 Self::resolve_entry_point_ids(runtime_entry_points, &path_to_id);
883 let test_entry_point_ids = Self::resolve_entry_point_ids(test_entry_points, &path_to_id);
884
885 for file in files {
886 if is_declaration_file_path(&file.path)
887 && !unseeded_declaration_files.contains(&file.id)
888 {
889 entry_point_ids.insert(file.id);
890 }
891 }
892
893 let (mut graph, namespace_features) = Self::populate_edges(&build::PopulateEdgesInput {
894 files,
895 module_by_id: &module_by_id,
896 entry_point_ids: &entry_point_ids,
897 runtime_entry_point_ids: &runtime_entry_point_ids,
898 test_entry_point_ids: &test_entry_point_ids,
899 module_count,
900 total_capacity,
901 });
902 graph.index_exports(resolved_modules, consumer_checked);
903
904 let test_reachability_plan = reachability::TestReachabilityPlan::new(
905 &test_entry_point_ids,
906 replaced_module_targets,
907 total_capacity,
908 );
909
910 let mut reference_paths =
911 ReferencePathInterner::new(test_reachability_plan.requires_reference_provenance());
912 let mut whole_module_targets =
913 graph.populate_references(&module_by_id, &entry_point_ids, &mut reference_paths);
914 graph.namespace_escapes = whole_module_targets.take_escapes();
915 let entry_reachable = graph.collect_reachable(&entry_point_ids, total_capacity);
920 let exposed_namespace_targets = graph.collect_exposed_namespace_targets(
921 &whole_module_targets,
922 &entry_reachable,
923 &module_by_id,
924 );
925
926 if namespace_features.has_aliases || namespace_features.has_re_exports {
927 propagate_namespace_references(
928 &mut graph,
929 &module_by_id,
930 namespace_features,
931 &exposed_namespace_targets,
932 &mut reference_paths,
933 );
934 }
935
936 graph.mark_reachable(
937 &entry_reachable,
938 &entry_point_ids,
939 &runtime_entry_point_ids,
940 test_reachability_plan,
941 total_capacity,
942 );
943
944 graph.re_export_cycles = graph.resolve_re_export_chains(
945 &module_by_id,
946 &exposed_namespace_targets,
947 consumer_checked,
948 &mut reference_paths,
949 );
950 graph.credit_platform_family_re_exports(&module_by_id);
951 namespace_escapes::normalize(&mut graph.namespace_escapes);
952 let finalized_paths = reference_paths.finalize(&mut graph.modules);
953 graph.reference_paths = finalized_paths.paths;
954 graph.reference_routes = finalized_paths.routes;
955
956 graph
957 }
958
959 #[must_use]
961 pub const fn module_count(&self) -> usize {
962 self.modules.len()
963 }
964
965 #[inline]
968 #[must_use]
969 pub fn modules(&self) -> &[ModuleNode] {
970 &self.modules
971 }
972
973 #[inline]
975 #[must_use]
976 pub fn module(&self, file_id: FileId) -> Option<&ModuleNode> {
977 self.modules.get(file_id.0 as usize)
978 }
979
980 #[cfg(any(test, feature = "testing"))]
983 #[must_use]
984 pub fn modules_mut(&mut self) -> &mut Vec<ModuleNode> {
985 &mut self.modules
986 }
987
988 #[must_use]
990 pub const fn edge_count(&self) -> usize {
991 self.edges.len()
992 }
993
994 #[must_use]
996 pub fn is_test_reachable(&self, file_id: FileId) -> bool {
997 self.modules
998 .get(file_id.0 as usize)
999 .is_some_and(ModuleNode::is_test_reachable)
1000 }
1001
1002 #[must_use]
1013 fn is_test_reference_covered(&self, export: &ExportSymbol, reference_index: usize) -> bool {
1014 let Some(reference) = export.references.get(reference_index) else {
1015 return false;
1016 };
1017 if !self.reference_runs_export(reference) {
1018 return false;
1019 }
1020 if self.test_reachability_index.profile_count == 0 {
1021 return self.is_test_reachable(reference.from_file);
1022 }
1023
1024 let Some(path) = export.reference_path(reference_index) else {
1025 return false;
1026 };
1027
1028 self.test_reachability_index.covers_reference_path(
1029 reference.from_file,
1030 path,
1031 &self.reference_paths,
1032 &self.reference_routes,
1033 )
1034 }
1035
1036 fn reference_runs_export(&self, reference: &SymbolReference) -> bool {
1042 reference.namespace == ExportNamespace::Value
1043 || reference.decorator_metadata.is_some_and(|emit| {
1044 self.decorator_metadata_elision
1045 .get(&reference.from_file)
1046 .is_some_and(|elision| elision.reads_decorator_metadata(emit))
1047 })
1048 }
1049
1050 pub fn read_decorator_metadata_options(
1055 &mut self,
1056 elision_of: &mut dyn FnMut(&Path) -> ImportElision,
1057 ) {
1058 self.decorator_metadata_elision = self
1059 .modules
1060 .iter()
1061 .filter(|module| module.has_decorator_metadata())
1062 .map(|module| {
1063 let elision = import_elision::ImporterElision::new(&module.path)
1064 .get(&module.path, elision_of);
1065 (module.file_id, elision)
1066 })
1067 .collect();
1068 }
1069
1070 #[must_use]
1073 pub fn is_any_test_reference_covered(&self, export: &ExportSymbol) -> bool {
1074 (0..export.references.len())
1075 .any(|reference_index| self.is_test_reference_covered(export, reference_index))
1076 }
1077
1078 #[cfg(test)]
1079 fn reference_path_hops(
1080 &self,
1081 export: &ExportSymbol,
1082 reference_index: usize,
1083 ) -> Vec<(FileId, ModuleLoadMechanism)> {
1084 let mut hops = Vec::new();
1085 let mut next = export.reference_path(reference_index);
1086 while let Some(path_id) = next {
1087 let Some(node) = self.reference_paths.get(path_id.index()) else {
1088 return Vec::new();
1089 };
1090 next = node.parent();
1091 match *node {
1092 ReferencePathNode::Hop {
1093 target, mechanism, ..
1094 } => hops.push((target, mechanism)),
1095 ReferencePathNode::Route {
1096 graph,
1097 start,
1098 terminal,
1099 start_mechanism,
1100 ..
1101 } => hops.extend(self.reference_routes.canonical_hops(
1102 graph,
1103 start,
1104 terminal,
1105 start_mechanism,
1106 )),
1107 }
1108 }
1109 hops
1110 }
1111
1112 pub(crate) fn reconstruct_namespace_imported(&mut self) {
1127 let capacity = self
1128 .edges
1129 .iter()
1130 .map(|edge| edge.target.0 as usize + 1)
1131 .max()
1132 .unwrap_or(0)
1133 .max(self.modules.len());
1134 let mut bitset = FixedBitSet::with_capacity(capacity);
1135 for edge in &self.edges {
1136 if edge
1137 .symbols
1138 .iter()
1139 .any(|sym| matches!(sym.imported_name, ImportedName::Namespace))
1140 {
1141 let idx = edge.target.0 as usize;
1142 if idx < capacity {
1143 bitset.insert(idx);
1144 }
1145 }
1146 }
1147 self.namespace_imported = bitset;
1148 }
1149
1150 #[must_use]
1156 pub fn resolve_export(
1157 &self,
1158 file_id: FileId,
1159 name: &str,
1160 namespace: ExportNamespace,
1161 ) -> EffectiveExportResolution {
1162 self.effective_exports.resolve(file_id, name, namespace)
1163 }
1164
1165 #[must_use]
1172 pub fn effective_bindings_share_declaration_group(
1173 &self,
1174 left: EffectiveExportBinding,
1175 right: EffectiveExportBinding,
1176 ) -> bool {
1177 if left == right || left.origin_file() != right.origin_file() {
1178 return left == right;
1179 }
1180 let Some(right_slot) = right.origin_slot() else {
1181 return false;
1182 };
1183 self.effective_exports
1184 .declaration_group_slots(left)
1185 .contains(&right_slot)
1186 }
1187
1188 #[must_use]
1194 pub fn resolve_export_origin(
1195 &self,
1196 file_id: FileId,
1197 name: &str,
1198 namespace: ExportNamespace,
1199 ) -> Option<EffectiveExportOrigin<'_>> {
1200 let EffectiveExportResolution::Unique(binding) =
1201 self.resolve_export(file_id, name, namespace)
1202 else {
1203 return None;
1204 };
1205 self.export_binding_origin(binding)
1206 }
1207
1208 #[must_use]
1211 pub fn effective_export_surface(
1212 &self,
1213 file_id: FileId,
1214 name: &str,
1215 namespace: ExportNamespace,
1216 ) -> Option<EffectiveExportSurface<'_>> {
1217 let EffectiveExportResolution::Unique(binding) =
1218 self.resolve_export(file_id, name, namespace)
1219 else {
1220 return None;
1221 };
1222 let module = self.modules.get(file_id.0 as usize)?;
1223 let exact_surface = module.exports.iter().find(|export| {
1224 export.name.matches_str(name)
1225 && match namespace {
1226 ExportNamespace::Type => export.is_type_only,
1227 ExportNamespace::Value => !export.is_type_only,
1228 }
1229 });
1230 let surface_export = exact_surface.or_else(|| {
1231 module
1232 .exports
1233 .iter()
1234 .find(|export| export.name.matches_str(name))
1235 });
1236 let origin = self.export_binding_origin(binding);
1237 let export = surface_export.or_else(|| origin.map(|o| o.export));
1238 Some(EffectiveExportSurface {
1239 binding,
1240 namespace,
1241 export,
1242 origin,
1243 local_export: surface_export.is_some(),
1244 })
1245 }
1246
1247 #[must_use]
1253 pub fn effective_export_surface_re_export(
1254 &self,
1255 file_id: FileId,
1256 name: &str,
1257 namespace: ExportNamespace,
1258 ) -> Option<&ReExportEdge> {
1259 let EffectiveExportResolution::Unique(binding) =
1260 self.resolve_export(file_id, name, namespace)
1261 else {
1262 return None;
1263 };
1264 self.modules
1265 .get(file_id.0 as usize)?
1266 .re_exports
1267 .iter()
1268 .find(|re_export| {
1269 re_export.exported_name == name
1270 && (namespace == ExportNamespace::Type || !re_export.is_type_only)
1271 && if re_export.imported_name == "*" {
1272 binding.namespace_source() == Some(re_export.source_file)
1273 } else {
1274 self.resolve_export(
1275 re_export.source_file,
1276 &re_export.imported_name,
1277 namespace,
1278 ) == EffectiveExportResolution::Unique(binding)
1279 }
1280 })
1281 }
1282
1283 #[must_use]
1289 pub fn effective_export_surface_references(
1290 &self,
1291 file_id: FileId,
1292 name: &str,
1293 namespace: ExportNamespace,
1294 ) -> Vec<&SymbolReference> {
1295 let Some(surface) = self.effective_export_surface(file_id, name, namespace) else {
1296 return Vec::new();
1297 };
1298 let Some(export) = surface.export() else {
1299 return Vec::new();
1300 };
1301 if surface.local_export
1302 || surface
1303 .origin()
1304 .is_none_or(|origin| origin.file_id() == file_id)
1305 {
1306 return export.references_in(namespace).collect();
1307 }
1308 let mut exposed: FxHashMap<FileId, FxHashSet<String>> = FxHashMap::default();
1309 exposed.entry(file_id).or_default().insert(name.to_string());
1310 for route in self.effective_re_export_routes(file_id, name, namespace) {
1311 exposed
1312 .entry(route.barrel_file())
1313 .or_default()
1314 .insert(route.exported_name().to_string());
1315 }
1316 export
1317 .references
1318 .iter()
1319 .filter(|reference| {
1320 reference.namespace == namespace
1321 && self.reference_reaches_surface(reference, &exposed, namespace)
1322 })
1323 .collect()
1324 }
1325
1326 fn reference_reaches_surface(
1327 &self,
1328 reference: &SymbolReference,
1329 exposed: &FxHashMap<FileId, FxHashSet<String>>,
1330 namespace: ExportNamespace,
1331 ) -> bool {
1332 if reference.kind == ReferenceKind::ReExport && exposed.contains_key(&reference.from_file) {
1333 return true;
1334 }
1335 self.outgoing_symbol_edges(reference.from_file)
1336 .any(|(target, symbols)| {
1337 let Some(names) = exposed.get(&target) else {
1338 return false;
1339 };
1340 symbols.iter().any(|symbol| {
1341 symbol.import_span == reference.import_span
1342 && (namespace == ExportNamespace::Type
1343 || !symbol.is_type_only
1344 || symbol.is_value_bearing_ambient_star())
1345 && match &symbol.imported_name {
1346 ImportedName::Named(imported) => names.contains(imported.as_str()),
1347 ImportedName::Default => names.contains("default"),
1348 ImportedName::Namespace => true,
1349 ImportedName::SideEffect => false,
1350 }
1351 })
1352 })
1353 }
1354
1355 #[must_use]
1357 pub fn export_binding_origin(
1358 &self,
1359 binding: EffectiveExportBinding,
1360 ) -> Option<EffectiveExportOrigin<'_>> {
1361 let origin_file = binding.origin_file();
1362 let export = self
1363 .modules
1364 .get(origin_file.0 as usize)?
1365 .exports
1366 .get(binding.origin_slot()?)?;
1367 Some(EffectiveExportOrigin {
1368 file_id: origin_file,
1369 export,
1370 })
1371 }
1372
1373 #[must_use]
1378 pub fn unique_export_bindings(
1379 &self,
1380 file_id: FileId,
1381 namespace: ExportNamespace,
1382 ) -> FxHashSet<EffectiveExportBinding> {
1383 self.effective_exports.unique_bindings(file_id, namespace)
1384 }
1385
1386 #[must_use]
1394 pub fn importer_connects_export_origin(
1395 &self,
1396 importer: FileId,
1397 source: FileId,
1398 name: &str,
1399 namespace: ExportNamespace,
1400 ) -> bool {
1401 let Some(importer_module) = self.modules.get(importer.0 as usize) else {
1402 return false;
1403 };
1404 let re_export_count = importer_module
1405 .re_exports
1406 .iter()
1407 .filter(|re_export| re_export.source_file == source)
1408 .count();
1409 if self.edges[importer_module.edge_range.clone()]
1410 .iter()
1411 .any(|edge| edge.target == source && edge.symbols.len() > re_export_count)
1412 {
1413 return true;
1414 }
1415
1416 importer_module.re_exports.iter().any(|re_export| {
1417 if re_export.source_file != source
1418 || (namespace == ExportNamespace::Value && re_export.is_type_only)
1419 {
1420 return false;
1421 }
1422 let exported_name = if re_export.imported_name == "*" {
1423 if re_export.exported_name != "*" || name == "default" {
1424 return false;
1425 }
1426 name
1427 } else {
1428 if re_export.imported_name != name {
1429 return false;
1430 }
1431 &re_export.exported_name
1432 };
1433 self.effective_exports.contributes_through(
1434 importer,
1435 exported_name,
1436 source,
1437 name,
1438 namespace,
1439 )
1440 })
1441 }
1442
1443 #[must_use]
1446 pub fn has_namespace_import(&self, file_id: FileId) -> bool {
1447 self.namespace_imported.contains(file_id.0 as usize)
1449 }
1450
1451 #[must_use]
1453 pub fn edges_for(&self, file_id: FileId) -> Vec<FileId> {
1454 let idx = file_id.0 as usize;
1455 if idx >= self.modules.len() {
1456 return Vec::new();
1457 }
1458 let range = &self.modules[idx].edge_range;
1459 self.edges[range.clone()].iter().map(|e| e.target).collect()
1460 }
1461
1462 pub fn outgoing_symbol_edges(
1468 &self,
1469 file_id: FileId,
1470 ) -> impl Iterator<Item = (FileId, &[ImportedSymbol])> + '_ {
1471 let idx = file_id.0 as usize;
1472 let range = if idx < self.modules.len() {
1473 self.modules[idx].edge_range.clone()
1474 } else {
1475 0..0
1476 };
1477 self.edges[range]
1478 .iter()
1479 .map(|edge| (edge.target, edge.symbols.as_slice()))
1480 }
1481
1482 #[must_use]
1486 pub fn importers_of(&self, target: FileId) -> &[FileId] {
1487 self.reverse_deps
1488 .get(target.0 as usize)
1489 .map_or(&[], Vec::as_slice)
1490 }
1491
1492 #[must_use]
1497 pub fn direct_importer_summaries(&self, target: FileId) -> Vec<DirectImporterSummary> {
1498 let Some(importers) = self.reverse_deps.get(target.0 as usize) else {
1499 return Vec::new();
1500 };
1501
1502 let mut summaries = Vec::new();
1503 for &source in importers {
1504 let idx = source.0 as usize;
1505 let Some(source_node) = self.modules.get(idx) else {
1506 continue;
1507 };
1508 let mut symbols = Vec::new();
1509 for edge in &self.edges[source_node.edge_range.clone()] {
1510 if edge.target != target {
1511 continue;
1512 }
1513 symbols.extend(edge.symbols.iter().map(|symbol| ImportedSymbolSummary {
1514 imported: imported_name_label(&symbol.imported_name),
1515 local: symbol.local_name.clone(),
1516 type_only: symbol.is_type_only,
1517 }));
1518 }
1519 symbols.sort_by(|a, b| {
1520 a.imported
1521 .cmp(&b.imported)
1522 .then_with(|| a.local.cmp(&b.local))
1523 .then_with(|| a.type_only.cmp(&b.type_only))
1524 });
1525 symbols.dedup();
1526 summaries.push(DirectImporterSummary { source, symbols });
1527 }
1528 summaries.sort_by_key(|summary| summary.source.0);
1529 summaries
1530 }
1531
1532 pub fn outgoing_edge_summaries(
1552 &self,
1553 file_id: FileId,
1554 ) -> impl Iterator<Item = OutgoingEdgeSummary<'_>> + '_ {
1555 self.outgoing_symbol_edges(file_id)
1556 .filter_map(|(target, symbols)| {
1557 let mut loading = symbols.iter().filter(|s| s.loads_target()).peekable();
1558 let first = loading.peek().copied()?;
1559 let value = loading.find(|s| !s.is_type_only);
1560 Some(OutgoingEdgeSummary {
1561 target,
1562 all_type_only: value.is_none(),
1563 span_start: Some(value.unwrap_or(first).import_span.start),
1564 symbols,
1565 })
1566 })
1567 }
1568
1569 pub fn outgoing_edge_symbols(
1580 &self,
1581 file_id: FileId,
1582 ) -> impl Iterator<Item = (FileId, &[ImportedSymbol])> + '_ {
1583 let idx = file_id.0 as usize;
1584 let range = if idx < self.modules.len() {
1585 self.modules[idx].edge_range.clone()
1586 } else {
1587 0..0
1588 };
1589 self.edges[range]
1590 .iter()
1591 .map(|edge| (edge.target, edge.symbols.as_slice()))
1592 }
1593
1594 pub fn outgoing_edge_summaries_with_exclusions<'a>(
1613 &'a self,
1614 file_id: FileId,
1615 excluded_span_starts: &'a FxHashSet<u32>,
1616 ) -> impl Iterator<Item = (FileId, bool, Option<u32>, bool)> + 'a {
1617 let idx = file_id.0 as usize;
1618 let range = if idx < self.modules.len() {
1619 self.modules[idx].edge_range.clone()
1620 } else {
1621 0..0
1622 };
1623 self.edges[range].iter().filter_map(move |edge| {
1624 let loading = || edge.symbols.iter().filter(|s| s.loads_target());
1625 let first = loading().next()?;
1626 let erased = |s: &&ImportedSymbol| {
1627 s.is_type_only || self.names_only_type_exports(edge.target, &s.imported_name)
1628 };
1629 let all_type_only = loading().all(|s| erased(&s));
1630 let span = loading()
1631 .find(|s| !erased(s))
1632 .unwrap_or(first)
1633 .import_span
1634 .start;
1635 let mut value_symbols = loading().filter(|s| !erased(s)).peekable();
1639 let all_client_only = value_symbols.peek().is_some()
1640 && value_symbols.all(|s| excluded_span_starts.contains(&s.import_span.start));
1641 Some((edge.target, all_type_only, Some(span), all_client_only))
1642 })
1643 }
1644}
1645
1646impl ModuleGraph {
1647 fn names_only_type_exports(&self, target: FileId, name: &ImportedName) -> bool {
1652 let ImportedName::Named(name) = name else {
1653 return false;
1654 };
1655 matches!(
1656 self.resolve_export(target, name, ExportNamespace::Value),
1657 EffectiveExportResolution::Missing
1658 ) && matches!(
1659 self.resolve_export(target, name, ExportNamespace::Type),
1660 EffectiveExportResolution::Unique(_)
1661 )
1662 }
1663
1664 fn has_build_time_edge(&self) -> bool {
1668 self.edges.iter().any(|edge| {
1669 edge.symbols
1670 .iter()
1671 .any(|symbol| symbol.load_kind == ImportLoadKind::BuildTime)
1672 })
1673 }
1674
1675 fn collect_runtime_reachable(
1678 &self,
1679 entry_points: &FxHashSet<FileId>,
1680 total_capacity: usize,
1681 ) -> FixedBitSet {
1682 self.collect_reachable_along(
1683 entry_points,
1684 total_capacity,
1685 Edge::runs_target_code_at_runtime,
1686 )
1687 }
1688}
1689
1690fn imported_name_label(name: &ImportedName) -> String {
1691 match name {
1692 ImportedName::Named(name) => name.clone(),
1693 ImportedName::Default => "default".to_string(),
1694 ImportedName::Namespace => "*".to_string(),
1695 ImportedName::SideEffect => "side-effect".to_string(),
1696 }
1697}
1698
1699#[cfg(test)]
1700#[path = "graph_tests.rs"]
1701mod tests;