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