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