fallow-core 2.102.0

Analysis orchestration for fallow codebase intelligence (dead code, duplication, plugins, cross-reference)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
//! Symbol-level call chains (`fallow trace <symbol> --callers --callees`).
//!
//! Best-effort, syntactic (ADR-001), EXPLICITLY OFF the ranked path. This walk
//! NEVER feeds the focus map / ranking (verified by a dedicated test in the
//! CLI crate). It reports resolved-vs-unresolved callees HONESTLY: a referenced
//! callee that the syntactic walk cannot resolve to an import-symbol edge is
//! surfaced in [`SymbolChainTrace::unresolved_callees`], never silently dropped.
//!
//! ## What "resolved" means (honest scoping)
//!
//! The graph models import-symbol edges: module A imports binding `foo` from
//! module B. From those edges this walk reconstructs:
//!
//! - **Callers (UP):** for a symbol `S` defined in module `M`, every module that
//!   imports `S` from `M` (via [`ModuleGraph::importers_of`] + the per-edge
//!   `ImportedSymbol` set), recursed through the importer's own binding up to
//!   `depth`.
//! - **Callees (DOWN):** the import-symbol edges OUT of `M` (resolved callees,
//!   each a `(local, imported, target_module)` triple), recursed into the target
//!   module's exports up to `depth`, PLUS the call sites in `M`
//!   (`ModuleInfo.callee_uses`) whose leading identifier is bound to no import
//!   (unresolved callees: locals, globals, dynamic dispatch, re-bound callees).
//!
//! NOT resolved (reported as unresolved or absent, the same class of limits the
//! security taint walk carries): computed-member calls, dynamic dispatch,
//! re-bound callees, methods reached only through type inference, and any callee
//! with no import-symbol edge. The walk is MODULE-scoped, not per-function: a
//! true intra-function dataflow is beyond ADR-001 syntactic scope.

use std::path::{Path, PathBuf};

use fallow_types::extract::{ImportedName, ModuleInfo};
use fallow_types::serde_path;
use rustc_hash::{FxHashMap, FxHashSet};
use serde::Serialize;

use crate::discover::FileId;
use crate::graph::ModuleGraph;

/// Default chain depth when `--depth` is unset. Small by design: symbol-level is
/// best-effort, so a shallow bound keeps the trace legible and bounded.
pub const DEFAULT_TRACE_DEPTH: u32 = 2;

/// Which directions to walk.
#[derive(Debug, Clone, Copy)]
pub struct TraceDirections {
    /// Walk UP to callers (modules that import the symbol).
    pub callers: bool,
    /// Walk DOWN to callees (modules / call sites the symbol's module reaches).
    pub callees: bool,
}

/// The result of a symbol-level call-chain trace. Its own surface (`kind:
/// "trace"`), NOT folded into the ranked brief.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SymbolChainTrace {
    /// The file containing the traced symbol (project-root-relative).
    #[serde(serialize_with = "serde_path::serialize")]
    pub file: PathBuf,
    /// The traced symbol name.
    pub symbol: String,
    /// Whether the symbol's defining export was found in the graph. When
    /// `false`, the chains are empty and `reason` explains why.
    pub symbol_found: bool,
    /// The chain depth applied to both directions.
    pub depth: u32,
    /// Whether this trace is best-effort (always `true`: symbol-level chains are
    /// labeled best-effort, syntactic per ADR-001).
    pub best_effort: bool,
    /// Caller chain hops (UP). Present only when `--callers` was requested.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub callers: Option<Vec<ChainHop>>,
    /// Callee chain hops (DOWN) resolved to an import-symbol edge. Present only
    /// when `--callees` was requested.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub callees: Option<Vec<ChainHop>>,
    /// Callees referenced at a call site in the symbol's module that the
    /// syntactic walk could NOT resolve to an import-symbol edge (locals,
    /// globals, dynamic dispatch, re-bound callees). Reported, never dropped.
    /// Present only when `--callees` was requested.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unresolved_callees: Option<Vec<UnresolvedCallee>>,
    /// A human-readable summary of the trace outcome.
    pub reason: String,
}

/// One hop in a caller / callee chain.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ChainHop {
    /// The file at this hop (project-root-relative). For a caller hop this is
    /// the importing module; for a callee hop the imported module.
    #[serde(serialize_with = "serde_path::serialize")]
    pub file: PathBuf,
    /// The symbol name as imported across the edge (`default`, `*` for namespace,
    /// the imported name otherwise).
    pub imported_as: String,
    /// The local binding name in the file at this hop.
    pub local_name: String,
    /// Whether the import edge is type-only (`import type { ... }`).
    pub type_only: bool,
    /// The hop's depth (1 = direct caller/callee of the symbol).
    pub depth: u32,
}

/// A callee referenced at a call site that did not resolve to an import-symbol
/// edge. Surfaced so a missing callee is never silently dropped.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnresolvedCallee {
    /// The callee path as written at the call site (e.g. `helper`,
    /// `obj.method`).
    pub callee: String,
    /// Why it is unresolved (best-effort classification).
    pub reason: UnresolvedReason,
}

/// Best-effort classification of why a callee did not resolve to an edge.
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum UnresolvedReason {
    /// A bare identifier call with no matching import binding (a same-module
    /// local function, a global, or a re-bound callee).
    LocalOrGlobal,
    /// A computed / member-expression callee (`obj.method`, dynamic dispatch).
    MemberOrDynamic,
}

/// Target + traversal parameters for a symbol-chain trace.
#[derive(Debug, Clone, Copy)]
pub struct SymbolChainQuery<'a> {
    /// File path of the target symbol (root-relative or absolute).
    pub file: &'a str,
    /// The exported symbol name to trace.
    pub symbol: &'a str,
    /// Maximum traversal depth in each direction.
    pub depth: u32,
    /// Which directions to walk (callers UP / callees DOWN).
    pub directions: TraceDirections,
}

/// Trace the symbol-level call chain for `query.symbol` in `query.file`.
///
/// `modules` is the parsed `ModuleInfo` set (retained from the pipeline) used to
/// surface unresolved callees; pass an empty slice to skip unresolved-callee
/// reporting (callers / resolved callees still work from the graph alone).
#[must_use]
pub fn trace_symbol_chain(
    graph: &ModuleGraph,
    modules: &[ModuleInfo],
    root: &Path,
    query: SymbolChainQuery<'_>,
) -> Option<SymbolChainTrace> {
    let SymbolChainQuery {
        file,
        symbol,
        depth,
        directions,
    } = query;
    let module = graph
        .modules
        .iter()
        .find(|m| path_matches(&m.path, root, file))?;
    let rel_file = relativize(&module.path, root);

    let symbol_found = module.exports.iter().any(|e| e.name.to_string() == *symbol);

    let module_by_id: FxHashMap<FileId, &ModuleInfo> =
        modules.iter().map(|m| (m.file_id, m)).collect();

    let callers = directions
        .callers
        .then(|| collect_callers(graph, root, module.file_id, symbol, depth));
    let callees_walk = directions
        .callees
        .then(|| collect_callees(graph, &module_by_id, root, module.file_id, symbol, depth));
    let (callees, unresolved_callees) = match callees_walk {
        Some((resolved, unresolved)) => (Some(resolved), Some(unresolved)),
        None => (None, None),
    };

    let reason = build_reason(
        symbol_found,
        callers.as_deref(),
        callees.as_deref(),
        unresolved_callees.as_deref(),
    );

    Some(SymbolChainTrace {
        file: rel_file,
        symbol: symbol.to_string(),
        symbol_found,
        depth,
        best_effort: true,
        callers,
        callees,
        unresolved_callees,
        reason,
    })
}

/// Shared walk state, so the recursive helpers stay under the argument cap.
struct WalkCtx<'a> {
    graph: &'a ModuleGraph,
    root: &'a Path,
    max_depth: u32,
}

/// Walk UP: every module that imports `symbol` from `target`, recursed through
/// each importer's own binding up to `depth`.
fn collect_callers(
    graph: &ModuleGraph,
    root: &Path,
    target: FileId,
    symbol: &str,
    depth: u32,
) -> Vec<ChainHop> {
    let ctx = WalkCtx {
        graph,
        root,
        max_depth: depth,
    };
    let mut hops = Vec::new();
    let mut visited: FxHashSet<(FileId, String)> = FxHashSet::default();
    walk_callers_recursive(&ctx, target, symbol, 1, &mut visited, &mut hops);
    hops.sort_by(|a, b| {
        a.depth
            .cmp(&b.depth)
            .then_with(|| a.file.cmp(&b.file))
            .then_with(|| a.local_name.cmp(&b.local_name))
    });
    hops
}

fn walk_callers_recursive(
    ctx: &WalkCtx<'_>,
    target: FileId,
    symbol: &str,
    current_depth: u32,
    visited: &mut FxHashSet<(FileId, String)>,
    hops: &mut Vec<ChainHop>,
) {
    if current_depth > ctx.max_depth {
        return;
    }
    for &importer in ctx.graph.importers_of(target) {
        for (edge_target, symbols) in ctx.graph.outgoing_symbol_edges(importer) {
            if edge_target != target {
                continue;
            }
            for sym in symbols {
                if !imported_name_matches(&sym.imported_name, symbol) {
                    continue;
                }
                let key = (importer, sym.local_name.clone());
                if !visited.insert(key) {
                    continue;
                }
                let importer_path = ctx.graph.modules.get(importer.0 as usize).map_or_else(
                    || PathBuf::from("<unknown>"),
                    |m| relativize(&m.path, ctx.root),
                );
                hops.push(ChainHop {
                    file: importer_path,
                    imported_as: imported_name_label(&sym.imported_name),
                    local_name: sym.local_name.clone(),
                    type_only: sym.is_type_only,
                    depth: current_depth,
                });
                // Recurse: the importer's local binding becomes the next symbol
                // whose callers we walk (covers a re-exported / forwarded symbol).
                walk_callers_recursive(
                    ctx,
                    importer,
                    &sym.local_name,
                    current_depth + 1,
                    visited,
                    hops,
                );
            }
        }
    }
}

/// Walk DOWN: the import-symbol edges OUT of `module_id` (resolved callees),
/// recursed into each target module's exports up to `depth`, plus the call sites
/// in `module_id` whose callee did not resolve to an import binding (unresolved).
fn collect_callees(
    graph: &ModuleGraph,
    module_by_id: &FxHashMap<FileId, &ModuleInfo>,
    root: &Path,
    module_id: FileId,
    _symbol: &str,
    depth: u32,
) -> (Vec<ChainHop>, Vec<UnresolvedCallee>) {
    let ctx = WalkCtx {
        graph,
        root,
        max_depth: depth,
    };
    let mut resolved = Vec::new();
    let mut visited: FxHashSet<FileId> = FxHashSet::default();
    visited.insert(module_id);
    walk_callees_recursive(&ctx, module_id, 1, &mut visited, &mut resolved);
    resolved.sort_by(|a, b| {
        a.depth
            .cmp(&b.depth)
            .then_with(|| a.file.cmp(&b.file))
            .then_with(|| a.local_name.cmp(&b.local_name))
    });

    let unresolved = module_by_id
        .get(&module_id)
        .map(|info| collect_unresolved_callees(info))
        .unwrap_or_default();

    (resolved, unresolved)
}

fn walk_callees_recursive(
    ctx: &WalkCtx<'_>,
    module_id: FileId,
    current_depth: u32,
    visited: &mut FxHashSet<FileId>,
    hops: &mut Vec<ChainHop>,
) {
    if current_depth > ctx.max_depth {
        return;
    }
    for (edge_target, symbols) in ctx.graph.outgoing_symbol_edges(module_id) {
        let target_path = ctx.graph.modules.get(edge_target.0 as usize).map_or_else(
            || PathBuf::from("<unknown>"),
            |m| relativize(&m.path, ctx.root),
        );
        for sym in symbols {
            // Side-effect imports carry no value-level callee; skip them.
            if matches!(sym.imported_name, ImportedName::SideEffect) {
                continue;
            }
            hops.push(ChainHop {
                file: target_path.clone(),
                imported_as: imported_name_label(&sym.imported_name),
                local_name: sym.local_name.clone(),
                type_only: sym.is_type_only,
                depth: current_depth,
            });
        }
        if visited.insert(edge_target) {
            walk_callees_recursive(ctx, edge_target, current_depth + 1, visited, hops);
        }
    }
}

/// Build the unresolved-callee list from a module's call sites: every
/// `callee_uses` path whose leading identifier is bound to no import is
/// surfaced (best-effort classification). A dotted path is `MemberOrDynamic`; a
/// bare identifier with no import binding is `LocalOrGlobal`.
fn collect_unresolved_callees(info: &ModuleInfo) -> Vec<UnresolvedCallee> {
    let import_locals: FxHashSet<&str> =
        info.imports.iter().map(|i| i.local_name.as_str()).collect();

    let mut out = Vec::new();
    let mut seen: FxHashSet<&str> = FxHashSet::default();
    for callee in &info.callee_uses {
        let path = callee.callee_path.as_str();
        let leading = path.split('.').next().unwrap_or(path);
        // A callee whose leading identifier is an imported binding resolves to a
        // graph edge already (covered by the resolved callee list); skip it.
        if import_locals.contains(leading) {
            continue;
        }
        if !seen.insert(path) {
            continue;
        }
        let reason = if path.contains('.') {
            UnresolvedReason::MemberOrDynamic
        } else {
            UnresolvedReason::LocalOrGlobal
        };
        out.push(UnresolvedCallee {
            callee: path.to_string(),
            reason,
        });
    }
    out.sort_by(|a, b| a.callee.cmp(&b.callee));
    out
}

fn build_reason(
    symbol_found: bool,
    callers: Option<&[ChainHop]>,
    callees: Option<&[ChainHop]>,
    unresolved: Option<&[UnresolvedCallee]>,
) -> String {
    if !symbol_found {
        return "symbol not found as an export of this file; chains are file-scoped best-effort and may be empty".to_string();
    }
    let mut parts = Vec::new();
    if let Some(callers) = callers {
        parts.push(format!("{} caller hop(s)", callers.len()));
    }
    if let Some(callees) = callees {
        parts.push(format!("{} resolved callee hop(s)", callees.len()));
    }
    if let Some(unresolved) = unresolved {
        parts.push(format!(
            "{} unresolved callee(s) reported",
            unresolved.len()
        ));
    }
    format!(
        "best-effort syntactic chain (ADR-001): {}",
        parts.join(", ")
    )
}

/// True when an [`ImportedName`] refers to `symbol`. A namespace import (`*`)
/// brings every export of the target into scope, so it matches any symbol.
fn imported_name_matches(name: &ImportedName, symbol: &str) -> bool {
    match name {
        ImportedName::Named(n) => n == symbol,
        ImportedName::Default => symbol == "default",
        ImportedName::Namespace => true,
        ImportedName::SideEffect => false,
    }
}

fn imported_name_label(name: &ImportedName) -> String {
    match name {
        ImportedName::Named(name) => name.clone(),
        ImportedName::Default => "default".to_string(),
        ImportedName::Namespace => "*".to_string(),
        ImportedName::SideEffect => "side-effect".to_string(),
    }
}

fn relativize(path: &Path, root: &Path) -> PathBuf {
    path.strip_prefix(root).unwrap_or(path).to_path_buf()
}

/// Match a user-provided file path against a module's actual path. Mirrors
/// `trace::path_matches` (kept local to avoid widening that private helper).
fn path_matches(module_path: &Path, root: &Path, user_path: &str) -> bool {
    let user_path_norm = user_path.replace('\\', "/");
    let rel = module_path.strip_prefix(root).unwrap_or(module_path);
    let rel_str = rel.to_string_lossy().replace('\\', "/");
    let module_str = module_path.to_string_lossy().replace('\\', "/");
    if rel_str == user_path_norm || module_str == user_path_norm {
        return true;
    }
    if dunce::canonicalize(root).is_ok_and(|canonical_root| {
        module_path
            .strip_prefix(&canonical_root)
            .is_ok_and(|rel| rel.to_string_lossy().replace('\\', "/") == user_path_norm)
    }) {
        return true;
    }
    module_str.ends_with(&format!("/{user_path_norm}"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::analyze::test_support::empty_module;

    #[test]
    fn imported_name_matches_named_default_namespace() {
        assert!(imported_name_matches(
            &ImportedName::Named("foo".to_string()),
            "foo"
        ));
        assert!(!imported_name_matches(
            &ImportedName::Named("bar".to_string()),
            "foo"
        ));
        assert!(imported_name_matches(&ImportedName::Default, "default"));
        assert!(!imported_name_matches(&ImportedName::Default, "foo"));
        // A namespace import brings every export into scope.
        assert!(imported_name_matches(&ImportedName::Namespace, "anything"));
        assert!(!imported_name_matches(&ImportedName::SideEffect, "foo"));
    }

    #[test]
    fn unresolved_reason_classifies_member_vs_bare() {
        let info = ModuleInfo {
            callee_uses: vec![
                fallow_types::extract::CalleeUse {
                    callee_path: "localHelper".to_string(),
                    span_start: 0,
                },
                fallow_types::extract::CalleeUse {
                    callee_path: "obj.method".to_string(),
                    span_start: 10,
                },
            ],
            ..empty_module()
        };
        let unresolved = collect_unresolved_callees(&info);
        assert_eq!(unresolved.len(), 2);
        assert_eq!(unresolved[0].callee, "localHelper");
        assert_eq!(unresolved[0].reason, UnresolvedReason::LocalOrGlobal);
        assert_eq!(unresolved[1].callee, "obj.method");
        assert_eq!(unresolved[1].reason, UnresolvedReason::MemberOrDynamic);
    }

    #[test]
    fn imported_callees_are_not_listed_as_unresolved() {
        let info = ModuleInfo {
            imports: vec![fallow_types::extract::ImportInfo {
                source: "./dep".to_string(),
                imported_name: ImportedName::Named("dep".to_string()),
                local_name: "dep".to_string(),
                is_type_only: false,
                from_style: false,
                span: oxc_span::Span::default(),
                source_span: oxc_span::Span::default(),
            }],
            callee_uses: vec![
                fallow_types::extract::CalleeUse {
                    callee_path: "dep".to_string(),
                    span_start: 0,
                },
                fallow_types::extract::CalleeUse {
                    callee_path: "ghost".to_string(),
                    span_start: 5,
                },
            ],
            ..empty_module()
        };
        let unresolved = collect_unresolved_callees(&info);
        // `dep` resolves to an import (covered by resolved callees); only `ghost`
        // is unresolved.
        assert_eq!(unresolved.len(), 1);
        assert_eq!(unresolved[0].callee, "ghost");
    }
}