Skip to main content

fallow_graph/graph/
effective_exports.rs

1//! Canonical effective export bindings for direct and transitive re-exports.
2
3use 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/// The namespace in which an exported name is resolved.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
14pub enum ExportNamespace {
15    /// Type declarations and the type side of dual-space declarations.
16    Type,
17    /// Runtime value declarations.
18    Value,
19}
20
21/// One canonical declaration that an exported name resolves to.
22#[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    /// A named re-export whose declaration lives outside this graph: an
36    /// external package, an external file, or an unresolved specifier.
37    /// The re-export slot keeps opaque bindings distinct without pretending
38    /// that Fallow can inspect or canonicalize the external declaration.
39    ExternalReExport(usize),
40}
41
42impl EffectiveExportBinding {
43    /// Module that owns the resolved declaration or opaque external surface.
44    #[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    /// Source module represented by a namespace-object export.
59    #[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    /// Whether this binding is the implicit default export of an SFC file.
70    #[must_use]
71    pub const fn is_implicit_default(self) -> bool {
72        matches!(self.kind, EffectiveExportBindingKind::ImplicitDefault)
73    }
74}
75
76/// Effective resolution for one module/name/namespace tuple.
77#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
78pub enum EffectiveExportResolution {
79    /// The module does not export this name in the requested namespace.
80    #[default]
81    Missing,
82    /// Exactly one canonical declaration supplies the exported name.
83    Unique(EffectiveExportBinding),
84    /// Multiple distinct star-exported declarations supply the same name.
85    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/// Bitset over the two export namespaces, for consumer-side namespace demand.
101#[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/// Propagation lane for one exported name.
159///
160/// The type namespace is resolved in two lanes. `Type` holds declarations that
161/// really occupy TypeScript's type space (`interface`, `type`, `export type`).
162/// `TypeFallback` holds the type meaning synthesized for plain value exports so
163/// dual-space declarations (`class`, `enum`) keep resolving as types. A real
164/// type declaration therefore wins over a synthesized one instead of colliding
165/// with it, while two real declarations still collide into `Ambiguous`.
166///
167/// `TypeFallback` is only seeded where it can differ from `Value`, which is
168/// along re-export paths that reach a type-only re-export; see
169/// [`modules_needing_type_fallback`]. Everywhere else a type query reads the
170/// value lane directly, because both lanes carry the same seeds over the same
171/// edges.
172#[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/// Which lanes of one exported name are claimed by the module itself.
202///
203/// The resolution entry stores these bits so seeding and observer registration
204/// need no separate hash lookup for each lane. Index construction rebuilds the
205/// flags, so the serialized cache omits them.
206#[derive(Debug, Clone, Copy, Default)]
207struct SeededLanes(u8);
208
209impl SeededLanes {
210    /// A value declaration owns its module's type surface without declaring a
211    /// type. Its reservation lives in its own bit so that a same-module type
212    /// declaration can still claim the type lane whichever order they are
213    /// seeded in.
214    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    /// Claim `lane` as locally declared, reporting whether it was unclaimed.
240    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    /// Merge `incoming` into `lane`, reporting whether the lane advanced.
267    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    /// Whether this name collides in type space.
294    ///
295    /// The type meaning synthesized for a colliding value export collides with
296    /// it by construction, so reading the fallback lane unconditionally would
297    /// report one collision twice. A fallback collision only stands on its own
298    /// where the value lane never collided, which is how `export type *`
299    /// sources colliding over value declarations land: the type-only star drops
300    /// the value lane, so the collision exists solely in the fallback lane.
301    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            // Where the fallback lane is not seeded it is also not needed: the
311            // value lane then carries the same seeds over the same edges, so
312            // it answers the type query unchanged.
313            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/// Upfront element counts for the propagation tables.
325///
326/// The tables are keyed by interned name, so they grow into the thousands on
327/// real projects and re-hash repeatedly when they start empty. Counting is a
328/// linear scan over already-resident slices and buys exact capacity.
329#[derive(Clone, Copy)]
330struct ProjectExportSizes {
331    /// Distinct `(file, name)` pairs, an upper bound on the resolution table.
332    keys: usize,
333    /// Distinct `(file, name, lane)` triples, an upper bound on seeded lanes.
334    lane_keys: usize,
335    /// Interned name upper bound: every export plus every re-export alias.
336    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    /// Whether the barrel takes part in the type-fallback lane at all.
401    type_fallback: bool,
402}
403
404/// Destinations fed by one source lane.
405///
406/// A re-exported name almost always has a single barrel destination, so the
407/// common case stays inline instead of allocating a one-element vector per
408/// observed lane.
409enum 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/// Immutable effective export bindings for one resolved project.
444///
445/// Resolution is a finite monotone propagation: each key advances at most from
446/// missing to one binding and then to ambiguous. Cycles therefore terminate,
447/// while multiple paths to the same binding remain unique.
448#[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 resolved on each module, so [`EffectiveExportIndex::unique_bindings`]
453    /// reads one module instead of scanning every key in the project.
454    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    /// The interned id of `name`, or `None` when no module resolves it.
512    pub(in crate::graph) fn name_id(&self, name: &str) -> Option<ExportNameId> {
513        self.name_ids.get(name).copied()
514    }
515
516    /// The names that resolve on `file_id` in any namespace.
517    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    /// Whether `name` resolves on `file_id` in any namespace. A `false` means
522    /// that [`Self::resolve`] returns `Missing` for both namespaces.
523    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    /// Exported names that resolve to a star-export collision.
573    ///
574    /// Every consumer of an `Ambiguous` resolution abstains, so the collision
575    /// itself never reaches a reporting surface even though it is the only
576    /// fact that explains the abstention.
577    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    /// Exported names that collide on one module, for single-symbol queries.
586    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    /// Resolve interned ids back to text, building the reverse table only when
623    /// a collision was actually found: on a project without one the table is a
624    /// pure allocation over every name in the project.
625    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    /// Interned names indexed by their id, for reporting an id back as text.
645    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    /// Append the declaration slots for one name into `slots`.
750    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/// One name's candidate export slots on a module.
782#[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
850/// Modules whose value declarations must also travel the type-fallback lane.
851///
852/// The lane only earns its cost where it can diverge from the value lane, and
853/// the sole divergence is a type-only re-export: it drops the value lane while
854/// still carrying a type meaning. So the lane must reach every module a
855/// type-only re-export feeds, and every module those in turn re-export from,
856/// because a lane that carries one path of a name has to carry all of them or
857/// a collision would resolve as unique.
858fn 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
895/// Internal re-export edges that read a source module's resolution lanes.
896struct 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
931/// Whether a re-export resolves through the source module's own lanes. A
932/// namespace re-export synthesizes its binding instead, so it neither reads
933/// nor needs the source's fallback lane.
934fn 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            // Same-name declarations inside one module form one local export
961            // entry. This covers legal TypeScript declaration merging (for
962            // example class/function plus namespace) without weakening the
963            // ambiguity rule for distinct bindings arriving through stars.
964            if entry.seeded.claim_direct(lane) && entry.merge(lane, binding) {
965                queue.push_back(key);
966            }
967            if lane == ResolutionLane::Value {
968                // A locally declared name owns its module's type surface even
969                // when the declaration only occupies value space, so the type
970                // lane stays reserved and star sources cannot propagate into it.
971                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_sfc_default(module, interner, resolutions, queue);
985    }
986}
987
988fn seed_implicit_sfc_default(
989    module: &ResolvedModule,
990    interner: &mut ExportNameInterner,
991    resolutions: &mut FxHashMap<ExportKey, NamespaceResolutions>,
992    queue: &mut VecDeque<ExportLookup>,
993) {
994    if !is_sfc_path(&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 is_sfc_path(path: &std::path::Path) -> bool {
1016    matches!(
1017        path.extension().and_then(std::ffi::OsStr::to_str),
1018        Some("vue" | "svelte" | "astro")
1019    )
1020}
1021
1022fn collect_observers(
1023    modules: &[ResolvedModule],
1024    type_fallback_modules: &FxHashSet<FileId>,
1025    interner: &mut ExportNameInterner,
1026    resolutions: &mut FxHashMap<ExportKey, NamespaceResolutions>,
1027    queue: &mut VecDeque<ExportLookup>,
1028) -> PropagationObservers {
1029    let mut observers = PropagationObservers {
1030        named: FxHashMap::default(),
1031        star: FxHashMap::default(),
1032    };
1033    for module in modules {
1034        let type_fallback = type_fallback_modules.contains(&module.file_id);
1035        for (re_export_index, re_export) in module.re_exports.iter().enumerate() {
1036            let Some(source) = re_export.target.internal_file_id() else {
1037                if re_export.info.exported_name != "*" {
1038                    register_opaque_re_export(
1039                        module.file_id,
1040                        re_export_index,
1041                        &re_export.info,
1042                        interner,
1043                        resolutions,
1044                        queue,
1045                    );
1046                }
1047                continue;
1048            };
1049            if re_export.info.exported_name == "*" {
1050                observers
1051                    .star
1052                    .entry(source)
1053                    .or_default()
1054                    .push(StarObserver {
1055                        barrel: module.file_id,
1056                        type_only: re_export.info.is_type_only,
1057                        type_fallback,
1058                    });
1059                continue;
1060            }
1061            register_named_observer(
1062                module.file_id,
1063                source,
1064                &re_export.info,
1065                ObserverBuildState {
1066                    type_fallback,
1067                    interner,
1068                    resolutions,
1069                    queue,
1070                    observers: &mut observers,
1071                },
1072            );
1073        }
1074    }
1075    observers
1076}
1077
1078/// Seed an opaque barrel-owned binding for a named re-export whose declaration
1079/// Fallow cannot inspect: an external package, a file outside the project, or
1080/// an unresolved specifier (for example a build output that is not in the
1081/// checkout). The barrel names the export explicitly, so consumers importing
1082/// through the barrel credit the barrel export instead of losing it to a
1083/// missing resolution. The unresolved-import finding keeps the unknown hop
1084/// visible. Star re-exports never reach this path: an unknown star surface
1085/// has no names to credit.
1086fn register_opaque_re_export(
1087    barrel: FileId,
1088    re_export_index: usize,
1089    info: &fallow_types::extract::ReExportInfo,
1090    interner: &mut ExportNameInterner,
1091    resolutions: &mut FxHashMap<ExportKey, NamespaceResolutions>,
1092    queue: &mut VecDeque<ExportLookup>,
1093) {
1094    let exported_name = interner.intern(&info.exported_name);
1095    let binding = EffectiveExportResolution::Unique(EffectiveExportBinding {
1096        file_id: barrel,
1097        kind: EffectiveExportBindingKind::ExternalReExport(re_export_index),
1098    });
1099    let lanes: &[ResolutionLane] = if info.is_type_only {
1100        &[ResolutionLane::Type]
1101    } else {
1102        &[ResolutionLane::Type, ResolutionLane::Value]
1103    };
1104    for &lane in lanes {
1105        let destination = ExportLookup::new(barrel, exported_name, lane);
1106        let entry = resolutions.entry(destination.key).or_default();
1107        if entry.seeded.is_direct(lane) {
1108            continue;
1109        }
1110        entry.seeded.claim_explicit(lane);
1111        if entry.merge(lane, binding) {
1112            queue.push_back(destination);
1113        }
1114    }
1115}
1116
1117fn register_named_observer(
1118    barrel: FileId,
1119    source: FileId,
1120    info: &fallow_types::extract::ReExportInfo,
1121    state: ObserverBuildState<'_>,
1122) {
1123    let ObserverBuildState {
1124        type_fallback,
1125        interner,
1126        resolutions,
1127        queue,
1128        observers,
1129    } = state;
1130    let exported_name = interner.intern(&info.exported_name);
1131    if info.imported_name == "*" {
1132        let lanes: &[ResolutionLane] = if info.is_type_only {
1133            &[ResolutionLane::Type]
1134        } else {
1135            &[ResolutionLane::Type, ResolutionLane::Value]
1136        };
1137        let binding = EffectiveExportResolution::Unique(EffectiveExportBinding {
1138            file_id: barrel,
1139            kind: EffectiveExportBindingKind::NamespaceObject { source },
1140        });
1141        for &lane in lanes {
1142            let destination = ExportLookup::new(barrel, exported_name, lane);
1143            let entry = resolutions.entry(destination.key).or_default();
1144            if entry.seeded.is_direct(lane) {
1145                continue;
1146            }
1147            entry.seeded.claim_explicit(lane);
1148            if entry.merge(lane, binding) {
1149                queue.push_back(destination);
1150            }
1151        }
1152        return;
1153    }
1154
1155    let imported_name = interner.intern(&info.imported_name);
1156    let lanes: &[ResolutionLane] = match (info.is_type_only, type_fallback) {
1157        (true, _) => &[ResolutionLane::Type, ResolutionLane::TypeFallback],
1158        (false, true) => &[
1159            ResolutionLane::Type,
1160            ResolutionLane::TypeFallback,
1161            ResolutionLane::Value,
1162        ],
1163        (false, false) => &[ResolutionLane::Type, ResolutionLane::Value],
1164    };
1165    for &lane in lanes {
1166        let destination = ExportLookup::new(barrel, exported_name, lane);
1167        let entry = resolutions.entry(destination.key).or_default();
1168        if entry.seeded.is_direct(lane) {
1169            continue;
1170        }
1171        entry.seeded.claim_explicit(lane);
1172        observers
1173            .named
1174            .entry(ExportLookup::new(source, imported_name, lane))
1175            .and_modify(|destinations| destinations.push(destination))
1176            .or_insert(NamedDestinations::One(destination));
1177    }
1178}
1179
1180fn propagate_bindings(
1181    resolutions: &mut FxHashMap<ExportKey, NamespaceResolutions>,
1182    queue: &mut VecDeque<ExportLookup>,
1183    observers: &PropagationObservers,
1184) {
1185    while let Some(source_key) = queue.pop_front() {
1186        let Some(source_resolution) = resolutions
1187            .get(&source_key.key)
1188            .map(|resolutions| resolutions.get(source_key.lane))
1189        else {
1190            continue;
1191        };
1192        if let Some(destinations) = observers.named.get(&source_key) {
1193            for destination in destinations.iter() {
1194                merge_resolution(resolutions, queue, *destination, source_resolution);
1195            }
1196        }
1197        propagate_star_binding(
1198            resolutions,
1199            queue,
1200            observers,
1201            &source_key,
1202            source_resolution,
1203        );
1204    }
1205}
1206
1207fn propagate_star_binding(
1208    resolutions: &mut FxHashMap<ExportKey, NamespaceResolutions>,
1209    queue: &mut VecDeque<ExportLookup>,
1210    observers: &PropagationObservers,
1211    source_key: &ExportLookup,
1212    source_resolution: EffectiveExportResolution,
1213) {
1214    if source_key.key.name == ExportNameId::DEFAULT {
1215        return;
1216    }
1217    let Some(star_observers) = observers.star.get(&source_key.key.file_id) else {
1218        return;
1219    };
1220    for observer in star_observers {
1221        if observer.type_only && source_key.lane == ResolutionLane::Value {
1222            continue;
1223        }
1224        if !observer.type_fallback && source_key.lane == ResolutionLane::TypeFallback {
1225            continue;
1226        }
1227        let destination = source_key.with_file(observer.barrel);
1228        let entry = resolutions.entry(destination.key).or_default();
1229        if entry.seeded.is_explicit(destination.lane) {
1230            continue;
1231        }
1232        if entry.merge(destination.lane, source_resolution) {
1233            queue.push_back(destination);
1234        }
1235    }
1236}
1237
1238fn merge_resolution(
1239    resolutions: &mut FxHashMap<ExportKey, NamespaceResolutions>,
1240    queue: &mut VecDeque<ExportLookup>,
1241    key: ExportLookup,
1242    incoming: EffectiveExportResolution,
1243) {
1244    if resolutions
1245        .entry(key.key)
1246        .or_default()
1247        .merge(key.lane, incoming)
1248    {
1249        queue.push_back(key);
1250    }
1251}
1252
1253#[cfg(test)]
1254mod tests {
1255    use super::*;
1256    use crate::resolve::{ResolveResult, ResolvedReExport};
1257    use fallow_types::extract::{ExportInfo, ReExportInfo, VisibilityTag};
1258
1259    fn value_export(name: &str) -> ExportInfo {
1260        ExportInfo {
1261            name: ExportName::Named(name.to_string()),
1262            local_name: Some(name.to_string()),
1263            is_type_only: false,
1264            visibility: VisibilityTag::None,
1265            expected_unused_reason: None,
1266            span: oxc_span::Span::default(),
1267            members: Vec::new(),
1268            is_side_effect_used: false,
1269            super_class: None,
1270            deprecated: false,
1271            deprecated_reason: None,
1272        }
1273    }
1274
1275    fn re_export(source: FileId, imported: &str, exported: &str) -> ResolvedReExport {
1276        ResolvedReExport {
1277            info: ReExportInfo {
1278                source: format!("./{}", source.0),
1279                imported_name: imported.to_string(),
1280                exported_name: exported.to_string(),
1281                is_type_only: false,
1282                span: oxc_span::Span::default(),
1283                statement_span: oxc_span::Span::default(),
1284                source_span: oxc_span::Span::default(),
1285                visibility: VisibilityTag::None,
1286                expected_unused_reason: None,
1287            },
1288            target: ResolveResult::InternalModule(source),
1289        }
1290    }
1291
1292    fn module(
1293        file_id: u32,
1294        exports: Vec<ExportInfo>,
1295        re_exports: Vec<ResolvedReExport>,
1296    ) -> ResolvedModule {
1297        ResolvedModule {
1298            file_id: FileId(file_id),
1299            exports: exports.into(),
1300            re_exports,
1301            ..Default::default()
1302        }
1303    }
1304
1305    fn resolves_through(
1306        index: &EffectiveExportIndex,
1307        barrel: FileId,
1308        source: FileId,
1309        name: &str,
1310    ) -> bool {
1311        index.resolves_through(barrel, name, source, name, ExportNamespace::Value)
1312    }
1313
1314    fn external_re_export(imported: &str, exported: &str, type_only: bool) -> ResolvedReExport {
1315        ResolvedReExport {
1316            info: ReExportInfo {
1317                source: "node:path".to_string(),
1318                imported_name: imported.to_string(),
1319                exported_name: exported.to_string(),
1320                is_type_only: type_only,
1321                span: oxc_span::Span::default(),
1322                statement_span: oxc_span::Span::default(),
1323                source_span: oxc_span::Span::default(),
1324                visibility: VisibilityTag::None,
1325                expected_unused_reason: None,
1326            },
1327            target: ResolveResult::NpmPackage("node:path".to_string()),
1328        }
1329    }
1330
1331    #[test]
1332    fn external_named_re_exports_keep_an_opaque_local_binding() {
1333        let index = EffectiveExportIndex::build(&[module(
1334            0,
1335            Vec::new(),
1336            vec![
1337                external_re_export("join", "join", false),
1338                external_re_export("Stats", "Stats", true),
1339                external_re_export("*", "path", false),
1340            ],
1341        )]);
1342        let encoded = postcard::to_allocvec(&index).expect("encode effective export index");
1343        let decoded: EffectiveExportIndex =
1344            postcard::from_bytes(&encoded).expect("decode effective export index");
1345
1346        let value = decoded.resolve(FileId(0), "join", ExportNamespace::Value);
1347        assert!(matches!(
1348            value,
1349            EffectiveExportResolution::Unique(binding)
1350                if binding.origin_file() == FileId(0) && binding.origin_slot().is_none()
1351        ));
1352        assert_eq!(
1353            value,
1354            decoded.resolve(FileId(0), "join", ExportNamespace::Type)
1355        );
1356        assert!(matches!(
1357            decoded.resolve(FileId(0), "Stats", ExportNamespace::Type),
1358            EffectiveExportResolution::Unique(_)
1359        ));
1360        assert_eq!(
1361            decoded.resolve(FileId(0), "Stats", ExportNamespace::Value),
1362            EffectiveExportResolution::Missing
1363        );
1364        assert_eq!(
1365            decoded.resolve(FileId(0), "path", ExportNamespace::Type),
1366            decoded.resolve(FileId(0), "path", ExportNamespace::Value)
1367        );
1368    }
1369
1370    #[test]
1371    fn unresolved_named_re_exports_keep_an_opaque_local_binding() {
1372        let mut unresolved = external_re_export("missing", "missing", false);
1373        unresolved.target = ResolveResult::Unresolvable("./missing".to_string());
1374        let mut unresolved_star = external_re_export("*", "*", false);
1375        unresolved_star.target = ResolveResult::Unresolvable("./missing-star".to_string());
1376        let index = EffectiveExportIndex::build(&[module(
1377            0,
1378            Vec::new(),
1379            vec![unresolved, unresolved_star],
1380        )]);
1381
1382        for namespace in [ExportNamespace::Type, ExportNamespace::Value] {
1383            assert!(matches!(
1384                index.resolve(FileId(0), "missing", namespace),
1385                EffectiveExportResolution::Unique(binding)
1386                    if binding.origin_file() == FileId(0) && binding.origin_slot().is_none()
1387            ));
1388            assert_eq!(
1389                index.resolve(FileId(0), "other", namespace),
1390                EffectiveExportResolution::Missing,
1391                "an unresolved star re-export must not invent names"
1392            );
1393        }
1394    }
1395
1396    #[test]
1397    fn missing_export_is_explicit_in_the_resolution_contract() {
1398        let index = EffectiveExportIndex::build(&[module(0, Vec::new(), Vec::new())]);
1399
1400        assert_eq!(
1401            index.resolve(FileId(0), "missing", ExportNamespace::Value),
1402            EffectiveExportResolution::Missing
1403        );
1404    }
1405
1406    #[test]
1407    fn same_module_declaration_merges_keep_one_binding() {
1408        let index = EffectiveExportIndex::build(&[module(
1409            0,
1410            vec![value_export("Merged"), value_export("Merged")],
1411            Vec::new(),
1412        )]);
1413
1414        assert!(matches!(
1415            index.resolve(FileId(0), "Merged", ExportNamespace::Value),
1416            EffectiveExportResolution::Unique(binding) if binding.origin_file() == FileId(0)
1417        ));
1418    }
1419
1420    #[test]
1421    fn declaration_merge_groups_survive_graph_cache_roundtrip() {
1422        let mut interface = value_export("Merged");
1423        interface.is_type_only = true;
1424        interface.span = oxc_span::Span::new(0, 6);
1425        let mut namespace = value_export("Merged");
1426        namespace.span = oxc_span::Span::new(10, 16);
1427        let modules = vec![ResolvedModule {
1428            file_id: FileId(0),
1429            exports: vec![interface, namespace].into(),
1430            semantic_facts: vec![fallow_types::extract::SemanticFact::DeclarationMerge(
1431                fallow_types::extract::DeclarationMergeFact {
1432                    export_spans: vec![(0, 6), (10, 16)],
1433                },
1434            )]
1435            .into(),
1436            ..Default::default()
1437        }];
1438        let index = EffectiveExportIndex::build(&modules);
1439        let encoded = postcard::to_allocvec(&index).expect("encode effective export index");
1440        let decoded: EffectiveExportIndex =
1441            postcard::from_bytes(&encoded).expect("decode effective export index");
1442        let EffectiveExportResolution::Unique(binding) =
1443            decoded.resolve(FileId(0), "Merged", ExportNamespace::Type)
1444        else {
1445            panic!("merged type binding must remain unique");
1446        };
1447
1448        assert_eq!(decoded.declaration_group_slots(binding), &[0, 1]);
1449    }
1450
1451    #[test]
1452    fn explicit_re_export_shadows_a_star_binding() {
1453        let modules = vec![
1454            module(
1455                0,
1456                Vec::new(),
1457                vec![
1458                    re_export(FileId(1), "*", "*"),
1459                    re_export(FileId(2), "foo", "foo"),
1460                ],
1461            ),
1462            module(1, vec![value_export("foo")], Vec::new()),
1463            module(2, vec![value_export("foo")], Vec::new()),
1464        ];
1465        let index = EffectiveExportIndex::build(&modules);
1466
1467        assert!(!resolves_through(&index, FileId(0), FileId(1), "foo"));
1468        assert!(resolves_through(&index, FileId(0), FileId(2), "foo"));
1469        assert!(!index.contributes_through(
1470            FileId(0),
1471            "foo",
1472            FileId(1),
1473            "foo",
1474            ExportNamespace::Value
1475        ));
1476    }
1477
1478    #[test]
1479    fn distinct_star_bindings_are_ambiguous() {
1480        let modules = vec![
1481            module(
1482                0,
1483                Vec::new(),
1484                vec![
1485                    re_export(FileId(1), "*", "*"),
1486                    re_export(FileId(2), "*", "*"),
1487                ],
1488            ),
1489            module(1, vec![value_export("foo")], Vec::new()),
1490            module(2, vec![value_export("foo")], Vec::new()),
1491        ];
1492        let index = EffectiveExportIndex::build(&modules);
1493
1494        assert!(!resolves_through(&index, FileId(0), FileId(1), "foo"));
1495        assert!(!resolves_through(&index, FileId(0), FileId(2), "foo"));
1496        assert!(index.contributes_through(
1497            FileId(0),
1498            "foo",
1499            FileId(1),
1500            "foo",
1501            ExportNamespace::Value
1502        ));
1503        assert!(index.contributes_through(
1504            FileId(0),
1505            "foo",
1506            FileId(2),
1507            "foo",
1508            ExportNamespace::Value
1509        ));
1510    }
1511
1512    #[test]
1513    fn convergent_star_paths_keep_one_binding() {
1514        let modules = vec![
1515            module(
1516                0,
1517                Vec::new(),
1518                vec![
1519                    re_export(FileId(1), "*", "*"),
1520                    re_export(FileId(2), "*", "*"),
1521                ],
1522            ),
1523            module(1, Vec::new(), vec![re_export(FileId(3), "*", "*")]),
1524            module(2, Vec::new(), vec![re_export(FileId(3), "*", "*")]),
1525            module(3, vec![value_export("foo")], Vec::new()),
1526        ];
1527        let index = EffectiveExportIndex::build(&modules);
1528
1529        assert!(resolves_through(&index, FileId(0), FileId(1), "foo"));
1530        assert!(resolves_through(&index, FileId(0), FileId(2), "foo"));
1531    }
1532
1533    #[test]
1534    fn a_real_type_declaration_wins_over_a_value_type_fallback() {
1535        let mut interface = value_export("User");
1536        interface.is_type_only = true;
1537        let modules = vec![
1538            module(
1539                0,
1540                Vec::new(),
1541                vec![
1542                    re_export(FileId(1), "*", "*"),
1543                    re_export(FileId(2), "*", "*"),
1544                ],
1545            ),
1546            module(1, vec![value_export("User")], Vec::new()),
1547            module(2, vec![interface], Vec::new()),
1548        ];
1549        let index = EffectiveExportIndex::build(&modules);
1550
1551        assert!(matches!(
1552            index.resolve(FileId(0), "User", ExportNamespace::Type),
1553            EffectiveExportResolution::Unique(binding) if binding.origin_file() == FileId(2)
1554        ));
1555        assert!(matches!(
1556            index.resolve(FileId(0), "User", ExportNamespace::Value),
1557            EffectiveExportResolution::Unique(binding) if binding.origin_file() == FileId(1)
1558        ));
1559        assert!(index.resolves_through(
1560            FileId(0),
1561            "User",
1562            FileId(2),
1563            "User",
1564            ExportNamespace::Type
1565        ));
1566        assert!(index.resolves_through(
1567            FileId(0),
1568            "User",
1569            FileId(1),
1570            "User",
1571            ExportNamespace::Value
1572        ));
1573    }
1574
1575    #[test]
1576    fn colliding_real_type_declarations_stay_ambiguous() {
1577        let type_export = |name: &str| {
1578            let mut export = value_export(name);
1579            export.is_type_only = true;
1580            export
1581        };
1582        let modules = vec![
1583            module(
1584                0,
1585                Vec::new(),
1586                vec![
1587                    re_export(FileId(1), "*", "*"),
1588                    re_export(FileId(2), "*", "*"),
1589                ],
1590            ),
1591            module(1, vec![type_export("User")], Vec::new()),
1592            module(2, vec![type_export("User")], Vec::new()),
1593        ];
1594        let index = EffectiveExportIndex::build(&modules);
1595
1596        assert_eq!(
1597            index.resolve(FileId(0), "User", ExportNamespace::Type),
1598            EffectiveExportResolution::Ambiguous
1599        );
1600        assert_eq!(
1601            index.ambiguous_names_on(FileId(0)),
1602            vec![(FileId(0), "User", ExportNamespace::Type)]
1603        );
1604    }
1605
1606    #[test]
1607    fn a_colliding_value_export_reports_one_collision_in_the_value_namespace() {
1608        let modules = vec![
1609            module(
1610                0,
1611                Vec::new(),
1612                vec![
1613                    re_export(FileId(1), "*", "*"),
1614                    re_export(FileId(2), "*", "*"),
1615                ],
1616            ),
1617            module(1, vec![value_export("foo")], Vec::new()),
1618            module(2, vec![value_export("foo")], Vec::new()),
1619        ];
1620        let index = EffectiveExportIndex::build(&modules);
1621
1622        assert_eq!(
1623            index.ambiguous_names(),
1624            vec![(FileId(0), "foo", ExportNamespace::Value)]
1625        );
1626    }
1627
1628    #[test]
1629    fn a_value_export_still_carries_its_type_meaning_through_a_barrel() {
1630        let modules = vec![
1631            module(0, Vec::new(), vec![re_export(FileId(1), "*", "*")]),
1632            module(1, vec![value_export("Widget")], Vec::new()),
1633        ];
1634        let index = EffectiveExportIndex::build(&modules);
1635
1636        assert!(index.resolves_through(
1637            FileId(0),
1638            "Widget",
1639            FileId(1),
1640            "Widget",
1641            ExportNamespace::Type
1642        ));
1643    }
1644
1645    #[test]
1646    fn a_type_only_re_export_carries_a_value_declaration_as_a_type_only() {
1647        let mut type_only = re_export(FileId(1), "Widget", "Widget");
1648        type_only.info.is_type_only = true;
1649        let index = EffectiveExportIndex::build(&[
1650            module(0, Vec::new(), vec![type_only]),
1651            module(1, vec![value_export("Widget")], Vec::new()),
1652        ]);
1653
1654        assert!(matches!(
1655            index.resolve(FileId(0), "Widget", ExportNamespace::Type),
1656            EffectiveExportResolution::Unique(binding) if binding.origin_file() == FileId(1)
1657        ));
1658        assert_eq!(
1659            index.resolve(FileId(0), "Widget", ExportNamespace::Value),
1660            EffectiveExportResolution::Missing
1661        );
1662    }
1663
1664    #[test]
1665    fn a_type_only_re_export_reaches_a_value_declaration_behind_a_barrel() {
1666        let mut type_only = re_export(FileId(1), "Widget", "Widget");
1667        type_only.info.is_type_only = true;
1668        let index = EffectiveExportIndex::build(&[
1669            module(0, Vec::new(), vec![type_only]),
1670            module(1, Vec::new(), vec![re_export(FileId(2), "*", "*")]),
1671            module(2, vec![value_export("Widget")], Vec::new()),
1672        ]);
1673
1674        assert!(matches!(
1675            index.resolve(FileId(0), "Widget", ExportNamespace::Type),
1676            EffectiveExportResolution::Unique(binding) if binding.origin_file() == FileId(2)
1677        ));
1678    }
1679
1680    #[test]
1681    fn a_type_only_re_export_shadows_a_star_binding_in_the_type_namespace() {
1682        let mut type_only = re_export(FileId(1), "foo", "foo");
1683        type_only.info.is_type_only = true;
1684        let index = EffectiveExportIndex::build(&[
1685            module(
1686                0,
1687                Vec::new(),
1688                vec![type_only, re_export(FileId(2), "*", "*")],
1689            ),
1690            module(1, vec![value_export("foo")], Vec::new()),
1691            module(2, vec![value_export("foo")], Vec::new()),
1692        ]);
1693
1694        assert!(matches!(
1695            index.resolve(FileId(0), "foo", ExportNamespace::Type),
1696            EffectiveExportResolution::Unique(binding) if binding.origin_file() == FileId(1)
1697        ));
1698        assert!(matches!(
1699            index.resolve(FileId(0), "foo", ExportNamespace::Value),
1700            EffectiveExportResolution::Unique(binding) if binding.origin_file() == FileId(2)
1701        ));
1702    }
1703
1704    #[test]
1705    fn a_type_only_barrel_still_sees_a_star_collision_as_ambiguous() {
1706        let mut type_only = re_export(FileId(1), "foo", "foo");
1707        type_only.info.is_type_only = true;
1708        let index = EffectiveExportIndex::build(&[
1709            module(0, Vec::new(), vec![type_only]),
1710            module(
1711                1,
1712                Vec::new(),
1713                vec![
1714                    re_export(FileId(2), "*", "*"),
1715                    re_export(FileId(3), "*", "*"),
1716                ],
1717            ),
1718            module(2, vec![value_export("foo")], Vec::new()),
1719            module(3, vec![value_export("foo")], Vec::new()),
1720        ]);
1721
1722        assert_eq!(
1723            index.resolve(FileId(0), "foo", ExportNamespace::Type),
1724            EffectiveExportResolution::Ambiguous
1725        );
1726    }
1727
1728    #[test]
1729    fn a_star_collision_stays_ambiguous_beside_an_unrelated_type_only_barrel() {
1730        let mut type_only = re_export(FileId(1), "foo", "foo");
1731        type_only.info.is_type_only = true;
1732        let index = EffectiveExportIndex::build(&[
1733            module(0, Vec::new(), vec![type_only]),
1734            module(1, Vec::new(), vec![re_export(FileId(2), "*", "*")]),
1735            module(2, vec![value_export("foo")], Vec::new()),
1736            module(
1737                3,
1738                Vec::new(),
1739                vec![
1740                    re_export(FileId(2), "*", "*"),
1741                    re_export(FileId(4), "*", "*"),
1742                ],
1743            ),
1744            module(4, vec![value_export("foo")], Vec::new()),
1745        ]);
1746
1747        assert_eq!(
1748            index.resolve(FileId(3), "foo", ExportNamespace::Type),
1749            EffectiveExportResolution::Ambiguous
1750        );
1751    }
1752
1753    #[test]
1754    fn star_exports_exclude_default_bindings() {
1755        let mut default = value_export("local");
1756        default.name = ExportName::Default;
1757        let index = EffectiveExportIndex::build(&[
1758            module(0, Vec::new(), vec![re_export(FileId(1), "*", "*")]),
1759            module(1, vec![default], Vec::new()),
1760        ]);
1761
1762        assert_eq!(
1763            index.resolve(FileId(0), "default", ExportNamespace::Value),
1764            EffectiveExportResolution::Missing
1765        );
1766    }
1767
1768    #[test]
1769    fn star_cycles_converge_on_the_same_binding() {
1770        let index = EffectiveExportIndex::build(&[
1771            module(0, Vec::new(), vec![re_export(FileId(1), "*", "*")]),
1772            module(
1773                1,
1774                Vec::new(),
1775                vec![
1776                    re_export(FileId(0), "*", "*"),
1777                    re_export(FileId(2), "*", "*"),
1778                ],
1779            ),
1780            module(2, vec![value_export("foo")], Vec::new()),
1781        ]);
1782
1783        assert!(resolves_through(&index, FileId(0), FileId(2), "foo"));
1784        assert!(resolves_through(&index, FileId(1), FileId(2), "foo"));
1785    }
1786
1787    #[test]
1788    fn type_only_namespace_re_export_resolves_only_in_type_namespace() {
1789        let mut namespace = re_export(FileId(1), "*", "Types");
1790        namespace.info.is_type_only = true;
1791        let index = EffectiveExportIndex::build(&[
1792            module(0, Vec::new(), vec![namespace]),
1793            module(1, vec![value_export("foo")], Vec::new()),
1794        ]);
1795
1796        assert!(matches!(
1797            index.resolve(FileId(0), "Types", ExportNamespace::Type),
1798            EffectiveExportResolution::Unique(_)
1799        ));
1800        assert_eq!(
1801            index.resolve(FileId(0), "Types", ExportNamespace::Value),
1802            EffectiveExportResolution::Missing
1803        );
1804    }
1805
1806    #[test]
1807    fn normal_namespace_re_export_resolves_in_both_namespaces() {
1808        let index = EffectiveExportIndex::build(&[
1809            module(0, Vec::new(), vec![re_export(FileId(1), "*", "Namespace")]),
1810            module(1, vec![value_export("foo")], Vec::new()),
1811        ]);
1812
1813        let type_binding = index.resolve(FileId(0), "Namespace", ExportNamespace::Type);
1814        let value_binding = index.resolve(FileId(0), "Namespace", ExportNamespace::Value);
1815        assert!(matches!(type_binding, EffectiveExportResolution::Unique(_)));
1816        assert_eq!(type_binding, value_binding);
1817    }
1818
1819    #[test]
1820    fn persisted_index_remains_queryable_without_reconstruction() {
1821        let index = EffectiveExportIndex::build(&[
1822            module(0, Vec::new(), vec![re_export(FileId(1), "foo", "bar")]),
1823            module(1, vec![value_export("foo")], Vec::new()),
1824        ]);
1825        let encoded = postcard::to_allocvec(&index).expect("encode effective export index");
1826        let decoded: EffectiveExportIndex =
1827            postcard::from_bytes(&encoded).expect("decode effective export index");
1828
1829        assert!(matches!(
1830            decoded.resolve(FileId(0), "bar", ExportNamespace::Value),
1831            EffectiveExportResolution::Unique(binding) if binding.origin_file() == FileId(1)
1832        ));
1833        assert_eq!(
1834            decoded.resolve(FileId(0), "missing", ExportNamespace::Value),
1835            EffectiveExportResolution::Missing
1836        );
1837    }
1838
1839    #[test]
1840    fn sfc_file_has_an_implicit_default_value_binding() {
1841        let mut sfc = module(0, Vec::new(), Vec::new());
1842        sfc.path = std::path::PathBuf::from("/project/Widget.vue");
1843        let index = EffectiveExportIndex::build(&[sfc]);
1844
1845        assert!(matches!(
1846            index.resolve(FileId(0), "default", ExportNamespace::Value),
1847            EffectiveExportResolution::Unique(binding) if binding.origin_file() == FileId(0)
1848        ));
1849    }
1850}