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