Skip to main content

fallow_engine/
trace_impl.rs

1use std::path::{Path, PathBuf};
2
3use fallow_types::discover::FileId;
4use fallow_types::trace::{
5    ClassMemberTrace, CloneTrace, DependencyTrace, ExportReference, ExportTrace, FileTrace,
6    ImpactClosureGap, ImpactClosureTrace, ImportPathHop, ImportPathTrace,
7    ImportPathTraceSchemaVersion, NamespacedExportReferences, PeerClosureSeeds, ReExportChain,
8    SearchGapReason, ToolingCredit, TracedCloneGroup, TracedExport, TracedReExport,
9};
10use fallow_types::trace_chain::StarExportAmbiguity;
11use rustc_hash::{FxHashMap, FxHashSet};
12
13use crate::duplicates::{
14    CloneFingerprintSet, CloneGroup, CloneInstance, DuplicationReport, dominant_identifier,
15    group_refactoring_suggestion,
16};
17use crate::graph::{
18    ExportNamespace, ImportPathHop as GraphImportPathHop, ModuleGraph, ModuleNode, ReferenceKind,
19};
20use crate::search_visibility::{SearchCheck, SearchTarget, SourceCache};
21
22/// Match exact module paths before considering abbreviated suffixes.
23///
24/// A root-relative `src/a.ts` must not select `packages/x/src/a.ts` merely
25/// because discovery listed that module first. Suffix matches remain useful
26/// for abbreviated requests, but callers must preserve their ambiguity.
27pub fn matching_module_indexes(graph: &ModuleGraph, root: &Path, user_path: &str) -> Vec<usize> {
28    let normalized = user_path.replace('\\', "/");
29    // The root-relative forms are joined once, so each module costs a path
30    // comparison instead of a `strip_prefix` component walk.
31    let exact_targets: Vec<PathBuf> = [
32        Some(root.join(&normalized)),
33        dunce::canonicalize(root)
34            .ok()
35            .map(|canonical_root| canonical_root.join(&normalized)),
36        dunce::canonicalize(root.join(&normalized)).ok(),
37    ]
38    .into_iter()
39    .flatten()
40    .collect();
41    let mut exact = Vec::new();
42    let mut suffix = Vec::new();
43    let suffix_pattern = format!("/{normalized}");
44    for (index, module) in graph.modules.iter().enumerate() {
45        let module_path = forward_slash_path(&module.path);
46        let is_exact = module_path == normalized || exact_targets.contains(&module.path);
47        if is_exact {
48            exact.push(index);
49        } else if module_path.ends_with(&suffix_pattern) {
50            suffix.push(index);
51        }
52    }
53    if exact.is_empty() { suffix } else { exact }
54}
55
56/// Render a path with forward slashes. Borrows when no rewrite is needed, so
57/// the per-module comparison in a lookup does not allocate on Unix.
58fn forward_slash_path(path: &Path) -> std::borrow::Cow<'_, str> {
59    let lossy = path.to_string_lossy();
60    if lossy.contains('\\') {
61        std::borrow::Cow::Owned(lossy.replace('\\', "/"))
62    } else {
63        lossy
64    }
65}
66
67/// Module paths indexed once for callers that resolve many user paths
68/// against one graph.
69///
70/// [`ModulePathLookup::matching`] returns the same indexes, in graph order, as
71/// [`matching_module_indexes`]. A single lookup does not need this index; a
72/// loop over many references would otherwise scan every module per reference.
73struct ModulePathLookup<'g> {
74    graph: &'g ModuleGraph,
75    root: &'g Path,
76    canonical_root: Option<PathBuf>,
77    /// Component-normalized, forward-slash module path to module indexes.
78    by_path: FxHashMap<String, Vec<usize>>,
79    /// Last path segment to module indexes, for suffix matches.
80    by_file_name: FxHashMap<String, Vec<usize>>,
81}
82
83impl<'g> ModulePathLookup<'g> {
84    fn new(graph: &'g ModuleGraph, root: &'g Path) -> Self {
85        let mut by_path: FxHashMap<String, Vec<usize>> = FxHashMap::default();
86        let mut by_file_name: FxHashMap<String, Vec<usize>> = FxHashMap::default();
87        for (index, module) in graph.modules.iter().enumerate() {
88            by_path
89                .entry(path_key(&module.path))
90                .or_default()
91                .push(index);
92            let module_path = forward_slash_path(&module.path);
93            let file_name = module_path.rsplit('/').next().unwrap_or_default();
94            by_file_name
95                .entry(file_name.to_owned())
96                .or_default()
97                .push(index);
98        }
99        Self {
100            graph,
101            root,
102            canonical_root: dunce::canonicalize(root).ok(),
103            by_path,
104            by_file_name,
105        }
106    }
107
108    fn matching(&self, user_path: &str) -> Vec<usize> {
109        let normalized = user_path.replace('\\', "/");
110        let joined = self.root.join(&normalized);
111        let mut targets = vec![path_key(Path::new(&normalized)), path_key(&joined)];
112        if let Some(canonical_root) = &self.canonical_root {
113            targets.push(path_key(&canonical_root.join(&normalized)));
114        }
115        if let Ok(canonical_target) = dunce::canonicalize(&joined) {
116            targets.push(path_key(&canonical_target));
117        }
118        let mut exact: Vec<usize> = targets
119            .iter()
120            .filter_map(|target| self.by_path.get(target))
121            .flatten()
122            .copied()
123            .collect();
124        if !exact.is_empty() {
125            exact.sort_unstable();
126            exact.dedup();
127            return exact;
128        }
129        let suffix_pattern = format!("/{normalized}");
130        let file_name = normalized.rsplit('/').next().unwrap_or_default();
131        self.by_file_name
132            .get(file_name)
133            .into_iter()
134            .flatten()
135            .copied()
136            .filter(|&index| {
137                forward_slash_path(&self.graph.modules[index].path).ends_with(&suffix_pattern)
138            })
139            .collect()
140    }
141}
142
143/// A path rendered from its components with forward slashes, so paths that
144/// `Path` equality treats as equal get the same key.
145fn path_key(path: &Path) -> String {
146    forward_slash_path(&path.components().collect::<PathBuf>()).into_owned()
147}
148
149/// Find the module for a user path.
150///
151/// An exact match wins. Otherwise the first suffix match in graph order wins,
152/// so an abbreviated path keeps its earlier behaviour.
153pub fn find_module<'a>(
154    graph: &'a ModuleGraph,
155    root: &Path,
156    user_path: &str,
157) -> Option<&'a ModuleNode> {
158    matching_module_indexes(graph, root, user_path)
159        .first()
160        .map(|&index| &graph.modules[index])
161}
162
163/// Reconcile checker-backed reference evidence with the retained graph's
164/// entry-point reachability. Evidence from unreachable files remains visible,
165/// but cannot produce a complete `references-found` assertion.
166pub fn reconcile_semantic_trace_reachability(
167    graph: &ModuleGraph,
168    root: &Path,
169    target_reachable: bool,
170    trace: &mut fallow_types::semantic::SemanticSymbolTrace,
171) {
172    if trace.assertion != "references-found" || trace.references.is_empty() {
173        return;
174    }
175    let has_reachable_reference = target_reachable && {
176        let lookup = ModulePathLookup::new(graph, root);
177        trace.references.iter().any(|reference| {
178            lookup
179                .matching(&reference.path.to_string_lossy())
180                .iter()
181                .any(|&index| graph.modules[index].is_reachable())
182        })
183    };
184    if has_reachable_reference {
185        return;
186    }
187
188    trace.assertion = "references-only-in-unreachable-files".to_string();
189    trace.status = fallow_types::semantic::SemanticCompleteness::Partial;
190    trace.identity.completeness = fallow_types::semantic::SemanticCompleteness::Partial;
191    let action =
192        "Review the unreachable consumer files before removing this declaration.".to_string();
193    if !trace.actions.contains(&action) {
194        trace.actions.push(action);
195    }
196}
197
198/// Map a reference's `from_file` id to a root-relative [`ExportReference`].
199fn reference_to_export_reference(
200    graph: &ModuleGraph,
201    root: &Path,
202    r: &crate::graph::SymbolReference,
203) -> ExportReference {
204    let from_path = graph.modules.get(r.from_file.0 as usize).map_or_else(
205        || PathBuf::from(format!("<unknown:{}>", r.from_file.0)),
206        |m| m.path.strip_prefix(root).unwrap_or(&m.path).to_path_buf(),
207    );
208    ExportReference::new(from_path, format_reference_kind(r.kind))
209}
210
211/// Project graph-owned effective routes into the public trace contract.
212fn collect_re_export_chains(
213    graph: &ModuleGraph,
214    root: &Path,
215    target_file_id: crate::discover::FileId,
216    export_name: &str,
217    namespace: ExportNamespace,
218) -> Vec<ReExportChain> {
219    graph
220        .effective_re_export_routes(target_file_id, export_name, namespace)
221        .into_iter()
222        .filter_map(|route| {
223            let module = graph.modules.get(route.barrel_file().0 as usize)?;
224            Some(ReExportChain {
225                barrel_file: relative_module_path(&module.path, root),
226                exported_as: route.exported_name().to_string(),
227                reference_count: graph
228                    .effective_export_surface_references(
229                        route.barrel_file(),
230                        route.exported_name(),
231                        namespace,
232                    )
233                    .into_iter()
234                    .filter(|reference| {
235                        graph
236                            .modules
237                            .get(reference.from_file.0 as usize)
238                            .is_some_and(crate::graph::ModuleNode::is_reachable)
239                    })
240                    .count(),
241            })
242        })
243        .collect()
244}
245
246/// Trace why an export is considered used or unused.
247#[must_use]
248pub fn trace_export(
249    graph: &ModuleGraph,
250    root: &Path,
251    file_path: &str,
252    export_name: &str,
253) -> Option<ExportTrace> {
254    let module = find_module(graph, root, file_path)?;
255
256    let star_export_ambiguity =
257        trace_star_export_ambiguity(graph, root, module.file_id, export_name);
258    let Some(surface) = select_export(graph, module, export_name) else {
259        let ambiguity = star_export_ambiguity?;
260        let namespace = ambiguity.namespaces.first().copied().unwrap_or_default();
261        return Some(ExportTrace {
262            file: relative_module_path(&module.path, root),
263            export_name: export_name.to_string(),
264            namespace,
265            file_reachable: module.is_reachable(),
266            is_entry_point: module.is_entry_point(),
267            is_used: false,
268            direct_references: Vec::new(),
269            direct_references_by_namespace: Vec::new(),
270            star_export_ambiguity: Some(ambiguity),
271            re_export_chains: Vec::new(),
272            plugin_credits: Vec::new(),
273            kept_by_tag: None,
274            reason: "Star re-export collision makes this name ambiguous".to_string(),
275            semantic: None,
276        });
277    };
278    let (namespace, direct_references, direct_references_by_namespace) =
279        crediting_export_references(graph, root, module.file_id, export_name, surface);
280
281    let re_export_chains =
282        collect_re_export_chains(graph, root, module.file_id, export_name, namespace);
283
284    let reference_count = direct_references.len();
285    let is_used = module.is_reachable() && reference_count > 0;
286    let (kept_by_tag, reason) = super::trace_export_reason::export_verdict(
287        module,
288        (export_name, namespace),
289        reference_count,
290        &re_export_chains,
291        star_export_ambiguity.is_some(),
292    );
293
294    Some(ExportTrace {
295        file: relative_module_path(&module.path, root),
296        export_name: export_name.to_string(),
297        namespace: match namespace {
298            ExportNamespace::Type => fallow_types::semantic::SemanticNamespace::Type,
299            ExportNamespace::Value => fallow_types::semantic::SemanticNamespace::Value,
300        },
301        file_reachable: module.is_reachable(),
302        is_entry_point: module.is_entry_point(),
303        is_used,
304        direct_references,
305        direct_references_by_namespace,
306        star_export_ambiguity,
307        re_export_chains,
308        plugin_credits: Vec::new(),
309        kept_by_tag: kept_by_tag.map(str::to_owned),
310        reason,
311        semantic: None,
312    })
313}
314
315/// The root-relative path of a module, or the path as it is outside `root`.
316fn relative_module_path(path: &Path, root: &Path) -> PathBuf {
317    path.strip_prefix(root).unwrap_or(path).to_path_buf()
318}
319
320/// Distinct referencing files of one module export surface in one namespace.
321///
322/// Each reference carries the literal-search check: the consumer source is
323/// read on demand and compared with a whole-word search for the export name.
324fn direct_export_references(
325    graph: &ModuleGraph,
326    root: &Path,
327    sources: &mut SourceCache<'_>,
328    file_id: crate::discover::FileId,
329    export_name: &str,
330    namespace: ExportNamespace,
331) -> Vec<ExportReference> {
332    let mut referenced_files = FxHashSet::default();
333    let references: Vec<_> = graph
334        .effective_export_surface_references(file_id, export_name, namespace)
335        .into_iter()
336        .filter(|reference| {
337            graph
338                .modules
339                .get(reference.from_file.0 as usize)
340                .is_some_and(crate::graph::ModuleNode::is_reachable)
341        })
342        .filter(|reference| referenced_files.insert(reference.from_file))
343        .collect();
344    if references.is_empty() {
345        return Vec::new();
346    }
347    let target = SearchTarget::new(graph, sources, file_id, export_name, namespace);
348    references
349        .into_iter()
350        .map(|reference| {
351            let mut export_reference = reference_to_export_reference(graph, root, reference);
352            if let Some(check) = target.check(graph, sources, reference) {
353                apply_search_check(&mut export_reference, check);
354            }
355            export_reference
356        })
357        .collect()
358}
359
360fn apply_search_check(reference: &mut ExportReference, check: SearchCheck) {
361    reference.line = check.line;
362    reference.search_visibility = Some(check.visibility);
363    reference.reason = check.reason;
364    reference.search_as = check.search_as;
365}
366
367/// References that credit the traced declaration, with the namespace that
368/// carries them.
369///
370/// The preferred surface wins whenever its lane carries a reference. When it
371/// carries none, the other namespace is consulted only if it resolves to the
372/// same effective binding: that is the type lane falling back onto a
373/// value-only declaration (`import type { helper }` of `export const helper`),
374/// which the unused-export analyzer counts as a use regardless of namespace.
375/// A distinct same-name declaration in the other namespace keeps the preferred
376/// lane, because its references credit that other declaration and dead-code
377/// still reports the traced one. See issue #2371.
378fn crediting_export_references(
379    graph: &ModuleGraph,
380    root: &Path,
381    file_id: crate::discover::FileId,
382    export_name: &str,
383    surface: crate::graph::EffectiveExportSurface<'_>,
384) -> (
385    ExportNamespace,
386    Vec<ExportReference>,
387    Vec<NamespacedExportReferences>,
388) {
389    let namespace = surface.namespace();
390    let mut sources = SourceCache::new(graph);
391    let references =
392        direct_export_references(graph, root, &mut sources, file_id, export_name, namespace);
393    let other = match namespace {
394        ExportNamespace::Type => ExportNamespace::Value,
395        ExportNamespace::Value => ExportNamespace::Type,
396    };
397    let same_binding = graph
398        .effective_export_surface(file_id, export_name, other)
399        .is_some_and(|candidate| {
400            graph.effective_bindings_share_declaration_group(candidate.binding(), surface.binding())
401        });
402    if !same_binding {
403        return (namespace, references, Vec::new());
404    }
405    let other_references =
406        direct_export_references(graph, root, &mut sources, file_id, export_name, other);
407    let by_namespace = if references.is_empty() || other_references.is_empty() {
408        Vec::new()
409    } else {
410        vec![
411            namespaced_references(namespace, references.clone()),
412            namespaced_references(other, other_references.clone()),
413        ]
414    };
415    if references.is_empty() && !other_references.is_empty() {
416        (other, other_references, by_namespace)
417    } else {
418        (namespace, references, by_namespace)
419    }
420}
421
422fn namespaced_references(
423    namespace: ExportNamespace,
424    references: Vec<ExportReference>,
425) -> NamespacedExportReferences {
426    NamespacedExportReferences {
427        namespace: match namespace {
428            ExportNamespace::Type => fallow_types::semantic::SemanticNamespace::Type,
429            ExportNamespace::Value => fallow_types::semantic::SemanticNamespace::Value,
430        },
431        reference_count: references.len(),
432        references,
433    }
434}
435
436fn trace_star_export_ambiguity(
437    graph: &ModuleGraph,
438    root: &Path,
439    file_id: crate::discover::FileId,
440    export_name: &str,
441) -> Option<StarExportAmbiguity> {
442    let collisions: Vec<_> = graph
443        .ambiguous_star_exports()
444        .into_iter()
445        .filter(|collision| {
446            collision.name.as_ref() == export_name
447                && (collision.barrel == file_id || collision.contributors.contains(&file_id))
448        })
449        .collect();
450    if collisions.is_empty() {
451        return None;
452    }
453    let mut sources: Vec<_> = collisions
454        .iter()
455        .flat_map(|collision| collision.contributors.iter())
456        .filter_map(|contributor| graph.modules.get(contributor.0 as usize))
457        .map(|module| relative_module_path(&module.path, root))
458        .collect();
459    sources.sort();
460    sources.dedup();
461    let mut namespaces: Vec<_> = collisions
462        .iter()
463        .map(|collision| match collision.namespace {
464            ExportNamespace::Type => fallow_types::semantic::SemanticNamespace::Type,
465            ExportNamespace::Value => fallow_types::semantic::SemanticNamespace::Value,
466        })
467        .collect();
468    namespaces.sort_unstable_by_key(|namespace| match namespace {
469        fallow_types::semantic::SemanticNamespace::Type => 0,
470        fallow_types::semantic::SemanticNamespace::Value => 1,
471    });
472    namespaces.dedup();
473    Some(StarExportAmbiguity {
474        sources,
475        namespaces,
476    })
477}
478
479/// Resolve the exact source identity required by the semantic sidecar for a
480/// graph export. This does not perform semantic analysis itself.
481#[must_use]
482pub fn semantic_symbol_for_export(
483    graph: &ModuleGraph,
484    root: &Path,
485    file_path: &str,
486    export_name: &str,
487) -> Option<fallow_types::semantic::SemanticSymbol> {
488    use fallow_types::semantic::{SemanticNamespace, SemanticSymbol};
489
490    let module = find_module(graph, root, file_path)?;
491    let surface = select_export(graph, module, export_name)?;
492    let namespace = surface.namespace();
493    let (identity_module, span, identity_exported_name, local_name) = if let Some(re_export) =
494        graph.effective_export_surface_re_export(module.file_id, export_name, namespace)
495    {
496        let local_name = if re_export.imported_name == "*" {
497            export_name
498        } else {
499            re_export.imported_name.as_str()
500        };
501        (module, re_export.span, export_name, local_name)
502    } else {
503        let origin = surface.origin()?;
504        let origin_module = graph.modules.get(origin.file_id().0 as usize)?;
505        let origin_export = origin.export();
506        let origin_name = match &origin_export.name {
507            fallow_types::extract::ExportName::Named(name) => name.as_str(),
508            fallow_types::extract::ExportName::Default => "default",
509        };
510        (origin_module, origin_export.span, origin_name, origin_name)
511    };
512    let source = std::fs::read_to_string(&identity_module.path).ok()?;
513    let offsets = fallow_types::extract::compute_line_offsets(&source);
514    let (line, col) = fallow_types::extract::byte_offset_to_line_col(&offsets, span.start);
515    Some(SemanticSymbol {
516        path: identity_module
517            .path
518            .strip_prefix(root)
519            .unwrap_or(&identity_module.path)
520            .to_path_buf(),
521        namespace: match namespace {
522            ExportNamespace::Type => SemanticNamespace::Type,
523            ExportNamespace::Value => SemanticNamespace::Value,
524        },
525        declaration_kind: "export".to_string(),
526        exported_name: identity_exported_name.to_string(),
527        local_name: local_name.to_string(),
528        owner: None,
529        line,
530        col,
531    })
532}
533
534/// Resolve the source identity for a public class member semantic query.
535#[must_use]
536pub fn semantic_symbol_for_class_member(
537    graph: &ModuleGraph,
538    root: &Path,
539    file_path: &str,
540    member_name: &str,
541) -> Option<fallow_types::semantic::SemanticSymbol> {
542    use fallow_types::extract::MemberKind;
543    use fallow_types::semantic::{SemanticNamespace, SemanticSymbol};
544
545    let module = find_module(graph, root, file_path)?;
546    let (owner, member) = module
547        .exports
548        .iter()
549        .filter_map(|export| {
550            export
551                .members
552                .iter()
553                .find(|member| member.name == member_name)
554                .map(|member| (export, member))
555        })
556        .max_by_key(|(export, _)| (!export.references.is_empty(), !export.is_type_only))?;
557    let declaration_kind = match member.kind {
558        MemberKind::ClassMethod => "class_method",
559        MemberKind::ClassProperty => "class_property",
560        _ => return None,
561    };
562    let source = std::fs::read_to_string(&module.path).ok()?;
563    let offsets = fallow_types::extract::compute_line_offsets(&source);
564    let (line, col) = fallow_types::extract::byte_offset_to_line_col(&offsets, member.span.start);
565    Some(SemanticSymbol {
566        path: relative_module_path(&module.path, root),
567        namespace: SemanticNamespace::Value,
568        declaration_kind: declaration_kind.to_string(),
569        exported_name: member_name.to_string(),
570        local_name: member_name.to_string(),
571        owner: Some(owner.name.to_string()),
572        line,
573        col,
574    })
575}
576
577/// Stable reason why an exact class-method target cannot be resolved.
578#[derive(Debug, Clone, Copy, PartialEq, Eq)]
579pub enum SemanticClassMethodResolutionError {
580    /// The requested file is not part of the retained module graph.
581    FileNotFound,
582    /// The requested owner or method does not exist in the file.
583    SymbolNotFound,
584    /// More than one declaration matches the exact owner and method.
585    AmbiguousSymbol,
586    /// The matching declaration is not a supported class method.
587    UnsupportedSyntax,
588}
589
590impl std::fmt::Display for SemanticClassMethodResolutionError {
591    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
592        let reason = match self {
593            Self::FileNotFound => "file-not-found",
594            Self::SymbolNotFound => "unknown-symbol",
595            Self::AmbiguousSymbol => "ambiguous-symbol",
596            Self::UnsupportedSyntax => "unsupported-syntax",
597        };
598        formatter.write_str(reason)
599    }
600}
601
602/// Resolve one exact exported class method without a name-based fallback.
603pub fn semantic_symbol_for_exact_class_method(
604    graph: &ModuleGraph,
605    root: &Path,
606    file_path: &str,
607    owner_name: &str,
608    member_name: &str,
609) -> Result<fallow_types::semantic::SemanticSymbol, SemanticClassMethodResolutionError> {
610    use fallow_types::extract::MemberKind;
611    use fallow_types::semantic::{SemanticNamespace, SemanticSymbol};
612
613    let module = find_module(graph, root, file_path)
614        .ok_or(SemanticClassMethodResolutionError::FileNotFound)?;
615    let mut owners = module
616        .exports
617        .iter()
618        .filter(|export| export.name.matches_str(owner_name));
619    let owner = owners
620        .next()
621        .ok_or(SemanticClassMethodResolutionError::SymbolNotFound)?;
622    if owners.next().is_some() {
623        return Err(SemanticClassMethodResolutionError::AmbiguousSymbol);
624    }
625    let mut members = owner
626        .members
627        .iter()
628        .filter(|member| member.name == member_name);
629    let member = members
630        .next()
631        .ok_or(SemanticClassMethodResolutionError::SymbolNotFound)?;
632    if members.next().is_some() {
633        return Err(SemanticClassMethodResolutionError::AmbiguousSymbol);
634    }
635    if member.kind != MemberKind::ClassMethod {
636        return Err(SemanticClassMethodResolutionError::UnsupportedSyntax);
637    }
638    let source = std::fs::read_to_string(&module.path)
639        .map_err(|_| SemanticClassMethodResolutionError::SymbolNotFound)?;
640    let offsets = fallow_types::extract::compute_line_offsets(&source);
641    let (line, col) = fallow_types::extract::byte_offset_to_line_col(&offsets, member.span.start);
642    Ok(SemanticSymbol {
643        path: relative_module_path(&module.path, root),
644        namespace: SemanticNamespace::Value,
645        declaration_kind: "class_method".to_string(),
646        exported_name: member_name.to_string(),
647        local_name: member_name.to_string(),
648        owner: Some(owner_name.to_string()),
649        line,
650        col,
651    })
652}
653
654/// Trace a class / enum / store MEMBER when `--trace FILE:NAME`'s `NAME` is not
655/// a top-level export but a member declared on one (issue #1744). Runs on the
656/// graph only, so it reports the OWNING export's reachability and usage (the
657/// gating precondition for member crediting) plus a pointer to the right
658/// `--unused-*-members` command, not per-member crediting provenance.
659#[must_use]
660pub fn trace_class_member(
661    graph: &ModuleGraph,
662    root: &Path,
663    file_path: &str,
664    member_name: &str,
665) -> Option<ClassMemberTrace> {
666    use fallow_types::extract::MemberKind;
667
668    let module = find_module(graph, root, file_path)?;
669
670    // Find the export that declares this member. When several declare a member
671    // of the same name (rare), prefer a used, non-type-only owner so the trace
672    // reports the reachable one.
673    let (owner, member_kind, is_protected) = module
674        .exports
675        .iter()
676        .filter_map(|export| {
677            export
678                .members
679                .iter()
680                .find(|member| member.name == member_name)
681                .map(|member| (export, member.kind, member.is_protected))
682        })
683        .max_by_key(|(export, _, _)| (!export.references.is_empty(), !export.is_type_only))?;
684
685    let owner_name = owner.name.to_string();
686    // Reuse the export trace to compute the owner's reachability / usage /
687    // references consistently with a plain `--trace FILE:OWNER`. The `?` here is
688    // a belt-and-suspenders guard: `owner` was just located in this module's
689    // `exports`, so `trace_export` resolves it in practice; the fallthrough to
690    // `None` (and the caller's "not found" error) is unreachable barring a graph
691    // inconsistency.
692    let owner_trace = trace_export(graph, root, file_path, &owner_name)?;
693
694    let class_filter = if is_protected {
695        "--unused-protected-class-members"
696    } else {
697        "--unused-class-members"
698    };
699    let (kind_str, filter_flag) = match member_kind {
700        MemberKind::ClassMethod => ("class-method", Some(class_filter)),
701        MemberKind::ClassProperty => ("class-property", Some(class_filter)),
702        MemberKind::EnumMember => ("enum-member", Some("--unused-enum-members")),
703        MemberKind::StoreMember => ("store-member", Some("--unused-store-members")),
704        MemberKind::NamespaceMember => ("namespace-member", Some("--unused-namespace-members")),
705    };
706
707    let reason = class_member_trace_reason(
708        member_name,
709        &owner_name,
710        kind_str,
711        filter_flag,
712        file_path,
713        &owner_trace,
714    );
715
716    Some(ClassMemberTrace {
717        file: owner_trace.file,
718        member_name: member_name.to_string(),
719        member_kind: kind_str.to_string(),
720        owner_export: owner_name,
721        owner_namespace: owner_trace.namespace,
722        owner_is_used: owner_trace.is_used,
723        owner_file_reachable: owner_trace.file_reachable,
724        owner_is_entry_point: owner_trace.is_entry_point,
725        owner_direct_references: owner_trace.direct_references,
726        owner_re_export_chains: owner_trace.re_export_chains,
727        reason,
728        semantic: None,
729    })
730}
731
732/// Build the human-readable reason for a class-member trace, keyed on the
733/// owner's reachability / usage (the precondition that gates member crediting).
734fn class_member_trace_reason(
735    member_name: &str,
736    owner_name: &str,
737    kind_str: &str,
738    filter_flag: Option<&str>,
739    file_path: &str,
740    owner_trace: &ExportTrace,
741) -> String {
742    let head =
743        format!("'{member_name}' is a {kind_str} of '{owner_name}', not a top-level export. ");
744    let body = if !owner_trace.file_reachable {
745        format!(
746            "The file is not reachable from any entry point, so '{owner_name}' and all its \
747             members are dead (see the unused-file finding)."
748        )
749    } else if !owner_trace.is_used {
750        format!(
751            "'{owner_name}' is reachable but referenced by no file, so it is reported as an \
752             unused export and its members are not judged individually."
753        )
754    } else {
755        let refs = owner_trace.direct_references.len();
756        match filter_flag {
757            Some(flag) => format!(
758                "'{owner_name}' is used by {refs} file(s); whether '{member_name}' itself is \
759                 flagged depends on cross-file member-access resolution. Run \
760                 `fallow dead-code {flag} --file {file_path}` to see the member finding."
761            ),
762            None => format!(
763                "'{owner_name}' is used by {refs} file(s); '{member_name}' is credited through \
764                 its namespace export."
765            ),
766        }
767    };
768    format!("{head}{body}")
769}
770
771fn select_export<'graph>(
772    graph: &'graph ModuleGraph,
773    module: &'graph crate::graph::ModuleNode,
774    export_name: &str,
775) -> Option<crate::graph::EffectiveExportSurface<'graph>> {
776    [ExportNamespace::Value, ExportNamespace::Type]
777        .into_iter()
778        .find_map(|namespace| {
779            graph.effective_export_surface(module.file_id, export_name, namespace)
780        })
781}
782
783/// Map a module's exports to [`TracedExport`] entries with relativized references.
784fn traced_exports(
785    graph: &ModuleGraph,
786    root: &Path,
787    module: &crate::graph::ModuleNode,
788) -> Vec<TracedExport> {
789    module
790        .exports
791        .iter()
792        .map(|e| {
793            let referenced_by: Vec<_> = e
794                .physical_references()
795                .map(|r| reference_to_export_reference(graph, root, r))
796                .collect();
797            TracedExport {
798                name: e.name.to_string(),
799                is_type_only: e.is_type_only,
800                reference_count: referenced_by.len(),
801                referenced_by,
802                plugin_credits: Vec::new(),
803            }
804        })
805        .collect()
806}
807
808/// Collect the root-relative paths a file imports from (forward graph edges).
809fn traced_imports_from(
810    graph: &ModuleGraph,
811    root: &Path,
812    module: &crate::graph::ModuleNode,
813) -> Vec<PathBuf> {
814    graph
815        .edges_for(module.file_id)
816        .iter()
817        .filter_map(|target_id| {
818            graph
819                .modules
820                .get(target_id.0 as usize)
821                .map(|m| m.path.strip_prefix(root).unwrap_or(&m.path).to_path_buf())
822        })
823        .collect()
824}
825
826/// Collect the root-relative paths that import a file (reverse graph edges).
827fn traced_imported_by(
828    graph: &ModuleGraph,
829    root: &Path,
830    module: &crate::graph::ModuleNode,
831) -> Vec<PathBuf> {
832    graph
833        .reverse_deps
834        .get(module.file_id.0 as usize)
835        .map(|deps| {
836            deps.iter()
837                .filter_map(|fid| {
838                    graph
839                        .modules
840                        .get(fid.0 as usize)
841                        .map(|m| m.path.strip_prefix(root).unwrap_or(&m.path).to_path_buf())
842                })
843                .collect()
844        })
845        .unwrap_or_default()
846}
847
848/// Map a module's re-exports to [`TracedReExport`] entries with relativized source paths.
849fn traced_re_exports(
850    graph: &ModuleGraph,
851    root: &Path,
852    module: &crate::graph::ModuleNode,
853) -> Vec<TracedReExport> {
854    module
855        .re_exports
856        .iter()
857        .map(|re| {
858            let source_path = graph.modules.get(re.source_file.0 as usize).map_or_else(
859                || PathBuf::from(format!("<unknown:{}>", re.source_file.0)),
860                |m| m.path.strip_prefix(root).unwrap_or(&m.path).to_path_buf(),
861            );
862            TracedReExport {
863                source_file: source_path,
864                imported_name: re.imported_name.clone(),
865                exported_name: re.exported_name.clone(),
866            }
867        })
868        .collect()
869}
870
871/// Trace all edges for a file.
872#[must_use]
873pub fn trace_file(graph: &ModuleGraph, root: &Path, file_path: &str) -> Option<FileTrace> {
874    let module = find_module(graph, root, file_path)?;
875
876    Some(FileTrace {
877        file: relative_module_path(&module.path, root),
878        is_reachable: module.is_reachable(),
879        is_entry_point: module.is_entry_point(),
880        exports: traced_exports(graph, root, module),
881        imports_from: traced_imports_from(graph, root, module),
882        imported_by: traced_imported_by(graph, root, module),
883        re_exports: traced_re_exports(graph, root, module),
884        ..FileTrace::default()
885    })
886}
887
888/// The packages that the dependency trace credits although no file imports
889/// them.
890pub struct DependencyCredit<'a> {
891    /// The packages that scripts, CI configs and git hooks run.
892    pub script_used_packages: &'a FxHashSet<String>,
893    /// The packages that start the peer-dependency closures in addition to
894    /// the imported packages.
895    pub peer_seeds: &'a PeerClosureSeeds,
896}
897
898/// Trace where a dependency is used.
899///
900/// `script_used_packages` carries the package names recorded as binary invocations
901/// in package.json scripts (`build: microbundle ...`) and CI configs
902/// (`.github/workflows/*.yml`, `.gitlab-ci.yml`). The same set the unused-deps
903/// detector consults; passing it in lets the trace output match the detector's
904/// view of "used" instead of reporting `is_used=false` for tools invoked only
905/// through scripts. `ignore_patterns` hide workspace manifests from the peer
906/// closure, as in the unused-dependency check.
907#[must_use]
908pub fn trace_dependency(
909    graph: &ModuleGraph,
910    root: &Path,
911    workspace_roots: &[&Path],
912    ignore_patterns: &fallow_config::IgnorePatternSet,
913    package_name: &str,
914    credit: &DependencyCredit<'_>,
915) -> DependencyTrace {
916    let (imported_by, type_only_imported_by) = package_importers(graph, root, package_name);
917
918    let import_count = imported_by.len();
919    let used_in_scripts = credit.script_used_packages.contains(package_name);
920    let peer_of = crate::core_backend::peer_dependency_hosts(
921        graph,
922        root,
923        workspace_roots,
924        ignore_patterns,
925        package_name,
926        credit.peer_seeds,
927    );
928    let mut trace = DependencyTrace {
929        package_name: package_name.to_string(),
930        imported_by,
931        type_only_imported_by,
932        used_in_scripts,
933        is_used: import_count > 0 || used_in_scripts || !peer_of.is_empty(),
934        import_count,
935        peer_of,
936        sources: Vec::new(),
937        tooling_credit: None,
938        unused_in: Vec::new(),
939        usage: None,
940    };
941    trace.apply_tooling_credit(imported_types_target_credit(graph, package_name));
942    trace
943}
944
945/// The files that import `package_name`, each listed once, and the subset
946/// whose every import of the package is type-only.
947///
948/// The graph records one usage entry per import, so a file with two imports
949/// of the package appears twice. A file with a type-only import and a value
950/// import is not a type-only importer.
951fn package_importers(
952    graph: &ModuleGraph,
953    root: &Path,
954    package_name: &str,
955) -> (Vec<PathBuf>, Vec<PathBuf>) {
956    let counts = |usage: &FxHashMap<String, Vec<FileId>>| {
957        let mut counts: FxHashMap<FileId, usize> = FxHashMap::default();
958        for &fid in usage.get(package_name).into_iter().flatten() {
959            *counts.entry(fid).or_default() += 1;
960        }
961        counts
962    };
963    let mut all = counts(&graph.package_usage);
964    let type_only = counts(&graph.type_only_package_usage);
965    let mut imported_by = Vec::new();
966    let mut type_only_imported_by = Vec::new();
967    for &fid in graph.package_usage.get(package_name).into_iter().flatten() {
968        // The first entry of a file takes its count, so a repeat finds none.
969        let Some(total) = all.remove(&fid) else {
970            continue;
971        };
972        let Some(module) = graph.modules.get(fid.0 as usize) else {
973            continue;
974        };
975        let path = relative_module_path(&module.path, root);
976        if type_only.get(&fid) == Some(&total) {
977            type_only_imported_by.push(path.clone());
978        }
979        imported_by.push(path);
980    }
981    (imported_by, type_only_imported_by)
982}
983
984/// The credit of a `@types/X` package whose target `X` the code imports, as
985/// the unused devDependency check gives it.
986fn imported_types_target_credit(graph: &ModuleGraph, package_name: &str) -> Option<ToolingCredit> {
987    let target = crate::core_backend::types_package_target(package_name)?;
988    graph
989        .package_usage
990        .get(target.as_str())
991        .is_some_and(|ids| !ids.is_empty())
992        .then(|| ToolingCredit {
993            reason: "types-target".to_string(),
994            plugin: None,
995            config: None,
996            reference: Some(target),
997        })
998}
999
1000fn format_reference_kind(kind: ReferenceKind) -> String {
1001    match kind {
1002        ReferenceKind::NamedImport => "named import".to_string(),
1003        ReferenceKind::DefaultImport => "default import".to_string(),
1004        ReferenceKind::NamespaceImport => "namespace import".to_string(),
1005        ReferenceKind::ReExport => "re-export".to_string(),
1006        ReferenceKind::DynamicImport => "dynamic import".to_string(),
1007        ReferenceKind::SideEffectImport => "side-effect import".to_string(),
1008    }
1009}
1010
1011/// Compute the impact closure for a single file as the seed.
1012///
1013/// Resolves `file_path` to a graph `FileId`, walks `reverse_deps` + re-export
1014/// chains to the transitive affected set, and reports the coordination gap (the
1015/// seed's exported contracts consumed by modules outside the seed). Returns
1016/// `None` when the file is not in the module graph.
1017///
1018/// Each coordination gap carries the literal-search check, so this reads the
1019/// source of each consumer of the seed exports.
1020#[must_use]
1021pub fn trace_impact_closure(
1022    graph: &ModuleGraph,
1023    root: &Path,
1024    file_path: &str,
1025) -> Option<ImpactClosureTrace> {
1026    impact_closure_trace(graph, root, file_path, true)
1027}
1028
1029/// Compute the impact closure like [`trace_impact_closure`], without the
1030/// literal-search check. The coordination gaps have no search fields, and no
1031/// consumer source is read. Use it when only the affected set is needed.
1032#[must_use]
1033pub fn trace_impact_closure_without_search(
1034    graph: &ModuleGraph,
1035    root: &Path,
1036    file_path: &str,
1037) -> Option<ImpactClosureTrace> {
1038    impact_closure_trace(graph, root, file_path, false)
1039}
1040
1041fn impact_closure_trace(
1042    graph: &ModuleGraph,
1043    root: &Path,
1044    file_path: &str,
1045    check_search: bool,
1046) -> Option<ImpactClosureTrace> {
1047    let module = find_module(graph, root, file_path)?;
1048
1049    let closure = graph.impact_closure(&[module.file_id]);
1050    let paths = graph.closure_with_paths(&closure, root);
1051
1052    let seed = paths
1053        .in_diff
1054        .first()
1055        .cloned()
1056        .unwrap_or_else(|| file_path.replace('\\', "/"));
1057
1058    let mut checks: FxHashMap<String, (String, SearchCheck)> =
1059        if !check_search || paths.coordination_gap.is_empty() {
1060            FxHashMap::default()
1061        } else {
1062            consumer_search_checks(graph, module.file_id)
1063                .into_iter()
1064                .filter_map(|(file_id, check)| {
1065                    let consumer = graph.modules.get(file_id.0 as usize)?;
1066                    let path = consumer
1067                        .path
1068                        .strip_prefix(root)
1069                        .unwrap_or(&consumer.path)
1070                        .to_string_lossy()
1071                        .replace('\\', "/");
1072                    Some((path, check))
1073                })
1074                .collect()
1075        };
1076    let coordination_gap = paths
1077        .coordination_gap
1078        .into_iter()
1079        .map(|gap| {
1080            let (search_symbol, check) = checks.remove(&gap.consumer_file).unzip();
1081            ImpactClosureGap {
1082                consumer_file: gap.consumer_file,
1083                consumed_symbols: gap.consumed_symbols,
1084                note: "syntactic attention pointer, not a correctness proof".to_string(),
1085                search_visibility: check.as_ref().map(|check| check.visibility),
1086                reason: check.as_ref().and_then(|check| check.reason),
1087                search_as: check.and_then(|check| check.search_as),
1088                search_symbol,
1089            }
1090        })
1091        .collect();
1092
1093    Some(ImpactClosureTrace {
1094        seed,
1095        affected_not_shown: paths.affected_not_shown,
1096        coordination_gap,
1097    })
1098}
1099
1100/// The worst literal-search check per consumer of the value exports of
1101/// `seed`, over every export the consumer references, with the name of the
1102/// export that the check belongs to. The order of the levels is `missed`, then
1103/// `renamed`, then `found`.
1104fn consumer_search_checks(
1105    graph: &ModuleGraph,
1106    seed: FileId,
1107) -> FxHashMap<FileId, (String, SearchCheck)> {
1108    let mut checks: FxHashMap<FileId, (String, SearchCheck)> = FxHashMap::default();
1109    let Some(module) = graph.modules.get(seed.0 as usize) else {
1110        return checks;
1111    };
1112    let mut sources = SourceCache::new(graph);
1113    for export in module.exports.iter().filter(|export| !export.is_type_only) {
1114        let name = export.name.to_string();
1115        let target = SearchTarget::new(graph, &mut sources, seed, &name, ExportNamespace::Value);
1116        let mut seen = FxHashSet::default();
1117        for reference in &export.references {
1118            if reference.from_file == seed || !seen.insert(reference.from_file) {
1119                continue;
1120            }
1121            let Some(check) = target.check(graph, &mut sources, reference) else {
1122                continue;
1123            };
1124            // A local use of one export outranks a pass-through of another.
1125            let worse = checks.get(&reference.from_file).is_none_or(|(_, known)| {
1126                check.visibility > known.visibility
1127                    || (check.visibility == known.visibility
1128                        && known.reason == Some(SearchGapReason::PassThrough)
1129                        && check.reason != Some(SearchGapReason::PassThrough))
1130            });
1131            if worse {
1132                checks.insert(reference.from_file, (name.clone(), check));
1133            }
1134        }
1135    }
1136    checks
1137}
1138
1139/// Which endpoint of a `--path` request did not resolve to exactly one module.
1140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1141pub enum ImportPathEndpoint {
1142    /// The module the walk would start from.
1143    From,
1144    /// The module the walk is looking for.
1145    To,
1146    /// Several modules match the starting path abbreviation.
1147    AmbiguousFrom,
1148    /// Several modules match the destination path abbreviation.
1149    AmbiguousTo,
1150}
1151
1152impl ImportPathEndpoint {
1153    /// The flag position this endpoint occupies, for diagnostics.
1154    #[must_use]
1155    pub const fn label(self) -> &'static str {
1156        match self {
1157            Self::From | Self::AmbiguousFrom => "from",
1158            Self::To | Self::AmbiguousTo => "to",
1159        }
1160    }
1161
1162    /// Whether the endpoint matched several modules instead of no module.
1163    #[must_use]
1164    pub const fn is_ambiguous(self) -> bool {
1165        matches!(self, Self::AmbiguousFrom | Self::AmbiguousTo)
1166    }
1167}
1168
1169fn import_path_endpoint_index(
1170    graph: &ModuleGraph,
1171    root: &Path,
1172    path: &str,
1173    missing: ImportPathEndpoint,
1174    ambiguous: ImportPathEndpoint,
1175) -> Result<usize, ImportPathEndpoint> {
1176    match matching_module_indexes(graph, root, path).as_slice() {
1177        [index] => Ok(*index),
1178        [] => Err(missing),
1179        _ => Err(ambiguous),
1180    }
1181}
1182
1183/// Resolve graph-level hops to the wire shape, turning each import span into a
1184/// 1-based line. Each source file is read at most once per trace; a file that
1185/// cannot be read yields `import_line: None` rather than a guessed line.
1186fn resolve_import_path_hops(
1187    graph: &ModuleGraph,
1188    root: &Path,
1189    hops: &[GraphImportPathHop],
1190) -> Vec<ImportPathHop> {
1191    let mut line_offsets: FxHashMap<FileId, Option<Vec<u32>>> = FxHashMap::default();
1192    hops.iter()
1193        .filter_map(|hop| {
1194            let from = graph.modules.get(hop.from.0 as usize)?;
1195            let to = graph.modules.get(hop.to.0 as usize)?;
1196            let import_line = hop.import_span_start.and_then(|span_start| {
1197                line_offsets
1198                    .entry(hop.from)
1199                    .or_insert_with(|| {
1200                        std::fs::read_to_string(&from.path)
1201                            .ok()
1202                            .map(|source| fallow_types::extract::compute_line_offsets(&source))
1203                    })
1204                    .as_ref()
1205                    .map(|offsets| {
1206                        fallow_types::extract::byte_offset_to_line_col(offsets, span_start).0
1207                    })
1208            });
1209            Some(ImportPathHop {
1210                from: relativize(&from.path, root),
1211                to: relativize(&to.path, root),
1212                type_only: hop.all_type_only,
1213                dynamic: hop.dynamic,
1214                import_line,
1215            })
1216        })
1217        .collect()
1218}
1219
1220/// Relativize a module path against the project root, forward-slashed.
1221pub fn relativize(path: &Path, root: &Path) -> String {
1222    path.strip_prefix(root)
1223        .unwrap_or(path)
1224        .to_string_lossy()
1225        .replace('\\', "/")
1226}
1227
1228/// Build a [`TracedCloneGroup`] from a raw clone group, computing the
1229/// fingerprint, group-level suggestion, and dominant-identifier name and
1230/// relativizing every instance path against `root`.
1231fn build_traced_group(
1232    group: &CloneGroup,
1233    root: &Path,
1234    fingerprints: &CloneFingerprintSet,
1235) -> TracedCloneGroup {
1236    TracedCloneGroup {
1237        fingerprint: fingerprints.fingerprint_for_group(group),
1238        token_count: group.token_count,
1239        line_count: group.line_count,
1240        spread: group.spread(),
1241        similarity: group.similarity,
1242        instances: group
1243            .instances
1244            .iter()
1245            .map(|inst| relativize_instance(inst, root))
1246            .collect(),
1247        suggestion: group_refactoring_suggestion(group),
1248        suggested_name: dominant_identifier(group),
1249    }
1250}
1251
1252#[must_use]
1253pub fn trace_clone(
1254    report: &DuplicationReport,
1255    root: &Path,
1256    file_path: &str,
1257    line: usize,
1258) -> CloneTrace {
1259    let resolved = root.join(file_path);
1260    let mut matched_instance = None;
1261    let mut clone_groups = Vec::new();
1262    let fingerprints = CloneFingerprintSet::from_groups(&report.clone_groups);
1263
1264    for group in &report.clone_groups {
1265        let matching = group.instances.iter().find(|inst| {
1266            let inst_matches = inst.file == resolved
1267                || inst.file.strip_prefix(root).unwrap_or(&inst.file) == Path::new(file_path);
1268            inst_matches && inst.start_line <= line && line <= inst.end_line
1269        });
1270
1271        if let Some(matched) = matching {
1272            if matched_instance.is_none() {
1273                matched_instance = Some(relativize_instance(matched, root));
1274            }
1275            clone_groups.push(build_traced_group(group, root, &fingerprints));
1276        }
1277    }
1278
1279    CloneTrace {
1280        file: PathBuf::from(file_path),
1281        line,
1282        matched_instance,
1283        clone_groups,
1284    }
1285}
1286
1287/// Trace a clone group by its stable content fingerprint.
1288///
1289/// Fingerprints are usually `dup:<8hex>` and widen only when needed to avoid a
1290/// collision inside the same report.
1291///
1292/// Returns a [`CloneTrace`] whose single `clone_groups` entry is the matched
1293/// group and whose `file` / `line` / `matched_instance` come from that group's
1294/// representative (first) instance. `matched_instance` is `None` (and
1295/// `clone_groups` empty) when no group matches the fingerprint.
1296#[must_use]
1297pub fn trace_clone_by_fingerprint(
1298    report: &DuplicationReport,
1299    root: &Path,
1300    fingerprint: &str,
1301) -> CloneTrace {
1302    let fingerprints = CloneFingerprintSet::from_groups(&report.clone_groups);
1303    let matched = fingerprints.find_group(&report.clone_groups, fingerprint);
1304
1305    let Some(group) = matched else {
1306        return CloneTrace {
1307            file: PathBuf::new(),
1308            line: 0,
1309            matched_instance: None,
1310            clone_groups: Vec::new(),
1311        };
1312    };
1313
1314    let representative = group
1315        .instances
1316        .first()
1317        .map(|inst| relativize_instance(inst, root));
1318    let (file, line) = representative.as_ref().map_or_else(
1319        || (PathBuf::new(), 0),
1320        |inst| (inst.file.clone(), inst.start_line),
1321    );
1322
1323    CloneTrace {
1324        file,
1325        line,
1326        matched_instance: representative,
1327        clone_groups: vec![build_traced_group(group, root, &fingerprints)],
1328    }
1329}
1330
1331/// Return a copy of `inst` with `file` rewritten relative to `root` (forward-slash normalized
1332/// for cross-platform JSON parity with `serde_path::serialize`). If `inst.file` is already
1333/// outside `root`, the path is left unchanged.
1334fn relativize_instance(inst: &CloneInstance, root: &Path) -> CloneInstance {
1335    let rel = inst.file.strip_prefix(root).map_or_else(
1336        |_| inst.file.clone(),
1337        |p| PathBuf::from(p.to_string_lossy().replace('\\', "/")),
1338    );
1339    CloneInstance {
1340        file: rel,
1341        ..inst.clone()
1342    }
1343}
1344
1345#[path = "trace_import_path.rs"]
1346mod trace_import_path;
1347pub use trace_import_path::trace_import_path;
1348
1349#[cfg(test)]
1350#[path = "trace_impl_dependency_tests.rs"]
1351mod dependency_tests;
1352
1353#[cfg(test)]
1354mod tests {
1355    use super::*;
1356
1357    use crate::discover::{DiscoveredFile, EntryPoint, EntryPointSource, FileId};
1358    use fallow_graph::resolve::{ResolveResult, ResolvedImport, ResolvedModule, ResolvedReExport};
1359    use fallow_types::extract::ReExportInfo;
1360    use fallow_types::extract::{ExportInfo, ExportName, ImportInfo, ImportedName, VisibilityTag};
1361
1362    fn resolved_re_export(
1363        source: FileId,
1364        imported_name: &str,
1365        exported_name: &str,
1366    ) -> ResolvedReExport {
1367        ResolvedReExport {
1368            info: ReExportInfo {
1369                source: "./source".to_string(),
1370                imported_name: imported_name.to_string(),
1371                exported_name: exported_name.to_string(),
1372                is_type_only: false,
1373                span: oxc_span::Span::default(),
1374                ..Default::default()
1375            },
1376            target: ResolveResult::InternalModule(source),
1377        }
1378    }
1379
1380    fn build_test_graph() -> ModuleGraph {
1381        build_test_graph_at(Path::new("/project"))
1382    }
1383
1384    /// The `entry -> utils` graph with module paths under `root`.
1385    fn build_test_graph_at(root: &Path) -> ModuleGraph {
1386        let src = |name: &str| root.join("src").join(name);
1387        let files = vec![
1388            DiscoveredFile {
1389                id: FileId(0),
1390                path: src("entry.ts"),
1391                size_bytes: 100,
1392            },
1393            DiscoveredFile {
1394                id: FileId(1),
1395                path: src("utils.ts"),
1396                size_bytes: 50,
1397            },
1398            DiscoveredFile {
1399                id: FileId(2),
1400                path: src("unused.ts"),
1401                size_bytes: 30,
1402            },
1403        ];
1404
1405        let entry_points = vec![EntryPoint {
1406            path: src("entry.ts"),
1407            source: EntryPointSource::PackageJsonMain,
1408        }];
1409
1410        let resolved_modules = vec![
1411            ResolvedModule {
1412                file_id: FileId(0),
1413                path: src("entry.ts"),
1414                resolved_imports: vec![ResolvedImport {
1415                    info: ImportInfo {
1416                        source: "./utils".to_string(),
1417                        imported_name: ImportedName::Named("foo".to_string()),
1418                        local_name: "foo".to_string(),
1419                        is_type_only: false,
1420                        is_type_only_star: false,
1421                        from_style: false,
1422                        span: oxc_span::Span::new(0, 10),
1423                        source_span: oxc_span::Span::default(),
1424                    },
1425                    target: ResolveResult::InternalModule(FileId(1)),
1426                }],
1427                ..Default::default()
1428            },
1429            ResolvedModule {
1430                file_id: FileId(1),
1431                path: src("utils.ts"),
1432                exports: vec![
1433                    ExportInfo {
1434                        name: ExportName::Named("foo".to_string()),
1435                        local_name: Some("foo".to_string()),
1436                        is_type_only: false,
1437                        visibility: VisibilityTag::None,
1438                        expected_unused_reason: None,
1439                        span: oxc_span::Span::new(0, 20),
1440                        members: vec![],
1441                        is_side_effect_used: false,
1442                        super_class: None,
1443                        deprecated: false,
1444                        deprecated_reason: None,
1445                    },
1446                    ExportInfo {
1447                        name: ExportName::Named("bar".to_string()),
1448                        local_name: Some("bar".to_string()),
1449                        is_type_only: false,
1450                        visibility: VisibilityTag::None,
1451                        expected_unused_reason: None,
1452                        span: oxc_span::Span::new(21, 40),
1453                        members: vec![],
1454                        is_side_effect_used: false,
1455                        super_class: None,
1456                        deprecated: false,
1457                        deprecated_reason: None,
1458                    },
1459                ]
1460                .into(),
1461                ..Default::default()
1462            },
1463            ResolvedModule {
1464                file_id: FileId(2),
1465                path: src("unused.ts"),
1466                exports: vec![ExportInfo {
1467                    name: ExportName::Named("baz".to_string()),
1468                    local_name: Some("baz".to_string()),
1469                    is_type_only: false,
1470                    visibility: VisibilityTag::None,
1471                    expected_unused_reason: None,
1472                    span: oxc_span::Span::new(0, 15),
1473                    members: vec![],
1474                    is_side_effect_used: false,
1475                    super_class: None,
1476                    deprecated: false,
1477                    deprecated_reason: None,
1478                }]
1479                .into(),
1480                ..Default::default()
1481            },
1482        ];
1483
1484        ModuleGraph::build(&resolved_modules, &entry_points, &files)
1485    }
1486
1487    #[test]
1488    fn trace_used_export() {
1489        let graph = build_test_graph();
1490        let root = Path::new("/project");
1491
1492        let trace = trace_export(&graph, root, "src/utils.ts", "foo").unwrap();
1493        assert!(trace.is_used);
1494        assert!(trace.file_reachable);
1495        assert_eq!(trace.direct_references.len(), 1);
1496        assert_eq!(
1497            trace.direct_references[0].from_file,
1498            PathBuf::from("src/entry.ts")
1499        );
1500        assert_eq!(trace.direct_references[0].kind, "named import");
1501    }
1502
1503    #[test]
1504    fn trace_unused_export() {
1505        let graph = build_test_graph();
1506        let root = Path::new("/project");
1507
1508        let trace = trace_export(&graph, root, "src/utils.ts", "bar").unwrap();
1509        assert!(!trace.is_used);
1510        assert!(trace.file_reachable);
1511        assert!(trace.direct_references.is_empty());
1512        assert_eq!(
1513            trace.namespace,
1514            fallow_types::semantic::SemanticNamespace::Value,
1515            "an unreferenced value export stays in the value namespace"
1516        );
1517    }
1518
1519    #[test]
1520    fn trace_unreachable_file_export() {
1521        let graph = build_test_graph();
1522        let root = Path::new("/project");
1523
1524        let trace = trace_export(&graph, root, "src/unused.ts", "baz").unwrap();
1525        assert!(!trace.is_used);
1526        assert!(!trace.file_reachable);
1527        assert!(trace.reason.contains("unreachable"));
1528    }
1529
1530    #[test]
1531    fn trace_nonexistent_export() {
1532        let graph = build_test_graph();
1533        let root = Path::new("/project");
1534
1535        let trace = trace_export(&graph, root, "src/utils.ts", "nonexistent");
1536        assert!(trace.is_none());
1537    }
1538
1539    fn assert_no_search_fields(reference: &ExportReference) {
1540        assert_eq!(reference.line, None);
1541        assert_eq!(reference.search_visibility, None);
1542        assert_eq!(reference.reason, None);
1543        assert_eq!(reference.search_as, None);
1544    }
1545
1546    fn assert_gap_has_no_search_fields(gap: &ImpactClosureGap) {
1547        assert_eq!(gap.search_visibility, None);
1548        assert_eq!(gap.reason, None);
1549        assert_eq!(gap.search_as, None);
1550        assert_eq!(gap.search_symbol, None);
1551    }
1552
1553    #[test]
1554    fn unreadable_consumer_leaves_the_search_fields_absent() {
1555        // The paths under `/project` do not exist, so no consumer source can be read.
1556        let graph = build_test_graph();
1557        let root = Path::new("/project");
1558
1559        let trace = trace_export(&graph, root, "src/utils.ts", "foo").unwrap();
1560        assert_eq!(trace.direct_references.len(), 1);
1561        assert_no_search_fields(&trace.direct_references[0]);
1562
1563        let impact = trace_impact_closure(&graph, root, "src/utils.ts").unwrap();
1564        assert_eq!(impact.coordination_gap.len(), 1);
1565        assert_gap_has_no_search_fields(&impact.coordination_gap[0]);
1566    }
1567
1568    #[test]
1569    fn impact_closure_without_search_reads_no_consumer_source() {
1570        let dir = tempfile::tempdir().expect("tempdir");
1571        let src = dir.path().join("src");
1572        std::fs::create_dir_all(&src).unwrap();
1573        std::fs::write(
1574            src.join("entry.ts"),
1575            "import { foo } from './utils';\nfoo();\n",
1576        )
1577        .unwrap();
1578        std::fs::write(
1579            src.join("utils.ts"),
1580            "export const foo = 1;\nexport const bar = 2;\n",
1581        )
1582        .unwrap();
1583        let graph = build_test_graph_at(dir.path());
1584
1585        let checked = trace_impact_closure(&graph, dir.path(), "src/utils.ts").unwrap();
1586        assert_eq!(checked.coordination_gap.len(), 1);
1587        assert_eq!(
1588            checked.coordination_gap[0].search_visibility,
1589            Some(fallow_types::trace::SearchVisibility::Found)
1590        );
1591        assert_eq!(
1592            checked.coordination_gap[0].search_symbol.as_deref(),
1593            Some("foo")
1594        );
1595
1596        let unchecked =
1597            trace_impact_closure_without_search(&graph, dir.path(), "src/utils.ts").unwrap();
1598        assert_eq!(unchecked.coordination_gap.len(), 1);
1599        assert_gap_has_no_search_fields(&unchecked.coordination_gap[0]);
1600        assert_eq!(unchecked.affected_not_shown, checked.affected_not_shown);
1601    }
1602
1603    #[test]
1604    fn trace_reports_only_the_effective_re_export_origin() {
1605        let files: Vec<_> = ["entry", "barrel", "star-source", "explicit-source"]
1606            .into_iter()
1607            .enumerate()
1608            .map(|(index, name)| DiscoveredFile {
1609                id: FileId(index as u32),
1610                path: PathBuf::from(format!("/project/src/{name}.ts")),
1611                size_bytes: 10,
1612            })
1613            .collect();
1614        let entry_points = vec![EntryPoint {
1615            path: files[0].path.clone(),
1616            source: EntryPointSource::PackageJsonMain,
1617        }];
1618        let re_export = |source: FileId, imported: &str, exported: &str| ResolvedReExport {
1619            info: ReExportInfo {
1620                source: format!("./{}", source.0),
1621                imported_name: imported.to_string(),
1622                exported_name: exported.to_string(),
1623                is_type_only: false,
1624                span: oxc_span::Span::default(),
1625                ..Default::default()
1626            },
1627            target: ResolveResult::InternalModule(source),
1628        };
1629        let export = || ExportInfo {
1630            name: ExportName::Named("foo".to_string()),
1631            local_name: Some("foo".to_string()),
1632            is_type_only: false,
1633            visibility: VisibilityTag::None,
1634            expected_unused_reason: None,
1635            span: oxc_span::Span::new(0, 3),
1636            members: Vec::new(),
1637            is_side_effect_used: false,
1638            super_class: None,
1639            deprecated: false,
1640            deprecated_reason: None,
1641        };
1642        let resolved = vec![
1643            ResolvedModule {
1644                file_id: FileId(0),
1645                path: files[0].path.clone(),
1646                resolved_imports: vec![ResolvedImport {
1647                    info: ImportInfo {
1648                        source: "./barrel".to_string(),
1649                        imported_name: ImportedName::Named("foo".to_string()),
1650                        local_name: "foo".to_string(),
1651                        is_type_only: false,
1652                        is_type_only_star: false,
1653                        from_style: false,
1654                        span: oxc_span::Span::default(),
1655                        source_span: oxc_span::Span::default(),
1656                    },
1657                    target: ResolveResult::InternalModule(FileId(1)),
1658                }],
1659                ..Default::default()
1660            },
1661            ResolvedModule {
1662                file_id: FileId(1),
1663                path: files[1].path.clone(),
1664                re_exports: vec![
1665                    re_export(FileId(2), "*", "*"),
1666                    re_export(FileId(3), "foo", "foo"),
1667                ],
1668                ..Default::default()
1669            },
1670            ResolvedModule {
1671                file_id: FileId(2),
1672                path: files[2].path.clone(),
1673                exports: vec![export()].into(),
1674                ..Default::default()
1675            },
1676            ResolvedModule {
1677                file_id: FileId(3),
1678                path: files[3].path.clone(),
1679                exports: vec![export()].into(),
1680                ..Default::default()
1681            },
1682        ];
1683        let graph = ModuleGraph::build(&resolved, &entry_points, &files);
1684
1685        let shadowed = trace_export(&graph, Path::new("/project"), "src/star-source.ts", "foo")
1686            .expect("shadowed source export exists");
1687        let effective = trace_export(
1688            &graph,
1689            Path::new("/project"),
1690            "src/explicit-source.ts",
1691            "foo",
1692        )
1693        .expect("effective source export exists");
1694
1695        assert!(shadowed.re_export_chains.is_empty());
1696        assert_eq!(effective.re_export_chains.len(), 1);
1697        assert_eq!(effective.re_export_chains[0].exported_as, "foo");
1698    }
1699
1700    fn star_surface_trace_graph(root: &Path) -> ModuleGraph {
1701        let src = root.join("src");
1702        std::fs::create_dir_all(&src).expect("create source directory");
1703        let paths: Vec<_> = ["source", "barrel-a", "barrel-b", "outer", "entry"]
1704            .into_iter()
1705            .map(|name| src.join(format!("{name}.ts")))
1706            .collect();
1707        std::fs::write(&paths[0], "\n\nexport const foo = 1;\n").expect("write source");
1708        for path in &paths[1..] {
1709            std::fs::write(path, "export {};\n").expect("write module");
1710        }
1711        let files: Vec<_> = paths
1712            .iter()
1713            .enumerate()
1714            .map(|(index, path)| DiscoveredFile {
1715                id: FileId(index as u32),
1716                path: path.clone(),
1717                size_bytes: 20,
1718            })
1719            .collect();
1720        let resolved = vec![
1721            ResolvedModule {
1722                file_id: FileId(0),
1723                path: paths[0].clone(),
1724                exports: vec![ExportInfo {
1725                    name: ExportName::Named("foo".to_string()),
1726                    local_name: Some("foo".to_string()),
1727                    is_type_only: false,
1728                    visibility: VisibilityTag::None,
1729                    expected_unused_reason: None,
1730                    span: oxc_span::Span::new(2, 5),
1731                    members: Vec::new(),
1732                    is_side_effect_used: false,
1733                    super_class: None,
1734                    deprecated: false,
1735                    deprecated_reason: None,
1736                }]
1737                .into(),
1738                ..Default::default()
1739            },
1740            ResolvedModule {
1741                file_id: FileId(1),
1742                path: paths[1].clone(),
1743                re_exports: vec![resolved_re_export(FileId(0), "*", "*")],
1744                ..Default::default()
1745            },
1746            ResolvedModule {
1747                file_id: FileId(2),
1748                path: paths[2].clone(),
1749                re_exports: vec![resolved_re_export(FileId(0), "*", "*")],
1750                ..Default::default()
1751            },
1752            ResolvedModule {
1753                file_id: FileId(3),
1754                path: paths[3].clone(),
1755                re_exports: vec![
1756                    resolved_re_export(FileId(1), "foo", "left"),
1757                    resolved_re_export(FileId(1), "foo", "right"),
1758                ],
1759                ..Default::default()
1760            },
1761            ResolvedModule {
1762                file_id: FileId(4),
1763                path: paths[4].clone(),
1764                resolved_imports: vec![
1765                    ResolvedImport {
1766                        info: ImportInfo {
1767                            source: "./outer".to_string(),
1768                            imported_name: ImportedName::Named("left".to_string()),
1769                            local_name: "left".to_string(),
1770                            is_type_only: false,
1771                            is_type_only_star: false,
1772                            from_style: false,
1773                            span: oxc_span::Span::new(10, 20),
1774                            source_span: oxc_span::Span::default(),
1775                        },
1776                        target: ResolveResult::InternalModule(FileId(3)),
1777                    },
1778                    ResolvedImport {
1779                        info: ImportInfo {
1780                            source: "./barrel-b".to_string(),
1781                            imported_name: ImportedName::Named("foo".to_string()),
1782                            local_name: "otherFoo".to_string(),
1783                            is_type_only: false,
1784                            is_type_only_star: false,
1785                            from_style: false,
1786                            span: oxc_span::Span::new(30, 40),
1787                            source_span: oxc_span::Span::default(),
1788                        },
1789                        target: ResolveResult::InternalModule(FileId(2)),
1790                    },
1791                ],
1792                ..Default::default()
1793            },
1794        ];
1795        let entry_points = vec![EntryPoint {
1796            path: paths[4].clone(),
1797            source: EntryPointSource::PackageJsonMain,
1798        }];
1799        ModuleGraph::build(&resolved, &entry_points, &files)
1800    }
1801
1802    #[test]
1803    fn star_surface_trace_keeps_aliases_separate_and_uses_origin_identity() {
1804        let root = tempfile::tempdir().expect("temporary project");
1805        let graph = star_surface_trace_graph(root.path());
1806
1807        let used = trace_export(&graph, root.path(), "src/barrel-a.ts", "foo")
1808            .expect("aliased barrel exposes foo");
1809        let sibling = trace_export(&graph, root.path(), "src/barrel-b.ts", "foo")
1810            .expect("sibling barrel exposes foo");
1811        assert!(used.is_used);
1812        assert_eq!(used.direct_references.len(), 1);
1813        assert!(sibling.is_used);
1814        assert_eq!(sibling.direct_references.len(), 1);
1815
1816        let source_trace = trace_export(&graph, root.path(), "src/source.ts", "foo")
1817            .expect("source declaration is traceable");
1818        let chain_count = |file: &str, name: &str| {
1819            source_trace
1820                .re_export_chains
1821                .iter()
1822                .find(|chain| chain.barrel_file == Path::new(file) && chain.exported_as == name)
1823                .map(|chain| chain.reference_count)
1824        };
1825        assert_eq!(chain_count("src/barrel-a.ts", "foo"), Some(1));
1826        assert_eq!(chain_count("src/barrel-b.ts", "foo"), Some(1));
1827        assert_eq!(chain_count("src/outer.ts", "left"), Some(1));
1828        assert_eq!(chain_count("src/outer.ts", "right"), Some(0));
1829
1830        let semantic = semantic_symbol_for_export(&graph, root.path(), "src/barrel-a.ts", "foo")
1831            .expect("star surface resolves to its declaration identity");
1832        assert_eq!(semantic.path, Path::new("src/source.ts"));
1833        assert_eq!(semantic.exported_name, "foo");
1834        assert_eq!(semantic.local_name, "foo");
1835        assert_eq!((semantic.line, semantic.col), (3, 0));
1836
1837        let alias = semantic_symbol_for_export(&graph, root.path(), "src/outer.ts", "left")
1838            .expect("named re-export keeps its export-specifier identity");
1839        assert_eq!(alias.path, Path::new("src/outer.ts"));
1840        assert_eq!(alias.exported_name, "left");
1841        assert_eq!(alias.local_name, "foo");
1842    }
1843
1844    #[test]
1845    fn trace_follows_renamed_and_convergent_re_export_routes() {
1846        let names = [
1847            "source",
1848            "renamed",
1849            "final",
1850            "left",
1851            "right",
1852            "diamond-entry",
1853        ];
1854        let files: Vec<_> = names
1855            .into_iter()
1856            .enumerate()
1857            .map(|(index, name)| DiscoveredFile {
1858                id: FileId(index as u32),
1859                path: PathBuf::from(format!("/project/src/{name}.ts")),
1860                size_bytes: 10,
1861            })
1862            .collect();
1863        let re_export = |source: FileId, imported: &str, exported: &str| ResolvedReExport {
1864            info: ReExportInfo {
1865                source: format!("./{}", source.0),
1866                imported_name: imported.to_string(),
1867                exported_name: exported.to_string(),
1868                is_type_only: false,
1869                span: oxc_span::Span::default(),
1870                ..Default::default()
1871            },
1872            target: ResolveResult::InternalModule(source),
1873        };
1874        let mut resolved: Vec<_> = files
1875            .iter()
1876            .map(|file| ResolvedModule {
1877                file_id: file.id,
1878                path: file.path.clone(),
1879                ..Default::default()
1880            })
1881            .collect();
1882        resolved[0].exports = vec![ExportInfo {
1883            name: ExportName::Named("foo".to_string()),
1884            local_name: Some("foo".to_string()),
1885            is_type_only: false,
1886            visibility: VisibilityTag::None,
1887            expected_unused_reason: None,
1888            span: oxc_span::Span::new(0, 3),
1889            members: Vec::new(),
1890            is_side_effect_used: false,
1891            super_class: None,
1892            deprecated: false,
1893            deprecated_reason: None,
1894        }]
1895        .into();
1896        resolved[1].re_exports = vec![re_export(FileId(0), "foo", "bar")];
1897        resolved[2].re_exports = vec![re_export(FileId(1), "bar", "baz")];
1898        resolved[3].re_exports = vec![re_export(FileId(0), "*", "*")];
1899        resolved[4].re_exports = vec![re_export(FileId(0), "*", "*")];
1900        resolved[5].re_exports = vec![
1901            re_export(FileId(3), "*", "*"),
1902            re_export(FileId(4), "*", "*"),
1903        ];
1904        let entry_points = vec![EntryPoint {
1905            path: files[5].path.clone(),
1906            source: EntryPointSource::PackageJsonMain,
1907        }];
1908        let graph = ModuleGraph::build(&resolved, &entry_points, &files);
1909
1910        let trace = trace_export(&graph, Path::new("/project"), "src/source.ts", "foo")
1911            .expect("source export exists");
1912        let routes: FxHashSet<_> = trace
1913            .re_export_chains
1914            .iter()
1915            .map(|route| (route.barrel_file.as_path(), route.exported_as.as_str()))
1916            .collect();
1917
1918        assert_eq!(routes.len(), 5);
1919        assert!(routes.contains(&(Path::new("src/renamed.ts"), "bar")));
1920        assert!(routes.contains(&(Path::new("src/final.ts"), "baz")));
1921        assert!(routes.contains(&(Path::new("src/left.ts"), "foo")));
1922        assert!(routes.contains(&(Path::new("src/right.ts"), "foo")));
1923        assert!(routes.contains(&(Path::new("src/diamond-entry.ts"), "foo")));
1924    }
1925
1926    #[test]
1927    fn trace_prefers_the_value_namespace_independent_of_usage() {
1928        let files = vec![
1929            DiscoveredFile {
1930                id: FileId(0),
1931                path: PathBuf::from("/project/src/entry.ts"),
1932                size_bytes: 10,
1933            },
1934            DiscoveredFile {
1935                id: FileId(1),
1936                path: PathBuf::from("/project/src/source.ts"),
1937                size_bytes: 10,
1938            },
1939        ];
1940        let export = |is_type_only| ExportInfo {
1941            name: ExportName::Named("Foo".to_string()),
1942            local_name: Some("Foo".to_string()),
1943            is_type_only,
1944            visibility: VisibilityTag::None,
1945            expected_unused_reason: None,
1946            span: oxc_span::Span::new(0, 3),
1947            members: Vec::new(),
1948            is_side_effect_used: false,
1949            super_class: None,
1950            deprecated: false,
1951            deprecated_reason: None,
1952        };
1953        let resolved = vec![
1954            ResolvedModule {
1955                file_id: FileId(0),
1956                path: files[0].path.clone(),
1957                resolved_imports: vec![ResolvedImport {
1958                    info: ImportInfo {
1959                        source: "./source".to_string(),
1960                        imported_name: ImportedName::Named("Foo".to_string()),
1961                        local_name: "Foo".to_string(),
1962                        is_type_only: true,
1963                        is_type_only_star: false,
1964                        from_style: false,
1965                        span: oxc_span::Span::default(),
1966                        source_span: oxc_span::Span::default(),
1967                    },
1968                    target: ResolveResult::InternalModule(FileId(1)),
1969                }],
1970                ..Default::default()
1971            },
1972            ResolvedModule {
1973                file_id: FileId(1),
1974                path: files[1].path.clone(),
1975                exports: vec![export(false), export(true)].into(),
1976                ..Default::default()
1977            },
1978        ];
1979        let entry_points = vec![EntryPoint {
1980            path: files[0].path.clone(),
1981            source: EntryPointSource::PackageJsonMain,
1982        }];
1983        let graph = ModuleGraph::build(&resolved, &entry_points, &files);
1984
1985        let trace = trace_export(&graph, Path::new("/project"), "src/source.ts", "Foo")
1986            .expect("value export exists");
1987
1988        // The type import credits the distinct `export type Foo` declaration,
1989        // so dead-code still reports the value `Foo`; the trace must agree and
1990        // must not borrow the type lane here (issue #2371). A declaration
1991        // merge that splits across lanes, `interface Foo` next to `class Foo`,
1992        // reaches the graph as this same pair of surfaces, so it is the shape
1993        // the documented gap names: dead-code credits the class through the
1994        // merge while the trace still reports it unused.
1995        assert_eq!(
1996            trace.namespace,
1997            fallow_types::semantic::SemanticNamespace::Value
1998        );
1999        assert!(!trace.is_used, "type usage must not select the type export");
2000    }
2001
2002    /// Consumer `entry.ts` importing `Foo` from `source.ts`, whose exports are
2003    /// supplied by the caller.
2004    fn source_consumer_graph(
2005        source_exports: Vec<ExportInfo>,
2006        import_is_type_only: bool,
2007        classified_usage: bool,
2008        semantic_facts: Vec<fallow_types::extract::SemanticFact>,
2009    ) -> ModuleGraph {
2010        let files = vec![
2011            DiscoveredFile {
2012                id: FileId(0),
2013                path: PathBuf::from("/project/src/entry.ts"),
2014                size_bytes: 10,
2015            },
2016            DiscoveredFile {
2017                id: FileId(1),
2018                path: PathBuf::from("/project/src/source.ts"),
2019                size_bytes: 10,
2020            },
2021        ];
2022        let classified = if classified_usage {
2023            vec!["Foo".to_string()]
2024        } else {
2025            Vec::new()
2026        };
2027        let resolved = vec![
2028            ResolvedModule {
2029                file_id: FileId(0),
2030                path: files[0].path.clone(),
2031                resolved_imports: vec![ResolvedImport {
2032                    info: ImportInfo {
2033                        source: "./source".to_string(),
2034                        imported_name: ImportedName::Named("Foo".to_string()),
2035                        local_name: "Foo".to_string(),
2036                        is_type_only: import_is_type_only,
2037                        is_type_only_star: false,
2038                        from_style: false,
2039                        span: oxc_span::Span::new(0, 10),
2040                        source_span: oxc_span::Span::default(),
2041                    },
2042                    target: ResolveResult::InternalModule(FileId(1)),
2043                }],
2044                type_referenced_import_bindings: classified.clone(),
2045                value_referenced_import_bindings: classified,
2046                ..Default::default()
2047            },
2048            ResolvedModule {
2049                file_id: FileId(1),
2050                path: files[1].path.clone(),
2051                exports: source_exports.into(),
2052                semantic_facts: semantic_facts.into(),
2053                ..Default::default()
2054            },
2055        ];
2056        let entry_points = vec![EntryPoint {
2057            path: files[0].path.clone(),
2058            source: EntryPointSource::PackageJsonMain,
2059        }];
2060        ModuleGraph::build(&resolved, &entry_points, &files)
2061    }
2062
2063    /// Two consumers of `source.ts`: `entry.ts` imports `Foo` in value
2064    /// position and `typed.ts` imports the same name with `import type`, so
2065    /// one effective binding carries a reference in both lanes.
2066    fn dual_lane_consumer_graph(source_exports: Vec<ExportInfo>) -> ModuleGraph {
2067        let files = vec![
2068            DiscoveredFile {
2069                id: FileId(0),
2070                path: PathBuf::from("/project/src/entry.ts"),
2071                size_bytes: 10,
2072            },
2073            DiscoveredFile {
2074                id: FileId(1),
2075                path: PathBuf::from("/project/src/source.ts"),
2076                size_bytes: 10,
2077            },
2078            DiscoveredFile {
2079                id: FileId(2),
2080                path: PathBuf::from("/project/src/typed.ts"),
2081                size_bytes: 10,
2082            },
2083        ];
2084        let consumer = |file_id: FileId, path: PathBuf, is_type_only: bool| ResolvedModule {
2085            file_id,
2086            path,
2087            resolved_imports: vec![ResolvedImport {
2088                info: ImportInfo {
2089                    source: "./source".to_string(),
2090                    imported_name: ImportedName::Named("Foo".to_string()),
2091                    local_name: "Foo".to_string(),
2092                    is_type_only,
2093                    is_type_only_star: false,
2094                    from_style: false,
2095                    span: oxc_span::Span::new(0, 10),
2096                    source_span: oxc_span::Span::default(),
2097                },
2098                target: ResolveResult::InternalModule(FileId(1)),
2099            }],
2100            ..Default::default()
2101        };
2102        let resolved = vec![
2103            consumer(FileId(0), files[0].path.clone(), false),
2104            ResolvedModule {
2105                file_id: FileId(1),
2106                path: files[1].path.clone(),
2107                exports: source_exports.into(),
2108                ..Default::default()
2109            },
2110            consumer(FileId(2), files[2].path.clone(), true),
2111        ];
2112        let entry_points = vec![
2113            EntryPoint {
2114                path: files[0].path.clone(),
2115                source: EntryPointSource::PackageJsonMain,
2116            },
2117            EntryPoint {
2118                path: files[2].path.clone(),
2119                source: EntryPointSource::PackageJsonMain,
2120            },
2121        ];
2122        ModuleGraph::build(&resolved, &entry_points, &files)
2123    }
2124
2125    fn class_method(name: &str, start: u32, end: u32) -> fallow_types::extract::MemberInfo {
2126        use fallow_types::extract::{MemberInfo, MemberKind};
2127        MemberInfo {
2128            name: name.to_string(),
2129            kind: MemberKind::ClassMethod,
2130            span: oxc_span::Span::new(start, end),
2131            has_decorator: false,
2132            decorator_names: vec![],
2133            is_instance_returning_static: false,
2134            is_self_returning: false,
2135            override_base: None,
2136            is_protected: false,
2137            is_static: false,
2138        }
2139    }
2140
2141    fn named_foo_export(is_type_only: bool) -> ExportInfo {
2142        ExportInfo {
2143            name: ExportName::Named("Foo".to_string()),
2144            local_name: Some("Foo".to_string()),
2145            is_type_only,
2146            visibility: VisibilityTag::None,
2147            expected_unused_reason: None,
2148            span: oxc_span::Span::new(0, 3),
2149            members: Vec::new(),
2150            is_side_effect_used: false,
2151            super_class: None,
2152            deprecated: false,
2153            deprecated_reason: None,
2154        }
2155    }
2156
2157    #[test]
2158    fn trace_credits_a_value_only_export_through_the_type_lane() {
2159        // Issue #2371: `import type { Foo }` of `export const Foo` lands on the
2160        // value declaration through the type-lane fallback, and dead-code
2161        // counts that as a use. The trace reports the crediting lane.
2162        let graph = source_consumer_graph(vec![named_foo_export(false)], true, false, Vec::new());
2163
2164        let trace = trace_export(&graph, Path::new("/project"), "src/source.ts", "Foo")
2165            .expect("value export exists");
2166
2167        assert_eq!(
2168            trace.namespace,
2169            fallow_types::semantic::SemanticNamespace::Type,
2170            "the type lane carries the only credit"
2171        );
2172        assert!(
2173            trace.is_used,
2174            "a type-only import credits a value-only export"
2175        );
2176        assert_eq!(trace.direct_references.len(), 1);
2177        assert_eq!(
2178            trace.direct_references[0].from_file,
2179            PathBuf::from("src/entry.ts")
2180        );
2181        assert_eq!(trace.direct_references[0].kind, "named import");
2182        assert_eq!(trace.reason, "Used by 1 file(s)");
2183    }
2184
2185    #[test]
2186    fn trace_omits_redundant_single_namespace_evidence() {
2187        let graph = source_consumer_graph(vec![named_foo_export(false)], false, false, Vec::new());
2188
2189        let trace = trace_export(&graph, Path::new("/project"), "src/source.ts", "Foo")
2190            .expect("value export exists");
2191
2192        assert_eq!(
2193            trace.namespace,
2194            fallow_types::semantic::SemanticNamespace::Value
2195        );
2196        assert_eq!(trace.direct_references.len(), 1);
2197        assert!(trace.direct_references_by_namespace.is_empty());
2198        let json = serde_json::to_value(&trace).expect("serialize trace");
2199        assert!(json.get("direct_references_by_namespace").is_none());
2200    }
2201
2202    #[test]
2203    fn trace_keeps_the_value_lane_when_one_binding_carries_both_lanes() {
2204        // The preferred lane wins whenever it carries a reference, including
2205        // when the other lane resolves to the SAME binding and carries one
2206        // too: `export class Foo` consumed by a value importer and by an
2207        // `import type` importer must keep reporting the value consumer.
2208        // Without that rule the type lane would take over the payload.
2209        let graph = dual_lane_consumer_graph(vec![named_foo_export(false)]);
2210
2211        let trace = trace_export(&graph, Path::new("/project"), "src/source.ts", "Foo")
2212            .expect("value export exists");
2213
2214        assert_eq!(
2215            trace.namespace,
2216            fallow_types::semantic::SemanticNamespace::Value
2217        );
2218        assert!(trace.is_used);
2219        assert_eq!(trace.direct_references.len(), 1);
2220        assert_eq!(
2221            trace.direct_references[0].from_file,
2222            PathBuf::from("src/entry.ts"),
2223            "the value consumer stays the listed reference"
2224        );
2225        assert_eq!(trace.direct_references_by_namespace.len(), 2);
2226        assert!(trace.direct_references_by_namespace.iter().any(|lane| {
2227            lane.namespace == fallow_types::semantic::SemanticNamespace::Type
2228                && lane.reference_count == 1
2229                && lane.references[0].from_file == Path::new("src/typed.ts")
2230        }));
2231    }
2232
2233    #[test]
2234    fn trace_credits_a_declaration_merge_that_stays_one_binding() {
2235        // A merge whose parts share the value lane, `class Foo` next to
2236        // `namespace Foo`, is one effective binding in both lanes, so a bound
2237        // `import type` credits it and the trace reports the crediting lane.
2238        let graph = source_consumer_graph(
2239            vec![named_foo_export(false), named_foo_export(false)],
2240            true,
2241            false,
2242            Vec::new(),
2243        );
2244
2245        let trace = trace_export(&graph, Path::new("/project"), "src/source.ts", "Foo")
2246            .expect("value export exists");
2247
2248        assert_eq!(
2249            trace.namespace,
2250            fallow_types::semantic::SemanticNamespace::Type,
2251            "the merged binding is reachable from the type lane"
2252        );
2253        assert!(trace.is_used);
2254        assert_eq!(trace.direct_references.len(), 1);
2255        assert_eq!(
2256            trace.direct_references[0].from_file,
2257            PathBuf::from("src/entry.ts")
2258        );
2259    }
2260
2261    #[test]
2262    fn trace_credits_a_class_interface_declaration_merge() {
2263        let mut interface = named_foo_export(true);
2264        interface.span = oxc_span::Span::new(0, 3);
2265        let mut class = named_foo_export(false);
2266        class.span = oxc_span::Span::new(4, 7);
2267        let graph = source_consumer_graph(
2268            vec![interface, class],
2269            true,
2270            true,
2271            vec![fallow_types::extract::SemanticFact::DeclarationMerge(
2272                fallow_types::extract::DeclarationMergeFact {
2273                    export_spans: vec![(0, 3), (4, 7)],
2274                },
2275            )],
2276        );
2277
2278        let trace = trace_export(&graph, Path::new("/project"), "src/source.ts", "Foo")
2279            .expect("merged class export exists");
2280
2281        assert_eq!(
2282            trace.namespace,
2283            fallow_types::semantic::SemanticNamespace::Type
2284        );
2285        assert!(trace.is_used);
2286        assert_eq!(trace.direct_references.len(), 1);
2287    }
2288
2289    #[test]
2290    fn trace_keeps_the_value_namespace_when_lanes_hold_distinct_bindings() {
2291        // Deliberate negative control: two same-name declarations in opposite
2292        // lanes are two bindings, so the value lane is kept even though the
2293        // type lane also carries a reference. The value lane holds the
2294        // reference here, so this pins the preferred-lane rule;
2295        // `trace_prefers_the_value_namespace_independent_of_usage` is the test
2296        // that reaches and pins the binding-equality guard.
2297        let graph = source_consumer_graph(
2298            vec![named_foo_export(false), named_foo_export(true)],
2299            false,
2300            true,
2301            Vec::new(),
2302        );
2303
2304        let trace = trace_export(&graph, Path::new("/project"), "src/source.ts", "Foo")
2305            .expect("value export exists");
2306
2307        assert_eq!(
2308            trace.namespace,
2309            fallow_types::semantic::SemanticNamespace::Value
2310        );
2311        assert!(trace.is_used);
2312        assert_eq!(trace.direct_references.len(), 1);
2313        assert_eq!(
2314            trace.direct_references[0].from_file,
2315            PathBuf::from("src/entry.ts")
2316        );
2317    }
2318
2319    #[test]
2320    fn class_member_trace_inherits_the_type_lane_credit_of_its_owner() {
2321        // Issue #2371: the member trace is built from the owner's export
2322        // trace, so an owner credited only through the type lane reports a
2323        // used owner instead of the "referenced by no file" reason.
2324        let mut owner = named_foo_export(false);
2325        owner.members = vec![class_method("run", 0, 3)];
2326        let graph = source_consumer_graph(vec![owner], true, false, Vec::new());
2327
2328        let trace = trace_class_member(&graph, Path::new("/project"), "src/source.ts", "run")
2329            .expect("member of the traced export");
2330
2331        assert!(trace.owner_is_used, "the type lane credits the owner");
2332        assert_eq!(
2333            trace.owner_namespace,
2334            fallow_types::semantic::SemanticNamespace::Type,
2335            "the member payload names the lane that credits its owner"
2336        );
2337        assert_eq!(trace.owner_direct_references.len(), 1);
2338        assert_eq!(
2339            trace.owner_direct_references[0].from_file,
2340            PathBuf::from("src/entry.ts")
2341        );
2342        assert!(
2343            trace.reason.contains("'Foo' is used by 1 file(s)"),
2344            "the reason must follow the owner's credit: {}",
2345            trace.reason
2346        );
2347    }
2348
2349    #[test]
2350    #[expect(
2351        clippy::too_many_lines,
2352        reason = "the fixture names every ExportInfo field so a new field is a compile error here"
2353    )]
2354    fn trace_preserves_dual_namespace_named_re_exports() {
2355        let files: Vec<_> = ["entry", "barrel", "types", "values"]
2356            .into_iter()
2357            .enumerate()
2358            .map(|(index, name)| DiscoveredFile {
2359                id: FileId(index as u32),
2360                path: PathBuf::from(format!("/project/src/{name}.ts")),
2361                size_bytes: 10,
2362            })
2363            .collect();
2364        let export = |is_type_only| ExportInfo {
2365            name: ExportName::Named("Foo".to_string()),
2366            local_name: Some("Foo".to_string()),
2367            is_type_only,
2368            visibility: VisibilityTag::None,
2369            expected_unused_reason: None,
2370            span: oxc_span::Span::new(0, 3),
2371            members: Vec::new(),
2372            is_side_effect_used: false,
2373            super_class: None,
2374            deprecated: false,
2375            deprecated_reason: None,
2376        };
2377        let re_export = |source: FileId, is_type_only| ResolvedReExport {
2378            info: ReExportInfo {
2379                source: format!("./{}", source.0),
2380                imported_name: "Foo".to_string(),
2381                exported_name: "Foo".to_string(),
2382                is_type_only,
2383                span: oxc_span::Span::default(),
2384                statement_span: oxc_span::Span::default(),
2385                source_span: oxc_span::Span::default(),
2386                visibility: VisibilityTag::None,
2387                expected_unused_reason: None,
2388            },
2389            target: ResolveResult::InternalModule(source),
2390        };
2391        let mut resolved = vec![
2392            ResolvedModule {
2393                file_id: FileId(0),
2394                path: files[0].path.clone(),
2395                resolved_imports: vec![ResolvedImport {
2396                    info: ImportInfo {
2397                        source: "./barrel".to_string(),
2398                        imported_name: ImportedName::Named("Foo".to_string()),
2399                        local_name: "Foo".to_string(),
2400                        is_type_only: false,
2401                        is_type_only_star: false,
2402                        from_style: false,
2403                        span: oxc_span::Span::new(0, 10),
2404                        source_span: oxc_span::Span::default(),
2405                    },
2406                    target: ResolveResult::InternalModule(FileId(1)),
2407                }],
2408                ..Default::default()
2409            },
2410            ResolvedModule {
2411                file_id: FileId(1),
2412                path: files[1].path.clone(),
2413                re_exports: vec![re_export(FileId(2), true), re_export(FileId(3), false)],
2414                ..Default::default()
2415            },
2416            ResolvedModule {
2417                file_id: FileId(2),
2418                path: files[2].path.clone(),
2419                exports: vec![export(true)].into(),
2420                ..Default::default()
2421            },
2422            ResolvedModule {
2423                file_id: FileId(3),
2424                path: files[3].path.clone(),
2425                exports: vec![export(false)].into(),
2426                ..Default::default()
2427            },
2428        ];
2429        let entry_points = vec![EntryPoint {
2430            path: files[0].path.clone(),
2431            source: EntryPointSource::PackageJsonMain,
2432        }];
2433        let graph = ModuleGraph::build(&resolved, &entry_points, &files);
2434        resolved[1].re_exports.reverse();
2435        let reversed_graph = ModuleGraph::build(&resolved, &entry_points, &files);
2436
2437        let trace = trace_export(&graph, Path::new("/project"), "src/barrel.ts", "Foo")
2438            .expect("barrel exposes Foo in both namespaces");
2439
2440        assert_eq!(
2441            trace.namespace,
2442            fallow_types::semantic::SemanticNamespace::Value
2443        );
2444        assert!(
2445            trace.is_used,
2446            "the value import must credit the value surface"
2447        );
2448        assert_eq!(trace.direct_references.len(), 1);
2449        let reversed_trace = trace_export(
2450            &reversed_graph,
2451            Path::new("/project"),
2452            "src/barrel.ts",
2453            "Foo",
2454        )
2455        .expect("reversed declarations expose the same surface");
2456        assert_eq!(
2457            serde_json::to_value(trace).expect("serialize trace"),
2458            serde_json::to_value(reversed_trace).expect("serialize reversed trace")
2459        );
2460    }
2461
2462    fn build_class_member_graph() -> ModuleGraph {
2463        let files = vec![
2464            DiscoveredFile {
2465                id: FileId(0),
2466                path: PathBuf::from("/project/src/entry.ts"),
2467                size_bytes: 100,
2468            },
2469            DiscoveredFile {
2470                id: FileId(1),
2471                path: PathBuf::from("/project/src/controller.ts"),
2472                size_bytes: 50,
2473            },
2474        ];
2475        let entry_points = vec![EntryPoint {
2476            path: PathBuf::from("/project/src/entry.ts"),
2477            source: EntryPointSource::PackageJsonMain,
2478        }];
2479        let method = |name: &str| class_method(name, 0, 4);
2480        let resolved_modules = vec![
2481            ResolvedModule {
2482                file_id: FileId(0),
2483                path: PathBuf::from("/project/src/entry.ts"),
2484                resolved_imports: vec![ResolvedImport {
2485                    info: ImportInfo {
2486                        source: "./controller".to_string(),
2487                        imported_name: ImportedName::Named("Ctrl".to_string()),
2488                        local_name: "Ctrl".to_string(),
2489                        is_type_only: false,
2490                        is_type_only_star: false,
2491                        from_style: false,
2492                        span: oxc_span::Span::new(0, 10),
2493                        source_span: oxc_span::Span::default(),
2494                    },
2495                    target: ResolveResult::InternalModule(FileId(1)),
2496                }],
2497                ..Default::default()
2498            },
2499            ResolvedModule {
2500                file_id: FileId(1),
2501                path: PathBuf::from("/project/src/controller.ts"),
2502                exports: vec![ExportInfo {
2503                    name: ExportName::Named("Ctrl".to_string()),
2504                    local_name: Some("Ctrl".to_string()),
2505                    is_type_only: false,
2506                    visibility: VisibilityTag::None,
2507                    expected_unused_reason: None,
2508                    span: oxc_span::Span::new(0, 20),
2509                    members: vec![method("used"), method("dead")],
2510                    is_side_effect_used: false,
2511                    super_class: None,
2512                    deprecated: false,
2513                    deprecated_reason: None,
2514                }]
2515                .into(),
2516                ..Default::default()
2517            },
2518        ];
2519        ModuleGraph::build(&resolved_modules, &entry_points, &files)
2520    }
2521
2522    #[test]
2523    fn trace_class_member_reports_owner_class() {
2524        // #1744: `--trace FILE:MEMBER` on a class member reports the owning
2525        // class instead of erroring "export not found".
2526        let graph = build_class_member_graph();
2527        let root = Path::new("/project");
2528
2529        let trace = trace_class_member(&graph, root, "src/controller.ts", "dead").unwrap();
2530        assert_eq!(trace.owner_export, "Ctrl");
2531        assert_eq!(trace.member_name, "dead");
2532        assert_eq!(trace.member_kind, "class-method");
2533        assert!(trace.owner_is_used);
2534        assert!(trace.owner_file_reachable);
2535        assert_eq!(trace.owner_direct_references.len(), 1);
2536        assert!(
2537            trace.reason.contains("--unused-class-members"),
2538            "reason should point at the member command: {}",
2539            trace.reason
2540        );
2541    }
2542
2543    #[test]
2544    fn trace_class_member_absent_name_is_none() {
2545        // A name that is neither a top-level export nor a declared member falls
2546        // through so the caller emits the "not found" error.
2547        let graph = build_class_member_graph();
2548        let root = Path::new("/project");
2549        assert!(trace_class_member(&graph, root, "src/controller.ts", "nope").is_none());
2550    }
2551
2552    fn exact_class_method_fixture() -> (tempfile::TempDir, ModuleGraph) {
2553        let temp = tempfile::tempdir().unwrap();
2554        let root = temp.path();
2555        let path = root.join("repository.ts");
2556        let source =
2557            "export class Repository {\n  save(): void;\n  save(): void {}\n  run(): void {}\n}\n";
2558        std::fs::write(&path, source).unwrap();
2559        let first = source.find("save").unwrap() as u32;
2560        let second = source.rfind("save").unwrap() as u32;
2561        let run = source.find("run").unwrap() as u32;
2562        let member = |name: &str, start| class_method(name, start, start + 4);
2563        let files = vec![DiscoveredFile {
2564            id: FileId(0),
2565            path: path.clone(),
2566            size_bytes: source.len() as u64,
2567        }];
2568        let resolved_modules = vec![ResolvedModule {
2569            file_id: FileId(0),
2570            path,
2571            exports: vec![ExportInfo {
2572                name: ExportName::Named("Repository".to_string()),
2573                local_name: Some("Repository".to_string()),
2574                is_type_only: false,
2575                visibility: VisibilityTag::None,
2576                expected_unused_reason: None,
2577                span: oxc_span::Span::new(0, source.len() as u32),
2578                members: vec![
2579                    member("save", first),
2580                    member("save", second),
2581                    member("run", run),
2582                ],
2583                is_side_effect_used: false,
2584                super_class: None,
2585                deprecated: false,
2586                deprecated_reason: None,
2587            }]
2588            .into(),
2589            ..Default::default()
2590        }];
2591        let graph = ModuleGraph::build(&resolved_modules, &[], &files);
2592        (temp, graph)
2593    }
2594
2595    #[test]
2596    fn exact_class_method_resolution_rejects_overloads_without_guessing() {
2597        let (temp, graph) = exact_class_method_fixture();
2598        let root = temp.path();
2599        assert_eq!(
2600            semantic_symbol_for_exact_class_method(
2601                &graph,
2602                root,
2603                "repository.ts",
2604                "Repository",
2605                "save",
2606            ),
2607            Err(SemanticClassMethodResolutionError::AmbiguousSymbol)
2608        );
2609        assert_eq!(
2610            semantic_symbol_for_exact_class_method(
2611                &graph,
2612                root,
2613                "repository.ts",
2614                "OtherRepository",
2615                "save",
2616            ),
2617            Err(SemanticClassMethodResolutionError::SymbolNotFound)
2618        );
2619        let resolved = semantic_symbol_for_exact_class_method(
2620            &graph,
2621            root,
2622            "repository.ts",
2623            "Repository",
2624            "run",
2625        )
2626        .unwrap();
2627        assert_eq!(resolved.owner.as_deref(), Some("Repository"));
2628        assert_eq!(resolved.local_name, "run");
2629    }
2630
2631    #[test]
2632    fn exact_class_method_resolution_preserves_error_precedence() {
2633        use fallow_types::extract::MemberKind;
2634
2635        let (temp, mut graph) = exact_class_method_fixture();
2636        let root = temp.path();
2637        for (file, owner, member, expected) in [
2638            (
2639                "missing.ts",
2640                "Repository",
2641                "run",
2642                SemanticClassMethodResolutionError::FileNotFound,
2643            ),
2644            (
2645                "repository.ts",
2646                "Repository",
2647                "missing",
2648                SemanticClassMethodResolutionError::SymbolNotFound,
2649            ),
2650        ] {
2651            assert_eq!(
2652                semantic_symbol_for_exact_class_method(&graph, root, file, owner, member),
2653                Err(expected),
2654            );
2655        }
2656        graph.modules[0].exports[0].members[2].kind = MemberKind::ClassProperty;
2657        assert_eq!(
2658            semantic_symbol_for_exact_class_method(
2659                &graph,
2660                root,
2661                "repository.ts",
2662                "Repository",
2663                "run"
2664            ),
2665            Err(SemanticClassMethodResolutionError::UnsupportedSyntax),
2666        );
2667        graph.modules[0].exports[0].members[2].kind = MemberKind::ClassMethod;
2668        std::fs::remove_file(&graph.modules[0].path).expect("remove fixture source");
2669        assert_eq!(
2670            semantic_symbol_for_exact_class_method(
2671                &graph,
2672                root,
2673                "repository.ts",
2674                "Repository",
2675                "run"
2676            ),
2677            Err(SemanticClassMethodResolutionError::SymbolNotFound),
2678        );
2679        let (_other_temp, mut other_graph) = exact_class_method_fixture();
2680        let duplicate = other_graph.modules[0]
2681            .exports
2682            .pop()
2683            .expect("fixture declares an owner");
2684        graph.modules[0].exports.push(duplicate);
2685        assert_eq!(
2686            semantic_symbol_for_exact_class_method(
2687                &graph,
2688                root,
2689                "repository.ts",
2690                "Repository",
2691                "run"
2692            ),
2693            Err(SemanticClassMethodResolutionError::AmbiguousSymbol),
2694            "owner ambiguity must be reported before reading source",
2695        );
2696    }
2697
2698    /// Build a graph where the controller declaring `Ctrl` is NOT imported by
2699    /// the entry, so its file is unreachable and every member is dead.
2700    fn build_unreachable_class_member_graph() -> ModuleGraph {
2701        let files = vec![
2702            DiscoveredFile {
2703                id: FileId(0),
2704                path: PathBuf::from("/project/src/entry.ts"),
2705                size_bytes: 100,
2706            },
2707            DiscoveredFile {
2708                id: FileId(1),
2709                path: PathBuf::from("/project/src/controller.ts"),
2710                size_bytes: 50,
2711            },
2712        ];
2713        let entry_points = vec![EntryPoint {
2714            path: PathBuf::from("/project/src/entry.ts"),
2715            source: EntryPointSource::PackageJsonMain,
2716        }];
2717        let method = |name: &str| class_method(name, 0, 4);
2718        let resolved_modules = vec![
2719            ResolvedModule {
2720                file_id: FileId(0),
2721                path: PathBuf::from("/project/src/entry.ts"),
2722                // Entry imports nothing, so controller.ts is unreachable.
2723                ..Default::default()
2724            },
2725            ResolvedModule {
2726                file_id: FileId(1),
2727                path: PathBuf::from("/project/src/controller.ts"),
2728                exports: vec![ExportInfo {
2729                    name: ExportName::Named("Ctrl".to_string()),
2730                    local_name: Some("Ctrl".to_string()),
2731                    is_type_only: false,
2732                    visibility: VisibilityTag::None,
2733                    expected_unused_reason: None,
2734                    span: oxc_span::Span::new(0, 20),
2735                    members: vec![method("dead")],
2736                    is_side_effect_used: false,
2737                    super_class: None,
2738                    deprecated: false,
2739                    deprecated_reason: None,
2740                }]
2741                .into(),
2742                ..Default::default()
2743            },
2744        ];
2745        ModuleGraph::build(&resolved_modules, &entry_points, &files)
2746    }
2747
2748    #[test]
2749    fn trace_class_member_unreachable_owner_reports_dead_reason() {
2750        // `!file_reachable` branch: the owning file is not reachable from any
2751        // entry point, so the reason states the class and its members are dead.
2752        let graph = build_unreachable_class_member_graph();
2753        let root = Path::new("/project");
2754
2755        let trace = trace_class_member(&graph, root, "src/controller.ts", "dead").unwrap();
2756        assert!(!trace.owner_file_reachable);
2757        assert!(
2758            trace.reason.contains("not reachable"),
2759            "unreachable owner reason should say so: {}",
2760            trace.reason
2761        );
2762        // The unreachable branch does not point at a member command (the file is
2763        // dead wholesale via the unused-file finding).
2764        assert!(!trace.reason.contains("--unused-class-members"));
2765    }
2766
2767    #[test]
2768    fn trace_class_member_prefers_used_owner_on_name_collision() {
2769        // Two exports declare a member of the same name; the tie-break in
2770        // `max_by_key` must prefer the used, non-type-only owner so the trace
2771        // reports the reachable class rather than a type-only shadow.
2772
2773        let files = vec![
2774            DiscoveredFile {
2775                id: FileId(0),
2776                path: PathBuf::from("/project/src/entry.ts"),
2777                size_bytes: 100,
2778            },
2779            DiscoveredFile {
2780                id: FileId(1),
2781                path: PathBuf::from("/project/src/controller.ts"),
2782                size_bytes: 50,
2783            },
2784        ];
2785        let entry_points = vec![EntryPoint {
2786            path: PathBuf::from("/project/src/entry.ts"),
2787            source: EntryPointSource::PackageJsonMain,
2788        }];
2789        let method = |name: &str| class_method(name, 0, 4);
2790        let resolved_modules = vec![
2791            ResolvedModule {
2792                file_id: FileId(0),
2793                path: PathBuf::from("/project/src/entry.ts"),
2794                resolved_imports: vec![ResolvedImport {
2795                    info: ImportInfo {
2796                        source: "./controller".to_string(),
2797                        imported_name: ImportedName::Named("UsedCtrl".to_string()),
2798                        local_name: "UsedCtrl".to_string(),
2799                        is_type_only: false,
2800                        is_type_only_star: false,
2801                        from_style: false,
2802                        span: oxc_span::Span::new(0, 10),
2803                        source_span: oxc_span::Span::default(),
2804                    },
2805                    target: ResolveResult::InternalModule(FileId(1)),
2806                }],
2807                ..Default::default()
2808            },
2809            ResolvedModule {
2810                file_id: FileId(1),
2811                path: PathBuf::from("/project/src/controller.ts"),
2812                exports: vec![
2813                    // Type-only, unreferenced owner declared FIRST: must lose the
2814                    // tie-break to the used, non-type-only owner below.
2815                    ExportInfo {
2816                        name: ExportName::Named("TypeCtrl".to_string()),
2817                        local_name: Some("TypeCtrl".to_string()),
2818                        is_type_only: true,
2819                        visibility: VisibilityTag::None,
2820                        expected_unused_reason: None,
2821                        span: oxc_span::Span::new(0, 20),
2822                        members: vec![method("shared")],
2823                        is_side_effect_used: false,
2824                        super_class: None,
2825                        deprecated: false,
2826                        deprecated_reason: None,
2827                    },
2828                    ExportInfo {
2829                        name: ExportName::Named("UsedCtrl".to_string()),
2830                        local_name: Some("UsedCtrl".to_string()),
2831                        is_type_only: false,
2832                        visibility: VisibilityTag::None,
2833                        expected_unused_reason: None,
2834                        span: oxc_span::Span::new(0, 20),
2835                        members: vec![method("shared")],
2836                        is_side_effect_used: false,
2837                        super_class: None,
2838                        deprecated: false,
2839                        deprecated_reason: None,
2840                    },
2841                ]
2842                .into(),
2843                ..Default::default()
2844            },
2845        ];
2846        let graph = ModuleGraph::build(&resolved_modules, &entry_points, &files);
2847        let root = Path::new("/project");
2848
2849        let trace = trace_class_member(&graph, root, "src/controller.ts", "shared").unwrap();
2850        assert_eq!(
2851            trace.owner_export, "UsedCtrl",
2852            "tie-break must prefer the used, non-type-only owner"
2853        );
2854        assert!(trace.owner_is_used);
2855    }
2856
2857    #[test]
2858    fn trace_nonexistent_file() {
2859        let graph = build_test_graph();
2860        let root = Path::new("/project");
2861
2862        let trace = trace_export(&graph, root, "src/nope.ts", "foo");
2863        assert!(trace.is_none());
2864    }
2865
2866    #[test]
2867    fn trace_file_edges() {
2868        let graph = build_test_graph();
2869        let root = Path::new("/project");
2870
2871        let trace = trace_file(&graph, root, "src/entry.ts").unwrap();
2872        assert!(trace.is_entry_point);
2873        assert!(trace.is_reachable);
2874        assert_eq!(trace.imports_from.len(), 1);
2875        assert_eq!(trace.imports_from[0], PathBuf::from("src/utils.ts"));
2876        assert!(trace.imported_by.is_empty());
2877    }
2878
2879    fn build_nested_duplicate_path_graph() -> ModuleGraph {
2880        let export = |name: &str| ExportInfo {
2881            name: ExportName::Named(name.to_string()),
2882            local_name: Some(name.to_string()),
2883            is_type_only: false,
2884            visibility: VisibilityTag::None,
2885            expected_unused_reason: None,
2886            span: oxc_span::Span::new(0, 20),
2887            members: vec![],
2888            is_side_effect_used: false,
2889            super_class: None,
2890            deprecated: false,
2891            deprecated_reason: None,
2892        };
2893        let nested = PathBuf::from("/project/packages/x/src/a.ts");
2894        let root_file = PathBuf::from("/project/src/a.ts");
2895        let files = vec![
2896            DiscoveredFile {
2897                id: FileId(0),
2898                path: nested.clone(),
2899                size_bytes: 20,
2900            },
2901            DiscoveredFile {
2902                id: FileId(1),
2903                path: root_file.clone(),
2904                size_bytes: 20,
2905            },
2906        ];
2907        let entry_points = vec![EntryPoint {
2908            path: root_file.clone(),
2909            source: EntryPointSource::PackageJsonMain,
2910        }];
2911        let resolved_modules = vec![
2912            ResolvedModule {
2913                file_id: FileId(0),
2914                path: nested,
2915                exports: vec![export("nestedOnly")].into(),
2916                ..Default::default()
2917            },
2918            ResolvedModule {
2919                file_id: FileId(1),
2920                path: root_file,
2921                exports: vec![export("rootOnly")].into(),
2922                ..Default::default()
2923            },
2924        ];
2925        ModuleGraph::build(&resolved_modules, &entry_points, &files)
2926    }
2927
2928    fn graph_with_module_paths(paths: &[PathBuf]) -> ModuleGraph {
2929        let files: Vec<DiscoveredFile> = paths
2930            .iter()
2931            .enumerate()
2932            .map(|(index, path)| DiscoveredFile {
2933                id: FileId(u32::try_from(index).expect("small fixture")),
2934                path: path.clone(),
2935                size_bytes: 1,
2936            })
2937            .collect();
2938        let resolved_modules: Vec<ResolvedModule> = files
2939            .iter()
2940            .map(|file| ResolvedModule {
2941                file_id: file.id,
2942                path: file.path.clone(),
2943                ..Default::default()
2944            })
2945            .collect();
2946        ModuleGraph::build(&resolved_modules, &[], &files)
2947    }
2948
2949    fn assert_lookup_matches_single_scan(graph: &ModuleGraph, root: &Path, queries: &[&str]) {
2950        let lookup = ModulePathLookup::new(graph, root);
2951        for query in queries {
2952            assert_eq!(
2953                lookup.matching(query),
2954                matching_module_indexes(graph, root, query),
2955                "query {query:?}"
2956            );
2957        }
2958    }
2959
2960    const LOOKUP_QUERIES: &[&str] = &[
2961        "src/a.ts",
2962        "./src/a.ts",
2963        "src//a.ts",
2964        r"src\a.ts",
2965        "a.ts",
2966        "x/src/a.ts",
2967        "packages/x/src/a.ts",
2968        "sub/c.ts",
2969        "c.ts",
2970        "src/",
2971        "",
2972        "missing.ts",
2973        "/elsewhere/src/a.ts",
2974    ];
2975
2976    /// The indexed lookup must return the same modules, in the same order, as
2977    /// the single-scan lookup for exact, suffix, ambiguous and missing paths.
2978    #[test]
2979    fn module_path_lookup_matches_single_scan_lookup() {
2980        let root = Path::new("/project");
2981        let paths: Vec<PathBuf> = [
2982            "src/a.ts",
2983            "packages/x/src/a.ts",
2984            "packages/y/a.ts",
2985            "src/sub/c.ts",
2986            "lib/b.ts",
2987        ]
2988        .iter()
2989        .map(|relative| root.join(relative))
2990        .collect();
2991        let graph = graph_with_module_paths(&paths);
2992        let mut queries = LOOKUP_QUERIES.to_vec();
2993        let absolute = root.join("src/a.ts").to_string_lossy().into_owned();
2994        queries.push(&absolute);
2995        assert_lookup_matches_single_scan(&graph, root, &queries);
2996    }
2997
2998    /// With real files, the canonical-root and canonical-target forms take
2999    /// part too. On macOS the temp dir sits behind a symlink.
3000    #[test]
3001    fn module_path_lookup_matches_single_scan_lookup_on_disk() {
3002        let dir = tempfile::tempdir().expect("tempdir");
3003        let root = dir.path();
3004        for relative in ["src/a.ts", "packages/x/src/a.ts", "src/sub/c.ts"] {
3005            let path = root.join(relative);
3006            std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
3007            std::fs::write(&path, "").expect("write");
3008        }
3009        let canonical_root = dunce::canonicalize(root).expect("canonical root");
3010        let paths: Vec<PathBuf> = ["src/a.ts", "packages/x/src/a.ts", "src/sub/c.ts"]
3011            .iter()
3012            .map(|relative| canonical_root.join(relative))
3013            .collect();
3014        let graph = graph_with_module_paths(&paths);
3015        assert_lookup_matches_single_scan(&graph, root, LOOKUP_QUERIES);
3016    }
3017
3018    #[test]
3019    fn root_relative_path_prefers_exact_module_over_nested_suffix() {
3020        let graph = build_nested_duplicate_path_graph();
3021        let root = Path::new("/project");
3022
3023        let file = trace_file(&graph, root, "src/a.ts").expect("root file resolves");
3024        assert_eq!(file.file, PathBuf::from("src/a.ts"));
3025        assert!(file.is_entry_point);
3026
3027        let export = trace_export(&graph, root, "src/a.ts", "rootOnly");
3028        assert!(
3029            export.is_some(),
3030            "an export of the root-level file must resolve"
3031        );
3032    }
3033
3034    #[test]
3035    fn abbreviated_path_keeps_first_suffix_match() {
3036        let graph = build_nested_duplicate_path_graph();
3037        let root = Path::new("/project");
3038
3039        let file = trace_file(&graph, root, "a.ts").expect("suffix match resolves");
3040        assert_eq!(file.file, PathBuf::from("packages/x/src/a.ts"));
3041    }
3042
3043    #[test]
3044    fn trace_file_imported_by() {
3045        let graph = build_test_graph();
3046        let root = Path::new("/project");
3047
3048        let trace = trace_file(&graph, root, "src/utils.ts").unwrap();
3049        assert!(!trace.is_entry_point);
3050        assert!(trace.is_reachable);
3051        assert_eq!(trace.exports.len(), 2);
3052        assert_eq!(trace.imported_by.len(), 1);
3053        assert_eq!(trace.imported_by[0], PathBuf::from("src/entry.ts"));
3054    }
3055
3056    #[test]
3057    fn trace_unreachable_file() {
3058        let graph = build_test_graph();
3059        let root = Path::new("/project");
3060
3061        let trace = trace_file(&graph, root, "src/unused.ts").unwrap();
3062        assert!(!trace.is_reachable);
3063        assert!(!trace.is_entry_point);
3064        assert!(trace.imported_by.is_empty());
3065    }
3066
3067    #[test]
3068    fn trace_clone_finds_matching_group() {
3069        use crate::duplicates::{CloneGroup, CloneInstance, DuplicationReport, DuplicationStats};
3070        let report = DuplicationReport {
3071            clone_groups: vec![CloneGroup {
3072                instances: vec![
3073                    CloneInstance {
3074                        is_symlink: false,
3075                        file: PathBuf::from("/project/src/a.ts"),
3076                        start_line: 10,
3077                        end_line: 20,
3078                        start_col: 0,
3079                        end_col: 0,
3080                        fragment: "fn foo() {}".to_string(),
3081                    },
3082                    CloneInstance {
3083                        is_symlink: false,
3084                        file: PathBuf::from("/project/src/b.ts"),
3085                        start_line: 5,
3086                        end_line: 15,
3087                        start_col: 0,
3088                        end_col: 0,
3089                        fragment: "fn foo() {}".to_string(),
3090                    },
3091                ],
3092                token_count: 60,
3093                line_count: 11,
3094                similarity: None,
3095            }],
3096            stats: DuplicationStats {
3097                total_files: 2,
3098                files_with_clones: 2,
3099                total_lines: 100,
3100                duplicated_lines: 22,
3101                total_tokens: 200,
3102                duplicated_tokens: 120,
3103                clone_groups: 1,
3104                clone_families: 0,
3105                clone_instances: 2,
3106                duplication_percentage: 22.0,
3107                clone_groups_below_min_occurrences: 0,
3108                clone_groups_ignored: 0,
3109                near_candidates_skipped: 0,
3110            },
3111            ..Default::default()
3112        };
3113        let trace = trace_clone(&report, Path::new("/project"), "src/a.ts", 15);
3114        assert!(trace.matched_instance.is_some());
3115        assert_eq!(trace.clone_groups.len(), 1);
3116        assert_eq!(trace.clone_groups[0].instances.len(), 2);
3117        assert!(trace.clone_groups[0].fingerprint.starts_with("dup:"));
3118        assert_eq!(trace.clone_groups[0].suggestion.estimated_savings, 11);
3119    }
3120
3121    #[test]
3122    fn trace_clone_by_fingerprint_resolves_and_misses() {
3123        use crate::duplicates::{
3124            CloneGroup, CloneInstance, DuplicationReport, DuplicationStats, clone_fingerprint,
3125        };
3126        let report = DuplicationReport {
3127            clone_groups: vec![CloneGroup {
3128                instances: vec![
3129                    CloneInstance {
3130                        is_symlink: false,
3131                        file: PathBuf::from("/project/src/a.ts"),
3132                        start_line: 10,
3133                        end_line: 20,
3134                        start_col: 0,
3135                        end_col: 0,
3136                        fragment: "fn buildInvoice() {}".to_string(),
3137                    },
3138                    CloneInstance {
3139                        is_symlink: false,
3140                        file: PathBuf::from("/project/src/b.ts"),
3141                        start_line: 5,
3142                        end_line: 15,
3143                        start_col: 0,
3144                        end_col: 0,
3145                        fragment: "fn buildInvoice() {}".to_string(),
3146                    },
3147                ],
3148                token_count: 60,
3149                line_count: 11,
3150                similarity: None,
3151            }],
3152            stats: DuplicationStats::default(),
3153            ..Default::default()
3154        };
3155        let fp = clone_fingerprint(&report.clone_groups[0].instances);
3156
3157        let hit = trace_clone_by_fingerprint(&report, Path::new("/project"), &fp);
3158        assert!(hit.matched_instance.is_some());
3159        assert_eq!(hit.clone_groups.len(), 1);
3160        assert_eq!(hit.clone_groups[0].fingerprint, fp);
3161        assert_eq!(hit.line, 10);
3162
3163        let miss = trace_clone_by_fingerprint(&report, Path::new("/project"), "dup:deadbeef");
3164        assert!(miss.matched_instance.is_none());
3165        assert!(miss.clone_groups.is_empty());
3166    }
3167
3168    #[test]
3169    fn trace_clone_no_match() {
3170        use crate::duplicates::{CloneGroup, CloneInstance, DuplicationReport, DuplicationStats};
3171        let report = DuplicationReport {
3172            clone_groups: vec![CloneGroup {
3173                instances: vec![CloneInstance {
3174                    is_symlink: false,
3175                    file: PathBuf::from("/project/src/a.ts"),
3176                    start_line: 10,
3177                    end_line: 20,
3178                    start_col: 0,
3179                    end_col: 0,
3180                    fragment: "fn foo() {}".to_string(),
3181                }],
3182                token_count: 60,
3183                line_count: 11,
3184                similarity: None,
3185            }],
3186            stats: DuplicationStats {
3187                total_files: 1,
3188                files_with_clones: 1,
3189                total_lines: 50,
3190                duplicated_lines: 11,
3191                total_tokens: 100,
3192                duplicated_tokens: 60,
3193                clone_groups: 1,
3194                clone_families: 0,
3195                clone_instances: 1,
3196                duplication_percentage: 22.0,
3197                clone_groups_below_min_occurrences: 0,
3198                clone_groups_ignored: 0,
3199                near_candidates_skipped: 0,
3200            },
3201            ..Default::default()
3202        };
3203        let trace = trace_clone(&report, Path::new("/project"), "src/a.ts", 25);
3204        assert!(trace.matched_instance.is_none());
3205        assert!(trace.clone_groups.is_empty());
3206    }
3207
3208    #[test]
3209    fn trace_clone_line_boundary() {
3210        use crate::duplicates::{CloneGroup, CloneInstance, DuplicationReport, DuplicationStats};
3211        let report = DuplicationReport {
3212            clone_groups: vec![CloneGroup {
3213                instances: vec![
3214                    CloneInstance {
3215                        is_symlink: false,
3216                        file: PathBuf::from("/project/src/a.ts"),
3217                        start_line: 10,
3218                        end_line: 20,
3219                        start_col: 0,
3220                        end_col: 0,
3221                        fragment: "code".to_string(),
3222                    },
3223                    CloneInstance {
3224                        is_symlink: false,
3225                        file: PathBuf::from("/project/src/b.ts"),
3226                        start_line: 1,
3227                        end_line: 11,
3228                        start_col: 0,
3229                        end_col: 0,
3230                        fragment: "code".to_string(),
3231                    },
3232                ],
3233                token_count: 50,
3234                line_count: 11,
3235                similarity: None,
3236            }],
3237            stats: DuplicationStats {
3238                total_files: 2,
3239                files_with_clones: 2,
3240                total_lines: 100,
3241                duplicated_lines: 22,
3242                total_tokens: 200,
3243                duplicated_tokens: 100,
3244                clone_groups: 1,
3245                clone_families: 0,
3246                clone_instances: 2,
3247                duplication_percentage: 22.0,
3248                clone_groups_below_min_occurrences: 0,
3249                clone_groups_ignored: 0,
3250                near_candidates_skipped: 0,
3251            },
3252            ..Default::default()
3253        };
3254        let root = Path::new("/project");
3255        assert!(
3256            trace_clone(&report, root, "src/a.ts", 10)
3257                .matched_instance
3258                .is_some()
3259        );
3260        assert!(
3261            trace_clone(&report, root, "src/a.ts", 20)
3262                .matched_instance
3263                .is_some()
3264        );
3265        assert!(
3266            trace_clone(&report, root, "src/a.ts", 21)
3267                .matched_instance
3268                .is_none()
3269        );
3270    }
3271
3272    #[test]
3273    fn trace_clone_returns_relative_instance_paths() {
3274        use crate::duplicates::{CloneGroup, CloneInstance, DuplicationReport, DuplicationStats};
3275        let report = DuplicationReport {
3276            clone_groups: vec![CloneGroup {
3277                instances: vec![
3278                    CloneInstance {
3279                        is_symlink: false,
3280                        file: PathBuf::from("/project/src/a.ts"),
3281                        start_line: 1,
3282                        end_line: 10,
3283                        start_col: 0,
3284                        end_col: 0,
3285                        fragment: "code".to_string(),
3286                    },
3287                    CloneInstance {
3288                        is_symlink: false,
3289                        file: PathBuf::from("/project/src/b.ts"),
3290                        start_line: 1,
3291                        end_line: 10,
3292                        start_col: 0,
3293                        end_col: 0,
3294                        fragment: "code".to_string(),
3295                    },
3296                ],
3297                token_count: 50,
3298                line_count: 10,
3299                similarity: None,
3300            }],
3301            stats: DuplicationStats {
3302                total_files: 2,
3303                files_with_clones: 2,
3304                total_lines: 50,
3305                duplicated_lines: 20,
3306                total_tokens: 100,
3307                duplicated_tokens: 100,
3308                clone_groups: 1,
3309                clone_families: 0,
3310                clone_instances: 2,
3311                duplication_percentage: 40.0,
3312                clone_groups_below_min_occurrences: 0,
3313                clone_groups_ignored: 0,
3314                near_candidates_skipped: 0,
3315            },
3316            ..Default::default()
3317        };
3318        let trace = trace_clone(&report, Path::new("/project"), "src/a.ts", 5);
3319        let matched = trace.matched_instance.as_ref().expect("match expected");
3320        assert_eq!(matched.file, PathBuf::from("src/a.ts"));
3321        for group in &trace.clone_groups {
3322            for inst in &group.instances {
3323                let as_str = inst.file.to_string_lossy();
3324                assert!(
3325                    !as_str.starts_with('/'),
3326                    "instance file should be relative, got {as_str}",
3327                );
3328                assert!(
3329                    !as_str.contains(":\\") && !as_str.contains(":/"),
3330                    "instance file should not have a drive letter, got {as_str}",
3331                );
3332            }
3333        }
3334
3335        let json = serde_json::to_string(&trace).expect("serializes");
3336        assert!(
3337            !json.contains("\"/project/"),
3338            "serialized trace should not leak absolute paths: {json}",
3339        );
3340    }
3341
3342    /// Regression for the MCP e2e `trace_export` / `trace_file` Windows
3343    /// failures: the MCP layer passes forward-slashed user input
3344    /// (`src/utils.ts`) but `module_path` on Windows uses backslash
3345    /// separators (`D:\a\fallow\...\src\utils.ts`). The byte-level
3346    /// equality check missed every match. The lookup now normalises
3347    /// both sides to forward slashes before comparing.
3348    fn single_module_graph(path: &str) -> ModuleGraph {
3349        let path = PathBuf::from(path);
3350        let files = vec![DiscoveredFile {
3351            id: FileId(0),
3352            path: path.clone(),
3353            size_bytes: 10,
3354        }];
3355        let resolved_modules = vec![ResolvedModule {
3356            file_id: FileId(0),
3357            path,
3358            ..Default::default()
3359        }];
3360        ModuleGraph::build(&resolved_modules, &[], &files)
3361    }
3362
3363    #[test]
3364    fn find_module_normalises_windows_module_path_against_posix_user_path() {
3365        let root = Path::new(r"D:\a\fallow\fallow\tests\fixtures\basic-project");
3366        let graph =
3367            single_module_graph(r"D:\a\fallow\fallow\tests\fixtures\basic-project\src\utils.ts");
3368        assert!(find_module(&graph, root, "src/utils.ts").is_some());
3369        assert!(find_module(&graph, root, r"src\utils.ts").is_some());
3370    }
3371
3372    #[test]
3373    fn find_module_suffix_fallback_handles_mixed_separators() {
3374        let root = Path::new("/some/other/root");
3375        let graph =
3376            single_module_graph(r"D:\a\fallow\fallow\tests\fixtures\basic-project\src\utils.ts");
3377        assert!(find_module(&graph, root, "src/utils.ts").is_some());
3378    }
3379
3380    /// Regression for the MCP e2e trace_export / trace_file failures: even
3381    /// after `find_module` correctly identified the file on Windows, the
3382    /// trace output struct's `file: PathBuf` field serialized the stored
3383    /// backslash-shaped path verbatim. JSON consumers (MCP agents, CI
3384    /// pipelines, the cross-platform trace_file assertion in
3385    /// `e2e_trace_file_returns_json`) expect forward-slash. Pin the
3386    /// contract via raw-string Windows-shaped `PathBuf::from` so the test
3387    /// runs cross-platform.
3388    #[test]
3389    fn export_trace_serializes_windows_path_with_forward_slashes() {
3390        let trace = ExportTrace {
3391            file: PathBuf::from(r"src\utils.ts"),
3392            export_name: "foo".to_string(),
3393            namespace: fallow_types::semantic::SemanticNamespace::Value,
3394            file_reachable: true,
3395            is_entry_point: false,
3396            is_used: true,
3397            direct_references: vec![ExportReference::new(
3398                PathBuf::from(r"src\entry.ts"),
3399                "named import".to_string(),
3400            )],
3401            direct_references_by_namespace: Vec::new(),
3402            star_export_ambiguity: None,
3403            re_export_chains: vec![ReExportChain {
3404                barrel_file: PathBuf::from(r"src\index.ts"),
3405                exported_as: "foo".to_string(),
3406                reference_count: 1,
3407            }],
3408            plugin_credits: Vec::new(),
3409            kept_by_tag: None,
3410            reason: "ok".to_string(),
3411            semantic: None,
3412        };
3413        let json = serde_json::to_string(&trace).expect("serializes");
3414        assert!(
3415            json.contains("\"file\":\"src/utils.ts\""),
3416            "ExportTrace.file must serialize with forward slashes: {json}"
3417        );
3418        assert!(
3419            json.contains("\"from_file\":\"src/entry.ts\""),
3420            "ExportReference.from_file must serialize with forward slashes: {json}"
3421        );
3422        assert!(
3423            json.contains("\"barrel_file\":\"src/index.ts\""),
3424            "ReExportChain.barrel_file must serialize with forward slashes: {json}"
3425        );
3426        assert!(
3427            !json.contains(r"\\"),
3428            "no backslash sequence should remain anywhere in the JSON: {json}"
3429        );
3430    }
3431
3432    #[test]
3433    fn file_trace_serializes_windows_paths_with_forward_slashes() {
3434        let trace = FileTrace {
3435            file: PathBuf::from(r"src\utils.ts"),
3436            is_reachable: true,
3437            is_entry_point: false,
3438            exports: vec![],
3439            imports_from: vec![PathBuf::from(r"src\helpers.ts")],
3440            imported_by: vec![PathBuf::from(r"src\entry.ts")],
3441            re_exports: vec![TracedReExport {
3442                source_file: PathBuf::from(r"src\source.ts"),
3443                imported_name: "foo".to_string(),
3444                exported_name: "foo".to_string(),
3445            }],
3446            ..FileTrace::default()
3447        };
3448        let json = serde_json::to_string(&trace).expect("serializes");
3449        assert!(json.contains("\"file\":\"src/utils.ts\""), "got {json}");
3450        assert!(
3451            json.contains("\"imports_from\":[\"src/helpers.ts\"]"),
3452            "got {json}"
3453        );
3454        assert!(
3455            json.contains("\"imported_by\":[\"src/entry.ts\"]"),
3456            "got {json}"
3457        );
3458        assert!(
3459            json.contains("\"source_file\":\"src/source.ts\""),
3460            "got {json}"
3461        );
3462        assert!(!json.contains(r"\\"), "no backslash should remain: {json}");
3463    }
3464}