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