1use std::collections::VecDeque;
4
5use fallow_types::discover::FileId;
6use fallow_types::extract::ExportName;
7use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
8
9use super::types::ExportSymbol;
10use crate::resolve::ResolvedModule;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
14pub enum ExportNamespace {
15 Type,
17 Value,
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
23pub struct EffectiveExportBinding {
24 file_id: FileId,
25 kind: EffectiveExportBindingKind,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
29enum EffectiveExportBindingKind {
30 Declaration(usize),
31 NamespaceObject {
32 source: FileId,
33 },
34 ImplicitDefault,
35 ExternalReExport(usize),
40}
41
42impl EffectiveExportBinding {
43 #[must_use]
45 pub const fn origin_file(&self) -> FileId {
46 self.file_id
47 }
48
49 pub(in crate::graph) const fn origin_slot(self) -> Option<usize> {
50 match self.kind {
51 EffectiveExportBindingKind::Declaration(slot) => Some(slot),
52 EffectiveExportBindingKind::NamespaceObject { .. }
53 | EffectiveExportBindingKind::ImplicitDefault
54 | EffectiveExportBindingKind::ExternalReExport(_) => None,
55 }
56 }
57
58 #[must_use]
60 pub const fn namespace_source(self) -> Option<FileId> {
61 match self.kind {
62 EffectiveExportBindingKind::NamespaceObject { source } => Some(source),
63 EffectiveExportBindingKind::Declaration(_)
64 | EffectiveExportBindingKind::ImplicitDefault
65 | EffectiveExportBindingKind::ExternalReExport(_) => None,
66 }
67 }
68
69 #[must_use]
71 pub const fn is_implicit_default(self) -> bool {
72 matches!(self.kind, EffectiveExportBindingKind::ImplicitDefault)
73 }
74}
75
76#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
78pub enum EffectiveExportResolution {
79 #[default]
81 Missing,
82 Unique(EffectiveExportBinding),
84 Ambiguous,
86}
87
88impl EffectiveExportResolution {
89 fn merged_with(self, incoming: Self) -> Self {
90 match (self, incoming) {
91 (Self::Missing, resolution) | (resolution, Self::Missing) => resolution,
92 (Self::Unique(left), Self::Unique(right)) if left == right => self,
93 (Self::Ambiguous, _) | (_, Self::Ambiguous) | (Self::Unique(_), Self::Unique(_)) => {
94 Self::Ambiguous
95 }
96 }
97 }
98}
99
100#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
102pub(super) struct ExportNamespaces {
103 r#type: bool,
104 value: bool,
105}
106
107impl ExportNamespaces {
108 pub(super) const fn contains(self, namespace: ExportNamespace) -> bool {
109 match namespace {
110 ExportNamespace::Type => self.r#type,
111 ExportNamespace::Value => self.value,
112 }
113 }
114
115 pub(super) const fn insert(&mut self, namespace: ExportNamespace) -> bool {
116 let slot = match namespace {
117 ExportNamespace::Type => &mut self.r#type,
118 ExportNamespace::Value => &mut self.value,
119 };
120 let inserted = !*slot;
121 *slot = true;
122 inserted
123 }
124
125 pub(super) const fn extend(&mut self, namespaces: Self) {
126 self.r#type |= namespaces.r#type;
127 self.value |= namespaces.value;
128 }
129
130 pub(super) const fn is_empty(self) -> bool {
131 !self.r#type && !self.value
132 }
133}
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
136pub(in crate::graph) struct ExportNameId(usize);
137
138impl ExportNameId {
139 const DEFAULT: Self = Self(0);
140}
141
142#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
143struct ExportKey {
144 file_id: FileId,
145 name: ExportNameId,
146}
147
148impl ExportKey {
149 const fn new(file_id: FileId, name: ExportNameId) -> Self {
150 Self { file_id, name }
151 }
152
153 const fn with_file(self, file_id: FileId) -> Self {
154 Self { file_id, ..self }
155 }
156}
157
158#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
173enum ResolutionLane {
174 Type,
175 TypeFallback,
176 Value,
177}
178
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
180struct ExportLookup {
181 key: ExportKey,
182 lane: ResolutionLane,
183}
184
185impl ExportLookup {
186 const fn new(file_id: FileId, name: ExportNameId, lane: ResolutionLane) -> Self {
187 Self {
188 key: ExportKey::new(file_id, name),
189 lane,
190 }
191 }
192
193 const fn with_file(self, file_id: FileId) -> Self {
194 Self {
195 key: self.key.with_file(file_id),
196 ..self
197 }
198 }
199}
200
201#[derive(Debug, Clone, Copy, Default)]
207struct SeededLanes(u8);
208
209impl SeededLanes {
210 const VALUE_TYPE_RESERVATION: u8 = 1 << 6;
215
216 const fn bit(lane: ResolutionLane) -> u8 {
217 match lane {
218 ResolutionLane::Type => 1,
219 ResolutionLane::TypeFallback => 2,
220 ResolutionLane::Value => 4,
221 }
222 }
223
224 const fn direct_mask(lane: ResolutionLane) -> u8 {
225 match lane {
226 ResolutionLane::Type => Self::bit(lane) | Self::VALUE_TYPE_RESERVATION,
227 ResolutionLane::TypeFallback | ResolutionLane::Value => Self::bit(lane),
228 }
229 }
230
231 const fn is_direct(self, lane: ResolutionLane) -> bool {
232 self.0 & Self::direct_mask(lane) != 0
233 }
234
235 const fn reserve_type_for_value_declaration(&mut self) {
236 self.0 |= Self::VALUE_TYPE_RESERVATION;
237 }
238
239 const fn claim_direct(&mut self, lane: ResolutionLane) -> bool {
241 let bit = Self::bit(lane);
242 let claimed = self.0 & bit == 0;
243 self.0 |= bit;
244 claimed
245 }
246
247 const fn is_explicit(self, lane: ResolutionLane) -> bool {
248 self.0 & (Self::direct_mask(lane) | (Self::bit(lane) << 3)) != 0
249 }
250
251 const fn claim_explicit(&mut self, lane: ResolutionLane) {
252 self.0 |= Self::bit(lane) << 3;
253 }
254}
255
256#[derive(Debug, Clone, Copy, Default, serde::Serialize, serde::Deserialize)]
257struct NamespaceResolutions {
258 r#type: EffectiveExportResolution,
259 type_fallback: EffectiveExportResolution,
260 value: EffectiveExportResolution,
261 #[serde(skip)]
262 seeded: SeededLanes,
263}
264
265impl NamespaceResolutions {
266 fn merge(&mut self, lane: ResolutionLane, incoming: EffectiveExportResolution) -> bool {
268 let current = self.get(lane);
269 let next = current.merged_with(incoming);
270 if current == next {
271 return false;
272 }
273 self.set(lane, next);
274 true
275 }
276
277 const fn get(self, lane: ResolutionLane) -> EffectiveExportResolution {
278 match lane {
279 ResolutionLane::Type => self.r#type,
280 ResolutionLane::TypeFallback => self.type_fallback,
281 ResolutionLane::Value => self.value,
282 }
283 }
284
285 const fn set(&mut self, lane: ResolutionLane, resolution: EffectiveExportResolution) {
286 match lane {
287 ResolutionLane::Type => self.r#type = resolution,
288 ResolutionLane::TypeFallback => self.type_fallback = resolution,
289 ResolutionLane::Value => self.value = resolution,
290 }
291 }
292
293 const fn collides_in_type_space(self) -> bool {
302 matches!(self.r#type, EffectiveExportResolution::Ambiguous)
303 || (matches!(self.type_fallback, EffectiveExportResolution::Ambiguous)
304 && !matches!(self.value, EffectiveExportResolution::Ambiguous))
305 }
306
307 fn effective(self, namespace: ExportNamespace) -> EffectiveExportResolution {
308 match namespace {
309 ExportNamespace::Value => self.value,
310 ExportNamespace::Type => match (self.r#type, self.type_fallback) {
314 (EffectiveExportResolution::Missing, EffectiveExportResolution::Missing) => {
315 self.value
316 }
317 (EffectiveExportResolution::Missing, fallback) => fallback,
318 (resolution, _) => resolution,
319 },
320 }
321 }
322}
323
324#[derive(Clone, Copy)]
330struct ProjectExportSizes {
331 keys: usize,
333 lane_keys: usize,
335 names: usize,
337}
338
339impl ProjectExportSizes {
340 fn measure(modules: &[ResolvedModule], type_fallback_modules: &FxHashSet<FileId>) -> Self {
341 let mut keys = 0;
342 let mut lane_keys = 0;
343 let mut names = 0;
344 for module in modules {
345 let fallback_exports = if type_fallback_modules.contains(&module.file_id) {
346 module
347 .exports
348 .iter()
349 .filter(|export| !export.is_type_only)
350 .count()
351 } else {
352 0
353 };
354 keys += module.exports.len() + module.re_exports.len();
355 lane_keys += module.exports.len() + fallback_exports + module.re_exports.len() * 3;
356 names += module.exports.len() + module.re_exports.len() * 2;
357 }
358 Self {
359 keys,
360 lane_keys,
361 names,
362 }
363 }
364}
365
366struct ExportNameInterner {
367 ids: FxHashMap<Box<str>, ExportNameId>,
368 next_id: usize,
369}
370
371impl ExportNameInterner {
372 fn with_capacity(capacity: usize) -> Self {
373 let mut ids = FxHashMap::with_capacity_and_hasher(capacity + 1, FxBuildHasher);
374 ids.insert(Box::<str>::from("default"), ExportNameId::DEFAULT);
375 Self { ids, next_id: 1 }
376 }
377
378 fn intern_export_name(&mut self, name: &ExportName) -> ExportNameId {
379 match name {
380 ExportName::Default => ExportNameId::DEFAULT,
381 ExportName::Named(name) => self.intern(name),
382 }
383 }
384
385 fn intern(&mut self, name: &str) -> ExportNameId {
386 if let Some(id) = self.ids.get(name) {
387 return *id;
388 }
389 let id = ExportNameId(self.next_id);
390 self.next_id += 1;
391 self.ids.insert(Box::from(name), id);
392 id
393 }
394}
395
396#[derive(Clone, Copy)]
397struct StarObserver {
398 barrel: FileId,
399 type_only: bool,
400 type_fallback: bool,
402}
403
404enum NamedDestinations {
410 One(ExportLookup),
411 Many(Vec<ExportLookup>),
412}
413
414impl NamedDestinations {
415 fn push(&mut self, destination: ExportLookup) {
416 match self {
417 Self::One(first) => *self = Self::Many(vec![*first, destination]),
418 Self::Many(destinations) => destinations.push(destination),
419 }
420 }
421
422 fn iter(&self) -> std::slice::Iter<'_, ExportLookup> {
423 match self {
424 Self::One(destination) => std::slice::from_ref(destination).iter(),
425 Self::Many(destinations) => destinations.iter(),
426 }
427 }
428}
429
430struct PropagationObservers {
431 named: FxHashMap<ExportLookup, NamedDestinations>,
432 star: FxHashMap<FileId, Vec<StarObserver>>,
433}
434
435struct ObserverBuildState<'a> {
436 type_fallback: bool,
437 interner: &'a mut ExportNameInterner,
438 resolutions: &'a mut FxHashMap<ExportKey, NamespaceResolutions>,
439 queue: &'a mut VecDeque<ExportLookup>,
440 observers: &'a mut PropagationObservers,
441}
442
443#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
449pub(super) struct EffectiveExportIndex {
450 name_ids: FxHashMap<Box<str>, ExportNameId>,
451 resolutions: FxHashMap<ExportKey, NamespaceResolutions>,
452 names_by_file: FxHashMap<FileId, Box<[ExportNameId]>>,
455 declaration_merge_groups: DeclarationMergeGroups,
456}
457
458#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
459struct DeclarationMergeGroups {
460 groups: Vec<Box<[usize]>>,
461 group_by_slot: FxHashMap<(FileId, usize), usize>,
462}
463
464impl EffectiveExportIndex {
465 pub(super) fn build(modules: &[ResolvedModule]) -> Self {
466 let type_fallback_modules = modules_needing_type_fallback(modules);
467 let sizes = ProjectExportSizes::measure(modules, &type_fallback_modules);
468 let mut interner = ExportNameInterner::with_capacity(sizes.names);
469 let mut resolutions = FxHashMap::with_capacity_and_hasher(sizes.keys, FxBuildHasher);
470 let mut queue = VecDeque::with_capacity(sizes.lane_keys);
471 seed_direct_bindings(
472 modules,
473 &type_fallback_modules,
474 &mut interner,
475 &mut resolutions,
476 &mut queue,
477 );
478 let observers = collect_observers(
479 modules,
480 &type_fallback_modules,
481 &mut interner,
482 &mut resolutions,
483 &mut queue,
484 );
485 propagate_bindings(&mut resolutions, &mut queue, &observers);
486
487 Self {
488 name_ids: interner.ids,
489 names_by_file: index_names_by_file(&resolutions),
490 resolutions,
491 declaration_merge_groups: collect_declaration_merge_groups(modules),
492 }
493 }
494
495 pub(super) fn resolve(
496 &self,
497 file_id: FileId,
498 name: &str,
499 namespace: ExportNamespace,
500 ) -> EffectiveExportResolution {
501 let Some(name) = self.name_ids.get(name) else {
502 return EffectiveExportResolution::Missing;
503 };
504 self.resolutions
505 .get(&ExportKey::new(file_id, *name))
506 .map_or(EffectiveExportResolution::Missing, |resolutions| {
507 resolutions.effective(namespace)
508 })
509 }
510
511 pub(in crate::graph) fn name_id(&self, name: &str) -> Option<ExportNameId> {
513 self.name_ids.get(name).copied()
514 }
515
516 pub(in crate::graph) fn names_on(&self, file_id: FileId) -> &[ExportNameId] {
518 self.names_by_file.get(&file_id).map_or(&[], AsRef::as_ref)
519 }
520
521 pub(in crate::graph) fn has_name(&self, file_id: FileId, name: ExportNameId) -> bool {
524 self.resolutions
525 .contains_key(&ExportKey::new(file_id, name))
526 }
527
528 pub(super) fn resolves_through(
529 &self,
530 barrel: FileId,
531 barrel_name: &str,
532 source: FileId,
533 source_name: &str,
534 namespace: ExportNamespace,
535 ) -> bool {
536 matches!(
537 (
538 self.resolve(barrel, barrel_name, namespace),
539 self.resolve(source, source_name, namespace),
540 ),
541 (
542 EffectiveExportResolution::Unique(barrel_binding),
543 EffectiveExportResolution::Unique(source_binding),
544 ) if barrel_binding == source_binding
545 )
546 }
547
548 pub(super) fn contributes_through(
549 &self,
550 barrel: FileId,
551 barrel_name: &str,
552 source: FileId,
553 source_name: &str,
554 namespace: ExportNamespace,
555 ) -> bool {
556 match (
557 self.resolve(barrel, barrel_name, namespace),
558 self.resolve(source, source_name, namespace),
559 ) {
560 (
561 EffectiveExportResolution::Unique(barrel_binding),
562 EffectiveExportResolution::Unique(source_binding),
563 ) => barrel_binding == source_binding,
564 (
565 EffectiveExportResolution::Ambiguous,
566 EffectiveExportResolution::Unique(_) | EffectiveExportResolution::Ambiguous,
567 ) => true,
568 _ => false,
569 }
570 }
571
572 pub(super) fn ambiguous_names(&self) -> Vec<(FileId, &str, ExportNamespace)> {
578 let mut ambiguous = Vec::new();
579 for (file_id, names) in &self.names_by_file {
580 self.collect_ambiguous_ids(*file_id, names, &mut ambiguous);
581 }
582 self.name_texts(ambiguous)
583 }
584
585 pub(super) fn ambiguous_names_on(
587 &self,
588 file_id: FileId,
589 ) -> Vec<(FileId, &str, ExportNamespace)> {
590 let Some(names) = self.names_by_file.get(&file_id) else {
591 return Vec::new();
592 };
593 let mut ambiguous = Vec::new();
594 self.collect_ambiguous_ids(file_id, names, &mut ambiguous);
595 self.name_texts(ambiguous)
596 }
597
598 fn collect_ambiguous_ids(
599 &self,
600 file_id: FileId,
601 names: &[ExportNameId],
602 ambiguous: &mut Vec<(FileId, ExportNameId, ExportNamespace)>,
603 ) {
604 for name in names {
605 let Some(resolutions) = self.resolutions.get(&ExportKey::new(file_id, *name)) else {
606 continue;
607 };
608 for (namespace, collides) in [
609 (ExportNamespace::Type, resolutions.collides_in_type_space()),
610 (
611 ExportNamespace::Value,
612 matches!(resolutions.value, EffectiveExportResolution::Ambiguous),
613 ),
614 ] {
615 if collides {
616 ambiguous.push((file_id, *name, namespace));
617 }
618 }
619 }
620 }
621
622 fn name_texts(
626 &self,
627 ambiguous: Vec<(FileId, ExportNameId, ExportNamespace)>,
628 ) -> Vec<(FileId, &str, ExportNamespace)> {
629 if ambiguous.is_empty() {
630 return Vec::new();
631 }
632 let table = self.name_table();
633 ambiguous
634 .into_iter()
635 .filter_map(|(file_id, name, namespace)| {
636 table
637 .get(name.0)
638 .copied()
639 .map(|text| (file_id, text, namespace))
640 })
641 .collect()
642 }
643
644 fn name_table(&self) -> Vec<&str> {
646 let mut table = vec![""; self.name_ids.len()];
647 for (name, id) in &self.name_ids {
648 if let Some(slot) = table.get_mut(id.0) {
649 *slot = name.as_ref();
650 }
651 }
652 table
653 }
654
655 pub(super) fn unique_bindings(
656 &self,
657 file_id: FileId,
658 namespace: ExportNamespace,
659 ) -> FxHashSet<EffectiveExportBinding> {
660 let Some(names) = self.names_by_file.get(&file_id) else {
661 return FxHashSet::default();
662 };
663 names
664 .iter()
665 .filter_map(|name| {
666 match self
667 .resolutions
668 .get(&ExportKey::new(file_id, *name))?
669 .effective(namespace)
670 {
671 EffectiveExportResolution::Unique(binding) => Some(binding),
672 EffectiveExportResolution::Missing | EffectiveExportResolution::Ambiguous => {
673 None
674 }
675 }
676 })
677 .collect()
678 }
679
680 pub(super) fn declaration_group_slots(&self, binding: EffectiveExportBinding) -> &[usize] {
681 binding
682 .origin_slot()
683 .and_then(|slot| {
684 self.declaration_merge_groups
685 .group_by_slot
686 .get(&(binding.origin_file(), slot))
687 })
688 .and_then(|group| self.declaration_merge_groups.groups.get(*group))
689 .map_or(&[], Box::as_ref)
690 }
691
692 pub(super) fn is_declaration_slot(
693 &self,
694 exports: &[ExportSymbol],
695 file_id: FileId,
696 name: &str,
697 namespace: ExportNamespace,
698 export_index: usize,
699 ) -> bool {
700 let Some(export) = exports.get(export_index) else {
701 return false;
702 };
703 if !export.name.matches_str(name) {
704 return false;
705 }
706 let EffectiveExportResolution::Unique(binding) = self.resolve(file_id, name, namespace)
707 else {
708 return false;
709 };
710 if binding.origin_file() != file_id {
711 return true;
712 }
713 let Some(origin_slot) = binding.origin_slot() else {
714 return true;
715 };
716 if namespace == ExportNamespace::Type {
717 let group = self.declaration_group_slots(binding);
718 if !group.is_empty() {
719 return group.contains(&export_index);
720 }
721 }
722 exports
723 .get(origin_slot)
724 .is_some_and(|origin| export.is_type_only == origin.is_type_only)
725 }
726
727 pub(super) fn declaration_slots(
728 &self,
729 exports: &[ExportSymbol],
730 candidates: &[usize],
731 file_id: FileId,
732 name: &str,
733 namespace: ExportNamespace,
734 ) -> Vec<usize> {
735 let mut slots = Vec::new();
736 self.extend_declaration_slots(
737 DeclarationSlotQuery {
738 exports,
739 candidates,
740 file_id,
741 name,
742 namespace,
743 },
744 &mut slots,
745 );
746 slots
747 }
748
749 pub(super) fn extend_declaration_slots(
751 &self,
752 query: DeclarationSlotQuery<'_>,
753 slots: &mut Vec<usize>,
754 ) {
755 let DeclarationSlotQuery {
756 exports,
757 candidates,
758 file_id,
759 name,
760 namespace,
761 } = query;
762 let EffectiveExportResolution::Unique(binding) = self.resolve(file_id, name, namespace)
763 else {
764 return;
765 };
766 if binding.origin_file() == file_id && binding.origin_slot().is_some() {
767 slots.extend(candidates.iter().copied().filter(|&index| {
768 self.is_declaration_slot(exports, file_id, name, namespace, index)
769 }));
770 return;
771 }
772
773 let exact_type_only = namespace == ExportNamespace::Type
774 && candidates.iter().any(|&index| exports[index].is_type_only);
775 slots.extend(candidates.iter().copied().filter(|&index| {
776 exports[index].name.matches_str(name) && exports[index].is_type_only == exact_type_only
777 }));
778 }
779}
780
781#[derive(Clone, Copy)]
783pub(in crate::graph) struct DeclarationSlotQuery<'a> {
784 pub(in crate::graph) exports: &'a [ExportSymbol],
785 pub(in crate::graph) candidates: &'a [usize],
786 pub(in crate::graph) file_id: FileId,
787 pub(in crate::graph) name: &'a str,
788 pub(in crate::graph) namespace: ExportNamespace,
789}
790
791fn index_names_by_file(
792 resolutions: &FxHashMap<ExportKey, NamespaceResolutions>,
793) -> FxHashMap<FileId, Box<[ExportNameId]>> {
794 let mut names_by_file: FxHashMap<FileId, Vec<ExportNameId>> = FxHashMap::default();
795 for key in resolutions.keys() {
796 names_by_file.entry(key.file_id).or_default().push(key.name);
797 }
798 names_by_file
799 .into_iter()
800 .map(|(file_id, mut names)| {
801 names.sort_unstable_by_key(|name| name.0);
802 (file_id, names.into_boxed_slice())
803 })
804 .collect()
805}
806
807fn collect_declaration_merge_groups(modules: &[ResolvedModule]) -> DeclarationMergeGroups {
808 let mut collected = DeclarationMergeGroups::default();
809 for module in modules {
810 let merge_facts: Vec<_> = module
811 .semantic_facts
812 .iter()
813 .filter_map(|fact| match fact {
814 fallow_types::extract::SemanticFact::DeclarationMerge(group) => Some(group),
815 _ => None,
816 })
817 .collect();
818 if merge_facts.is_empty() {
819 continue;
820 }
821 let slot_by_span: FxHashMap<_, _> = module
822 .exports
823 .iter()
824 .enumerate()
825 .map(|(slot, export)| ((export.span.start, export.span.end), slot))
826 .collect();
827 for group in merge_facts {
828 let mut slots: Vec<_> = group
829 .export_spans
830 .iter()
831 .filter_map(|span| slot_by_span.get(span).copied())
832 .collect();
833 slots.sort_unstable();
834 slots.dedup();
835 if slots.len() < 2 {
836 continue;
837 }
838 let group_id = collected.groups.len();
839 for &slot in &slots {
840 collected
841 .group_by_slot
842 .insert((module.file_id, slot), group_id);
843 }
844 collected.groups.push(slots.into_boxed_slice());
845 }
846 }
847 collected
848}
849
850fn modules_needing_type_fallback(modules: &[ResolvedModule]) -> FxHashSet<FileId> {
859 let mut needing = FxHashSet::default();
860 let mut pending: Vec<FileId> = modules
861 .iter()
862 .filter(|module| {
863 module
864 .re_exports
865 .iter()
866 .any(|re_export| re_export.info.is_type_only && reads_source_lanes(&re_export.info))
867 })
868 .map(|module| module.file_id)
869 .collect();
870 if pending.is_empty() {
871 return needing;
872 }
873
874 let mut edges = ReExportEdges::collect(modules);
875 let mut fed_by_type_only = FxHashSet::default();
876 while let Some(file_id) = pending.pop() {
877 if !fed_by_type_only.insert(file_id) {
878 continue;
879 }
880 pending.extend(edges.barrels_by_source.remove(&file_id).unwrap_or_default());
881 }
882
883 let mut pending: Vec<FileId> = fed_by_type_only.into_iter().collect();
884 while let Some(file_id) = pending.pop() {
885 if !needing.insert(file_id) {
886 continue;
887 }
888 if let Some(sources) = edges.sources_by_barrel.get(&file_id) {
889 pending.extend(sources.iter().copied());
890 }
891 }
892 needing
893}
894
895struct ReExportEdges {
897 sources_by_barrel: FxHashMap<FileId, Vec<FileId>>,
898 barrels_by_source: FxHashMap<FileId, Vec<FileId>>,
899}
900
901impl ReExportEdges {
902 fn collect(modules: &[ResolvedModule]) -> Self {
903 let mut edges = Self {
904 sources_by_barrel: FxHashMap::default(),
905 barrels_by_source: FxHashMap::default(),
906 };
907 for module in modules {
908 for re_export in &module.re_exports {
909 if !reads_source_lanes(&re_export.info) {
910 continue;
911 }
912 let Some(source) = re_export.target.internal_file_id() else {
913 continue;
914 };
915 edges
916 .sources_by_barrel
917 .entry(module.file_id)
918 .or_default()
919 .push(source);
920 edges
921 .barrels_by_source
922 .entry(source)
923 .or_default()
924 .push(module.file_id);
925 }
926 }
927 edges
928 }
929}
930
931fn reads_source_lanes(info: &fallow_types::extract::ReExportInfo) -> bool {
935 info.imported_name != "*" || info.exported_name == "*"
936}
937
938fn seed_direct_bindings(
939 modules: &[ResolvedModule],
940 type_fallback_modules: &FxHashSet<FileId>,
941 interner: &mut ExportNameInterner,
942 resolutions: &mut FxHashMap<ExportKey, NamespaceResolutions>,
943 queue: &mut VecDeque<ExportLookup>,
944) {
945 for module in modules {
946 let seed_type_fallback = type_fallback_modules.contains(&module.file_id);
947 for (slot, export) in module.exports.iter().enumerate() {
948 let lane = if export.is_type_only {
949 ResolutionLane::Type
950 } else {
951 ResolutionLane::Value
952 };
953 let name = interner.intern_export_name(&export.name);
954 let key = ExportLookup::new(module.file_id, name, lane);
955 let binding = EffectiveExportResolution::Unique(EffectiveExportBinding {
956 file_id: module.file_id,
957 kind: EffectiveExportBindingKind::Declaration(slot),
958 });
959 let entry = resolutions.entry(key.key).or_default();
960 if entry.seeded.claim_direct(lane) && entry.merge(lane, binding) {
965 queue.push_back(key);
966 }
967 if lane == ResolutionLane::Value {
968 entry.seeded.reserve_type_for_value_declaration();
972 if seed_type_fallback
973 && entry.seeded.claim_direct(ResolutionLane::TypeFallback)
974 && entry.merge(ResolutionLane::TypeFallback, binding)
975 {
976 queue.push_back(ExportLookup::new(
977 module.file_id,
978 name,
979 ResolutionLane::TypeFallback,
980 ));
981 }
982 }
983 }
984 seed_implicit_default(module, interner, resolutions, queue);
985 }
986}
987
988fn seed_implicit_default(
989 module: &ResolvedModule,
990 interner: &mut ExportNameInterner,
991 resolutions: &mut FxHashMap<ExportKey, NamespaceResolutions>,
992 queue: &mut VecDeque<ExportLookup>,
993) {
994 if !has_implicit_default(&module.path) {
995 return;
996 }
997 let name = interner.intern("default");
998 let key = ExportKey::new(module.file_id, name);
999 let entry = resolutions.entry(key).or_default();
1000 if entry.seeded.is_direct(ResolutionLane::Value) {
1001 return;
1002 }
1003 let binding = EffectiveExportResolution::Unique(EffectiveExportBinding {
1004 file_id: module.file_id,
1005 kind: EffectiveExportBindingKind::ImplicitDefault,
1006 });
1007 for lane in [ResolutionLane::Value, ResolutionLane::Type] {
1008 entry.seeded.claim_direct(lane);
1009 if entry.merge(lane, binding) {
1010 queue.push_back(ExportLookup::new(module.file_id, name, lane));
1011 }
1012 }
1013}
1014
1015fn has_implicit_default(path: &std::path::Path) -> bool {
1021 matches!(
1022 path.extension().and_then(std::ffi::OsStr::to_str),
1023 Some("vue" | "svelte" | "astro")
1024 ) || super::build::is_css_module_path(path)
1025}
1026
1027fn collect_observers(
1028 modules: &[ResolvedModule],
1029 type_fallback_modules: &FxHashSet<FileId>,
1030 interner: &mut ExportNameInterner,
1031 resolutions: &mut FxHashMap<ExportKey, NamespaceResolutions>,
1032 queue: &mut VecDeque<ExportLookup>,
1033) -> PropagationObservers {
1034 let mut observers = PropagationObservers {
1035 named: FxHashMap::default(),
1036 star: FxHashMap::default(),
1037 };
1038 for module in modules {
1039 let type_fallback = type_fallback_modules.contains(&module.file_id);
1040 for (re_export_index, re_export) in module.re_exports.iter().enumerate() {
1041 let Some(source) = re_export.target.internal_file_id() else {
1042 if re_export.info.exported_name != "*" {
1043 register_opaque_re_export(
1044 module.file_id,
1045 re_export_index,
1046 &re_export.info,
1047 interner,
1048 resolutions,
1049 queue,
1050 );
1051 }
1052 continue;
1053 };
1054 if re_export.info.exported_name == "*" {
1055 observers
1056 .star
1057 .entry(source)
1058 .or_default()
1059 .push(StarObserver {
1060 barrel: module.file_id,
1061 type_only: re_export.info.is_type_only,
1062 type_fallback,
1063 });
1064 continue;
1065 }
1066 register_named_observer(
1067 module.file_id,
1068 source,
1069 &re_export.info,
1070 ObserverBuildState {
1071 type_fallback,
1072 interner,
1073 resolutions,
1074 queue,
1075 observers: &mut observers,
1076 },
1077 );
1078 }
1079 }
1080 observers
1081}
1082
1083fn register_opaque_re_export(
1092 barrel: FileId,
1093 re_export_index: usize,
1094 info: &fallow_types::extract::ReExportInfo,
1095 interner: &mut ExportNameInterner,
1096 resolutions: &mut FxHashMap<ExportKey, NamespaceResolutions>,
1097 queue: &mut VecDeque<ExportLookup>,
1098) {
1099 let exported_name = interner.intern(&info.exported_name);
1100 let binding = EffectiveExportResolution::Unique(EffectiveExportBinding {
1101 file_id: barrel,
1102 kind: EffectiveExportBindingKind::ExternalReExport(re_export_index),
1103 });
1104 let lanes: &[ResolutionLane] = if info.is_type_only {
1105 &[ResolutionLane::Type]
1106 } else {
1107 &[ResolutionLane::Type, ResolutionLane::Value]
1108 };
1109 for &lane in lanes {
1110 let destination = ExportLookup::new(barrel, exported_name, lane);
1111 let entry = resolutions.entry(destination.key).or_default();
1112 if entry.seeded.is_direct(lane) {
1113 continue;
1114 }
1115 entry.seeded.claim_explicit(lane);
1116 if entry.merge(lane, binding) {
1117 queue.push_back(destination);
1118 }
1119 }
1120}
1121
1122fn register_named_observer(
1123 barrel: FileId,
1124 source: FileId,
1125 info: &fallow_types::extract::ReExportInfo,
1126 state: ObserverBuildState<'_>,
1127) {
1128 let ObserverBuildState {
1129 type_fallback,
1130 interner,
1131 resolutions,
1132 queue,
1133 observers,
1134 } = state;
1135 let exported_name = interner.intern(&info.exported_name);
1136 if info.imported_name == "*" {
1137 let lanes: &[ResolutionLane] = if info.is_type_only {
1138 &[ResolutionLane::Type]
1139 } else {
1140 &[ResolutionLane::Type, ResolutionLane::Value]
1141 };
1142 let binding = EffectiveExportResolution::Unique(EffectiveExportBinding {
1143 file_id: barrel,
1144 kind: EffectiveExportBindingKind::NamespaceObject { source },
1145 });
1146 for &lane in lanes {
1147 let destination = ExportLookup::new(barrel, exported_name, lane);
1148 let entry = resolutions.entry(destination.key).or_default();
1149 if entry.seeded.is_direct(lane) {
1150 continue;
1151 }
1152 entry.seeded.claim_explicit(lane);
1153 if entry.merge(lane, binding) {
1154 queue.push_back(destination);
1155 }
1156 }
1157 return;
1158 }
1159
1160 let imported_name = interner.intern(&info.imported_name);
1161 let lanes: &[ResolutionLane] = match (info.is_type_only, type_fallback) {
1162 (true, _) => &[ResolutionLane::Type, ResolutionLane::TypeFallback],
1163 (false, true) => &[
1164 ResolutionLane::Type,
1165 ResolutionLane::TypeFallback,
1166 ResolutionLane::Value,
1167 ],
1168 (false, false) => &[ResolutionLane::Type, ResolutionLane::Value],
1169 };
1170 for &lane in lanes {
1171 let destination = ExportLookup::new(barrel, exported_name, lane);
1172 let entry = resolutions.entry(destination.key).or_default();
1173 if entry.seeded.is_direct(lane) {
1174 continue;
1175 }
1176 entry.seeded.claim_explicit(lane);
1177 observers
1178 .named
1179 .entry(ExportLookup::new(source, imported_name, lane))
1180 .and_modify(|destinations| destinations.push(destination))
1181 .or_insert(NamedDestinations::One(destination));
1182 }
1183}
1184
1185fn propagate_bindings(
1186 resolutions: &mut FxHashMap<ExportKey, NamespaceResolutions>,
1187 queue: &mut VecDeque<ExportLookup>,
1188 observers: &PropagationObservers,
1189) {
1190 while let Some(source_key) = queue.pop_front() {
1191 let Some(source_resolution) = resolutions
1192 .get(&source_key.key)
1193 .map(|resolutions| resolutions.get(source_key.lane))
1194 else {
1195 continue;
1196 };
1197 if let Some(destinations) = observers.named.get(&source_key) {
1198 for destination in destinations.iter() {
1199 merge_resolution(resolutions, queue, *destination, source_resolution);
1200 }
1201 }
1202 propagate_star_binding(
1203 resolutions,
1204 queue,
1205 observers,
1206 &source_key,
1207 source_resolution,
1208 );
1209 }
1210}
1211
1212fn propagate_star_binding(
1213 resolutions: &mut FxHashMap<ExportKey, NamespaceResolutions>,
1214 queue: &mut VecDeque<ExportLookup>,
1215 observers: &PropagationObservers,
1216 source_key: &ExportLookup,
1217 source_resolution: EffectiveExportResolution,
1218) {
1219 if source_key.key.name == ExportNameId::DEFAULT {
1220 return;
1221 }
1222 let Some(star_observers) = observers.star.get(&source_key.key.file_id) else {
1223 return;
1224 };
1225 for observer in star_observers {
1226 if observer.type_only && source_key.lane == ResolutionLane::Value {
1227 continue;
1228 }
1229 if !observer.type_fallback && source_key.lane == ResolutionLane::TypeFallback {
1230 continue;
1231 }
1232 let destination = source_key.with_file(observer.barrel);
1233 let entry = resolutions.entry(destination.key).or_default();
1234 if entry.seeded.is_explicit(destination.lane) {
1235 continue;
1236 }
1237 if entry.merge(destination.lane, source_resolution) {
1238 queue.push_back(destination);
1239 }
1240 }
1241}
1242
1243fn merge_resolution(
1244 resolutions: &mut FxHashMap<ExportKey, NamespaceResolutions>,
1245 queue: &mut VecDeque<ExportLookup>,
1246 key: ExportLookup,
1247 incoming: EffectiveExportResolution,
1248) {
1249 if resolutions
1250 .entry(key.key)
1251 .or_default()
1252 .merge(key.lane, incoming)
1253 {
1254 queue.push_back(key);
1255 }
1256}
1257
1258#[cfg(test)]
1259mod tests {
1260 use super::*;
1261 use crate::resolve::{ResolveResult, ResolvedReExport};
1262 use fallow_types::extract::{ExportInfo, ReExportInfo, VisibilityTag};
1263
1264 fn value_export(name: &str) -> ExportInfo {
1265 ExportInfo {
1266 name: ExportName::Named(name.to_string()),
1267 local_name: Some(name.to_string()),
1268 is_type_only: false,
1269 visibility: VisibilityTag::None,
1270 expected_unused_reason: None,
1271 span: oxc_span::Span::default(),
1272 members: Vec::new(),
1273 is_side_effect_used: false,
1274 super_class: None,
1275 deprecated: false,
1276 deprecated_reason: None,
1277 }
1278 }
1279
1280 fn re_export(source: FileId, imported: &str, exported: &str) -> ResolvedReExport {
1281 ResolvedReExport {
1282 info: ReExportInfo {
1283 source: format!("./{}", source.0),
1284 imported_name: imported.to_string(),
1285 exported_name: exported.to_string(),
1286 is_type_only: false,
1287 span: oxc_span::Span::default(),
1288 statement_span: oxc_span::Span::default(),
1289 source_span: oxc_span::Span::default(),
1290 visibility: VisibilityTag::None,
1291 expected_unused_reason: None,
1292 },
1293 target: ResolveResult::InternalModule(source),
1294 }
1295 }
1296
1297 fn module(
1298 file_id: u32,
1299 exports: Vec<ExportInfo>,
1300 re_exports: Vec<ResolvedReExport>,
1301 ) -> ResolvedModule {
1302 ResolvedModule {
1303 file_id: FileId(file_id),
1304 exports: exports.into(),
1305 re_exports,
1306 ..Default::default()
1307 }
1308 }
1309
1310 fn resolves_through(
1311 index: &EffectiveExportIndex,
1312 barrel: FileId,
1313 source: FileId,
1314 name: &str,
1315 ) -> bool {
1316 index.resolves_through(barrel, name, source, name, ExportNamespace::Value)
1317 }
1318
1319 fn external_re_export(imported: &str, exported: &str, type_only: bool) -> ResolvedReExport {
1320 ResolvedReExport {
1321 info: ReExportInfo {
1322 source: "node:path".to_string(),
1323 imported_name: imported.to_string(),
1324 exported_name: exported.to_string(),
1325 is_type_only: type_only,
1326 span: oxc_span::Span::default(),
1327 statement_span: oxc_span::Span::default(),
1328 source_span: oxc_span::Span::default(),
1329 visibility: VisibilityTag::None,
1330 expected_unused_reason: None,
1331 },
1332 target: ResolveResult::NpmPackage("node:path".to_string()),
1333 }
1334 }
1335
1336 #[test]
1337 fn external_named_re_exports_keep_an_opaque_local_binding() {
1338 let index = EffectiveExportIndex::build(&[module(
1339 0,
1340 Vec::new(),
1341 vec![
1342 external_re_export("join", "join", false),
1343 external_re_export("Stats", "Stats", true),
1344 external_re_export("*", "path", false),
1345 ],
1346 )]);
1347 let encoded = postcard::to_allocvec(&index).expect("encode effective export index");
1348 let decoded: EffectiveExportIndex =
1349 postcard::from_bytes(&encoded).expect("decode effective export index");
1350
1351 let value = decoded.resolve(FileId(0), "join", ExportNamespace::Value);
1352 assert!(matches!(
1353 value,
1354 EffectiveExportResolution::Unique(binding)
1355 if binding.origin_file() == FileId(0) && binding.origin_slot().is_none()
1356 ));
1357 assert_eq!(
1358 value,
1359 decoded.resolve(FileId(0), "join", ExportNamespace::Type)
1360 );
1361 assert!(matches!(
1362 decoded.resolve(FileId(0), "Stats", ExportNamespace::Type),
1363 EffectiveExportResolution::Unique(_)
1364 ));
1365 assert_eq!(
1366 decoded.resolve(FileId(0), "Stats", ExportNamespace::Value),
1367 EffectiveExportResolution::Missing
1368 );
1369 assert_eq!(
1370 decoded.resolve(FileId(0), "path", ExportNamespace::Type),
1371 decoded.resolve(FileId(0), "path", ExportNamespace::Value)
1372 );
1373 }
1374
1375 #[test]
1376 fn unresolved_named_re_exports_keep_an_opaque_local_binding() {
1377 let mut unresolved = external_re_export("missing", "missing", false);
1378 unresolved.target = ResolveResult::Unresolvable("./missing".to_string());
1379 let mut unresolved_star = external_re_export("*", "*", false);
1380 unresolved_star.target = ResolveResult::Unresolvable("./missing-star".to_string());
1381 let index = EffectiveExportIndex::build(&[module(
1382 0,
1383 Vec::new(),
1384 vec![unresolved, unresolved_star],
1385 )]);
1386
1387 for namespace in [ExportNamespace::Type, ExportNamespace::Value] {
1388 assert!(matches!(
1389 index.resolve(FileId(0), "missing", namespace),
1390 EffectiveExportResolution::Unique(binding)
1391 if binding.origin_file() == FileId(0) && binding.origin_slot().is_none()
1392 ));
1393 assert_eq!(
1394 index.resolve(FileId(0), "other", namespace),
1395 EffectiveExportResolution::Missing,
1396 "an unresolved star re-export must not invent names"
1397 );
1398 }
1399 }
1400
1401 #[test]
1402 fn missing_export_is_explicit_in_the_resolution_contract() {
1403 let index = EffectiveExportIndex::build(&[module(0, Vec::new(), Vec::new())]);
1404
1405 assert_eq!(
1406 index.resolve(FileId(0), "missing", ExportNamespace::Value),
1407 EffectiveExportResolution::Missing
1408 );
1409 }
1410
1411 #[test]
1412 fn same_module_declaration_merges_keep_one_binding() {
1413 let index = EffectiveExportIndex::build(&[module(
1414 0,
1415 vec![value_export("Merged"), value_export("Merged")],
1416 Vec::new(),
1417 )]);
1418
1419 assert!(matches!(
1420 index.resolve(FileId(0), "Merged", ExportNamespace::Value),
1421 EffectiveExportResolution::Unique(binding) if binding.origin_file() == FileId(0)
1422 ));
1423 }
1424
1425 #[test]
1426 fn declaration_merge_groups_survive_graph_cache_roundtrip() {
1427 let mut interface = value_export("Merged");
1428 interface.is_type_only = true;
1429 interface.span = oxc_span::Span::new(0, 6);
1430 let mut namespace = value_export("Merged");
1431 namespace.span = oxc_span::Span::new(10, 16);
1432 let modules = vec![ResolvedModule {
1433 file_id: FileId(0),
1434 exports: vec![interface, namespace].into(),
1435 semantic_facts: vec![fallow_types::extract::SemanticFact::DeclarationMerge(
1436 fallow_types::extract::DeclarationMergeFact {
1437 export_spans: vec![(0, 6), (10, 16)],
1438 },
1439 )]
1440 .into(),
1441 ..Default::default()
1442 }];
1443 let index = EffectiveExportIndex::build(&modules);
1444 let encoded = postcard::to_allocvec(&index).expect("encode effective export index");
1445 let decoded: EffectiveExportIndex =
1446 postcard::from_bytes(&encoded).expect("decode effective export index");
1447 let EffectiveExportResolution::Unique(binding) =
1448 decoded.resolve(FileId(0), "Merged", ExportNamespace::Type)
1449 else {
1450 panic!("merged type binding must remain unique");
1451 };
1452
1453 assert_eq!(decoded.declaration_group_slots(binding), &[0, 1]);
1454 }
1455
1456 #[test]
1457 fn explicit_re_export_shadows_a_star_binding() {
1458 let modules = vec![
1459 module(
1460 0,
1461 Vec::new(),
1462 vec![
1463 re_export(FileId(1), "*", "*"),
1464 re_export(FileId(2), "foo", "foo"),
1465 ],
1466 ),
1467 module(1, vec![value_export("foo")], Vec::new()),
1468 module(2, vec![value_export("foo")], Vec::new()),
1469 ];
1470 let index = EffectiveExportIndex::build(&modules);
1471
1472 assert!(!resolves_through(&index, FileId(0), FileId(1), "foo"));
1473 assert!(resolves_through(&index, FileId(0), FileId(2), "foo"));
1474 assert!(!index.contributes_through(
1475 FileId(0),
1476 "foo",
1477 FileId(1),
1478 "foo",
1479 ExportNamespace::Value
1480 ));
1481 }
1482
1483 #[test]
1484 fn distinct_star_bindings_are_ambiguous() {
1485 let modules = vec![
1486 module(
1487 0,
1488 Vec::new(),
1489 vec![
1490 re_export(FileId(1), "*", "*"),
1491 re_export(FileId(2), "*", "*"),
1492 ],
1493 ),
1494 module(1, vec![value_export("foo")], Vec::new()),
1495 module(2, vec![value_export("foo")], Vec::new()),
1496 ];
1497 let index = EffectiveExportIndex::build(&modules);
1498
1499 assert!(!resolves_through(&index, FileId(0), FileId(1), "foo"));
1500 assert!(!resolves_through(&index, FileId(0), FileId(2), "foo"));
1501 assert!(index.contributes_through(
1502 FileId(0),
1503 "foo",
1504 FileId(1),
1505 "foo",
1506 ExportNamespace::Value
1507 ));
1508 assert!(index.contributes_through(
1509 FileId(0),
1510 "foo",
1511 FileId(2),
1512 "foo",
1513 ExportNamespace::Value
1514 ));
1515 }
1516
1517 #[test]
1518 fn convergent_star_paths_keep_one_binding() {
1519 let modules = vec![
1520 module(
1521 0,
1522 Vec::new(),
1523 vec![
1524 re_export(FileId(1), "*", "*"),
1525 re_export(FileId(2), "*", "*"),
1526 ],
1527 ),
1528 module(1, Vec::new(), vec![re_export(FileId(3), "*", "*")]),
1529 module(2, Vec::new(), vec![re_export(FileId(3), "*", "*")]),
1530 module(3, vec![value_export("foo")], Vec::new()),
1531 ];
1532 let index = EffectiveExportIndex::build(&modules);
1533
1534 assert!(resolves_through(&index, FileId(0), FileId(1), "foo"));
1535 assert!(resolves_through(&index, FileId(0), FileId(2), "foo"));
1536 }
1537
1538 #[test]
1539 fn a_real_type_declaration_wins_over_a_value_type_fallback() {
1540 let mut interface = value_export("User");
1541 interface.is_type_only = true;
1542 let modules = vec![
1543 module(
1544 0,
1545 Vec::new(),
1546 vec![
1547 re_export(FileId(1), "*", "*"),
1548 re_export(FileId(2), "*", "*"),
1549 ],
1550 ),
1551 module(1, vec![value_export("User")], Vec::new()),
1552 module(2, vec![interface], Vec::new()),
1553 ];
1554 let index = EffectiveExportIndex::build(&modules);
1555
1556 assert!(matches!(
1557 index.resolve(FileId(0), "User", ExportNamespace::Type),
1558 EffectiveExportResolution::Unique(binding) if binding.origin_file() == FileId(2)
1559 ));
1560 assert!(matches!(
1561 index.resolve(FileId(0), "User", ExportNamespace::Value),
1562 EffectiveExportResolution::Unique(binding) if binding.origin_file() == FileId(1)
1563 ));
1564 assert!(index.resolves_through(
1565 FileId(0),
1566 "User",
1567 FileId(2),
1568 "User",
1569 ExportNamespace::Type
1570 ));
1571 assert!(index.resolves_through(
1572 FileId(0),
1573 "User",
1574 FileId(1),
1575 "User",
1576 ExportNamespace::Value
1577 ));
1578 }
1579
1580 #[test]
1581 fn colliding_real_type_declarations_stay_ambiguous() {
1582 let type_export = |name: &str| {
1583 let mut export = value_export(name);
1584 export.is_type_only = true;
1585 export
1586 };
1587 let modules = vec![
1588 module(
1589 0,
1590 Vec::new(),
1591 vec![
1592 re_export(FileId(1), "*", "*"),
1593 re_export(FileId(2), "*", "*"),
1594 ],
1595 ),
1596 module(1, vec![type_export("User")], Vec::new()),
1597 module(2, vec![type_export("User")], Vec::new()),
1598 ];
1599 let index = EffectiveExportIndex::build(&modules);
1600
1601 assert_eq!(
1602 index.resolve(FileId(0), "User", ExportNamespace::Type),
1603 EffectiveExportResolution::Ambiguous
1604 );
1605 assert_eq!(
1606 index.ambiguous_names_on(FileId(0)),
1607 vec![(FileId(0), "User", ExportNamespace::Type)]
1608 );
1609 }
1610
1611 #[test]
1612 fn a_colliding_value_export_reports_one_collision_in_the_value_namespace() {
1613 let modules = vec![
1614 module(
1615 0,
1616 Vec::new(),
1617 vec![
1618 re_export(FileId(1), "*", "*"),
1619 re_export(FileId(2), "*", "*"),
1620 ],
1621 ),
1622 module(1, vec![value_export("foo")], Vec::new()),
1623 module(2, vec![value_export("foo")], Vec::new()),
1624 ];
1625 let index = EffectiveExportIndex::build(&modules);
1626
1627 assert_eq!(
1628 index.ambiguous_names(),
1629 vec![(FileId(0), "foo", ExportNamespace::Value)]
1630 );
1631 }
1632
1633 #[test]
1634 fn a_value_export_still_carries_its_type_meaning_through_a_barrel() {
1635 let modules = vec![
1636 module(0, Vec::new(), vec![re_export(FileId(1), "*", "*")]),
1637 module(1, vec![value_export("Widget")], Vec::new()),
1638 ];
1639 let index = EffectiveExportIndex::build(&modules);
1640
1641 assert!(index.resolves_through(
1642 FileId(0),
1643 "Widget",
1644 FileId(1),
1645 "Widget",
1646 ExportNamespace::Type
1647 ));
1648 }
1649
1650 #[test]
1651 fn a_type_only_re_export_carries_a_value_declaration_as_a_type_only() {
1652 let mut type_only = re_export(FileId(1), "Widget", "Widget");
1653 type_only.info.is_type_only = true;
1654 let index = EffectiveExportIndex::build(&[
1655 module(0, Vec::new(), vec![type_only]),
1656 module(1, vec![value_export("Widget")], Vec::new()),
1657 ]);
1658
1659 assert!(matches!(
1660 index.resolve(FileId(0), "Widget", ExportNamespace::Type),
1661 EffectiveExportResolution::Unique(binding) if binding.origin_file() == FileId(1)
1662 ));
1663 assert_eq!(
1664 index.resolve(FileId(0), "Widget", ExportNamespace::Value),
1665 EffectiveExportResolution::Missing
1666 );
1667 }
1668
1669 #[test]
1670 fn a_type_only_re_export_reaches_a_value_declaration_behind_a_barrel() {
1671 let mut type_only = re_export(FileId(1), "Widget", "Widget");
1672 type_only.info.is_type_only = true;
1673 let index = EffectiveExportIndex::build(&[
1674 module(0, Vec::new(), vec![type_only]),
1675 module(1, Vec::new(), vec![re_export(FileId(2), "*", "*")]),
1676 module(2, vec![value_export("Widget")], Vec::new()),
1677 ]);
1678
1679 assert!(matches!(
1680 index.resolve(FileId(0), "Widget", ExportNamespace::Type),
1681 EffectiveExportResolution::Unique(binding) if binding.origin_file() == FileId(2)
1682 ));
1683 }
1684
1685 #[test]
1686 fn a_type_only_re_export_shadows_a_star_binding_in_the_type_namespace() {
1687 let mut type_only = re_export(FileId(1), "foo", "foo");
1688 type_only.info.is_type_only = true;
1689 let index = EffectiveExportIndex::build(&[
1690 module(
1691 0,
1692 Vec::new(),
1693 vec![type_only, re_export(FileId(2), "*", "*")],
1694 ),
1695 module(1, vec![value_export("foo")], Vec::new()),
1696 module(2, vec![value_export("foo")], Vec::new()),
1697 ]);
1698
1699 assert!(matches!(
1700 index.resolve(FileId(0), "foo", ExportNamespace::Type),
1701 EffectiveExportResolution::Unique(binding) if binding.origin_file() == FileId(1)
1702 ));
1703 assert!(matches!(
1704 index.resolve(FileId(0), "foo", ExportNamespace::Value),
1705 EffectiveExportResolution::Unique(binding) if binding.origin_file() == FileId(2)
1706 ));
1707 }
1708
1709 #[test]
1710 fn a_type_only_barrel_still_sees_a_star_collision_as_ambiguous() {
1711 let mut type_only = re_export(FileId(1), "foo", "foo");
1712 type_only.info.is_type_only = true;
1713 let index = EffectiveExportIndex::build(&[
1714 module(0, Vec::new(), vec![type_only]),
1715 module(
1716 1,
1717 Vec::new(),
1718 vec![
1719 re_export(FileId(2), "*", "*"),
1720 re_export(FileId(3), "*", "*"),
1721 ],
1722 ),
1723 module(2, vec![value_export("foo")], Vec::new()),
1724 module(3, vec![value_export("foo")], Vec::new()),
1725 ]);
1726
1727 assert_eq!(
1728 index.resolve(FileId(0), "foo", ExportNamespace::Type),
1729 EffectiveExportResolution::Ambiguous
1730 );
1731 }
1732
1733 #[test]
1734 fn a_star_collision_stays_ambiguous_beside_an_unrelated_type_only_barrel() {
1735 let mut type_only = re_export(FileId(1), "foo", "foo");
1736 type_only.info.is_type_only = true;
1737 let index = EffectiveExportIndex::build(&[
1738 module(0, Vec::new(), vec![type_only]),
1739 module(1, Vec::new(), vec![re_export(FileId(2), "*", "*")]),
1740 module(2, vec![value_export("foo")], Vec::new()),
1741 module(
1742 3,
1743 Vec::new(),
1744 vec![
1745 re_export(FileId(2), "*", "*"),
1746 re_export(FileId(4), "*", "*"),
1747 ],
1748 ),
1749 module(4, vec![value_export("foo")], Vec::new()),
1750 ]);
1751
1752 assert_eq!(
1753 index.resolve(FileId(3), "foo", ExportNamespace::Type),
1754 EffectiveExportResolution::Ambiguous
1755 );
1756 }
1757
1758 #[test]
1759 fn star_exports_exclude_default_bindings() {
1760 let mut default = value_export("local");
1761 default.name = ExportName::Default;
1762 let index = EffectiveExportIndex::build(&[
1763 module(0, Vec::new(), vec![re_export(FileId(1), "*", "*")]),
1764 module(1, vec![default], Vec::new()),
1765 ]);
1766
1767 assert_eq!(
1768 index.resolve(FileId(0), "default", ExportNamespace::Value),
1769 EffectiveExportResolution::Missing
1770 );
1771 }
1772
1773 #[test]
1774 fn star_cycles_converge_on_the_same_binding() {
1775 let index = EffectiveExportIndex::build(&[
1776 module(0, Vec::new(), vec![re_export(FileId(1), "*", "*")]),
1777 module(
1778 1,
1779 Vec::new(),
1780 vec![
1781 re_export(FileId(0), "*", "*"),
1782 re_export(FileId(2), "*", "*"),
1783 ],
1784 ),
1785 module(2, vec![value_export("foo")], Vec::new()),
1786 ]);
1787
1788 assert!(resolves_through(&index, FileId(0), FileId(2), "foo"));
1789 assert!(resolves_through(&index, FileId(1), FileId(2), "foo"));
1790 }
1791
1792 #[test]
1793 fn type_only_namespace_re_export_resolves_only_in_type_namespace() {
1794 let mut namespace = re_export(FileId(1), "*", "Types");
1795 namespace.info.is_type_only = true;
1796 let index = EffectiveExportIndex::build(&[
1797 module(0, Vec::new(), vec![namespace]),
1798 module(1, vec![value_export("foo")], Vec::new()),
1799 ]);
1800
1801 assert!(matches!(
1802 index.resolve(FileId(0), "Types", ExportNamespace::Type),
1803 EffectiveExportResolution::Unique(_)
1804 ));
1805 assert_eq!(
1806 index.resolve(FileId(0), "Types", ExportNamespace::Value),
1807 EffectiveExportResolution::Missing
1808 );
1809 }
1810
1811 #[test]
1812 fn normal_namespace_re_export_resolves_in_both_namespaces() {
1813 let index = EffectiveExportIndex::build(&[
1814 module(0, Vec::new(), vec![re_export(FileId(1), "*", "Namespace")]),
1815 module(1, vec![value_export("foo")], Vec::new()),
1816 ]);
1817
1818 let type_binding = index.resolve(FileId(0), "Namespace", ExportNamespace::Type);
1819 let value_binding = index.resolve(FileId(0), "Namespace", ExportNamespace::Value);
1820 assert!(matches!(type_binding, EffectiveExportResolution::Unique(_)));
1821 assert_eq!(type_binding, value_binding);
1822 }
1823
1824 #[test]
1825 fn persisted_index_remains_queryable_without_reconstruction() {
1826 let index = EffectiveExportIndex::build(&[
1827 module(0, Vec::new(), vec![re_export(FileId(1), "foo", "bar")]),
1828 module(1, vec![value_export("foo")], Vec::new()),
1829 ]);
1830 let encoded = postcard::to_allocvec(&index).expect("encode effective export index");
1831 let decoded: EffectiveExportIndex =
1832 postcard::from_bytes(&encoded).expect("decode effective export index");
1833
1834 assert!(matches!(
1835 decoded.resolve(FileId(0), "bar", ExportNamespace::Value),
1836 EffectiveExportResolution::Unique(binding) if binding.origin_file() == FileId(1)
1837 ));
1838 assert_eq!(
1839 decoded.resolve(FileId(0), "missing", ExportNamespace::Value),
1840 EffectiveExportResolution::Missing
1841 );
1842 }
1843
1844 #[test]
1845 fn sfc_file_has_an_implicit_default_value_binding() {
1846 let mut sfc = module(0, Vec::new(), Vec::new());
1847 sfc.path = std::path::PathBuf::from("/project/Widget.vue");
1848 let index = EffectiveExportIndex::build(&[sfc]);
1849
1850 assert!(matches!(
1851 index.resolve(FileId(0), "default", ExportNamespace::Value),
1852 EffectiveExportResolution::Unique(binding) if binding.origin_file() == FileId(0)
1853 ));
1854 }
1855}