Skip to main content

fallow_engine/
trace.rs

1//! Read-only trace helpers exposed through the engine boundary.
2
3use std::path::Path;
4
5use fallow_types::trace::PeerClosureSeeds;
6use rustc_hash::FxHashSet;
7
8use crate::duplicates::DuplicationReport;
9use crate::module_graph::RetainedModuleGraph;
10
11#[path = "trace_export_reason.rs"]
12mod trace_export_reason;
13#[path = "trace_export_references.rs"]
14mod trace_export_references;
15#[path = "trace_impl.rs"]
16pub(crate) mod trace_impl;
17#[path = "trace_usage_impl.rs"]
18mod trace_usage_impl;
19
20pub use fallow_types::trace_usage::{DependencyUsage, DependencyUsageQuery, SitePageRequest};
21pub use trace_usage_impl::UsageError;
22
23pub use fallow_types::trace::{
24    ClassMemberTrace, CloneTrace, DependencyTrace, ExportReference, ExportTrace, FileTrace,
25    ImpactClosureGap, ImpactClosureTrace, ImportPathHop, ImportPathTrace, PipelineTimings,
26    ReExportChain, TraceProvenance, TraceSource, TracedCloneGroup, TracedExport, TracedReExport,
27};
28pub use trace_impl::{ImportPathEndpoint, SemanticClassMethodResolutionError};
29
30/// Trace why an export is considered used or unused.
31#[must_use]
32pub fn trace_export(
33    graph: &RetainedModuleGraph,
34    root: &Path,
35    file_path: &str,
36    export_name: &str,
37) -> Option<ExportTrace> {
38    trace_impl::trace_export(graph.as_graph(), root, file_path, export_name)
39}
40
41/// Reconcile checker-backed trace evidence with graph reachability while
42/// retaining non-crediting evidence for inspection.
43pub fn reconcile_semantic_trace_reachability(
44    graph: &RetainedModuleGraph,
45    root: &Path,
46    target_reachable: bool,
47    trace: &mut fallow_types::semantic::SemanticSymbolTrace,
48) {
49    trace_impl::reconcile_semantic_trace_reachability(
50        graph.as_graph(),
51        root,
52        target_reachable,
53        trace,
54    );
55}
56
57/// Resolve the source identity for an exact semantic export query.
58#[must_use]
59pub fn semantic_symbol_for_export(
60    graph: &RetainedModuleGraph,
61    root: &Path,
62    file_path: &str,
63    export_name: &str,
64) -> Option<fallow_types::semantic::SemanticSymbol> {
65    trace_impl::semantic_symbol_for_export(graph.as_graph(), root, file_path, export_name)
66}
67
68/// Resolve the source identity for an exact semantic class-member query.
69#[must_use]
70pub fn semantic_symbol_for_class_member(
71    graph: &RetainedModuleGraph,
72    root: &Path,
73    file_path: &str,
74    member_name: &str,
75) -> Option<fallow_types::semantic::SemanticSymbol> {
76    trace_impl::semantic_symbol_for_class_member(graph.as_graph(), root, file_path, member_name)
77}
78
79/// Resolve one exact exported class method for semantic impact analysis.
80pub fn semantic_symbol_for_exact_class_method(
81    graph: &RetainedModuleGraph,
82    root: &Path,
83    file_path: &str,
84    owner_name: &str,
85    member_name: &str,
86) -> Result<fallow_types::semantic::SemanticSymbol, SemanticClassMethodResolutionError> {
87    trace_impl::semantic_symbol_for_exact_class_method(
88        graph.as_graph(),
89        root,
90        file_path,
91        owner_name,
92        member_name,
93    )
94}
95
96/// Trace a class / enum / store member (the `--trace FILE:MEMBER` fallback when
97/// `MEMBER` is not a top-level export). See issue #1744.
98#[must_use]
99pub fn trace_class_member(
100    graph: &RetainedModuleGraph,
101    root: &Path,
102    file_path: &str,
103    member_name: &str,
104) -> Option<ClassMemberTrace> {
105    trace_impl::trace_class_member(graph.as_graph(), root, file_path, member_name)
106}
107
108/// Trace all graph edges for a file.
109#[must_use]
110pub fn trace_file(graph: &RetainedModuleGraph, root: &Path, file_path: &str) -> Option<FileTrace> {
111    trace_impl::trace_file(graph.as_graph(), root, file_path)
112}
113
114/// Trace where a dependency is used.
115///
116/// `workspace_roots` are the roots of the workspaces, so the peer-dependency
117/// credit runs one closure per workspace, as the unused-dependency check does.
118/// `ignore_patterns` are the configured `ignorePatterns`. A workspace
119/// `package.json` that they match does not turn on an optional peer, as in the
120/// unused-dependency check.
121#[must_use]
122#[expect(
123    clippy::implicit_hasher,
124    reason = "fallow standardizes on FxHashSet across the workspace"
125)]
126pub fn trace_dependency(
127    graph: &RetainedModuleGraph,
128    root: &Path,
129    workspace_roots: &[&Path],
130    ignore_patterns: &fallow_config::IgnorePatternSet,
131    package_name: &str,
132    script_used_packages: &FxHashSet<String>,
133) -> DependencyTrace {
134    trace_impl::trace_dependency(
135        graph.as_graph(),
136        root,
137        workspace_roots,
138        ignore_patterns,
139        package_name,
140        &trace_impl::DependencyCredit {
141            script_used_packages,
142            peer_seeds: &PeerClosureSeeds::from_shared(script_used_packages.iter().cloned()),
143        },
144    )
145}
146
147/// The analysis facts that a dependency trace reads.
148pub struct DependencyTraceInputs<'a> {
149    /// The retained module graph.
150    pub graph: &'a RetainedModuleGraph,
151    /// The project root.
152    pub root: &'a Path,
153    /// The roots of the workspaces, for the peer-dependency credit.
154    pub workspace_roots: &'a [&'a Path],
155    /// The configured `ignorePatterns`.
156    pub ignore_patterns: &'a fallow_config::IgnorePatternSet,
157    /// Packages invoked from package.json scripts, CI configs and git hooks.
158    pub script_used_packages: &'a FxHashSet<String>,
159    /// Which configs name which files and dependency names.
160    pub provenance: &'a TraceProvenance,
161    /// The findings of the analysis, which name the manifests that the
162    /// unused-dependency check flags.
163    pub results: &'a fallow_types::results::AnalysisResults,
164}
165
166/// Build the complete dependency trace: the importers, the config sources,
167/// the tooling credit and the flagged manifests.
168///
169/// `fallow dead-code --trace-dependency`, `fallow trace --dependency` and the
170/// programmatic API share this builder, so the base fields agree on every
171/// surface.
172#[must_use]
173pub fn build_dependency_trace(
174    inputs: &DependencyTraceInputs<'_>,
175    package_name: &str,
176) -> DependencyTrace {
177    let mut trace = trace_impl::trace_dependency(
178        inputs.graph.as_graph(),
179        inputs.root,
180        inputs.workspace_roots,
181        inputs.ignore_patterns,
182        package_name,
183        &trace_impl::DependencyCredit {
184            script_used_packages: inputs.script_used_packages,
185            peer_seeds: inputs.provenance.peer_seeds(),
186        },
187    );
188    trace.sources = inputs.provenance.dependency_sources(package_name);
189    trace.apply_tooling_credit(inputs.provenance.tooling_credit(package_name));
190    trace.apply_unused_declarations(inputs.results, inputs.root);
191    trace
192}
193
194/// Trace a dependency with its per-specifier usage through an existing
195/// analysis session.
196///
197/// The inner `Result` carries a query error, such as a cursor that belongs
198/// to another query.
199///
200/// # Errors
201///
202/// Returns an error if parsing, graph construction, or analysis fails.
203pub fn trace_dependency_with_session(
204    session: &crate::session::AnalysisSession,
205    package_name: &str,
206    query: &DependencyUsageQuery,
207) -> crate::EngineResult<Result<DependencyTrace, UsageError>> {
208    // Keep the parsed modules: the usage walk reads their import facts.
209    let output = session.analyze_dead_code_with_shared_artifacts(true, true)?;
210    let graph = output.graph.as_ref().ok_or_else(|| {
211        crate::EngineError::new("trace --dependency requires a retained module graph")
212    })?;
213    let modules = output.modules.as_deref().unwrap_or(&[]);
214    let workspace_roots: Vec<&Path> = session
215        .workspaces()
216        .iter()
217        .map(|workspace| workspace.root.as_path())
218        .collect();
219    let mut trace = build_dependency_trace(
220        &DependencyTraceInputs {
221            graph,
222            root: session.root(),
223            workspace_roots: &workspace_roots,
224            ignore_patterns: &session.config().ignore_patterns,
225            script_used_packages: &output.script_used_packages,
226            provenance: &output.trace_provenance,
227            results: &output.results,
228        },
229        package_name,
230    );
231    match trace_usage_impl::dependency_usage(
232        graph.as_graph(),
233        modules,
234        session.root(),
235        package_name,
236        &trace.imported_by,
237        query,
238    ) {
239        Ok(usage) => {
240            trace.usage = Some(usage);
241            Ok(Ok(trace))
242        }
243        Err(err) => Ok(Err(err)),
244    }
245}
246
247/// Trace duplicate-code groups that contain a source location.
248#[must_use]
249pub fn trace_clone(
250    report: &DuplicationReport,
251    root: &Path,
252    file_path: &str,
253    line: usize,
254) -> CloneTrace {
255    trace_impl::trace_clone(report, root, file_path, line)
256}
257
258/// Trace a duplicate-code group by its stable content fingerprint.
259#[must_use]
260pub fn trace_clone_by_fingerprint(
261    report: &DuplicationReport,
262    root: &Path,
263    fingerprint: &str,
264) -> CloneTrace {
265    trace_impl::trace_clone_by_fingerprint(report, root, fingerprint)
266}
267
268/// Trace the impact closure for a file.
269#[must_use]
270pub fn trace_impact_closure(
271    graph: &RetainedModuleGraph,
272    root: &Path,
273    file_path: &str,
274) -> Option<ImpactClosureTrace> {
275    trace_impl::trace_impact_closure(graph.as_graph(), root, file_path)
276}
277
278/// Trace the impact closure for a file without the literal-search check.
279///
280/// The coordination gaps have no search fields, and no consumer source is
281/// read. Use it when only the affected set is needed.
282#[must_use]
283pub fn trace_impact_closure_without_search(
284    graph: &RetainedModuleGraph,
285    root: &Path,
286    file_path: &str,
287) -> Option<ImpactClosureTrace> {
288    trace_impl::trace_impact_closure_without_search(graph.as_graph(), root, file_path)
289}
290
291/// Trace the shortest import path between two modules.
292///
293/// # Errors
294///
295/// Returns the endpoint that did not resolve to exactly one module in the graph.
296pub fn trace_import_path(
297    graph: &RetainedModuleGraph,
298    root: &Path,
299    from_path: &str,
300    to_path: &str,
301) -> Result<ImportPathTrace, ImportPathEndpoint> {
302    trace_impl::trace_import_path(graph.as_graph(), root, from_path, to_path, false)
303}
304
305/// Trace the shortest import path over eager edges only: static imports that
306/// carry a runtime value. The route explains why `to_path` loads before
307/// `from_path` runs.
308///
309/// # Errors
310///
311/// Returns the endpoint that did not resolve to exactly one module in the graph.
312pub fn trace_eager_import_path(
313    graph: &RetainedModuleGraph,
314    root: &Path,
315    from_path: &str,
316    to_path: &str,
317) -> Result<ImportPathTrace, ImportPathEndpoint> {
318    trace_impl::trace_import_path(graph.as_graph(), root, from_path, to_path, true)
319}
320
321/// Trace the shortest import path through an existing analysis session.
322/// With `eager_only`, the walk follows static value imports only.
323///
324/// The inner `Result` carries the endpoint that did not resolve to a module.
325///
326/// # Errors
327///
328/// Returns an error if parsing or graph construction fails.
329pub fn trace_import_path_with_session(
330    session: &crate::session::AnalysisSession,
331    from_path: &str,
332    to_path: &str,
333    eager_only: bool,
334) -> crate::EngineResult<Result<ImportPathTrace, ImportPathEndpoint>> {
335    let output = session.analyze_dead_code_with_shared_artifacts(false, true)?;
336    let graph = output
337        .graph
338        .as_ref()
339        .ok_or_else(|| crate::EngineError::new("trace --path requires a retained module graph"))?;
340    Ok(trace_impl::trace_import_path(
341        graph.as_graph(),
342        session.root(),
343        from_path,
344        to_path,
345        eager_only,
346    ))
347}