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