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