1use std::cmp::Ordering;
4use std::num::NonZeroU32;
5use std::ops::Range;
6use std::path::PathBuf;
7
8use fallow_types::discover::{EntryPoint, FileId};
9use fallow_types::extract::{ExportName, ModuleLoadMechanism, VisibilityTag};
10use rustc_hash::{FxHashMap, FxHashSet};
11
12#[derive(Debug, Clone, Copy)]
14pub struct ReachabilityRoots<'a> {
15 pub all: &'a [EntryPoint],
17 pub runtime: &'a [EntryPoint],
19 pub test: &'a [EntryPoint],
21 pub consumer_checked: &'a FxHashSet<FileId>,
25}
26
27#[derive(Debug, serde::Serialize, serde::Deserialize)]
33pub struct ModuleNode {
34 pub file_id: FileId,
36 pub path: PathBuf,
38 pub edge_range: Range<usize>,
40 pub exports: Vec<ExportSymbol>,
42 pub re_exports: Vec<ReExportEdge>,
44 pub(crate) flags: u8,
46}
47
48const FLAG_ENTRY_POINT: u8 = 1 << 0;
49const FLAG_REACHABLE: u8 = 1 << 1;
50const FLAG_RUNTIME_REACHABLE: u8 = 1 << 2;
51const FLAG_TEST_REACHABLE: u8 = 1 << 3;
52const FLAG_CJS_EXPORTS: u8 = 1 << 4;
53const FLAG_CONSUMER_CHECKED: u8 = 1 << 5;
54const FLAG_FIXTURE_ENTRY: u8 = 1 << 6;
55
56impl ModuleNode {
57 #[inline]
59 pub const fn is_entry_point(&self) -> bool {
60 self.flags & FLAG_ENTRY_POINT != 0
61 }
62
63 #[inline]
70 pub(crate) const fn exposes_entry_surface(&self) -> bool {
71 self.flags & FLAG_ENTRY_POINT != 0 && self.flags & FLAG_CONSUMER_CHECKED == 0
72 }
73
74 #[inline]
78 pub const fn is_consumer_checked(&self) -> bool {
79 self.flags & FLAG_ENTRY_POINT != 0 && self.flags & FLAG_CONSUMER_CHECKED != 0
80 }
81
82 #[inline]
86 pub const fn is_fixture_entry(&self) -> bool {
87 self.is_consumer_checked() && self.flags & FLAG_FIXTURE_ENTRY != 0
88 }
89
90 #[inline]
91 pub(crate) const fn set_fixture_entry(&mut self) {
92 self.flags |= FLAG_FIXTURE_ENTRY;
93 }
94
95 #[inline]
97 pub(crate) const fn set_consumer_checked(&mut self) {
98 self.flags |= FLAG_CONSUMER_CHECKED;
99 }
100
101 pub(crate) fn export_is_public(&self, name: &str) -> bool {
105 self.exports
106 .iter()
107 .any(|export| export.visibility.suppresses_unused() && export.name.matches_str(name))
108 }
109
110 #[inline]
112 pub const fn is_reachable(&self) -> bool {
113 self.flags & FLAG_REACHABLE != 0
114 }
115
116 #[inline]
118 pub const fn is_runtime_reachable(&self) -> bool {
119 self.flags & FLAG_RUNTIME_REACHABLE != 0
120 }
121
122 #[inline]
124 pub const fn is_test_reachable(&self) -> bool {
125 self.flags & FLAG_TEST_REACHABLE != 0
126 }
127
128 #[inline]
130 pub const fn has_cjs_exports(&self) -> bool {
131 self.flags & FLAG_CJS_EXPORTS != 0
132 }
133
134 #[must_use]
143 pub fn forwards_default_as_module_object(&self) -> bool {
144 self.has_cjs_exports()
145 && self
146 .re_exports
147 .iter()
148 .any(|re_export| re_export.exported_name == "default")
149 }
150
151 #[inline]
153 pub fn set_reachable(&mut self, v: bool) {
154 if v {
155 self.flags |= FLAG_REACHABLE;
156 } else {
157 self.flags &= !FLAG_REACHABLE;
158 }
159 }
160
161 #[inline]
163 pub(crate) fn set_runtime_reachable(&mut self, v: bool) {
164 if v {
165 self.flags |= FLAG_RUNTIME_REACHABLE;
166 } else {
167 self.flags &= !FLAG_RUNTIME_REACHABLE;
168 }
169 }
170
171 #[inline]
173 pub(crate) fn set_test_reachable(&mut self, v: bool) {
174 if v {
175 self.flags |= FLAG_TEST_REACHABLE;
176 } else {
177 self.flags &= !FLAG_TEST_REACHABLE;
178 }
179 }
180
181 #[inline]
183 pub fn set_cjs_exports(&mut self, v: bool) {
184 if v {
185 self.flags |= FLAG_CJS_EXPORTS;
186 } else {
187 self.flags &= !FLAG_CJS_EXPORTS;
188 }
189 }
190
191 #[inline]
193 pub(crate) fn flags_from(
194 is_entry_point: bool,
195 is_runtime_reachable: bool,
196 has_cjs_exports: bool,
197 ) -> u8 {
198 let mut f = 0u8;
199 if is_entry_point {
200 f |= FLAG_ENTRY_POINT;
201 }
202 if is_runtime_reachable {
203 f |= FLAG_RUNTIME_REACHABLE;
204 }
205 if has_cjs_exports {
206 f |= FLAG_CJS_EXPORTS;
207 }
208 f
209 }
210}
211
212#[derive(Debug, serde::Serialize, serde::Deserialize)]
214pub struct ReExportEdge {
215 pub source_file: FileId,
217 pub imported_name: String,
219 pub exported_name: String,
221 pub is_type_only: bool,
223 #[serde(with = "crate::cache::span_serde")]
227 pub span: oxc_span::Span,
228}
229
230#[derive(Debug, serde::Serialize, serde::Deserialize)]
232pub struct ExportSymbol {
233 pub name: ExportName,
235 pub is_type_only: bool,
237 pub is_side_effect_used: bool,
242 pub visibility: VisibilityTag,
245 pub expected_unused_reason: Option<String>,
247 pub deprecated: bool,
249 pub deprecated_reason: Option<Box<str>>,
251 #[serde(with = "crate::cache::span_serde")]
253 pub span: oxc_span::Span,
254 pub references: Vec<SymbolReference>,
256 #[serde(default)]
265 pub reference_paths: Vec<Option<ReferencePathId>>,
266 #[serde(with = "crate::cache::member_serde")]
273 pub members: Vec<fallow_types::extract::MemberInfo>,
274}
275
276#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
278pub struct SymbolReference {
279 pub from_file: FileId,
281 pub kind: ReferenceKind,
283 pub namespace: super::ExportNamespace,
285 #[serde(with = "crate::cache::span_serde")]
288 pub import_span: oxc_span::Span,
289}
290
291#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
296pub struct ReferencePathId(NonZeroU32);
297
298#[derive(Clone, Copy)]
302pub(crate) struct RoutedReference {
303 pub(crate) reference: SymbolReference,
304 pub(crate) path: Option<ReferencePathId>,
305}
306
307pub(crate) type RoutedReferenceKey = (
308 FileId,
309 oxc_span::Span,
310 Option<ReferencePathId>,
311 super::ExportNamespace,
312);
313
314impl RoutedReference {
315 pub(crate) const fn key(self) -> RoutedReferenceKey {
316 (
317 self.reference.from_file,
318 self.reference.import_span,
319 self.path,
320 self.reference.namespace,
321 )
322 }
323}
324
325impl ExportSymbol {
326 const INLINE_PHYSICAL_REFERENCE_LIMIT: usize = 8;
327
328 pub fn references_in(
330 &self,
331 namespace: super::ExportNamespace,
332 ) -> impl Iterator<Item = &SymbolReference> {
333 self.references
334 .iter()
335 .filter(move |reference| reference.namespace == namespace)
336 }
337
338 pub fn physical_references(&self) -> impl Iterator<Item = &SymbolReference> {
341 let mut seen = (self.references.len() > Self::INLINE_PHYSICAL_REFERENCE_LIMIT)
342 .then(FxHashSet::default);
343 self.references
344 .iter()
345 .enumerate()
346 .filter(move |(index, reference)| {
347 let key = (
348 reference.from_file,
349 reference.import_span,
350 self.reference_path(*index),
351 );
352 if let Some(seen) = &mut seen {
353 return seen.insert(key);
354 }
355 !(0..*index).any(|prior_index| {
356 let prior = &self.references[prior_index];
357 key == (
358 prior.from_file,
359 prior.import_span,
360 self.reference_path(prior_index),
361 )
362 })
363 })
364 .map(|(_, reference)| reference)
365 }
366
367 pub(crate) fn reference_path(&self, index: usize) -> Option<ReferencePathId> {
369 self.reference_paths.get(index).copied().flatten()
370 }
371
372 pub(crate) fn has_reference_from(
375 &self,
376 from_file: FileId,
377 import_span: oxc_span::Span,
378 path: Option<ReferencePathId>,
379 namespace: super::ExportNamespace,
380 ) -> bool {
381 self.references
382 .iter()
383 .enumerate()
384 .any(|(index, reference)| {
385 reference.from_file == from_file
386 && reference.import_span == import_span
387 && self.reference_path(index) == path
388 && reference.namespace == namespace
389 })
390 }
391
392 pub(crate) fn push_reference(
397 &mut self,
398 reference: SymbolReference,
399 path: Option<ReferencePathId>,
400 ) {
401 if path.is_some() || !self.reference_paths.is_empty() {
402 self.reference_paths.resize(self.references.len(), None);
403 self.reference_paths.push(path);
404 }
405 self.references.push(reference);
406 }
407
408 pub(crate) fn routed_references(&self) -> impl Iterator<Item = RoutedReference> + '_ {
410 self.references
411 .iter()
412 .enumerate()
413 .map(|(index, reference)| RoutedReference {
414 reference: *reference,
415 path: self.reference_path(index),
416 })
417 }
418}
419
420#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
422pub(crate) enum ReferencePathNode {
423 Hop {
425 parent: Option<ReferencePathId>,
427 target: FileId,
429 mechanism: ModuleLoadMechanism,
431 },
432 Route {
434 parent: Option<ReferencePathId>,
437 graph: ReferenceRouteGraphId,
439 start: ReferenceRouteNodeId,
441 terminal: ReferenceRouteNodeId,
443 start_mechanism: Option<ModuleLoadMechanism>,
447 },
448}
449
450impl ReferencePathNode {
451 pub(crate) const fn parent(self) -> Option<ReferencePathId> {
452 match self {
453 Self::Hop { parent, .. } | Self::Route { parent, .. } => parent,
454 }
455 }
456
457 fn remap_parent(&mut self, remap: &[ReferencePathId]) {
458 match self {
459 Self::Hop { parent, .. } | Self::Route { parent, .. } => {
460 *parent = parent.map(|path| remap[path.index()]);
461 }
462 }
463 }
464}
465
466#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
468pub(crate) struct ReferenceRouteGraphId(pub(crate) u32);
469
470#[derive(
472 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
473)]
474pub(crate) struct ReferenceRouteNodeId(pub(crate) u32);
475
476#[derive(Debug, Clone, PartialEq, Eq, Hash)]
478pub(crate) struct ReferenceRouteNodeSpec {
479 target: FileId,
480 mechanism: ModuleLoadMechanism,
481 successors: Vec<ReferenceRouteNodeId>,
482}
483
484impl ReferenceRouteNodeSpec {
485 pub(crate) fn new(
486 target: FileId,
487 mechanism: ModuleLoadMechanism,
488 mut successors: Vec<ReferenceRouteNodeId>,
489 ) -> Self {
490 successors.sort_unstable_by_key(|successor| successor.0);
491 successors.dedup();
492 Self {
493 target,
494 mechanism,
495 successors,
496 }
497 }
498}
499
500#[derive(Debug, Clone, PartialEq, Eq, Hash)]
502pub(crate) struct ReferenceRouteGraphSpec {
503 nodes: Vec<ReferenceRouteNodeSpec>,
504}
505
506impl ReferenceRouteGraphSpec {
507 pub(crate) fn new(nodes: Vec<ReferenceRouteNodeSpec>) -> Self {
508 debug_assert!(nodes.iter().all(|node| {
509 node.successors
510 .iter()
511 .all(|successor| successor.0 < nodes.len() as u32)
512 }));
513 Self { nodes }
514 }
515}
516
517#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
519pub(crate) struct ReferenceRouteGraph {
520 pub(crate) nodes: Range<u32>,
521}
522
523#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
525pub(crate) struct ReferenceRouteNode {
526 pub(crate) target: FileId,
527 pub(crate) mechanism: ModuleLoadMechanism,
528 pub(crate) successors: Range<u32>,
529}
530
531#[derive(Debug, Default, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
533pub(crate) struct ReferenceRoutes {
534 pub(crate) graphs: Vec<ReferenceRouteGraph>,
535 pub(crate) nodes: Vec<ReferenceRouteNode>,
536 pub(crate) edges: Vec<ReferenceRouteNodeId>,
537}
538
539impl ReferenceRoutes {
540 #[cfg(test)]
541 pub(crate) fn canonical_hops(
542 &self,
543 graph_id: ReferenceRouteGraphId,
544 start: ReferenceRouteNodeId,
545 terminal: ReferenceRouteNodeId,
546 start_mechanism: Option<ModuleLoadMechanism>,
547 ) -> Vec<(FileId, ModuleLoadMechanism)> {
548 let Some(graph) = self.graphs.get(graph_id.0 as usize) else {
549 return Vec::new();
550 };
551 let node_count = graph.nodes.end.saturating_sub(graph.nodes.start) as usize;
552 let start_index = start.0 as usize;
553 let terminal_index = terminal.0 as usize;
554 if start_index >= node_count || terminal_index >= node_count {
555 return Vec::new();
556 }
557
558 let mut predecessor = vec![None; node_count];
559 let mut visited = vec![false; node_count];
560 let mut queue = std::collections::VecDeque::from([start_index]);
561 visited[start_index] = true;
562 while let Some(local_index) = queue.pop_front() {
563 if local_index == terminal_index {
564 break;
565 }
566 let Some(node) = self.nodes.get(graph.nodes.start as usize + local_index) else {
567 return Vec::new();
568 };
569 let Some(successors) = self
570 .edges
571 .get(node.successors.start as usize..node.successors.end as usize)
572 else {
573 return Vec::new();
574 };
575 for successor in successors {
576 let successor_index = successor.0 as usize;
577 if successor_index >= node_count || visited[successor_index] {
578 continue;
579 }
580 visited[successor_index] = true;
581 predecessor[successor_index] = Some(local_index);
582 queue.push_back(successor_index);
583 }
584 }
585 if !visited[terminal_index] {
586 return Vec::new();
587 }
588
589 let mut hops = Vec::new();
590 let mut current = terminal_index;
591 loop {
592 let node = &self.nodes[graph.nodes.start as usize + current];
593 if current == start_index {
594 if let Some(mechanism) = start_mechanism {
595 hops.push((node.target, mechanism));
596 }
597 break;
598 }
599 hops.push((node.target, node.mechanism));
600 let Some(parent) = predecessor[current] else {
601 return Vec::new();
602 };
603 current = parent;
604 }
605 hops
606 }
607}
608
609#[derive(Debug, PartialEq, Eq)]
611pub(crate) struct FinalizedReferencePaths {
612 pub(crate) paths: Vec<ReferencePathNode>,
613 pub(crate) routes: ReferenceRoutes,
614}
615
616pub(crate) struct ReferencePathInterner {
618 track_provenance: bool,
619 nodes: Vec<ReferencePathNode>,
620 metadata: Vec<ReferencePathMetadata>,
621 ids: FxHashMap<ReferencePathNode, ReferencePathId>,
622 route_graphs: Vec<ReferenceRouteGraphSpec>,
623 route_graph_ids: FxHashMap<ReferenceRouteGraphSpec, ReferenceRouteGraphId>,
624}
625
626#[derive(Clone, Copy)]
627struct ReferencePathMetadata {
628 depth: usize,
629 hop_target_bounds: Option<(FileId, FileId)>,
630}
631
632impl Default for ReferencePathInterner {
633 fn default() -> Self {
634 Self::new(true)
635 }
636}
637
638impl ReferencePathInterner {
639 pub(crate) fn new(track_provenance: bool) -> Self {
640 Self {
641 track_provenance,
642 nodes: Vec::new(),
643 metadata: Vec::new(),
644 ids: FxHashMap::default(),
645 route_graphs: Vec::new(),
646 route_graph_ids: FxHashMap::default(),
647 }
648 }
649
650 pub(crate) const fn tracks_provenance(&self) -> bool {
651 self.track_provenance
652 }
653
654 pub(crate) fn direct(
656 &mut self,
657 target: FileId,
658 mechanism: ModuleLoadMechanism,
659 ) -> Option<ReferencePathId> {
660 self.track_provenance.then(|| {
661 self.intern(ReferencePathNode::Hop {
662 parent: None,
663 target,
664 mechanism,
665 })
666 })
667 }
668
669 pub(crate) fn extend(
671 &mut self,
672 parent: Option<ReferencePathId>,
673 target: FileId,
674 mechanism: ModuleLoadMechanism,
675 ) -> Option<ReferencePathId> {
676 if !self.track_provenance {
677 debug_assert!(parent.is_none());
678 return None;
679 }
680 let Some(parent) = parent else {
681 debug_assert!(false, "tracked reference paths require an interned parent");
682 return None;
683 };
684 let may_contain_target = self
685 .metadata
686 .get(parent.index())
687 .and_then(|metadata| metadata.hop_target_bounds)
688 .is_some_and(|(minimum, maximum)| target.0 >= minimum.0 && target.0 <= maximum.0);
689 if may_contain_target && self.contains_target(parent, target) {
690 return Some(parent);
691 }
692 Some(self.intern(ReferencePathNode::Hop {
693 parent: Some(parent),
694 target,
695 mechanism,
696 }))
697 }
698
699 pub(crate) fn intern_route_graph(
701 &mut self,
702 graph: ReferenceRouteGraphSpec,
703 ) -> ReferenceRouteGraphId {
704 debug_assert!(self.track_provenance);
705 if let Some(id) = self.route_graph_ids.get(&graph) {
706 return *id;
707 }
708 let id = ReferenceRouteGraphId(self.route_graphs.len() as u32);
709 self.route_graphs.push(graph.clone());
710 self.route_graph_ids.insert(graph, id);
711 id
712 }
713
714 pub(crate) fn route(
716 &mut self,
717 parent: Option<ReferencePathId>,
718 graph: ReferenceRouteGraphId,
719 start: ReferenceRouteNodeId,
720 terminal: ReferenceRouteNodeId,
721 start_mechanism: Option<ModuleLoadMechanism>,
722 ) -> Option<ReferencePathId> {
723 if !self.track_provenance {
724 return None;
725 }
726 Some(self.intern(ReferencePathNode::Route {
727 parent,
728 graph,
729 start,
730 terminal,
731 start_mechanism,
732 }))
733 }
734
735 fn contains_target(&self, mut path: ReferencePathId, target: FileId) -> bool {
736 loop {
737 let Some(node) = self.nodes.get(path.index()) else {
738 return false;
739 };
740 if let ReferencePathNode::Hop {
741 target: hop_target, ..
742 } = node
743 && *hop_target == target
744 {
745 return true;
746 }
747 let Some(parent) = node.parent() else {
748 return false;
749 };
750 path = parent;
751 }
752 }
753
754 fn intern(&mut self, node: ReferencePathNode) -> ReferencePathId {
755 if let Some(path) = self.ids.get(&node) {
756 return *path;
757 }
758 let path = ReferencePathId::from_index(self.nodes.len());
759 let parent_metadata = node
760 .parent()
761 .and_then(|parent| self.metadata.get(parent.index()).copied());
762 let depth = parent_metadata.map_or(0, |metadata| metadata.depth + 1);
763 let hop_target_bounds = match node {
764 ReferencePathNode::Hop { target, .. } => Some(
765 parent_metadata
766 .and_then(|metadata| metadata.hop_target_bounds)
767 .map_or((target, target), |(minimum, maximum)| {
768 (
769 FileId(minimum.0.min(target.0)),
770 FileId(maximum.0.max(target.0)),
771 )
772 }),
773 ),
774 ReferencePathNode::Route { .. } => {
775 parent_metadata.and_then(|metadata| metadata.hop_target_bounds)
776 }
777 };
778 self.nodes.push(node);
779 self.metadata.push(ReferencePathMetadata {
780 depth,
781 hop_target_bounds,
782 });
783 self.ids.insert(node, path);
784 path
785 }
786
787 pub(crate) fn finalize(self, modules: &mut [ModuleNode]) -> FinalizedReferencePaths {
793 if self.nodes.is_empty() && self.route_graphs.is_empty() {
794 return FinalizedReferencePaths {
795 paths: Vec::new(),
796 routes: ReferenceRoutes::default(),
797 };
798 }
799
800 let (routes, route_remap) = finalize_route_graphs(&self.route_graphs);
801 let max_depth = self
802 .metadata
803 .iter()
804 .map(|metadata| metadata.depth)
805 .max()
806 .unwrap_or(0);
807
808 let mut paths_by_depth = vec![Vec::new(); max_depth.saturating_add(1)];
809 for (old_index, metadata) in self.metadata.iter().enumerate() {
810 paths_by_depth[metadata.depth].push(old_index);
811 }
812
813 let mut remap = vec![ReferencePathId::from_index(0); self.nodes.len()];
814 let mut finalized = Vec::with_capacity(self.nodes.len());
815 for mut paths in paths_by_depth {
816 paths.sort_unstable_by(|&left, &right| {
817 compare_path_nodes(self.nodes[left], self.nodes[right], &remap, &route_remap)
818 });
819 for old_index in paths {
820 let mut node = self.nodes[old_index];
821 node.remap_parent(&remap);
822 if let ReferencePathNode::Route { graph, .. } = &mut node {
823 *graph = route_remap[graph.0 as usize];
824 }
825 let canonical = ReferencePathId::from_index(finalized.len());
826 remap[old_index] = canonical;
827 finalized.push(node);
828 }
829 }
830
831 for path in modules
832 .iter_mut()
833 .flat_map(|module| &mut module.exports)
834 .flat_map(|export| &mut export.reference_paths)
835 {
836 if let Some(existing) = *path {
837 *path = Some(remap[existing.index()]);
838 }
839 }
840
841 FinalizedReferencePaths {
842 paths: finalized,
843 routes,
844 }
845 }
846}
847
848fn compare_path_nodes(
849 left: ReferencePathNode,
850 right: ReferencePathNode,
851 path_remap: &[ReferencePathId],
852 route_remap: &[ReferenceRouteGraphId],
853) -> Ordering {
854 let left_parent = left.parent().map(|parent| path_remap[parent.index()].0);
855 let right_parent = right.parent().map(|parent| path_remap[parent.index()].0);
856 left_parent
857 .cmp(&right_parent)
858 .then_with(|| match (left, right) {
859 (
860 ReferencePathNode::Hop {
861 target: left_target,
862 mechanism: left_mechanism,
863 ..
864 },
865 ReferencePathNode::Hop {
866 target: right_target,
867 mechanism: right_mechanism,
868 ..
869 },
870 ) => {
871 (left_target.0, left_mechanism as u8).cmp(&(right_target.0, right_mechanism as u8))
872 }
873 (ReferencePathNode::Hop { .. }, ReferencePathNode::Route { .. }) => Ordering::Less,
874 (ReferencePathNode::Route { .. }, ReferencePathNode::Hop { .. }) => Ordering::Greater,
875 (
876 ReferencePathNode::Route {
877 graph: left_graph,
878 start: left_start,
879 terminal: left_terminal,
880 start_mechanism: left_mechanism,
881 ..
882 },
883 ReferencePathNode::Route {
884 graph: right_graph,
885 start: right_start,
886 terminal: right_terminal,
887 start_mechanism: right_mechanism,
888 ..
889 },
890 ) => (
891 route_remap[left_graph.0 as usize].0,
892 left_start.0,
893 left_terminal.0,
894 left_mechanism.map(|mechanism| mechanism as u8),
895 )
896 .cmp(&(
897 route_remap[right_graph.0 as usize].0,
898 right_start.0,
899 right_terminal.0,
900 right_mechanism.map(|mechanism| mechanism as u8),
901 )),
902 })
903}
904
905fn compare_route_graph_specs(
906 left: &ReferenceRouteGraphSpec,
907 right: &ReferenceRouteGraphSpec,
908) -> Ordering {
909 left.nodes.len().cmp(&right.nodes.len()).then_with(|| {
910 left.nodes
911 .iter()
912 .zip(&right.nodes)
913 .find_map(|(left_node, right_node)| {
914 let ordering = (
915 left_node.target.0,
916 left_node.mechanism as u8,
917 &left_node.successors,
918 )
919 .cmp(&(
920 right_node.target.0,
921 right_node.mechanism as u8,
922 &right_node.successors,
923 ));
924 (ordering != Ordering::Equal).then_some(ordering)
925 })
926 .unwrap_or(Ordering::Equal)
927 })
928}
929
930fn finalize_route_graphs(
931 graphs: &[ReferenceRouteGraphSpec],
932) -> (ReferenceRoutes, Vec<ReferenceRouteGraphId>) {
933 let mut order: Vec<usize> = (0..graphs.len()).collect();
934 order
935 .sort_unstable_by(|&left, &right| compare_route_graph_specs(&graphs[left], &graphs[right]));
936
937 let mut remap = vec![ReferenceRouteGraphId(0); graphs.len()];
938 let mut finalized = ReferenceRoutes::default();
939 for old_index in order {
940 let graph_id = ReferenceRouteGraphId(finalized.graphs.len() as u32);
941 remap[old_index] = graph_id;
942 let node_start = finalized.nodes.len() as u32;
943 for node in &graphs[old_index].nodes {
944 let edge_start = finalized.edges.len() as u32;
945 finalized.edges.extend_from_slice(&node.successors);
946 finalized.nodes.push(ReferenceRouteNode {
947 target: node.target,
948 mechanism: node.mechanism,
949 successors: edge_start..finalized.edges.len() as u32,
950 });
951 }
952 finalized.graphs.push(ReferenceRouteGraph {
953 nodes: node_start..finalized.nodes.len() as u32,
954 });
955 }
956 (finalized, remap)
957}
958
959impl ReferencePathId {
960 fn from_index(index: usize) -> Self {
961 let Some(encoded) = u32::try_from(index)
962 .ok()
963 .and_then(|index| index.checked_add(1))
964 .and_then(NonZeroU32::new)
965 else {
966 panic!("a process cannot allocate more than u32::MAX reference path nodes");
967 };
968 Self(encoded)
969 }
970
971 pub(crate) const fn index(self) -> usize {
972 (self.0.get() - 1) as usize
973 }
974}
975
976#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
978pub enum ReferenceKind {
979 NamedImport,
981 DefaultImport,
983 NamespaceImport,
985 ReExport,
987 DynamicImport,
989 SideEffectImport,
991}
992
993#[cfg(target_pointer_width = "64")]
994const _: () = assert!(std::mem::size_of::<ExportSymbol>() == 152);
995#[cfg(target_pointer_width = "64")]
996const _: () = assert!(std::mem::size_of::<SymbolReference>() == 16);
997#[cfg(target_pointer_width = "64")]
998const _: () = assert!(std::mem::size_of::<ReExportEdge>() == 64);
999#[cfg(all(target_pointer_width = "64", unix))]
1000const _: () = assert!(std::mem::size_of::<ModuleNode>() == 96);
1001
1002#[cfg(test)]
1003mod tests {
1004 use super::*;
1005 use crate::graph::ExportNamespace;
1006
1007 fn module_with_reference_paths(paths: &[Option<ReferencePathId>]) -> ModuleNode {
1008 ModuleNode {
1009 file_id: FileId(0),
1010 path: PathBuf::from("/project/source.ts"),
1011 edge_range: 0..0,
1012 exports: vec![ExportSymbol {
1013 name: ExportName::Named("value".to_string()),
1014 is_type_only: false,
1015 is_side_effect_used: false,
1016 visibility: VisibilityTag::None,
1017 expected_unused_reason: None,
1018 span: oxc_span::Span::default(),
1019 references: paths
1020 .iter()
1021 .map(|_| SymbolReference {
1022 from_file: FileId(0),
1023 kind: ReferenceKind::NamedImport,
1024 namespace: ExportNamespace::Value,
1025 import_span: oxc_span::Span::default(),
1026 })
1027 .collect(),
1028 reference_paths: paths.to_vec(),
1029 members: Vec::new(),
1030 deprecated: false,
1031 deprecated_reason: None,
1032 }],
1033 re_exports: Vec::new(),
1034 flags: 0,
1035 }
1036 }
1037
1038 fn export_with_reference_files(files: &[u32]) -> ExportSymbol {
1039 ExportSymbol {
1040 name: ExportName::Named("value".to_string()),
1041 is_type_only: false,
1042 is_side_effect_used: false,
1043 visibility: VisibilityTag::None,
1044 expected_unused_reason: None,
1045 span: oxc_span::Span::default(),
1046 references: files
1047 .iter()
1048 .map(|file| SymbolReference {
1049 from_file: FileId(*file),
1050 kind: ReferenceKind::NamedImport,
1051 namespace: ExportNamespace::Value,
1052 import_span: oxc_span::Span::default(),
1053 })
1054 .collect(),
1055 reference_paths: Vec::new(),
1056 members: Vec::new(),
1057 deprecated: false,
1058 deprecated_reason: None,
1059 }
1060 }
1061
1062 #[test]
1063 fn physical_references_deduplicate_small_and_large_sets() {
1064 let small = export_with_reference_files(&[0, 1, 2, 3, 4, 5, 6, 0]);
1065 let large = export_with_reference_files(&[0, 1, 2, 3, 4, 5, 6, 7, 0]);
1066
1067 assert_eq!(small.physical_references().count(), 7);
1068 assert_eq!(large.physical_references().count(), 8);
1069 }
1070
1071 #[test]
1072 fn reference_path_metadata_tracks_exact_depth_and_hop_bounds() {
1073 let mut interner = ReferencePathInterner::default();
1074 let root = interner
1075 .direct(FileId(10), ModuleLoadMechanism::EsModule)
1076 .expect("tracked interner must return a path");
1077 let lower = interner
1078 .extend(Some(root), FileId(5), ModuleLoadMechanism::EsModule)
1079 .expect("tracked interner must extend a path");
1080 let upper = interner
1081 .extend(Some(lower), FileId(20), ModuleLoadMechanism::EsModule)
1082 .expect("tracked interner must extend a path");
1083
1084 assert_eq!(interner.metadata[root.index()].depth, 0);
1085 assert_eq!(
1086 interner.metadata[lower.index()].hop_target_bounds,
1087 Some((FileId(5), FileId(10)))
1088 );
1089 assert_eq!(interner.metadata[upper.index()].depth, 2);
1090 assert_eq!(
1091 interner.metadata[upper.index()].hop_target_bounds,
1092 Some((FileId(5), FileId(20)))
1093 );
1094
1095 let repeated = interner.extend(Some(upper), FileId(10), ModuleLoadMechanism::EsModule);
1096 assert_eq!(repeated, Some(upper));
1097 }
1098
1099 #[test]
1100 fn finalized_reference_paths_are_independent_of_interning_order() {
1101 let mut first = ReferencePathInterner::default();
1102 let first_parent = first.direct(FileId(1), ModuleLoadMechanism::EsModule);
1103 let first_direct = first.direct(FileId(2), ModuleLoadMechanism::CommonJsRequire);
1104 let first_chain = first.extend(first_parent, FileId(3), ModuleLoadMechanism::EsModule);
1105 let mut first_modules = vec![module_with_reference_paths(&[first_direct, first_chain])];
1106 let first_nodes = first.finalize(&mut first_modules);
1107
1108 let mut second = ReferencePathInterner::default();
1109 let second_direct = second.direct(FileId(2), ModuleLoadMechanism::CommonJsRequire);
1110 let second_parent = second.direct(FileId(1), ModuleLoadMechanism::EsModule);
1111 let second_chain = second.extend(second_parent, FileId(3), ModuleLoadMechanism::EsModule);
1112 let mut second_modules = vec![module_with_reference_paths(&[second_direct, second_chain])];
1113 let second_nodes = second.finalize(&mut second_modules);
1114
1115 assert_eq!(first_nodes, second_nodes);
1116 assert_eq!(
1117 first_modules[0].exports[0].reference_paths,
1118 second_modules[0].exports[0].reference_paths
1119 );
1120 }
1121
1122 fn two_hop_route(first: FileId, second: FileId) -> ReferenceRouteGraphSpec {
1123 ReferenceRouteGraphSpec::new(vec![
1124 ReferenceRouteNodeSpec::new(
1125 first,
1126 ModuleLoadMechanism::EsModule,
1127 vec![ReferenceRouteNodeId(1)],
1128 ),
1129 ReferenceRouteNodeSpec::new(second, ModuleLoadMechanism::EsModule, Vec::new()),
1130 ])
1131 }
1132
1133 #[test]
1134 fn finalized_reference_routes_are_independent_of_interning_order() {
1135 let route_a = two_hop_route(FileId(1), FileId(2));
1136 let route_b = two_hop_route(FileId(3), FileId(4));
1137
1138 let mut first = ReferencePathInterner::default();
1139 let first_a = first.intern_route_graph(route_a.clone());
1140 let first_b = first.intern_route_graph(route_b.clone());
1141 let first_b_path = first.route(
1142 None,
1143 first_b,
1144 ReferenceRouteNodeId(0),
1145 ReferenceRouteNodeId(1),
1146 Some(ModuleLoadMechanism::CommonJsRequire),
1147 );
1148 let first_a_path = first.route(
1149 None,
1150 first_a,
1151 ReferenceRouteNodeId(0),
1152 ReferenceRouteNodeId(1),
1153 Some(ModuleLoadMechanism::EsModule),
1154 );
1155 let mut first_modules = vec![module_with_reference_paths(&[first_b_path, first_a_path])];
1156 let first_paths = first.finalize(&mut first_modules);
1157
1158 let mut second = ReferencePathInterner::default();
1159 let second_b = second.intern_route_graph(route_b);
1160 let second_a = second.intern_route_graph(route_a);
1161 let second_b_path = second.route(
1162 None,
1163 second_b,
1164 ReferenceRouteNodeId(0),
1165 ReferenceRouteNodeId(1),
1166 Some(ModuleLoadMechanism::CommonJsRequire),
1167 );
1168 let second_a_path = second.route(
1169 None,
1170 second_a,
1171 ReferenceRouteNodeId(0),
1172 ReferenceRouteNodeId(1),
1173 Some(ModuleLoadMechanism::EsModule),
1174 );
1175 let mut second_modules = vec![module_with_reference_paths(&[second_b_path, second_a_path])];
1176 let second_paths = second.finalize(&mut second_modules);
1177
1178 assert_eq!(first_paths, second_paths);
1179 assert_eq!(
1180 first_modules[0].exports[0].reference_paths,
1181 second_modules[0].exports[0].reference_paths
1182 );
1183 }
1184
1185 #[test]
1186 fn push_reference_without_paths_never_allocates_the_side_table() {
1187 let mut export = ExportSymbol {
1188 name: ExportName::Named("value".to_string()),
1189 is_type_only: false,
1190 is_side_effect_used: false,
1191 visibility: VisibilityTag::None,
1192 expected_unused_reason: None,
1193 span: oxc_span::Span::default(),
1194 references: Vec::new(),
1195 reference_paths: Vec::new(),
1196 members: Vec::new(),
1197 deprecated: false,
1198 deprecated_reason: None,
1199 };
1200 for id in 0..3 {
1201 export.push_reference(
1202 SymbolReference {
1203 from_file: FileId(id),
1204 kind: ReferenceKind::NamedImport,
1205 namespace: ExportNamespace::Value,
1206 import_span: oxc_span::Span::default(),
1207 },
1208 None,
1209 );
1210 }
1211 assert_eq!(export.references.len(), 3);
1212 assert!(export.reference_paths.is_empty());
1213 assert_eq!(export.reference_paths.capacity(), 0);
1214 assert_eq!(export.reference_path(1), None);
1215 assert!(export.has_reference_from(
1216 FileId(1),
1217 oxc_span::Span::default(),
1218 None,
1219 ExportNamespace::Value
1220 ));
1221 assert!(!export.has_reference_from(
1222 FileId(9),
1223 oxc_span::Span::default(),
1224 None,
1225 ExportNamespace::Value
1226 ));
1227 }
1228
1229 #[test]
1230 fn push_reference_backfills_the_side_table_on_the_first_tracked_path() {
1231 let mut export = ExportSymbol {
1232 name: ExportName::Named("value".to_string()),
1233 is_type_only: false,
1234 is_side_effect_used: false,
1235 visibility: VisibilityTag::None,
1236 expected_unused_reason: None,
1237 span: oxc_span::Span::default(),
1238 references: Vec::new(),
1239 reference_paths: Vec::new(),
1240 members: Vec::new(),
1241 deprecated: false,
1242 deprecated_reason: None,
1243 };
1244 let reference = SymbolReference {
1245 from_file: FileId(0),
1246 kind: ReferenceKind::NamedImport,
1247 namespace: ExportNamespace::Value,
1248 import_span: oxc_span::Span::default(),
1249 };
1250 export.push_reference(reference, None);
1251 let tracked = ReferencePathId::from_index(4);
1252 export.push_reference(reference, Some(tracked));
1253 export.push_reference(reference, None);
1254
1255 assert_eq!(export.reference_paths, vec![None, Some(tracked), None]);
1256 assert_eq!(export.reference_path(0), None);
1257 assert_eq!(export.reference_path(1), Some(tracked));
1258 assert!(export.has_reference_from(
1259 FileId(0),
1260 reference.import_span,
1261 Some(tracked),
1262 ExportNamespace::Value
1263 ));
1264 assert!(!export.has_reference_from(
1265 FileId(0),
1266 reference.import_span,
1267 Some(ReferencePathId::from_index(7)),
1268 ExportNamespace::Value
1269 ));
1270 }
1271
1272 #[test]
1273 fn module_node_construction() {
1274 let mut node = ModuleNode {
1275 file_id: FileId(0),
1276 path: PathBuf::from("/project/src/index.ts"),
1277 edge_range: 0..5,
1278 exports: vec![],
1279 re_exports: vec![],
1280 flags: ModuleNode::flags_from(true, true, false),
1281 };
1282 node.set_reachable(true);
1283 assert_eq!(node.file_id, FileId(0));
1284 assert!(node.is_entry_point());
1285 assert!(node.is_reachable());
1286 assert!(node.is_runtime_reachable());
1287 assert!(!node.is_test_reachable());
1288 assert!(!node.has_cjs_exports());
1289 assert_eq!(node.edge_range, 0..5);
1290 }
1291
1292 #[test]
1293 fn module_node_non_entry_unreachable() {
1294 let node = ModuleNode {
1295 file_id: FileId(5),
1296 path: PathBuf::from("/project/src/orphan.ts"),
1297 edge_range: 0..0,
1298 exports: vec![],
1299 re_exports: vec![],
1300 flags: ModuleNode::flags_from(false, false, false),
1301 };
1302 assert!(!node.is_entry_point());
1303 assert!(!node.is_reachable());
1304 assert!(!node.is_runtime_reachable());
1305 assert!(!node.is_test_reachable());
1306 assert!(node.edge_range.is_empty());
1307 }
1308
1309 #[test]
1310 fn module_node_cjs_exports() {
1311 let mut node = ModuleNode {
1312 file_id: FileId(2),
1313 path: PathBuf::from("/project/lib/legacy.js"),
1314 edge_range: 3..7,
1315 exports: vec![],
1316 re_exports: vec![],
1317 flags: ModuleNode::flags_from(false, true, true),
1318 };
1319 node.set_reachable(true);
1320 assert!(node.has_cjs_exports());
1321 assert!(node.is_runtime_reachable());
1322 assert_eq!(node.edge_range.len(), 4);
1323 }
1324
1325 #[test]
1326 fn module_node_with_exports_and_re_exports() {
1327 let node = ModuleNode {
1328 file_id: FileId(1),
1329 path: PathBuf::from("/project/src/barrel.ts"),
1330 edge_range: 0..3,
1331 exports: vec![ExportSymbol {
1332 name: ExportName::Named("localFn".to_string()),
1333 is_type_only: false,
1334 is_side_effect_used: false,
1335 visibility: VisibilityTag::None,
1336 expected_unused_reason: None,
1337 span: oxc_span::Span::new(0, 20),
1338 references: vec![],
1339 reference_paths: Vec::new(),
1340 members: vec![],
1341 deprecated: false,
1342 deprecated_reason: None,
1343 }],
1344 re_exports: vec![ReExportEdge {
1345 source_file: FileId(2),
1346 imported_name: "*".to_string(),
1347 exported_name: "*".to_string(),
1348 is_type_only: false,
1349 span: oxc_span::Span::default(),
1350 }],
1351 flags: ModuleNode::flags_from(false, true, false),
1352 };
1353 assert_eq!(node.exports.len(), 1);
1354 assert_eq!(node.re_exports.len(), 1);
1355 assert_eq!(node.re_exports[0].source_file, FileId(2));
1356 }
1357}