Skip to main content

aft_parse/
callgraph.rs

1//! Call graph engine: cross-file call resolution and forward traversal.
2//!
3//! Builds a lazy, worktree-scoped call graph that resolves calls across files
4//! using import chains. Supports depth-limited forward traversal with cycle
5//! detection.
6
7use std::cell::RefCell;
8use std::collections::{HashMap, HashSet};
9use std::path::{Path, PathBuf};
10use std::sync::{Arc, LazyLock, OnceLock, RwLock};
11
12use globset::{Glob, GlobSet, GlobSetBuilder};
13use serde::Serialize;
14use serde_json::Value;
15use tree_sitter::Node;
16
17use crate::callgraph_store::disk_facts::DiskFacts;
18use crate::callgraph_store::facts::{byte_path, EntryKind, FactPaths};
19use crate::callgraph_store::join::syntax_index::{Direct, Nav, SyntaxIndex};
20#[cfg(any(test, feature = "test-support"))]
21use crate::calls::{call_node_kinds, extract_callee_name, extract_full_callee};
22use crate::calls::{extract_calls_full_with, extract_rust_value_references_with};
23use crate::error::AftError;
24use crate::imports::{self, ImportBlock};
25use crate::parser::{detect_language, detect_language_from_source, LangId};
26use crate::symbols::{Range, Symbol, SymbolKind};
27
28// ---------------------------------------------------------------------------
29// Core types
30// ---------------------------------------------------------------------------
31
32type WorkspacePackageCache = HashMap<(PathBuf, String), Option<PathBuf>>;
33// A cell per canonical root coalesces simultaneous parse-pool misses without
34// holding the process-wide map lock while traversing unrelated workspaces.
35type WorkspaceMemberDirsCache = HashMap<PathBuf, Arc<OnceLock<Arc<Vec<PathBuf>>>>>;
36type RustCrateInfoCache = HashMap<PathBuf, Option<RustCrateInfo>>;
37type RustWorkspaceCrateCache = HashMap<PathBuf, HashMap<String, RustCrateInfo>>;
38
39static WORKSPACE_PACKAGE_CACHE: LazyLock<RwLock<WorkspacePackageCache>> =
40    LazyLock::new(|| RwLock::new(HashMap::new()));
41static WORKSPACE_MEMBER_DIRS_CACHE: LazyLock<RwLock<WorkspaceMemberDirsCache>> =
42    LazyLock::new(|| RwLock::new(HashMap::new()));
43static RUST_CRATE_INFO_CACHE: LazyLock<RwLock<RustCrateInfoCache>> =
44    LazyLock::new(|| RwLock::new(HashMap::new()));
45static RUST_WORKSPACE_CRATE_CACHE: LazyLock<RwLock<RustWorkspaceCrateCache>> =
46    LazyLock::new(|| RwLock::new(HashMap::new()));
47
48// Cold builds retain one resolver memo across every staged reference window. The
49// entry and retained-weight ceilings keep that speedup inside the bounded-build
50// working-set contract: at most 9 MiB of estimated keys/values are retained here,
51// plus 4 MiB for canonical probe identities owned by the same snapshot.
52const MODULE_RESOLUTION_MEMO_MAX_ENTRIES: usize = 32_768;
53const MODULE_RESOLUTION_MEMO_MAX_RETAINED_BYTES: usize = 3 * 1024 * 1024;
54const JSON_VALUE_MEMO_MAX_ENTRIES: usize = 8_192;
55const JSON_VALUE_MEMO_MAX_RETAINED_BYTES: usize = 3 * 1024 * 1024;
56const WORKSPACE_PACKAGE_MEMO_MAX_ENTRIES: usize = 2_048;
57const WORKSPACE_PACKAGE_MEMO_MAX_RETAINED_BYTES: usize = 1024 * 1024;
58const RUST_DECLARED_MODULE_MEMO_MAX_ENTRIES: usize = 8_192;
59const RUST_DECLARED_MODULE_MEMO_MAX_RETAINED_BYTES: usize = 2 * 1024 * 1024;
60const MEMO_ENTRY_OVERHEAD_BYTES: usize = 128;
61
62type ModuleResolutionKey = (PathBuf, String);
63
64trait ModuleKeyParts {
65    fn parts(&self) -> (&Path, &str);
66}
67
68impl ModuleKeyParts for ModuleResolutionKey {
69    fn parts(&self) -> (&Path, &str) {
70        (&self.0, &self.1)
71    }
72}
73
74impl ModuleKeyParts for (&Path, &str) {
75    fn parts(&self) -> (&Path, &str) {
76        *self
77    }
78}
79
80// Owned and borrowed compound keys must hash the same path/string pair. The
81// borrowed trait object lets HashMap probe without constructing either owner.
82impl std::hash::Hash for dyn ModuleKeyParts + '_ {
83    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
84        std::hash::Hash::hash(&self.parts(), state);
85    }
86}
87
88impl PartialEq for dyn ModuleKeyParts + '_ {
89    fn eq(&self, other: &Self) -> bool {
90        self.parts() == other.parts()
91    }
92}
93
94impl Eq for dyn ModuleKeyParts + '_ {}
95
96impl<'a> std::borrow::Borrow<dyn ModuleKeyParts + 'a> for ModuleResolutionKey {
97    fn borrow(&self) -> &(dyn ModuleKeyParts + 'a) {
98        self
99    }
100}
101
102#[cfg(any(test, feature = "test-support"))]
103thread_local! {
104    pub static OWNED_MODULE_KEY_COUNT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
105}
106
107fn owned_module_key(from_dir: &Path, module_path: &str) -> ModuleResolutionKey {
108    #[cfg(any(test, feature = "test-support"))]
109    OWNED_MODULE_KEY_COUNT.with(|count| count.set(count.get() + 1));
110    (from_dir.to_path_buf(), module_path.to_string())
111}
112type WorkspacePackageKey = (PathBuf, String);
113type RustDeclaredModuleMap = HashMap<String, Option<String>>;
114
115#[derive(Clone, Debug)]
116struct RustCrateTargets {
117    lib_root: Option<PathBuf>,
118    target_roots: Vec<PathBuf>,
119}
120
121/// Interior-mutable memo storage. A lock rather than a `RefCell` lets one memo
122/// be shared by the cold build's parse pool; each access holds it only for a
123/// single lookup or insert, never across the work that computes a value.
124#[derive(Default)]
125struct MemoCell<T>(std::sync::Mutex<T>);
126
127impl<T> MemoCell<T> {
128    fn new(value: T) -> Self {
129        Self(std::sync::Mutex::new(value))
130    }
131
132    fn borrow(&self) -> std::sync::MutexGuard<'_, T> {
133        self.0
134            .lock()
135            .unwrap_or_else(std::sync::PoisonError::into_inner)
136    }
137
138    fn borrow_mut(&self) -> std::sync::MutexGuard<'_, T> {
139        self.borrow()
140    }
141}
142
143#[derive(Clone, Default)]
144pub struct RustCrateRootMemo {
145    caller_roots: Arc<MemoCell<HashMap<PathBuf, Option<PathBuf>>>>,
146    crate_targets: Arc<MemoCell<HashMap<PathBuf, Option<RustCrateTargets>>>>,
147}
148
149test_support_visibility! {
150struct BoundedMemo<K, V> {
151    #[cfg(any(test, feature = "test-support"))]
152    pub entries: HashMap<K, (V, usize)>,
153    #[cfg(not(any(test, feature = "test-support")))]
154    entries: HashMap<K, (V, usize)>,
155    order: std::collections::VecDeque<K>,
156    #[cfg(any(test, feature = "test-support"))]
157    pub retained_weight: usize,
158    #[cfg(not(any(test, feature = "test-support")))]
159    retained_weight: usize,
160    max_entries: usize,
161    max_retained_weight: usize,
162}
163}
164
165test_support_visibility! {
166/// Heap bytes of a memo key, charged once more for the copy the eviction
167/// order keeps alongside the map entry.
168trait MemoKeyWeight {
169    fn key_weight(&self) -> usize;
170}
171}
172
173impl MemoKeyWeight for (PathBuf, String) {
174    fn key_weight(&self) -> usize {
175        path_retained_weight(&self.0) + self.1.len()
176    }
177}
178
179impl MemoKeyWeight for PathBuf {
180    fn key_weight(&self) -> usize {
181        path_retained_weight(self)
182    }
183}
184
185impl MemoKeyWeight for String {
186    fn key_weight(&self) -> usize {
187        self.len()
188    }
189}
190
191impl<K: Eq + std::hash::Hash + Clone + MemoKeyWeight, V> BoundedMemo<K, V> {
192    test_support_visibility! {
193    fn new(max_entries: usize, max_retained_weight: usize) -> Self {
194            Self {
195                entries: HashMap::new(),
196                order: std::collections::VecDeque::new(),
197                retained_weight: 0,
198                max_entries,
199                max_retained_weight,
200            }
201        }
202    }
203
204    test_support_visibility! {
205    fn get<Q>(&self, key: &Q) -> Option<&V>
206        where
207            K: std::borrow::Borrow<Q>,
208            Q: Eq + std::hash::Hash + ?Sized,
209        {
210            self.entries.get(key).map(|(value, _)| value)
211        }
212    }
213
214    test_support_visibility! {
215    fn insert(&mut self, key: K, value: V, retained_weight: usize) {
216            // The eviction order owns a second copy of the key, so charge its bytes
217            // too; the retained-byte ceiling then still covers everything held.
218            let retained_weight = retained_weight.saturating_add(key.key_weight());
219            if self.entries.contains_key(&key)
220                || self.max_entries == 0
221                || retained_weight > self.max_retained_weight
222            {
223                return;
224            }
225            // FIFO eviction keeps later resolution windows cacheable without
226            // relaxing either bound or flushing unrelated entries together.
227            while self.entries.len() >= self.max_entries
228                || self.retained_weight.saturating_add(retained_weight) > self.max_retained_weight
229            {
230                let oldest = self.order.pop_front().expect("full memo has an entry");
231                let (_, weight) = self.entries.remove(&oldest).expect("ordered memo entry");
232                self.retained_weight -= weight;
233            }
234            self.retained_weight += retained_weight;
235            self.order.push_back(key.clone());
236            self.entries.insert(key, (value, retained_weight));
237        }
238
239    }
240}
241
242/// Snapshot-scoped filesystem memo used by the staged cold-build resolver.
243///
244/// The cold build reads one fixed corpus, so no watcher invalidation is needed:
245/// the memo is dropped when publication completes or the build aborts.
246pub struct ModuleResolutionMemo {
247    enabled: bool,
248    module_paths: MemoCell<BoundedMemo<ModuleResolutionKey, Option<PathBuf>>>,
249    json_values: MemoCell<BoundedMemo<PathBuf, Option<Arc<Value>>>>,
250    workspace_packages: MemoCell<BoundedMemo<WorkspacePackageKey, Option<PathBuf>>>,
251    rust_declared_modules: MemoCell<BoundedMemo<String, Arc<RustDeclaredModuleMap>>>,
252    rust_crate_roots: RustCrateRootMemo,
253    #[cfg(any(test, feature = "test-support"))]
254    collect_metrics: bool,
255    #[cfg(any(test, feature = "test-support"))]
256    module_computations: MemoCell<HashMap<ModuleResolutionKey, usize>>,
257    #[cfg(any(test, feature = "test-support"))]
258    json_probes: MemoCell<HashMap<PathBuf, usize>>,
259    #[cfg(any(test, feature = "test-support"))]
260    rust_declaration_parses: MemoCell<HashMap<String, usize>>,
261}
262
263impl Default for ModuleResolutionMemo {
264    fn default() -> Self {
265        Self {
266            enabled: true,
267            module_paths: MemoCell::new(BoundedMemo::new(
268                MODULE_RESOLUTION_MEMO_MAX_ENTRIES,
269                MODULE_RESOLUTION_MEMO_MAX_RETAINED_BYTES,
270            )),
271            json_values: MemoCell::new(BoundedMemo::new(
272                JSON_VALUE_MEMO_MAX_ENTRIES,
273                JSON_VALUE_MEMO_MAX_RETAINED_BYTES,
274            )),
275            workspace_packages: MemoCell::new(BoundedMemo::new(
276                WORKSPACE_PACKAGE_MEMO_MAX_ENTRIES,
277                WORKSPACE_PACKAGE_MEMO_MAX_RETAINED_BYTES,
278            )),
279            rust_declared_modules: MemoCell::new(BoundedMemo::new(
280                RUST_DECLARED_MODULE_MEMO_MAX_ENTRIES,
281                RUST_DECLARED_MODULE_MEMO_MAX_RETAINED_BYTES,
282            )),
283            rust_crate_roots: RustCrateRootMemo::default(),
284            #[cfg(any(test, feature = "test-support"))]
285            collect_metrics: false,
286            #[cfg(any(test, feature = "test-support"))]
287            module_computations: MemoCell::new(HashMap::new()),
288            #[cfg(any(test, feature = "test-support"))]
289            json_probes: MemoCell::new(HashMap::new()),
290            #[cfg(any(test, feature = "test-support"))]
291            rust_declaration_parses: MemoCell::new(HashMap::new()),
292        }
293    }
294}
295
296impl ModuleResolutionMemo {
297    test_support_visibility! {
298    fn resolve_module_path(
299            &self,
300            from_dir: &Path,
301            module_path: &str,
302            facts: &FactPaths<'_>,
303        ) -> Option<PathBuf> {
304            if self.enabled {
305                let borrowed = (from_dir, module_path);
306                if let Some(cached) = self
307                    .module_paths
308                    .borrow()
309                    .get(&borrowed as &dyn ModuleKeyParts)
310                {
311                    facts.facts.memo_replay(from_dir, "module", module_path);
312                    return cached.clone();
313                }
314            }
315
316            let key = owned_module_key(from_dir, module_path);
317            self.note_module_computation(&key);
318            facts.facts.memo_start(from_dir, "module", module_path);
319            let resolved = resolve_module_path_uncached(from_dir, module_path, Some(self), facts);
320            facts.facts.memo_finish(from_dir, "module", module_path);
321            if self.enabled {
322                let retained_weight = module_resolution_entry_weight(&key, resolved.as_deref());
323                self.module_paths
324                    .borrow_mut()
325                    .insert(key, resolved.clone(), retained_weight);
326            }
327            resolved
328        }
329    }
330
331    fn json_value(&self, path: &Path, facts: &FactPaths<'_>) -> Option<Arc<Value>> {
332        if self.enabled {
333            if let Some(cached) = self.json_values.borrow().get(path) {
334                return cached.clone();
335            }
336        }
337
338        self.note_json_probe(path);
339        let parsed = facts
340            .attributed_bytes(path)
341            .and_then(|source| serde_json::from_slice(&source).ok())
342            .map(Arc::new);
343        if self.enabled {
344            let retained_weight = MEMO_ENTRY_OVERHEAD_BYTES
345                + path_retained_weight(path)
346                + parsed
347                    .as_deref()
348                    .map(json_retained_weight)
349                    .unwrap_or_default();
350            self.json_values.borrow_mut().insert(
351                path.to_path_buf(),
352                parsed.clone(),
353                retained_weight,
354            );
355        }
356        parsed
357    }
358
359    pub fn rust_crate_root_file(
360        &self,
361        project_root: &Path,
362        caller_file: &Path,
363        facts: &FactPaths<'_>,
364    ) -> Option<PathBuf> {
365        self.rust_crate_roots
366            .root_file(project_root, caller_file, facts)
367    }
368
369    pub fn rust_declared_module_target(
370        &self,
371        caller_file: &str,
372        module_name: &str,
373        populate: impl FnOnce() -> RustDeclaredModuleMap,
374    ) -> Option<String> {
375        if self.enabled {
376            if let Some(cached) = self.rust_declared_modules.borrow().get(caller_file) {
377                return cached.get(module_name).cloned().flatten();
378            }
379        }
380
381        self.note_rust_declaration_parse(caller_file);
382        let declared_modules = Arc::new(populate());
383        let resolved = declared_modules.get(module_name).cloned().flatten();
384        if self.enabled {
385            let retained_weight = rust_declared_module_entry_weight(caller_file, &declared_modules);
386            self.rust_declared_modules.borrow_mut().insert(
387                caller_file.to_string(),
388                declared_modules,
389                retained_weight,
390            );
391        }
392        resolved
393    }
394
395    fn workspace_package(&self, key: &WorkspacePackageKey) -> Option<Option<PathBuf>> {
396        self.enabled
397            .then(|| self.workspace_packages.borrow().get(key).cloned())
398            .flatten()
399    }
400
401    fn remember_workspace_package(&self, key: WorkspacePackageKey, resolved: Option<PathBuf>) {
402        if !self.enabled {
403            return;
404        }
405        let retained_weight = module_resolution_entry_weight(&key, resolved.as_deref());
406        self.workspace_packages
407            .borrow_mut()
408            .insert(key, resolved, retained_weight);
409    }
410
411    #[cfg(any(test, feature = "test-support"))]
412    fn note_module_computation(&self, key: &ModuleResolutionKey) {
413        if self.collect_metrics {
414            *self
415                .module_computations
416                .borrow_mut()
417                .entry(key.clone())
418                .or_default() += 1;
419        }
420    }
421
422    #[cfg(not(any(test, feature = "test-support")))]
423    fn note_module_computation(&self, _key: &ModuleResolutionKey) {}
424
425    #[cfg(any(test, feature = "test-support"))]
426    fn note_json_probe(&self, path: &Path) {
427        if self.collect_metrics {
428            *self
429                .json_probes
430                .borrow_mut()
431                .entry(path.to_path_buf())
432                .or_default() += 1;
433        }
434    }
435
436    #[cfg(not(any(test, feature = "test-support")))]
437    fn note_json_probe(&self, _path: &Path) {}
438
439    #[cfg(any(test, feature = "test-support"))]
440    fn note_rust_declaration_parse(&self, caller_file: &str) {
441        if self.collect_metrics {
442            *self
443                .rust_declaration_parses
444                .borrow_mut()
445                .entry(caller_file.to_string())
446                .or_default() += 1;
447        }
448    }
449
450    #[cfg(not(any(test, feature = "test-support")))]
451    fn note_rust_declaration_parse(&self, _caller_file: &str) {}
452}
453
454fn module_resolution_entry_weight(key: &(PathBuf, String), resolved: Option<&Path>) -> usize {
455    MEMO_ENTRY_OVERHEAD_BYTES
456        + path_retained_weight(&key.0)
457        + key.1.len()
458        + resolved.map(path_retained_weight).unwrap_or_default()
459}
460
461fn path_retained_weight(path: &Path) -> usize {
462    path.to_string_lossy().len()
463}
464
465fn rust_declared_module_entry_weight(
466    caller_file: &str,
467    declared_modules: &RustDeclaredModuleMap,
468) -> usize {
469    MEMO_ENTRY_OVERHEAD_BYTES
470        + caller_file.len()
471        + declared_modules
472            .iter()
473            .map(|(module_name, target)| {
474                MEMO_ENTRY_OVERHEAD_BYTES
475                    + module_name.len()
476                    + target.as_deref().map(str::len).unwrap_or_default()
477            })
478            .sum::<usize>()
479}
480
481fn json_retained_weight(value: &Value) -> usize {
482    std::mem::size_of::<Value>()
483        + match value {
484            Value::Null | Value::Bool(_) | Value::Number(_) => 0,
485            Value::String(value) => value.len(),
486            Value::Array(values) => values.iter().map(json_retained_weight).sum(),
487            Value::Object(values) => values
488                .iter()
489                .map(|(key, value)| {
490                    key.len() + MEMO_ENTRY_OVERHEAD_BYTES + json_retained_weight(value)
491                })
492                .sum(),
493        }
494}
495
496test_support_visibility! {
497const TOP_LEVEL_SYMBOL: &str = "<top-level>";
498}
499const JS_TS_EXTENSIONS: &[&str] = &["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"];
500const JS_TS_INDEX_FILES: &[&str] = &[
501    "index.ts",
502    "index.tsx",
503    "index.mts",
504    "index.cts",
505    "index.js",
506    "index.jsx",
507    "index.mjs",
508    "index.cjs",
509];
510
511test_support_visibility! {
512fn symbol_identity(symbol: &Symbol) -> String {
513    if symbol.scope_chain.is_empty() {
514        symbol.name.clone()
515    } else {
516        format!("{}::{}", symbol.scope_chain.join("::"), symbol.name)
517    }
518}
519}
520
521fn symbol_unqualified_name(symbol: &str) -> &str {
522    symbol.rsplit("::").next().unwrap_or(symbol)
523}
524
525pub fn is_bare_callee(full_callee: &str, short_name: &str) -> bool {
526    full_callee == short_name || (!full_callee.contains('.') && !full_callee.contains("::"))
527}
528
529/// A call or function-value dependency site owned by a symbol.
530#[derive(Debug, Clone, PartialEq, Eq)]
531pub struct CallSite {
532    pub kind: CallSiteKind,
533    /// The short callee name (last segment, e.g. "foo" for `utils.foo()`).
534    pub callee_name: String,
535    /// The full callee expression (e.g. "utils.foo" for `utils.foo()`).
536    pub full_callee: String,
537    /// 1-based line number of the call.
538    pub line: u32,
539    /// Byte range of the call expression in the source.
540    pub byte_start: usize,
541    pub byte_end: usize,
542}
543
544#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
545pub enum CallSiteKind {
546    #[default]
547    Call,
548    Construction,
549    CallbackReference,
550}
551
552/// Per-symbol metadata for entry point detection (avoids re-parsing).
553#[derive(Debug, Clone, Serialize)]
554pub struct SymbolMeta {
555    /// None means extraction could not establish whether the item is test code.
556    pub is_test: Option<bool>,
557    /// The kind of symbol (function, class, method, etc).
558    pub kind: SymbolKind,
559    /// Whether this symbol is exported.
560    pub exported: bool,
561    /// Function/method signature if available.
562    #[serde(skip_serializing_if = "Option::is_none")]
563    pub signature: Option<String>,
564    /// 1-based start line of the symbol.
565    pub line: u32,
566    /// 0-based source range of the symbol.
567    pub range: Range,
568    /// Attribute that marks the symbol as externally reachable, if any.
569    #[serde(skip_serializing_if = "Option::is_none")]
570    pub entry_point_attribute: Option<String>,
571    /// Whether the program starts here, as the symbol's language defines
572    /// it (see [`starts_program`]). For Rust this is only half the answer:
573    /// the file must also be the root of a binary target, which depends on
574    /// its path and Cargo manifest, so readers that know those check it.
575    #[serde(skip_serializing_if = "std::ops::Not::not")]
576    pub program_start: bool,
577}
578
579/// Whether the symbol `identity` of `kind` is where a program in `lang`
580/// starts, as the language defines it: `fn main` at the top of a Rust file,
581/// `func main` in a Go `package main` (`go_main_package`), and `main` in C,
582/// C++ and Objective-C. Go also starts every package's top-level
583/// `func init()` (`go_init`: the file declares one with no parameters)
584/// before `main`; the runtime calls it and code never can. A Python program
585/// starts in the module code run as `__main__`, which
586/// [`python_runs_as_main`] finds. JavaScript and TypeScript define no
587/// starting function.
588fn starts_program(
589    lang: LangId,
590    identity: &str,
591    kind: &SymbolKind,
592    go_main_package: bool,
593    go_init: bool,
594) -> bool {
595    if *kind != SymbolKind::Function {
596        return false;
597    }
598    match lang {
599        LangId::Rust | LangId::C | LangId::Cpp | LangId::ObjC => identity == "main",
600        LangId::Go => (identity == "main" && go_main_package) || (identity == "init" && go_init),
601        _ => false,
602    }
603}
604
605/// Whether a Go file declares a top-level `func init()`: a function, so no
606/// receiver, with no parameters. Go runs each one when the program starts.
607fn go_declares_init(source: &str, root: tree_sitter::Node<'_>) -> bool {
608    root.named_children(&mut root.walk()).any(|node| {
609        node.kind() == "function_declaration"
610            && node
611                .child_by_field_name("name")
612                .is_some_and(|name| &source[name.byte_range()] == "init")
613            && node
614                .child_by_field_name("parameters")
615                .is_some_and(|parameters| parameters.named_child_count() == 0)
616    })
617}
618
619/// Whether a Python module has a top-level `if __name__ == "__main__":`
620/// block: the code Python runs only when the module is the program itself.
621/// The module's top-level code then starts the program.
622fn python_runs_as_main(source: &str, root: tree_sitter::Node<'_>) -> bool {
623    root.named_children(&mut root.walk()).any(|node| {
624        node.kind() == "if_statement"
625            && node
626                .child_by_field_name("condition")
627                .is_some_and(|condition| {
628                    let text = source[condition.byte_range()]
629                        .chars()
630                        .filter(|ch| !ch.is_whitespace())
631                        .map(|ch| if ch == '\'' { '"' } else { ch })
632                        .collect::<String>();
633                    text == "__name__==\"__main__\"" || text == "\"__main__\"==__name__"
634                })
635    })
636}
637
638/// Per-file call data: call sites grouped by containing symbol, plus
639/// exported symbol names and parsed imports.
640#[derive(Debug, Clone)]
641pub struct FileCallData {
642    /// Map from symbol name → list of call sites within that symbol's body.
643    pub calls_by_symbol: HashMap<String, Vec<CallSite>>,
644    /// Rust function items referenced as values, grouped by containing symbol.
645    /// Callable targets participate in reverse references, not execution trees.
646    pub value_refs_by_symbol: HashMap<String, Vec<CallSite>>,
647    /// Calls written in a `macro_rules!` template outside any item defined in
648    /// that template, keyed by macro name with its `!` (e.g. `check!`). They
649    /// run wherever the macro is invoked, so `callers` reports the macro's
650    /// invocation sites for them instead of a caller in this file.
651    pub macro_body_calls_by_macro: HashMap<String, Vec<CallSite>>,
652    /// Identifiers inside Rust macro token trees that could not be parsed as
653    /// Rust, grouped by containing symbol. `callers` counts these as mentions
654    /// it could not analyze, so a target named only there is not reported as
655    /// having no callers without comment.
656    pub macro_mentions_by_symbol: HashMap<String, Vec<CallSite>>,
657    /// Names of exported symbols in this file.
658    pub exported_symbols: Vec<String>,
659    /// Per-symbol metadata (kind, exported, signature).
660    pub symbol_metadata: HashMap<String, SymbolMeta>,
661    /// Real or synthetic symbol name for this file's default export.
662    pub default_export_symbol: Option<String>,
663    /// Parsed import block for cross-file resolution.
664    pub import_block: ImportBlock,
665    /// Lexically selected Python import bindings, sorted by call-expression span.
666    pub python_bindings: Vec<python::CallBinding>,
667    /// Language of the file.
668    pub lang: LangId,
669}
670
671pub mod python;
672
673impl FileCallData {
674    /// Look up metadata for an exported symbol name.
675    ///
676    /// `exported_symbols` stores bare names (e.g. `total_disk_bytes`), but
677    /// `symbol_metadata` is keyed by scoped identity (e.g.
678    /// `BackupStore::total_disk_bytes` for impl methods, via
679    /// [`symbol_identity`]). A bare-name `.get()` therefore misses scoped
680    /// symbols and forces callers into degraded `unknown`/line-1 fallbacks.
681    /// This resolves an exact key first, then falls back to the first entry
682    /// whose unqualified name matches — recovering correct kind and line for
683    /// methods. (Bare-name exports are already ambiguous across scopes, so
684    /// first-match is the best available signal; this only affects displayed
685    /// metadata, never liveness, which keys on the symbol name.)
686    pub fn symbol_metadata_for(&self, name: &str) -> Option<&SymbolMeta> {
687        if let Some(meta) = self.symbol_metadata.get(name) {
688            return Some(meta);
689        }
690        self.symbol_metadata
691            .iter()
692            .find(|(key, _)| symbol_unqualified_name(key) == name)
693            .map(|(_, meta)| meta)
694    }
695}
696
697/// Result of resolving a cross-file call edge.
698#[derive(Debug, Clone, PartialEq, Eq)]
699pub enum EdgeResolution {
700    /// Successfully resolved to a specific file and symbol.
701    Resolved { file: PathBuf, symbol: String },
702    /// Could not resolve — callee name preserved for diagnostics.
703    Unresolved { callee_name: String },
704}
705
706test_support_visibility! {
707#[derive(Debug, Clone, PartialEq, Eq)]
708struct ResolvedSymbol {
709    file: PathBuf,
710    #[cfg(any(test, feature = "test-support"))]
711    pub symbol: String,
712    #[cfg(not(any(test, feature = "test-support")))]
713    symbol: String,
714}
715}
716
717#[derive(Debug, Clone)]
718struct RustCrateInfo {
719    package_root: PathBuf,
720    lib_name: String,
721    lib_root: Option<PathBuf>,
722    target_roots: Vec<PathBuf>,
723}
724
725#[derive(Debug, Clone)]
726struct RustModuleBase {
727    src_dir: PathBuf,
728    root_file: PathBuf,
729}
730
731#[derive(Debug, Clone)]
732struct RustUseEntry {
733    module_path: String,
734    local_name: String,
735    kind: RustUseKind,
736}
737
738#[derive(Debug, Clone)]
739enum RustUseKind {
740    Item { imported_name: String },
741    Module,
742}
743
744/// A node in the forward call tree.
745#[derive(Debug, Clone, Serialize)]
746pub struct CallTreeNode {
747    /// Symbol name.
748    pub name: String,
749    /// File path (relative to project root when possible).
750    pub file: String,
751    /// 1-based line number.
752    pub line: u32,
753    /// Function signature if available.
754    #[serde(skip_serializing_if = "Option::is_none")]
755    pub signature: Option<String>,
756    /// Whether this edge was resolved cross-file.
757    pub resolved: bool,
758    /// Child calls (recursive).
759    pub children: Vec<CallTreeNode>,
760    /// Whether traversal below this node stopped at the requested depth.
761    pub depth_limited: bool,
762    /// Number of omitted edges, a lower bound when the work budget is exhausted.
763    pub truncated: usize,
764    #[serde(flatten, skip_serializing_if = "Option::is_none")]
765    pub work_gap: Option<CallTreeWorkGap>,
766}
767
768/// The call-tree node budget as a literal, so the work-gap text below is built
769/// from the same number as the budget instead of repeating it.
770macro_rules! call_tree_node_budget {
771    () => {
772        1000
773    };
774}
775
776pub const CALL_TREE_NODE_BUDGET: usize = call_tree_node_budget!();
777pub const CALL_TREE_WORK_GAP: &str = concat!(
778    "Call tree cut short: examined ",
779    call_tree_node_budget!(),
780    " call nodes (work budget); additional nodes not examined · narrow: symbol, depth"
781);
782
783#[derive(Debug, Clone, Serialize)]
784pub struct CallTreeWorkGap {
785    pub complete: bool,
786    pub nodes_examined: usize,
787    pub gap: String,
788}
789
790// ---------------------------------------------------------------------------
791// Entry point detection
792// ---------------------------------------------------------------------------
793
794/// Well-known main/init function names (case-insensitive exact match).
795const MAIN_INIT_NAMES: &[&str] = &["main", "init", "setup", "bootstrap", "run"];
796
797/// Determine whether a symbol is an entry point.
798///
799/// Entry points are:
800/// - Exported standalone functions (not methods — methods are class members)
801/// - Functions matching well-known main/init patterns (any language)
802/// - Test functions matching language-specific patterns
803pub fn is_entry_point(name: &str, kind: &SymbolKind, exported: bool, lang: LangId) -> bool {
804    // Exported standalone functions
805    if exported && *kind == SymbolKind::Function {
806        return true;
807    }
808
809    // Main/init patterns (case-insensitive exact match, any kind)
810    let lower = name.to_lowercase();
811    if MAIN_INIT_NAMES.contains(&lower.as_str()) {
812        return true;
813    }
814
815    // Test patterns by language
816    match lang {
817        LangId::TypeScript | LangId::JavaScript | LangId::Tsx => {
818            // describe, it, test (exact), or starts with test/spec
819            matches!(lower.as_str(), "describe" | "it" | "test")
820                || lower.starts_with("test")
821                || lower.starts_with("spec")
822        }
823        LangId::Python => {
824            // starts with test_ or matches setUp/tearDown
825            lower.starts_with("test_") || matches!(name, "setUp" | "tearDown")
826        }
827        LangId::Rust => {
828            // starts with test_
829            lower.starts_with("test_")
830        }
831        LangId::Go => {
832            // starts with Test (case-sensitive)
833            name.starts_with("Test")
834        }
835        LangId::C
836        | LangId::Cpp
837        | LangId::Cuda
838        | LangId::Metal
839        | LangId::Zig
840        | LangId::CSharp
841        | LangId::Bash
842        | LangId::Solidity
843        | LangId::Scss
844        | LangId::Vue
845        | LangId::Json
846        | LangId::Scala
847        | LangId::Java
848        | LangId::Ruby
849        | LangId::Kotlin
850        | LangId::Swift
851        | LangId::Php
852        | LangId::Lua
853        | LangId::Perl
854        | LangId::Html
855        | LangId::Markdown
856        | LangId::Yaml
857        | LangId::Pascal
858        | LangId::R
859        | LangId::Groovy
860        | LangId::ObjC
861        | LangId::Toml
862        | LangId::Luau => false,
863    }
864}
865
866// ---------------------------------------------------------------------------
867// Trace-to types
868// ---------------------------------------------------------------------------
869
870/// A single hop in a trace path.
871#[derive(Debug, Clone, Serialize)]
872pub struct TraceHop {
873    /// Symbol name at this hop.
874    pub symbol: String,
875    /// File path (relative to project root).
876    pub file: String,
877    /// 1-based line number.
878    pub line: u32,
879    /// Function signature if available.
880    #[serde(skip_serializing_if = "Option::is_none")]
881    pub signature: Option<String>,
882    /// Whether this hop is an entry point.
883    pub is_entry_point: bool,
884}
885
886/// A complete path from an entry point to the target symbol (top-down).
887#[derive(Debug, Clone, Serialize)]
888pub struct TracePath {
889    /// Hops from entry point (first) to target (last).
890    pub hops: Vec<TraceHop>,
891}
892
893/// Result of a `trace_to` query.
894#[derive(Debug, Clone, Serialize)]
895pub struct TraceToResult {
896    /// The target symbol that was traced.
897    pub target_symbol: String,
898    /// The target file (relative to project root).
899    pub target_file: String,
900    /// Complete paths from entry points to the target.
901    pub paths: Vec<TracePath>,
902    /// Total number of complete paths found.
903    pub total_paths: usize,
904    /// Number of distinct entry points found across all paths.
905    pub entry_points_found: usize,
906    /// Whether any path was cut short by the depth limit.
907    pub max_depth_reached: bool,
908    /// Number of paths that reached a dead end (no callers, not entry point).
909    pub truncated_paths: usize,
910}
911
912/// A single hop in a `trace_to_symbol` path.
913#[derive(Debug, Clone, Serialize)]
914pub struct TraceToSymbolHop {
915    /// Symbol name at this hop.
916    pub symbol: String,
917    /// File path (relative to project root).
918    pub file: String,
919    /// 1-based definition line number.
920    pub line: u32,
921}
922
923/// Candidate target location for an ambiguous `trace_to_symbol` request.
924#[derive(Debug, Clone, Serialize)]
925pub struct TraceToSymbolCandidate {
926    /// File path (relative to project root).
927    pub file: String,
928    /// 1-based definition line number.
929    pub line: u32,
930}
931
932/// Result of a `trace_to_symbol` query.
933#[derive(Debug, Clone, Serialize)]
934pub struct TraceToSymbolResult {
935    /// Shortest path from the origin symbol to the target symbol, if found.
936    pub path: Option<Vec<TraceToSymbolHop>>,
937    /// Whether traversal was complete within the requested depth.
938    pub complete: bool,
939    /// Machine-readable explanation when `path` is null.
940    #[serde(skip_serializing_if = "Option::is_none")]
941    pub reason: Option<String>,
942}
943
944// ---------------------------------------------------------------------------
945// Data flow tracking types
946// ---------------------------------------------------------------------------
947
948/// A single hop in a data flow trace.
949#[derive(Debug, Clone, Serialize)]
950pub struct DataFlowHop {
951    /// File path (relative to project root).
952    pub file: String,
953    /// Symbol (function/method) containing this hop.
954    pub symbol: String,
955    /// Variable or parameter name being tracked at this hop.
956    pub variable: String,
957    /// 1-based line number.
958    pub line: u32,
959    /// Type of data flow: "assignment", "parameter", or "return".
960    pub flow_type: String,
961    /// Whether this hop is an approximation (destructuring, spread, unresolved).
962    pub approximate: bool,
963}
964
965/// Result of a `trace_data` query — tracks how an expression flows through
966/// variable assignments and function parameters.
967#[derive(Debug, Clone, Serialize)]
968pub struct TraceDataResult {
969    /// The expression being tracked.
970    pub expression: String,
971    /// The file where tracking started.
972    pub origin_file: String,
973    /// The symbol where tracking started.
974    pub origin_symbol: String,
975    /// Hops through assignments and parameters.
976    pub hops: Vec<DataFlowHop>,
977    /// Whether tracking stopped due to depth limit.
978    pub depth_limited: bool,
979}
980
981/// Extract parameter names from a function signature string.
982///
983/// Strips language-specific receivers (`self`, `&self`, `&mut self` for Rust,
984/// `self` for Python) and type annotations / default values. Returns just
985/// the parameter names.
986pub fn extract_parameters(signature: &str, lang: LangId) -> Vec<String> {
987    // Find the parameter list between parentheses
988    let start = match signature.find('(') {
989        Some(i) => i + 1,
990        None => return Vec::new(),
991    };
992    let end = match signature[start..].find(')') {
993        Some(i) => start + i,
994        None => return Vec::new(),
995    };
996
997    let params_str = &signature[start..end].trim();
998    if params_str.is_empty() {
999        return Vec::new();
1000    }
1001
1002    // Split on commas, respecting nested generics/brackets
1003    let parts = split_params(params_str);
1004
1005    let mut result = Vec::new();
1006    for part in parts {
1007        let trimmed = part.trim();
1008        if trimmed.is_empty() {
1009            continue;
1010        }
1011
1012        // Skip language-specific receivers
1013        match lang {
1014            LangId::Rust => {
1015                if trimmed == "self"
1016                    || trimmed == "mut self"
1017                    || trimmed.starts_with("&self")
1018                    || trimmed.starts_with("&mut self")
1019                {
1020                    continue;
1021                }
1022            }
1023            LangId::Python => {
1024                if trimmed == "self" || trimmed.starts_with("self:") {
1025                    continue;
1026                }
1027            }
1028            _ => {}
1029        }
1030
1031        // Extract just the parameter name
1032        let name = extract_param_name(trimmed, lang);
1033        if !name.is_empty() {
1034            result.push(name);
1035        }
1036    }
1037
1038    result
1039}
1040
1041/// Split parameter string on commas, respecting nested brackets/generics.
1042fn split_params(s: &str) -> Vec<String> {
1043    let mut parts = Vec::new();
1044    let mut current = String::new();
1045    let mut depth = 0i32;
1046
1047    for ch in s.chars() {
1048        match ch {
1049            '<' | '[' | '{' | '(' => {
1050                depth += 1;
1051                current.push(ch);
1052            }
1053            '>' | ']' | '}' | ')' => {
1054                depth -= 1;
1055                current.push(ch);
1056            }
1057            ',' if depth == 0 => {
1058                parts.push(current.clone());
1059                current.clear();
1060            }
1061            _ => {
1062                current.push(ch);
1063            }
1064        }
1065    }
1066    if !current.is_empty() {
1067        parts.push(current);
1068    }
1069    parts
1070}
1071
1072/// Extract the parameter name from a single parameter declaration.
1073///
1074/// Handles:
1075/// - TS/JS: `name: Type`, `name = default`, `...name`, `name?: Type`
1076/// - Python: `name: Type`, `name=default`, `*args`, `**kwargs`
1077/// - Rust: `name: Type`, `mut name: Type`
1078/// - Go: `name Type`, `name, name2 Type`
1079fn extract_param_name(param: &str, lang: LangId) -> String {
1080    let trimmed = param.trim();
1081
1082    // Handle rest/spread params
1083    let working = if trimmed.starts_with("...") {
1084        &trimmed[3..]
1085    } else if trimmed.starts_with("**") {
1086        &trimmed[2..]
1087    } else if trimmed.starts_with('*') && lang == LangId::Python {
1088        &trimmed[1..]
1089    } else {
1090        trimmed
1091    };
1092
1093    // Rust: `mut name: Type` → strip `mut `
1094    let working = if lang == LangId::Rust && working.starts_with("mut ") {
1095        &working[4..]
1096    } else {
1097        working
1098    };
1099
1100    // Strip type annotation (`: Type`) and default values (`= default`)
1101    // Take only the name part — everything before `:`, `=`, or `?`
1102    let name = working
1103        .split(|c: char| c == ':' || c == '=')
1104        .next()
1105        .unwrap_or("")
1106        .trim();
1107
1108    // Strip trailing `?` (optional params in TS)
1109    let name = name.trim_end_matches('?');
1110
1111    // For Go, the name might be just `name Type` — take the first word
1112    if lang == LangId::Go && !name.contains(' ') {
1113        return name.to_string();
1114    }
1115    if lang == LangId::Go {
1116        return name.split_whitespace().next().unwrap_or("").to_string();
1117    }
1118
1119    name.to_string()
1120}
1121
1122// ---------------------------------------------------------------------------
1123// CallGraph
1124// ---------------------------------------------------------------------------
1125
1126/// Worktree-scoped call graph with lazy per-file construction.
1127///
1128/// Files are parsed and analyzed on first access, then cached. The graph
1129/// can resolve cross-file call edges using the import engine.
1130pub struct CallGraph {
1131    /// Cached per-file call data.
1132    data: HashMap<PathBuf, FileCallData>,
1133    /// Project root for relative path resolution.
1134    project_root: PathBuf,
1135}
1136
1137impl CallGraph {
1138    /// Create a new call graph for a project.
1139    pub fn new(project_root: PathBuf) -> Self {
1140        clear_workspace_package_cache();
1141        Self {
1142            data: HashMap::new(),
1143            project_root,
1144        }
1145    }
1146
1147    /// Get the project root directory.
1148    pub fn project_root(&self) -> &Path {
1149        &self.project_root
1150    }
1151
1152    fn resolve_cross_file_edge_with_exports<F, D>(
1153        full_callee: &str,
1154        short_name: &str,
1155        caller_file: &Path,
1156        import_block: &ImportBlock,
1157        mut file_exports_symbol: F,
1158        mut file_default_export_symbol: D,
1159    ) -> EdgeResolution
1160    where
1161        F: FnMut(&Path, &str) -> bool,
1162        D: FnMut(&Path) -> Option<String>,
1163    {
1164        let caller_dir = caller_file.parent().unwrap_or(Path::new("."));
1165        let disk = DiskFacts::new(caller_dir.ancestors().last().unwrap_or(caller_dir));
1166        let facts = &FactPaths {
1167            root: &disk.project_root,
1168            facts: &disk,
1169        };
1170
1171        // Rust uses `::` module paths rather than JS/TS specifiers. Keep this
1172        // branch gated to `.rs` callers so the existing JS/TS resolver below
1173        // remains unchanged.
1174        if is_rust_source_file(caller_file) {
1175            if let Some(target) = resolve_rust_cross_file_edge(
1176                full_callee,
1177                short_name,
1178                caller_file,
1179                import_block,
1180                &mut file_exports_symbol,
1181            ) {
1182                return EdgeResolution::Resolved {
1183                    file: target.file,
1184                    symbol: target.symbol,
1185                };
1186            }
1187        }
1188
1189        // Check namespace imports: "utils.foo" where utils is a namespace import
1190        if full_callee.contains('.') {
1191            let parts: Vec<&str> = full_callee.splitn(2, '.').collect();
1192            if parts.len() == 2 {
1193                let namespace = parts[0];
1194                let member = parts[1];
1195
1196                for imp in &import_block.imports {
1197                    if imp.namespace_import.as_deref() == Some(namespace) {
1198                        if let Some(resolved_path) =
1199                            resolve_module_path(caller_dir, &imp.module_path)
1200                        {
1201                            if let Some(target) = resolve_reexported_symbol(
1202                                &resolved_path,
1203                                member,
1204                                &mut file_exports_symbol,
1205                                &mut file_default_export_symbol,
1206                            ) {
1207                                return EdgeResolution::Resolved {
1208                                    file: target.file,
1209                                    symbol: target.symbol,
1210                                };
1211                            }
1212                        }
1213                    }
1214                }
1215            }
1216        }
1217
1218        // Check named imports (direct and aliased)
1219        for imp in &import_block.imports {
1220            // Direct named import: import { foo } from './utils'
1221            if imp.names.iter().any(|name| name == short_name) {
1222                if let Some(resolved_path) = resolve_module_path(caller_dir, &imp.module_path) {
1223                    let target = resolve_reexported_symbol(
1224                        &resolved_path,
1225                        short_name,
1226                        &mut file_exports_symbol,
1227                        &mut file_default_export_symbol,
1228                    )
1229                    .unwrap_or(ResolvedSymbol {
1230                        file: resolved_path,
1231                        symbol: short_name.to_owned(),
1232                    });
1233                    return EdgeResolution::Resolved {
1234                        file: target.file,
1235                        symbol: target.symbol,
1236                    };
1237                }
1238            }
1239
1240            // Default import: import foo from './utils'
1241            if imp.default_import.as_deref() == Some(short_name) {
1242                if let Some(resolved_path) = resolve_module_path(caller_dir, &imp.module_path) {
1243                    let target = resolve_reexported_symbol(
1244                        &resolved_path,
1245                        "default",
1246                        &mut file_exports_symbol,
1247                        &mut file_default_export_symbol,
1248                    )
1249                    .unwrap_or_else(|| ResolvedSymbol {
1250                        symbol: file_default_export_symbol(&resolved_path)
1251                            .unwrap_or_else(|| synthetic_default_symbol(&resolved_path)),
1252                        file: resolved_path,
1253                    });
1254                    return EdgeResolution::Resolved {
1255                        file: target.file,
1256                        symbol: target.symbol,
1257                    };
1258                }
1259            }
1260        }
1261
1262        // Check aliased imports by examining the raw import text.
1263        // ImportStatement.names stores the original name (foo), but the local code
1264        // uses the alias (bar). We need to parse `import { foo as bar }` to find
1265        // that `bar` maps to `foo`.
1266        if let Some((original_name, resolved_path)) =
1267            resolve_aliased_import(short_name, import_block, caller_dir)
1268        {
1269            let target = resolve_reexported_symbol(
1270                &resolved_path,
1271                &original_name,
1272                &mut file_exports_symbol,
1273                &mut file_default_export_symbol,
1274            )
1275            .unwrap_or(ResolvedSymbol {
1276                file: resolved_path,
1277                symbol: original_name,
1278            });
1279            return EdgeResolution::Resolved {
1280                file: target.file,
1281                symbol: target.symbol,
1282            };
1283        }
1284
1285        // Try barrel file re-exports: if any import points to an index file,
1286        // check if that file re-exports the symbol
1287        for imp in &import_block.imports {
1288            if let Some(resolved_path) = resolve_module_path(caller_dir, &imp.module_path) {
1289                // Check if the resolved path is a directory (barrel file)
1290                if resolved_path.is_dir() {
1291                    if let Some(index_path) = find_index_file(&resolved_path, facts) {
1292                        // Check if the index file exports this symbol
1293                        if file_exports_symbol(&index_path, short_name) {
1294                            return EdgeResolution::Resolved {
1295                                file: index_path,
1296                                symbol: short_name.to_owned(),
1297                            };
1298                        }
1299                    }
1300                } else if file_exports_symbol(&resolved_path, short_name) {
1301                    return EdgeResolution::Resolved {
1302                        file: resolved_path,
1303                        symbol: short_name.to_owned(),
1304                    };
1305                }
1306            }
1307        }
1308
1309        EdgeResolution::Unresolved {
1310            callee_name: short_name.to_owned(),
1311        }
1312    }
1313
1314    /// Get or build the call data for a file.
1315    pub fn build_file(&mut self, path: &Path) -> Result<&FileCallData, AftError> {
1316        let canon = self.canonicalize(path)?;
1317
1318        if !self.data.contains_key(&canon) {
1319            let file_data = build_file_data(&canon)?;
1320            self.data.insert(canon.clone(), file_data);
1321        }
1322
1323        Ok(&self.data[&canon])
1324    }
1325
1326    /// Resolve a cross-file call edge.
1327    ///
1328    /// Given a callee expression and the calling file's import block,
1329    /// determines which file and symbol the call targets.
1330    pub fn resolve_cross_file_edge(
1331        &mut self,
1332        full_callee: &str,
1333        short_name: &str,
1334        caller_file: &Path,
1335        import_block: &ImportBlock,
1336    ) -> EdgeResolution {
1337        let graph = RefCell::new(self);
1338        Self::resolve_cross_file_edge_with_exports(
1339            full_callee,
1340            short_name,
1341            caller_file,
1342            import_block,
1343            |path, symbol_name| graph.borrow_mut().file_exports_symbol(path, symbol_name),
1344            |path| graph.borrow_mut().file_default_export_symbol(path),
1345        )
1346    }
1347
1348    /// Check if a file exports a given symbol name.
1349    fn file_exports_symbol(&mut self, path: &Path, symbol_name: &str) -> bool {
1350        match self.build_file(path) {
1351            Ok(data) => data.exported_symbols.iter().any(|name| name == symbol_name),
1352            Err(_) => false,
1353        }
1354    }
1355
1356    fn file_default_export_symbol(&mut self, path: &Path) -> Option<String> {
1357        self.build_file(path)
1358            .ok()
1359            .and_then(|data| data.default_export_symbol.clone())
1360    }
1361
1362    /// Invalidate a file by removing its cached call data.
1363    pub fn invalidate_file(&mut self, path: &Path) {
1364        // Remove from data cache (try both as-is and canonicalized)
1365        self.data.remove(path);
1366        if let Ok(canon) = self.canonicalize(path) {
1367            self.data.remove(&canon);
1368        }
1369        clear_workspace_package_cache();
1370    }
1371
1372    /// Canonicalize a path, falling back to the original if canonicalization fails.
1373    fn canonicalize(&self, path: &Path) -> Result<PathBuf, AftError> {
1374        // If the path is relative, resolve it against project_root
1375        let full_path = if path.is_relative() {
1376            self.project_root.join(path)
1377        } else {
1378            path.to_path_buf()
1379        };
1380
1381        // Try canonicalize, fall back to the full path
1382        Ok(std::fs::canonicalize(&full_path).unwrap_or(full_path))
1383    }
1384}
1385
1386// ---------------------------------------------------------------------------
1387// File-level building
1388// ---------------------------------------------------------------------------
1389
1390/// Build call data for a single file.
1391pub fn build_file_data(path: &Path) -> Result<FileCallData, AftError> {
1392    let source =
1393        crate::project_content::read_to_string(path).map_err(|e| AftError::FileNotFound {
1394            path: format!("{}: {}", path.display(), e),
1395        })?;
1396
1397    build_file_data_from_source(path, &source)
1398}
1399
1400pub fn build_file_data_from_source(path: &Path, source: &str) -> Result<FileCallData, AftError> {
1401    let lang =
1402        detect_language_from_source(path, source).ok_or_else(|| AftError::InvalidRequest {
1403            message: format!("unsupported file for call graph: {}", path.display()),
1404        })?;
1405    build_file_data_from_source_with_lang(path, source, lang)
1406}
1407
1408#[derive(Debug)]
1409struct SymbolCallRange {
1410    symbol_index: usize,
1411    byte_start: usize,
1412    byte_end: usize,
1413}
1414
1415test_support_visibility! {
1416type SourceLineIndex = crate::callgraph_store::LineIndex;
1417}
1418
1419test_support_visibility! {
1420fn collect_calls_by_symbol<'tree>(
1421    source: &str,
1422    root: Node<'tree>,
1423    lang: LangId,
1424    symbols: &[Symbol],
1425    line_index: &SourceLineIndex,
1426    nav: impl Nav<'tree>,
1427) -> HashMap<String, Vec<CallSite>> {
1428    attribute_sites_to_symbols(
1429        line_index,
1430        symbols,
1431        extract_calls_full_with(source, root, 0, source.len(), lang, nav),
1432        lang,
1433    )
1434}
1435}
1436
1437/// Separate calls written directly in a `macro_rules!` template from ordinary
1438/// calls. A call inside an item that the template itself defines (a method in
1439/// a macro that stamps out a whole `impl` body) stays an ordinary call of that
1440/// item. Any other call in a template belongs to the macro, keyed `name!`,
1441/// because attributing it to the code around the definition would name a
1442/// caller that never runs it.
1443fn split_macro_body_calls(
1444    line_index: &SourceLineIndex,
1445    symbols: &[Symbol],
1446    raw_calls: Vec<crate::calls::CallTuple>,
1447    bodies: &[crate::calls::RustMacroBody],
1448) -> (Vec<crate::calls::CallTuple>, HashMap<String, Vec<CallSite>>) {
1449    let mut body_calls: HashMap<String, Vec<CallSite>> = HashMap::new();
1450    if bodies.is_empty() {
1451        return (raw_calls, body_calls);
1452    }
1453    let symbol_ranges = symbols
1454        .iter()
1455        .map(|symbol| {
1456            (
1457                line_index.byte_offset(symbol.range.start_line, symbol.range.start_col),
1458                line_index.byte_offset(symbol.range.end_line, symbol.range.end_col),
1459            )
1460        })
1461        .collect::<Vec<_>>();
1462    // For each template, the items it defines itself.
1463    let body_symbols = bodies
1464        .iter()
1465        .map(|body| {
1466            symbol_ranges
1467                .iter()
1468                .copied()
1469                .filter(|(start, end)| body.byte_start <= *start && *end <= body.byte_end)
1470                .collect::<Vec<_>>()
1471        })
1472        .collect::<Vec<_>>();
1473
1474    let mut ordinary = Vec::with_capacity(raw_calls.len());
1475    for call in raw_calls {
1476        let (_, _, _, call_start, call_end) = call;
1477        // Templates can nest; the innermost one holding the call owns it.
1478        let innermost = bodies
1479            .iter()
1480            .enumerate()
1481            .filter(|(_, body)| body.byte_start <= call_start && call_end <= body.byte_end)
1482            .min_by_key(|(_, body)| body.byte_end - body.byte_start);
1483        let Some((body_index, body)) = innermost else {
1484            ordinary.push(call);
1485            continue;
1486        };
1487        let inside_defined_item = body_symbols[body_index]
1488            .iter()
1489            .any(|(start, end)| *start <= call_start && call_end <= *end);
1490        if inside_defined_item {
1491            ordinary.push(call);
1492            continue;
1493        }
1494        let (full, short, line, byte_start, byte_end) = call;
1495        body_calls
1496            .entry(format!("{}!", body.name))
1497            .or_default()
1498            .push(CallSite {
1499                kind: CallSiteKind::Call,
1500                callee_name: short,
1501                full_callee: full,
1502                line,
1503                byte_start,
1504                byte_end,
1505            });
1506    }
1507    (ordinary, body_calls)
1508}
1509
1510fn collect_rust_value_refs_by_symbol<'tree>(
1511    source: &str,
1512    root: Node<'tree>,
1513    symbols: &[Symbol],
1514    line_index: &SourceLineIndex,
1515    nav: impl Nav<'tree>,
1516) -> HashMap<String, Vec<CallSite>> {
1517    let mut references = attribute_sites_to_symbols(
1518        line_index,
1519        symbols,
1520        extract_rust_value_references_with(source, root, nav),
1521        LangId::Rust,
1522    );
1523    // A function item remains a reference whether it is passed to an API or
1524    // stored for later use. The resolver rejects non-callable value candidates.
1525    for site in references.values_mut().flatten() {
1526        site.kind = CallSiteKind::CallbackReference;
1527    }
1528    references
1529}
1530
1531fn rust_item_is_test<'tree>(
1532    source: &str,
1533    root: tree_sitter::Node<'tree>,
1534    byte: usize,
1535    nav: impl Nav<'tree>,
1536) -> Option<bool> {
1537    if root.has_error() {
1538        return None;
1539    }
1540    let mut node = root.descendant_for_byte_range(byte, byte)?;
1541    let mut item = node;
1542    while let Some(parent) = nav.parent(item) {
1543        if nav.kind(item) == "attribute_item" {
1544            while let Some(next) = nav.next_named_sibling(item) {
1545                item = next;
1546                if nav.kind(item) != "attribute_item" && !item.is_extra() {
1547                    break;
1548                }
1549            }
1550            node = item;
1551            break;
1552        }
1553        item = parent;
1554    }
1555    while let Some(parent) = nav.parent(node) {
1556        let mut sibling = nav.prev_named_sibling(node);
1557        while let Some(attribute) =
1558            sibling.filter(|n| nav.kind(*n) == "attribute_item" || n.is_extra())
1559        {
1560            let text = source[attribute.byte_range()]
1561                .split_whitespace()
1562                .collect::<String>();
1563            if text == "#[test]" || text == "#[cfg(test)]" {
1564                return Some(true);
1565            }
1566            sibling = nav.prev_named_sibling(attribute);
1567        }
1568        node = parent;
1569    }
1570    Some(false)
1571}
1572
1573fn attribute_sites_to_symbols(
1574    line_index: &SourceLineIndex,
1575    symbols: &[Symbol],
1576    raw_sites: Vec<(String, String, u32, usize, usize)>,
1577    lang: LangId,
1578) -> HashMap<String, Vec<CallSite>> {
1579    let mut ranges = symbols
1580        .iter()
1581        .enumerate()
1582        .map(|(symbol_index, symbol)| SymbolCallRange {
1583            symbol_index,
1584            byte_start: line_index.byte_offset(symbol.range.start_line, symbol.range.start_col),
1585            byte_end: line_index.byte_offset(symbol.range.end_line, symbol.range.end_col),
1586        })
1587        .collect::<Vec<_>>();
1588    ranges.sort_by(|left, right| {
1589        left.byte_start
1590            .cmp(&right.byte_start)
1591            .then_with(|| left.symbol_index.cmp(&right.symbol_index))
1592    });
1593
1594    let mut sites_by_symbol = vec![Vec::new(); symbols.len()];
1595    let mut top_level_sites = Vec::new();
1596    let mut active_ranges = Vec::<usize>::new();
1597    let mut next_range = 0usize;
1598
1599    for (full, short, line, byte_start, byte_end) in raw_sites {
1600        // AST preorder gives nondecreasing call starts. Expire by start only:
1601        // an outer call can end past a range that still contains a nested call.
1602        active_ranges.retain(|range_index| ranges[*range_index].byte_end > byte_start);
1603        while next_range < ranges.len() && ranges[next_range].byte_start <= byte_start {
1604            if ranges[next_range].byte_end > byte_start {
1605                active_ranges.push(next_range);
1606            }
1607            next_range += 1;
1608        }
1609
1610        let site = CallSite {
1611            kind: CallSiteKind::Call,
1612            callee_name: short,
1613            full_callee: full,
1614            line,
1615            byte_start,
1616            byte_end,
1617        };
1618        let mut attributed = false;
1619        for range_index in &active_ranges {
1620            let range = &ranges[*range_index];
1621            // Method bodies execute when the method is called, not when its class is constructed.
1622            if symbols[range.symbol_index].kind == SymbolKind::Class
1623                && active_ranges.iter().any(|index| {
1624                    let callable = &ranges[*index];
1625                    range.byte_start <= callable.byte_start
1626                        && callable.byte_end <= range.byte_end
1627                        && byte_end <= callable.byte_end
1628                        && matches!(
1629                            symbols[callable.symbol_index].kind,
1630                            SymbolKind::Function | SymbolKind::Method
1631                        )
1632                })
1633            {
1634                continue;
1635            }
1636            if byte_end <= range.byte_end {
1637                sites_by_symbol[range.symbol_index].push(site.clone());
1638                attributed = true;
1639            }
1640        }
1641        if !attributed {
1642            top_level_sites.push(site);
1643        }
1644    }
1645
1646    let mut calls_by_symbol = HashMap::new();
1647    for (symbol, sites) in symbols.iter().zip(sites_by_symbol) {
1648        if !sites.is_empty() {
1649            if lang == LangId::Go && symbol.kind == SymbolKind::Function && symbol.name == "init" {
1650                // Go runs every init declaration in a file. They share a
1651                // file-local owner, so retain all bodies rather than the last.
1652                calls_by_symbol
1653                    .entry(symbol_identity(symbol))
1654                    .or_insert_with(Vec::new)
1655                    .extend(sites);
1656            } else {
1657                calls_by_symbol.insert(symbol_identity(symbol), sites);
1658            }
1659        }
1660    }
1661    if !top_level_sites.is_empty() {
1662        calls_by_symbol.insert(TOP_LEVEL_SYMBOL.to_string(), top_level_sites);
1663    }
1664    calls_by_symbol
1665}
1666
1667pub fn build_file_data_from_source_with_lang(
1668    path: &Path,
1669    source: &str,
1670    lang: LangId,
1671) -> Result<FileCallData, AftError> {
1672    let (tree, lang) = crate::parser::parse_resolved_source(path, source, lang)?;
1673
1674    let line_index = SourceLineIndex::new(source);
1675    build_file_data_from_tree(path, source, lang, &tree, &line_index)
1676}
1677
1678#[derive(Default)]
1679struct CallSiteSyntax {
1680    construction: bool,
1681    argument: bool,
1682}
1683
1684#[cfg(any(test, feature = "test-support"))]
1685thread_local! {
1686    pub static CALL_SITE_KIND_NODE_VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1687}
1688
1689fn classify_call_site_kinds<'tree>(
1690    root: tree_sitter::Node<'tree>,
1691    calls: &mut HashMap<String, Vec<CallSite>>,
1692    value_refs: &mut HashMap<String, Vec<CallSite>>,
1693    nav: impl Nav<'tree>,
1694) {
1695    let mut syntax_by_span = calls
1696        .values()
1697        .chain(value_refs.values())
1698        .flatten()
1699        .map(|site| ((site.byte_start, site.byte_end), CallSiteSyntax::default()))
1700        .collect::<rustc_hash::FxHashMap<_, _>>();
1701    if syntax_by_span.is_empty() {
1702        return;
1703    }
1704
1705    // Looking every range up from the root repeats long descents on nested
1706    // calls. One walk keeps each node's parent kind, the argument context.
1707    nav.walk_with_parent_kind(root, |node, kind, parent_kind| {
1708        #[cfg(any(test, feature = "test-support"))]
1709        CALL_SITE_KIND_NODE_VISITS.with(|visits| visits.set(visits.get() + 1));
1710        if let Some(syntax) = syntax_by_span.get_mut(&(node.start_byte(), node.end_byte())) {
1711            // Equal-span descendants overwrite ancestors, matching the deepest range lookup.
1712            syntax.construction = kind == "new_expression";
1713            syntax.argument = matches!(parent_kind, Some("arguments" | "argument_list"));
1714        }
1715    });
1716    for site in calls.values_mut().flatten() {
1717        if syntax_by_span[&(site.byte_start, site.byte_end)].construction {
1718            site.kind = CallSiteKind::Construction;
1719        }
1720    }
1721    for site in value_refs.values_mut().flatten() {
1722        if syntax_by_span[&(site.byte_start, site.byte_end)].argument {
1723            site.kind = CallSiteKind::CallbackReference;
1724        }
1725    }
1726}
1727
1728/// Reuse a caller-owned syntax tree and position index during blob extraction.
1729pub fn build_file_data_from_tree(
1730    path: &Path,
1731    source: &str,
1732    lang: LangId,
1733    tree: &tree_sitter::Tree,
1734    line_index: &SourceLineIndex,
1735) -> Result<FileCallData, AftError> {
1736    build_file_data_from_tree_observed(path, source, lang, tree, line_index, false, Direct, None)
1737        .map(|(data, _)| data)
1738}
1739
1740/// Like [`build_file_data_from_tree`], with `index`, the tree's syntax
1741/// index, answering every walk and parent or sibling lookup. With
1742/// `outline`, also fills it with the file's symbols as the parser extracts
1743/// them, before the call graph qualifies, adds or merges any.
1744pub fn build_file_data_from_index<'tree>(
1745    path: &Path,
1746    source: &str,
1747    lang: LangId,
1748    tree: &'tree tree_sitter::Tree,
1749    line_index: &SourceLineIndex,
1750    index: &SyntaxIndex<'tree>,
1751    outline: Option<&mut Vec<Symbol>>,
1752) -> Result<FileCallData, AftError> {
1753    build_file_data_from_tree_observed(path, source, lang, tree, line_index, false, index, outline)
1754        .map(|(data, _)| data)
1755}
1756
1757#[allow(clippy::too_many_arguments)]
1758fn build_file_data_from_tree_observed<'tree>(
1759    path: &Path,
1760    source: &str,
1761    lang: LangId,
1762    tree: &'tree tree_sitter::Tree,
1763    line_index: &SourceLineIndex,
1764    collect_objects: bool,
1765    nav: impl Nav<'tree>,
1766    outline: Option<&mut Vec<Symbol>>,
1767) -> Result<
1768    (
1769        FileCallData,
1770        Option<crate::callgraph_store::join::ParseBlob>,
1771    ),
1772    AftError,
1773> {
1774    // Parse imports
1775    let python = (lang == LangId::Python).then(|| python::extract(source, tree.root_node()));
1776    let (import_block, python_bindings) = if let Some(python) = &python {
1777        (python.imports.clone(), python.bindings.clone())
1778    } else {
1779        (imports::parse_imports(&source, &tree, lang), Vec::new())
1780    };
1781
1782    // Get symbols (for call site extraction and export detection)
1783    let mut symbols = crate::parser::extract_symbols_from_tree_with(&source, &tree, lang, nav)?;
1784    if let Some(outline) = outline {
1785        outline.clone_from(&symbols);
1786    }
1787    if lang == LangId::Luau {
1788        symbols.extend(
1789            crate::luau::exports(source, tree.root_node())
1790                .into_values()
1791                .filter_map(|export| export.inline)
1792                .map(|declaration| crate::parser::luau_symbol(source, declaration)),
1793        );
1794    }
1795    let object_nodes = crate::callgraph_store::join::dispatch::complete_typescript_symbols(
1796        source,
1797        lang,
1798        tree.root_node(),
1799        &mut symbols,
1800        nav,
1801    );
1802    let mut rust_qualified = HashMap::new();
1803    if lang == LangId::Rust {
1804        rust_qualified = qualify_rust_impl_methods(source, tree.root_node(), &mut symbols, nav);
1805        symbols.extend(rust_trait_members(source, tree.root_node(), nav));
1806    }
1807
1808    let root = tree.root_node();
1809    let mut macro_body_calls_by_macro = HashMap::new();
1810    let mut macro_mentions_by_symbol = HashMap::new();
1811    let mut calls_by_symbol = if lang == LangId::Rust {
1812        let (raw_calls, macro_facts) = crate::calls::extract_rust_calls_with_macro_facts_with(
1813            &source,
1814            root,
1815            0,
1816            source.len(),
1817            nav,
1818        );
1819        let (raw_calls, body_calls) =
1820            split_macro_body_calls(line_index, &symbols, raw_calls, &macro_facts.bodies);
1821        macro_body_calls_by_macro = body_calls;
1822        macro_mentions_by_symbol =
1823            attribute_sites_to_symbols(line_index, &symbols, macro_facts.unparsed_mentions, lang);
1824        attribute_sites_to_symbols(line_index, &symbols, raw_calls, lang)
1825    } else {
1826        collect_calls_by_symbol(&source, root, lang, &symbols, line_index, nav)
1827    };
1828    if let Some(python) = &python {
1829        let mut owned = HashMap::<String, Vec<CallSite>>::new();
1830        let mut seen = HashSet::new();
1831        for site in calls_by_symbol.into_values().flatten() {
1832            if seen.insert((site.byte_start, site.byte_end)) {
1833                if let Some(owners) = python.owners.get(&site.byte_start) {
1834                    for owner in owners {
1835                        owned.entry(owner.clone()).or_default().push(site.clone());
1836                    }
1837                }
1838            }
1839        }
1840        for sites in owned.values_mut() {
1841            sites.sort_by_key(|site| (site.byte_start, site.byte_end));
1842        }
1843        calls_by_symbol = owned;
1844    }
1845    let mut value_refs_by_symbol = if lang == LangId::Rust {
1846        collect_rust_value_refs_by_symbol(&source, root, &symbols, line_index, nav)
1847    } else if lang == LangId::Go {
1848        attribute_sites_to_symbols(
1849            line_index,
1850            &symbols,
1851            crate::calls::extract_go_value_references(source, root),
1852            lang,
1853        )
1854    } else if matches!(lang, LangId::TypeScript | LangId::Tsx | LangId::JavaScript) {
1855        attribute_sites_to_symbols(
1856            line_index,
1857            &symbols,
1858            crate::calls::extract_js_callback_references_with(source, root, nav),
1859            lang,
1860        )
1861    } else {
1862        HashMap::new()
1863    };
1864
1865    let default_export = find_default_export(&source, root, path, lang, nav);
1866
1867    if let Some(default_export) = &default_export {
1868        if default_export.synthetic {
1869            let byte_start = default_export.node.byte_range().start;
1870            let byte_end = default_export.node.byte_range().end;
1871            let raw_calls = extract_calls_full_with(&source, root, byte_start, byte_end, lang, nav);
1872            let sites: Vec<CallSite> = raw_calls
1873                .into_iter()
1874                .filter(|(_, short, _, _, _)| *short != default_export.symbol)
1875                .map(
1876                    |(full, short, line, call_byte_start, call_byte_end)| CallSite {
1877                        kind: CallSiteKind::Call,
1878                        callee_name: short,
1879                        full_callee: full,
1880                        line,
1881                        byte_start: call_byte_start,
1882                        byte_end: call_byte_end,
1883                    },
1884                )
1885                .collect();
1886            if !sites.is_empty() {
1887                calls_by_symbol.insert(default_export.symbol.clone(), sites);
1888            }
1889        }
1890    }
1891
1892    classify_call_site_kinds(root, &mut calls_by_symbol, &mut value_refs_by_symbol, nav);
1893
1894    // Collect exported symbol names
1895    let mut exported_symbols: Vec<String> = symbols
1896        .iter()
1897        .filter(|s| s.exported)
1898        .map(|s| s.name.clone())
1899        .collect();
1900    if lang == LangId::Luau {
1901        // A symbol shown in the outline need not belong to the returned table.
1902        exported_symbols = crate::luau::exports(source, root).into_keys().collect();
1903    }
1904    if let Some(default_export) = &default_export {
1905        if !exported_symbols
1906            .iter()
1907            .any(|name| name == &default_export.symbol)
1908        {
1909            exported_symbols.push(default_export.symbol.clone());
1910        }
1911    }
1912
1913    let rust_attribute_entry_points = if lang == LangId::Rust {
1914        crate::parser::rust_attribute_entry_points_with(&source, root, nav)
1915            .into_iter()
1916            .map(|entry| {
1917                let name = rust_qualified
1918                    .get(&entry.scoped_name)
1919                    .and_then(|name| name.clone())
1920                    .unwrap_or(entry.scoped_name);
1921                (name, entry.attribute.to_string())
1922            })
1923            .collect::<HashMap<_, _>>()
1924    } else {
1925        HashMap::new()
1926    };
1927
1928    // Every Go variable of a main package initializes with the program.
1929    let go_main_package = lang == LangId::Go
1930        && root.named_children(&mut root.walk()).any(|n| {
1931            n.kind() == "package_clause" && source[n.byte_range()].trim() == "package main"
1932        });
1933    let python_main = lang == LangId::Python && python_runs_as_main(source, root);
1934    let go_init = lang == LangId::Go && go_declares_init(source, root);
1935    // Build per-symbol metadata for entry point detection
1936    let mut symbol_metadata: HashMap<String, SymbolMeta> = symbols
1937        .iter()
1938        .map(|s| {
1939            let identity = symbol_identity(s);
1940            (
1941                identity.clone(),
1942                SymbolMeta {
1943                    is_test: if lang == LangId::Rust {
1944                        rust_item_is_test(
1945                            source,
1946                            root,
1947                            line_index.byte_offset(s.range.start_line, s.range.start_col),
1948                            nav,
1949                        )
1950                    } else {
1951                        Some(false)
1952                    },
1953                    kind: s.kind.clone(),
1954                    exported: s.exported,
1955                    signature: s.signature.clone(),
1956                    line: s.range.start_line + 1,
1957                    range: s.range.clone(),
1958                    entry_point_attribute: rust_attribute_entry_points
1959                        .get(&identity)
1960                        .cloned()
1961                        .or_else(|| {
1962                            (go_main_package && s.kind == SymbolKind::Variable)
1963                                .then(|| "go_package_initializer".to_string())
1964                        }),
1965                    program_start: starts_program(
1966                        lang,
1967                        &identity,
1968                        &s.kind,
1969                        go_main_package,
1970                        go_init,
1971                    ),
1972                },
1973            )
1974        })
1975        .collect();
1976    if let Some(default_export) = &default_export {
1977        symbol_metadata
1978            .entry(default_export.symbol.clone())
1979            .or_insert_with(|| SymbolMeta {
1980                is_test: Some(false),
1981                kind: default_export.kind.clone(),
1982                exported: true,
1983                signature: Some(first_line_signature(&source, &default_export.node)),
1984                line: default_export.node.start_position().row as u32 + 1,
1985                range: crate::parser::node_range(&default_export.node),
1986                entry_point_attribute: None,
1987                program_start: false,
1988            });
1989    }
1990    // Template calls have a real macro owner. The owner is not a root: only
1991    // an invocation from reachable code can make its outgoing edges live.
1992    if lang == LangId::Rust {
1993        // A later definition of the same macro name replaces an earlier one,
1994        // in the order of a stack walk over named children.
1995        nav.walk_named(root, |node, kind| {
1996            if kind == "macro_definition" {
1997                if let Some(name) = node.child_by_field_name("name") {
1998                    symbol_metadata.insert(
1999                        format!("{}!", &source[name.byte_range()]),
2000                        SymbolMeta {
2001                            is_test: rust_item_is_test(source, root, node.start_byte(), nav),
2002                            kind: SymbolKind::Function,
2003                            exported: false,
2004                            signature: None,
2005                            line: node.start_position().row as u32 + 1,
2006                            range: crate::parser::node_range(&node),
2007                            entry_point_attribute: None,
2008                            program_start: false,
2009                        },
2010                    );
2011                }
2012            }
2013            true
2014        });
2015    }
2016    if calls_by_symbol.contains_key(TOP_LEVEL_SYMBOL)
2017        || value_refs_by_symbol.contains_key(TOP_LEVEL_SYMBOL)
2018    {
2019        symbol_metadata
2020            .entry(TOP_LEVEL_SYMBOL.to_string())
2021            .or_insert(SymbolMeta {
2022                is_test: Some(false),
2023                kind: SymbolKind::Function,
2024                exported: false,
2025                signature: None,
2026                line: 1,
2027                range: Range {
2028                    start_line: 0,
2029                    start_col: 0,
2030                    end_line: 0,
2031                    end_col: 0,
2032                },
2033                entry_point_attribute: None,
2034                program_start: python_main,
2035            });
2036    }
2037    if lang == LangId::Go {
2038        symbol_metadata.insert(
2039            "<go-package-init>".to_string(),
2040            SymbolMeta {
2041                is_test: Some(false),
2042                kind: SymbolKind::Function,
2043                exported: false,
2044                signature: None,
2045                line: 1,
2046                range: Range {
2047                    start_line: 0,
2048                    start_col: 0,
2049                    end_line: 0,
2050                    end_col: 0,
2051                },
2052                entry_point_attribute: None,
2053                program_start: false,
2054            },
2055        );
2056    }
2057
2058    let data = FileCallData {
2059        calls_by_symbol,
2060        value_refs_by_symbol,
2061        macro_body_calls_by_macro,
2062        macro_mentions_by_symbol,
2063        exported_symbols,
2064        symbol_metadata,
2065        default_export_symbol: default_export.map(|export| export.symbol),
2066        import_block,
2067        python_bindings,
2068        lang,
2069    };
2070    let objects = if collect_objects {
2071        crate::callgraph_store::join::dispatch::typescript_objects_from_data(
2072            source,
2073            lang,
2074            &object_nodes,
2075            &data,
2076        )
2077    } else {
2078        None
2079    };
2080    Ok((data, objects))
2081}
2082
2083/// `name` qualified by the inline modules around `node`.
2084pub fn rust_module_qualified_name<'tree>(
2085    node: Node<'tree>,
2086    source: &str,
2087    name: &str,
2088    nav: impl Nav<'tree>,
2089) -> String {
2090    let mut modules = Vec::new();
2091    let mut parent = nav.parent(node);
2092    while let Some(ancestor) = parent {
2093        if nav.kind(ancestor) == "mod_item" {
2094            if let Some(name) = ancestor.child_by_field_name("name") {
2095                modules.push(node_text(name, source));
2096            }
2097        }
2098        parent = nav.parent(ancestor);
2099    }
2100    modules.reverse();
2101    modules.push(name.to_string());
2102    modules.join("::")
2103}
2104
2105// Same-named types in separate inline modules must not share method identities.
2106fn qualify_rust_impl_methods<'tree>(
2107    source: &str,
2108    root: Node<'tree>,
2109    symbols: &mut [Symbol],
2110    nav: impl Nav<'tree>,
2111) -> HashMap<String, Option<String>> {
2112    let mut types = HashSet::new();
2113    nav.walk_named(root, |node, kind| {
2114        if matches!(
2115            kind,
2116            "struct_item" | "enum_item" | "trait_item" | "type_item"
2117        ) {
2118            if let Some(name) = node.child_by_field_name("name") {
2119                types.insert(rust_module_qualified_name(
2120                    node,
2121                    source,
2122                    &node_text(name, source),
2123                    nav,
2124                ));
2125            }
2126        }
2127        true
2128    });
2129    let mut scopes = HashMap::new();
2130    nav.walk_named(root, |node, kind| {
2131        if kind == "impl_item" {
2132            let declared_here = ["type", "trait"]
2133                .iter()
2134                .filter_map(|field| node.child_by_field_name(field))
2135                .any(|ty| {
2136                    let name = node_text(ty, source);
2137                    let base = name.split('<').next().unwrap_or(&name);
2138                    types.contains(&rust_module_qualified_name(node, source, base, nav))
2139                });
2140            if !declared_here {
2141                // Nothing under an impl of a type declared elsewhere is
2142                // qualified, nested impls included.
2143                return false;
2144            }
2145            if let Some(body) = node.child_by_field_name("body") {
2146                for method in body
2147                    .named_children(&mut body.walk())
2148                    .filter(|n| n.kind() == "function_item")
2149                {
2150                    if let Some(name) = method.child_by_field_name("name") {
2151                        let prefix = rust_module_qualified_name(node, source, "", nav);
2152                        scopes.insert(
2153                            (
2154                                method.end_position().row as u32,
2155                                method.end_position().column as u32,
2156                                node_text(name, source),
2157                            ),
2158                            prefix,
2159                        );
2160                    }
2161                }
2162            }
2163        }
2164        true
2165    });
2166    let mut translated = HashMap::new();
2167    for symbol in symbols.iter_mut().filter(|s| s.kind == SymbolKind::Method) {
2168        if let Some(prefix) = scopes.get(&(
2169            symbol.range.end_line,
2170            symbol.range.end_col,
2171            symbol.name.clone(),
2172        )) {
2173            if !prefix.is_empty() {
2174                let old = symbol_identity(symbol);
2175                let mut scope = prefix
2176                    .trim_end_matches("::")
2177                    .split("::")
2178                    .map(str::to_string)
2179                    .collect::<Vec<_>>();
2180                scope.extend(symbol.scope_chain.clone());
2181                symbol.scope_chain = scope;
2182                let new = symbol_identity(symbol);
2183                translated
2184                    .entry(old)
2185                    .and_modify(|name| *name = None)
2186                    .or_insert(Some(new));
2187            }
2188        }
2189    }
2190    translated
2191}
2192
2193pub fn rust_trait_members<'tree>(
2194    source: &str,
2195    root: Node<'tree>,
2196    nav: impl Nav<'tree>,
2197) -> Vec<Symbol> {
2198    let mut symbols = Vec::new();
2199    nav.walk_named(root, |node, kind| {
2200        if kind == "trait_item" {
2201            if let (Some(name), Some(body)) = (
2202                node.child_by_field_name("name"),
2203                node.child_by_field_name("body"),
2204            ) {
2205                let name = node_text(name, source);
2206                let mut scope = Vec::new();
2207                let mut parent = nav.parent(node);
2208                while let Some(ancestor) = parent {
2209                    if nav.kind(ancestor) == "mod_item" {
2210                        if let Some(module) = ancestor.child_by_field_name("name") {
2211                            scope.push(node_text(module, source));
2212                        }
2213                    }
2214                    parent = nav.parent(ancestor);
2215                }
2216                scope.reverse();
2217                scope.push(name.clone());
2218                for method in body.named_children(&mut body.walk()) {
2219                    if !matches!(method.kind(), "function_item" | "function_signature_item") {
2220                        continue;
2221                    }
2222                    let Some(method_name) = method.child_by_field_name("name") else {
2223                        continue;
2224                    };
2225                    let end = method
2226                        .child_by_field_name("body")
2227                        .map_or(method.end_byte(), |body| body.start_byte());
2228                    symbols.push(Symbol {
2229                        name: node_text(method_name, source),
2230                        kind: SymbolKind::Method,
2231                        range: crate::symbols::Range {
2232                            start_line: method.start_position().row as u32,
2233                            start_col: method.start_position().column as u32,
2234                            end_line: method.end_position().row as u32,
2235                            end_col: method.end_position().column as u32,
2236                        },
2237                        signature: Some(
2238                            source[method.start_byte()..end]
2239                                .trim()
2240                                .trim_end_matches(';')
2241                                .to_string(),
2242                        ),
2243                        scope_chain: scope.clone(),
2244                        // Members are reached through the trait, not imported from the module.
2245                        exported: false,
2246                        parent: Some(name.clone()),
2247                    });
2248                }
2249            }
2250        }
2251        true
2252    });
2253    symbols
2254}
2255
2256#[derive(Debug, Clone)]
2257struct DefaultExport<'tree> {
2258    symbol: String,
2259    synthetic: bool,
2260    kind: SymbolKind,
2261    node: Node<'tree>,
2262}
2263
2264fn find_default_export<'tree>(
2265    source: &str,
2266    root: Node<'tree>,
2267    path: &Path,
2268    lang: LangId,
2269    nav: impl Nav<'tree>,
2270) -> Option<DefaultExport<'tree>> {
2271    if !matches!(lang, LangId::TypeScript | LangId::Tsx | LangId::JavaScript) {
2272        return None;
2273    }
2274    // The first export statement in preorder that names a default export.
2275    let mut found = None;
2276    nav.walk(root, |node, kind| {
2277        if found.is_some() {
2278            return false;
2279        }
2280        if kind == "export_statement" {
2281            found = default_export_from_statement(source, node, path);
2282        }
2283        found.is_none()
2284    });
2285    found
2286}
2287
2288fn default_export_from_statement<'tree>(
2289    source: &str,
2290    node: Node<'tree>,
2291    path: &Path,
2292) -> Option<DefaultExport<'tree>> {
2293    let mut cursor = node.walk();
2294    if !cursor.goto_first_child() {
2295        return None;
2296    }
2297
2298    let mut saw_default = false;
2299    loop {
2300        let child = cursor.node();
2301        match child.kind() {
2302            "default" => saw_default = true,
2303            "function_declaration" | "generator_function_declaration" | "class_declaration"
2304                if saw_default =>
2305            {
2306                if let Some(name_node) = child.child_by_field_name("name") {
2307                    return Some(DefaultExport {
2308                        symbol: source[name_node.byte_range()].to_string(),
2309                        synthetic: false,
2310                        kind: default_export_kind(&child),
2311                        node: child,
2312                    });
2313                }
2314                return Some(DefaultExport {
2315                    symbol: synthetic_default_symbol(path),
2316                    synthetic: true,
2317                    kind: default_export_kind(&child),
2318                    node: child,
2319                });
2320            }
2321            "arrow_function"
2322            | "function"
2323            | "function_expression"
2324            | "class"
2325            | "class_expression"
2326                if saw_default =>
2327            {
2328                return Some(DefaultExport {
2329                    symbol: synthetic_default_symbol(path),
2330                    synthetic: true,
2331                    kind: default_export_kind(&child),
2332                    node: child,
2333                });
2334            }
2335            "identifier" | "type_identifier" | "property_identifier" if saw_default => {
2336                return Some(DefaultExport {
2337                    symbol: source[child.byte_range()].to_string(),
2338                    synthetic: false,
2339                    kind: SymbolKind::Function,
2340                    node: child,
2341                });
2342            }
2343            _ => {}
2344        }
2345        if !cursor.goto_next_sibling() {
2346            break;
2347        }
2348    }
2349
2350    None
2351}
2352
2353fn default_export_kind(node: &Node) -> SymbolKind {
2354    if node.kind().contains("class") {
2355        SymbolKind::Class
2356    } else {
2357        SymbolKind::Function
2358    }
2359}
2360
2361fn synthetic_default_symbol(path: &Path) -> String {
2362    let file_name = path
2363        .file_name()
2364        .and_then(|name| name.to_str())
2365        .unwrap_or("unknown");
2366    format!("<default:{file_name}>")
2367}
2368
2369fn first_line_signature(source: &str, node: &Node) -> String {
2370    let text = &source[node.byte_range()];
2371    let first_line = text.lines().next().unwrap_or(text);
2372    first_line
2373        .trim_end()
2374        .trim_end_matches('{')
2375        .trim_end()
2376        .to_string()
2377}
2378
2379fn node_text(node: tree_sitter::Node, source: &str) -> String {
2380    source[node.start_byte()..node.end_byte()].to_string()
2381}
2382
2383/// Find a direct child node by kind name.
2384fn find_child_by_kind<'a>(
2385    node: tree_sitter::Node<'a>,
2386    kind: &str,
2387) -> Option<tree_sitter::Node<'a>> {
2388    let mut cursor = node.walk();
2389    if cursor.goto_first_child() {
2390        loop {
2391            if cursor.node().kind() == kind {
2392                return Some(cursor.node());
2393            }
2394            if !cursor.goto_next_sibling() {
2395                break;
2396            }
2397        }
2398    }
2399    None
2400}
2401
2402#[cfg(any(test, feature = "test-support"))]
2403#[derive(Debug, Clone)]
2404pub struct CallSiteWithRange {
2405    pub full: String,
2406    pub short: String,
2407    pub line: u32,
2408    pub byte_start: usize,
2409    pub byte_end: usize,
2410}
2411
2412#[cfg(any(test, feature = "test-support"))]
2413pub fn collect_calls_full_with_ranges(
2414    root: tree_sitter::Node,
2415    source: &str,
2416    byte_start: usize,
2417    byte_end: usize,
2418    lang: LangId,
2419) -> Vec<CallSiteWithRange> {
2420    let mut results = Vec::new();
2421    let call_kinds = call_node_kinds(lang);
2422    collect_calls_full_with_ranges_inner(
2423        root,
2424        source,
2425        byte_start,
2426        byte_end,
2427        &call_kinds,
2428        &mut results,
2429    );
2430    results
2431}
2432
2433#[cfg(any(test, feature = "test-support"))]
2434fn collect_calls_full_with_ranges_inner(
2435    node: tree_sitter::Node,
2436    source: &str,
2437    byte_start: usize,
2438    byte_end: usize,
2439    call_kinds: &[&str],
2440    results: &mut Vec<CallSiteWithRange>,
2441) {
2442    let node_start = node.start_byte();
2443    let node_end = node.end_byte();
2444
2445    if node_end <= byte_start || node_start >= byte_end {
2446        return;
2447    }
2448
2449    if call_kinds.contains(&node.kind()) && node_start >= byte_start && node_end <= byte_end {
2450        if let (Some(full), Some(short)) = (
2451            extract_full_callee(&node, source),
2452            extract_callee_name(&node, source),
2453        ) {
2454            results.push(CallSiteWithRange {
2455                full,
2456                short,
2457                line: node.start_position().row as u32 + 1,
2458                byte_start: node_start,
2459                byte_end: node_end,
2460            });
2461        }
2462    }
2463
2464    let mut cursor = node.walk();
2465    if cursor.goto_first_child() {
2466        loop {
2467            collect_calls_full_with_ranges_inner(
2468                cursor.node(),
2469                source,
2470                byte_start,
2471                byte_end,
2472                call_kinds,
2473                results,
2474            );
2475            if !cursor.goto_next_sibling() {
2476                break;
2477            }
2478        }
2479    }
2480}
2481
2482// ---------------------------------------------------------------------------
2483// Module path resolution
2484// ---------------------------------------------------------------------------
2485
2486/// Resolve a module path (e.g. './utils') relative to a directory.
2487///
2488/// Tries common file extensions for TypeScript/JavaScript projects.
2489pub fn resolve_module_path(from_dir: &Path, module_path: &str) -> Option<PathBuf> {
2490    let disk = DiskFacts::new(from_dir.ancestors().last().unwrap_or(from_dir));
2491    let facts = &FactPaths {
2492        root: &disk.project_root,
2493        facts: &disk,
2494    };
2495    resolve_module_path_uncached(from_dir, module_path, None, facts)
2496}
2497
2498pub fn resolve_module_path_with_memo(
2499    from_dir: &Path,
2500    module_path: &str,
2501    memo: &ModuleResolutionMemo,
2502    facts: &FactPaths<'_>,
2503) -> Option<PathBuf> {
2504    memo.resolve_module_path(from_dir, module_path, facts)
2505}
2506
2507fn resolve_module_path_uncached(
2508    from_dir: &Path,
2509    module_path: &str,
2510    memo: Option<&ModuleResolutionMemo>,
2511    facts: &FactPaths<'_>,
2512) -> Option<PathBuf> {
2513    if module_path.starts_with('.') {
2514        return resolve_relative_module_path(from_dir, module_path, facts);
2515    }
2516
2517    if module_path.starts_with('/') {
2518        return None;
2519    }
2520
2521    if let Some(path) = resolve_tsconfig_path(from_dir, module_path, memo, facts) {
2522        return Some(path);
2523    }
2524
2525    resolve_workspace_module_path(from_dir, module_path, memo, facts)
2526}
2527
2528fn resolve_relative_module_path(
2529    from_dir: &Path,
2530    module_path: &str,
2531    facts: &FactPaths<'_>,
2532) -> Option<PathBuf> {
2533    let base = from_dir.join(module_path);
2534    resolve_file_like_path(&base, facts)
2535}
2536
2537fn resolve_file_like_path(base: &Path, facts: &FactPaths<'_>) -> Option<PathBuf> {
2538    let base = base.to_path_buf();
2539
2540    // Try exact path first
2541    if facts.is_file(&base) {
2542        return Some(facts.canonical(&base).unwrap_or(base));
2543    }
2544
2545    // Try common extensions, including ESM/CJS TypeScript pairs used by workspaces.
2546    for ext in JS_TS_EXTENSIONS {
2547        let with_ext = base.with_extension(ext);
2548        if facts.is_file(&with_ext) {
2549            return Some(facts.canonical(&with_ext).unwrap_or(with_ext));
2550        }
2551    }
2552
2553    // Try as directory with index file
2554    if facts.is_dir(&base) {
2555        if let Some(index) = find_index_file(&base, facts) {
2556            return Some(index);
2557        }
2558    }
2559
2560    None
2561}
2562
2563fn resolve_workspace_module_path(
2564    from_dir: &Path,
2565    module_path: &str,
2566    memo: Option<&ModuleResolutionMemo>,
2567    facts: &FactPaths<'_>,
2568) -> Option<PathBuf> {
2569    let (package_name, subpath) = split_package_import(module_path)?;
2570    let package_root = find_package_root_for_import(from_dir, &package_name, memo, facts)?;
2571    resolve_package_entry(&package_root, &subpath, memo, facts)
2572}
2573
2574fn is_rust_source_file(path: &Path) -> bool {
2575    path.extension().and_then(|ext| ext.to_str()) == Some("rs")
2576}
2577
2578fn resolve_rust_cross_file_edge<F>(
2579    full_callee: &str,
2580    short_name: &str,
2581    caller_file: &Path,
2582    import_block: &ImportBlock,
2583    file_exports_symbol: &mut F,
2584) -> Option<ResolvedSymbol>
2585where
2586    F: FnMut(&Path, &str) -> bool,
2587{
2588    if let Some(target) = resolve_rust_qualified_call(caller_file, full_callee, file_exports_symbol)
2589    {
2590        return Some(target);
2591    }
2592
2593    resolve_rust_imported_call(
2594        caller_file,
2595        full_callee,
2596        short_name,
2597        import_block,
2598        file_exports_symbol,
2599    )
2600}
2601
2602fn resolve_rust_qualified_call<F>(
2603    caller_file: &Path,
2604    full_callee: &str,
2605    file_exports_symbol: &mut F,
2606) -> Option<ResolvedSymbol>
2607where
2608    F: FnMut(&Path, &str) -> bool,
2609{
2610    if !full_callee.contains("::") {
2611        return None;
2612    }
2613
2614    let segments = rust_path_segments(full_callee)?;
2615    resolve_rust_call_segments(caller_file, &segments, file_exports_symbol)
2616}
2617
2618fn resolve_rust_imported_call<F>(
2619    caller_file: &Path,
2620    full_callee: &str,
2621    short_name: &str,
2622    import_block: &ImportBlock,
2623    file_exports_symbol: &mut F,
2624) -> Option<ResolvedSymbol>
2625where
2626    F: FnMut(&Path, &str) -> bool,
2627{
2628    let call_segments = rust_path_segments(full_callee).unwrap_or_default();
2629    let bare_call_name = if call_segments.len() <= 1 {
2630        call_segments
2631            .first()
2632            .map(String::as_str)
2633            .unwrap_or(short_name)
2634    } else {
2635        short_name
2636    };
2637
2638    for imp in &import_block.imports {
2639        for entry in rust_use_entries(imp) {
2640            match &entry.kind {
2641                RustUseKind::Item { imported_name } if call_segments.len() <= 1 => {
2642                    if entry.local_name != bare_call_name {
2643                        continue;
2644                    }
2645                    let Some(file) = resolve_rust_module_path(caller_file, &entry.module_path)
2646                    else {
2647                        continue;
2648                    };
2649                    if file_exports_symbol(&file, imported_name) {
2650                        return Some(ResolvedSymbol {
2651                            file,
2652                            symbol: imported_name.clone(),
2653                        });
2654                    }
2655                }
2656                RustUseKind::Module if call_segments.len() >= 2 => {
2657                    if call_segments.first().map(String::as_str) != Some(entry.local_name.as_str())
2658                    {
2659                        continue;
2660                    }
2661                    let symbol = call_segments.last()?.clone();
2662                    let mut module_path = entry.module_path.clone();
2663                    for segment in &call_segments[1..call_segments.len().saturating_sub(1)] {
2664                        module_path.push_str("::");
2665                        module_path.push_str(segment);
2666                    }
2667                    let Some(file) = resolve_rust_module_path(caller_file, &module_path) else {
2668                        continue;
2669                    };
2670                    if file_exports_symbol(&file, &symbol) {
2671                        return Some(ResolvedSymbol { file, symbol });
2672                    }
2673                }
2674                _ => {}
2675            }
2676        }
2677    }
2678
2679    None
2680}
2681
2682fn resolve_rust_call_segments<F>(
2683    caller_file: &Path,
2684    segments: &[String],
2685    file_exports_symbol: &mut F,
2686) -> Option<ResolvedSymbol>
2687where
2688    F: FnMut(&Path, &str) -> bool,
2689{
2690    if segments.len() < 2 {
2691        return None;
2692    }
2693
2694    let symbol = segments.last()?.clone();
2695    let module_path = segments[..segments.len() - 1].join("::");
2696    let file = resolve_rust_module_path(caller_file, &module_path)?;
2697    if file_exports_symbol(&file, &symbol) {
2698        Some(ResolvedSymbol { file, symbol })
2699    } else {
2700        None
2701    }
2702}
2703
2704fn resolve_rust_module_path(caller_file: &Path, module_path: &str) -> Option<PathBuf> {
2705    let segments = rust_path_segments(module_path)?;
2706    let first = segments.first()?.as_str();
2707
2708    match first {
2709        "std" | "core" | "alloc" => None,
2710        "crate" => {
2711            let crate_root = find_rust_crate_root(caller_file)?;
2712            let crate_info = rust_crate_info(&crate_root)?;
2713            let base = rust_module_base_for_caller(&crate_info, caller_file)?;
2714            resolve_rust_module_segments(&base, &segments[1..])
2715        }
2716        "self" => {
2717            let crate_root = find_rust_crate_root(caller_file)?;
2718            let crate_info = rust_crate_info(&crate_root)?;
2719            let base = rust_module_base_for_caller(&crate_info, caller_file)?;
2720            if segments.len() == 1 {
2721                return Some(canonicalize_path(caller_file));
2722            }
2723            let mut target_segments = rust_module_segments_for_file(&base, caller_file)?;
2724            target_segments.extend(segments[1..].iter().cloned());
2725            resolve_rust_module_segments(&base, &target_segments)
2726        }
2727        "super" => {
2728            let crate_root = find_rust_crate_root(caller_file)?;
2729            let crate_info = rust_crate_info(&crate_root)?;
2730            let base = rust_module_base_for_caller(&crate_info, caller_file)?;
2731            let mut target_segments = rust_module_segments_for_file(&base, caller_file)?;
2732            target_segments.pop();
2733            target_segments.extend(segments[1..].iter().cloned());
2734            resolve_rust_module_segments(&base, &target_segments)
2735        }
2736        crate_name => {
2737            let caller_dir = caller_file.parent().unwrap_or_else(|| Path::new("."));
2738            let workspace_crates = rust_workspace_crates(caller_dir)?;
2739            let crate_info = workspace_crates.get(crate_name)?;
2740            let base = rust_lib_module_base(crate_info)?;
2741            resolve_rust_module_segments(&base, &segments[1..])
2742        }
2743    }
2744}
2745
2746fn rust_use_entries(imp: &imports::ImportStatement) -> Vec<RustUseEntry> {
2747    let Some(body) = rust_use_body(&imp.raw_text) else {
2748        return Vec::new();
2749    };
2750    let mut entries = Vec::new();
2751    expand_rust_use_tree(body, &mut entries);
2752    entries
2753}
2754
2755/// Reuse the resolver's use-tree expansion when a caller only needs the names
2756/// introduced into scope, without resolving or reading imported modules.
2757pub fn rust_import_local_names(imp: &imports::ImportStatement) -> Vec<String> {
2758    rust_use_entries(imp)
2759        .into_iter()
2760        .map(|entry| entry.local_name)
2761        .collect()
2762}
2763
2764/// The local name and full path of each explicit Rust use-tree leaf.
2765pub fn rust_import_paths(raw: &str) -> Vec<(String, String)> {
2766    let mut entries = Vec::new();
2767    if let Some(body) = rust_use_body(raw) {
2768        expand_rust_use_tree(body.trim_start_matches("::"), &mut entries);
2769    }
2770    entries
2771        .into_iter()
2772        .filter_map(|entry| match entry.kind {
2773            RustUseKind::Module => Some((entry.local_name, entry.module_path)),
2774            RustUseKind::Item { .. } => None,
2775        })
2776        .collect()
2777}
2778
2779fn rust_use_body(raw: &str) -> Option<&str> {
2780    let use_pos = raw.find("use ")?;
2781    let body = raw[use_pos + 4..].trim();
2782    let body = body.strip_suffix(';').unwrap_or(body).trim();
2783    (!body.is_empty()).then_some(body)
2784}
2785
2786fn expand_rust_use_tree(path: &str, entries: &mut Vec<RustUseEntry>) {
2787    enum Work {
2788        Expand(String),
2789        ModuleSelf(String),
2790    }
2791    // Use trees can nest beyond the file walker's stack. Keep both subtrees
2792    // and `self` entries on the heap, in reverse order, so popping them emits
2793    // exactly the depth-first order stored by the recursive expansion.
2794    let mut pending = vec![Work::Expand(path.to_string())];
2795    while let Some(work) = pending.pop() {
2796        let path = match work {
2797            Work::ModuleSelf(prefix) => {
2798                if let Some(local_name) = rust_last_path_segment(&prefix) {
2799                    entries.push(RustUseEntry {
2800                        module_path: prefix,
2801                        local_name,
2802                        kind: RustUseKind::Module,
2803                    });
2804                }
2805                continue;
2806            }
2807            Work::Expand(path) => path,
2808        };
2809        let path = path.trim();
2810        if path.is_empty() {
2811            continue;
2812        }
2813        if let Some((prefix, inner)) = split_rust_use_braces(path) {
2814            let prefix = prefix.trim().trim_end_matches("::").trim();
2815            for part in split_top_level_commas(inner).into_iter().rev() {
2816                let part = part.trim();
2817                if part.is_empty() {
2818                    continue;
2819                }
2820                if part == "self" {
2821                    pending.push(Work::ModuleSelf(prefix.to_string()));
2822                } else {
2823                    pending.push(Work::Expand(if prefix.is_empty() {
2824                        part.to_string()
2825                    } else {
2826                        format!("{prefix}::{part}")
2827                    }));
2828                }
2829            }
2830        } else {
2831            add_rust_use_leaf(path, entries);
2832        }
2833    }
2834}
2835
2836fn split_rust_use_braces(path: &str) -> Option<(&str, &str)> {
2837    let mut depth = 0usize;
2838    let mut start = None;
2839    for (idx, ch) in path.char_indices() {
2840        match ch {
2841            '{' => {
2842                if depth == 0 {
2843                    start = Some(idx);
2844                }
2845                depth += 1;
2846            }
2847            '}' => {
2848                depth = depth.checked_sub(1)?;
2849                if depth == 0 {
2850                    let start = start?;
2851                    if !path[idx + ch.len_utf8()..].trim().is_empty() {
2852                        return None;
2853                    }
2854                    return Some((&path[..start], &path[start + 1..idx]));
2855                }
2856            }
2857            _ => {}
2858        }
2859    }
2860    None
2861}
2862
2863fn split_top_level_commas(value: &str) -> Vec<&str> {
2864    let mut parts = Vec::new();
2865    let mut depth = 0usize;
2866    let mut start = 0usize;
2867    for (idx, ch) in value.char_indices() {
2868        match ch {
2869            '{' => depth += 1,
2870            '}' => depth = depth.saturating_sub(1),
2871            ',' if depth == 0 => {
2872                parts.push(&value[start..idx]);
2873                start = idx + ch.len_utf8();
2874            }
2875            _ => {}
2876        }
2877    }
2878    parts.push(&value[start..]);
2879    parts
2880}
2881
2882fn add_rust_use_leaf(path: &str, entries: &mut Vec<RustUseEntry>) {
2883    let (path, alias) = split_rust_alias(path);
2884    let Some(segments) = rust_path_segments(path) else {
2885        return;
2886    };
2887    if segments.is_empty() || segments.last().map(String::as_str) == Some("*") {
2888        return;
2889    }
2890
2891    let imported_name = segments.last().cloned().unwrap_or_default();
2892    let local_name = alias.unwrap_or(&imported_name).to_string();
2893    if segments.len() >= 2 {
2894        entries.push(RustUseEntry {
2895            module_path: segments[..segments.len() - 1].join("::"),
2896            local_name: local_name.clone(),
2897            kind: RustUseKind::Item {
2898                imported_name: imported_name.clone(),
2899            },
2900        });
2901    }
2902
2903    entries.push(RustUseEntry {
2904        module_path: segments.join("::"),
2905        local_name,
2906        kind: RustUseKind::Module,
2907    });
2908}
2909
2910fn split_rust_alias(path: &str) -> (&str, Option<&str>) {
2911    if let Some(idx) = path.rfind(" as ") {
2912        let original = path[..idx].trim();
2913        let alias = path[idx + 4..].trim();
2914        if !original.is_empty() && !alias.is_empty() {
2915            return (original, Some(alias));
2916        }
2917    }
2918    (path.trim(), None)
2919}
2920
2921fn rust_path_segments(path: &str) -> Option<Vec<String>> {
2922    let path = path.trim().trim_end_matches(';').trim();
2923    if path.is_empty() || path.contains('{') || path.contains('}') {
2924        return None;
2925    }
2926
2927    let mut segments = Vec::new();
2928    for raw_segment in path.split("::") {
2929        let segment = raw_segment.trim();
2930        if segment.is_empty() || segment == "*" || segment.chars().any(char::is_whitespace) {
2931            return None;
2932        }
2933        let segment = segment.strip_prefix("r#").unwrap_or(segment);
2934        if segment
2935            .chars()
2936            .any(|ch| !(ch == '_' || ch.is_ascii_alphanumeric()))
2937        {
2938            return None;
2939        }
2940        segments.push(segment.to_string());
2941    }
2942
2943    (!segments.is_empty()).then_some(segments)
2944}
2945
2946fn rust_last_path_segment(path: &str) -> Option<String> {
2947    rust_path_segments(path)?.last().cloned()
2948}
2949
2950fn find_rust_crate_root(from: &Path) -> Option<PathBuf> {
2951    let mut current = if from.is_file() {
2952        from.parent()
2953    } else {
2954        Some(from)
2955    };
2956    while let Some(dir) = current {
2957        if dir.join("Cargo.toml").is_file() {
2958            return Some(canonicalize_path(dir));
2959        }
2960        current = dir.parent();
2961    }
2962    None
2963}
2964
2965fn rust_crate_info(crate_root: &Path) -> Option<RustCrateInfo> {
2966    let root = canonicalize_path(crate_root);
2967    if let Some(cached) = RUST_CRATE_INFO_CACHE
2968        .read()
2969        .ok()
2970        .and_then(|cache| cache.get(&root).cloned())
2971    {
2972        return cached;
2973    }
2974
2975    let resolved = read_rust_crate_info(&root);
2976    if let Ok(mut cache) = RUST_CRATE_INFO_CACHE.write() {
2977        cache.insert(root, resolved.clone());
2978    }
2979    resolved
2980}
2981
2982fn read_rust_crate_info(crate_root: &Path) -> Option<RustCrateInfo> {
2983    let cargo = rust_manifest_value(&crate_root.join("Cargo.toml"))?;
2984    let package = cargo.get("package")?;
2985    let package_name = package.get("name")?.as_str()?;
2986    let lib_name = cargo
2987        .get("lib")
2988        .and_then(|lib| lib.get("name"))
2989        .and_then(|name| name.as_str())
2990        .map(ToOwned::to_owned)
2991        .unwrap_or_else(|| package_name.replace('-', "_"));
2992
2993    let lib_root = cargo
2994        .get("lib")
2995        .and_then(|lib| lib.get("path"))
2996        .and_then(|path| path.as_str())
2997        .map(|path| crate_root.join(path))
2998        .unwrap_or_else(|| crate_root.join("src/lib.rs"));
2999    let lib_root = lib_root.is_file().then(|| canonicalize_path(&lib_root));
3000
3001    Some(RustCrateInfo {
3002        package_root: canonicalize_path(crate_root),
3003        lib_name,
3004        lib_root,
3005        target_roots: rust_target_roots(
3006            crate_root,
3007            &cargo,
3008            &FactPaths {
3009                root: crate_root,
3010                facts: &DiskFacts::new(crate_root),
3011            },
3012        ),
3013    })
3014}
3015
3016fn rust_manifest_value(path: &Path) -> Option<toml::Value> {
3017    let source = crate::project_content::read_to_string(path).ok()?;
3018    toml::from_str(&source).ok()
3019}
3020
3021fn rust_target_roots(
3022    crate_root: &Path,
3023    cargo: &toml::Value,
3024    facts: &FactPaths<'_>,
3025) -> Vec<PathBuf> {
3026    let mut roots = Vec::new();
3027    for (table, directory, auto_key) in [
3028        ("bin", "src/bin", "autobins"),
3029        ("example", "examples", "autoexamples"),
3030        ("test", "tests", "autotests"),
3031        ("bench", "benches", "autobenches"),
3032    ] {
3033        if let Some(targets) = cargo.get(table).and_then(toml::Value::as_array) {
3034            for path in targets.iter().filter_map(|target| {
3035                target
3036                    .get("path")
3037                    .and_then(toml::Value::as_str)
3038                    .map(|path| crate_root.join(path))
3039            }) {
3040                if facts.is_file(&path) {
3041                    roots.push(facts.canonical(&path).unwrap_or(path));
3042                }
3043            }
3044        }
3045        let enabled = cargo
3046            .get("package")
3047            .and_then(|package| package.get(auto_key))
3048            .and_then(toml::Value::as_bool)
3049            .unwrap_or(true);
3050        if !enabled {
3051            continue;
3052        }
3053        let directory = crate_root.join(directory);
3054        for entry in facts.list_dir(&directory) {
3055            let path = directory.join(byte_path(&entry.name));
3056            let root = match entry.kind {
3057                EntryKind::Regular
3058                    if path.extension().and_then(|ext| ext.to_str()) == Some("rs") =>
3059                {
3060                    Some(path)
3061                }
3062                EntryKind::Directory => Some(path.join("main.rs")),
3063                _ => None,
3064            };
3065            if let Some(root) = root.filter(|root| facts.is_file(root)) {
3066                roots.push(facts.canonical(&root).unwrap_or(root));
3067            }
3068        }
3069    }
3070    if cargo
3071        .get("package")
3072        .and_then(|package| package.get("autobins"))
3073        .and_then(toml::Value::as_bool)
3074        .unwrap_or(true)
3075    {
3076        let main = crate_root.join("src/main.rs");
3077        if facts.is_file(&main) {
3078            roots.push(facts.canonical(&main).unwrap_or(main));
3079        }
3080    }
3081    roots.sort();
3082    roots.dedup();
3083    roots
3084}
3085
3086impl RustCrateRootMemo {
3087    pub fn root_file(
3088        &self,
3089        project_root: &Path,
3090        caller_file: &Path,
3091        facts: &FactPaths<'_>,
3092    ) -> Option<PathBuf> {
3093        let caller = facts
3094            .canonical(caller_file)
3095            .unwrap_or_else(|| caller_file.to_path_buf());
3096        if let Some(cached) = self.caller_roots.borrow().get(&caller).cloned() {
3097            facts.facts.memo_replay(&caller, "rust-crate-root", "");
3098            return cached;
3099        }
3100
3101        facts.facts.memo_start(&caller, "rust-crate-root", "");
3102        let resolved = self.resolve_root_file(project_root, &caller, facts);
3103        facts.facts.memo_finish(&caller, "rust-crate-root", "");
3104        self.caller_roots
3105            .borrow_mut()
3106            .insert(caller, resolved.clone());
3107        resolved
3108    }
3109
3110    fn resolve_root_file(
3111        &self,
3112        project_root: &Path,
3113        caller: &Path,
3114        facts: &FactPaths<'_>,
3115    ) -> Option<PathBuf> {
3116        let mut current = caller.parent();
3117        let crate_root = loop {
3118            let dir = current?;
3119            if facts.is_file(&dir.join("Cargo.toml")) {
3120                break dir.to_path_buf();
3121            }
3122            if dir == project_root {
3123                return None;
3124            }
3125            current = dir.parent();
3126        };
3127        let cached_targets = { self.crate_targets.borrow().get(&crate_root).cloned() };
3128        let targets = if let Some(cached) = cached_targets {
3129            facts
3130                .facts
3131                .memo_replay(&crate_root, "rust-target-roots", "");
3132            cached
3133        } else {
3134            facts.facts.memo_start(&crate_root, "rust-target-roots", "");
3135            let resolved = read_rust_crate_targets(&crate_root, facts);
3136            facts
3137                .facts
3138                .memo_finish(&crate_root, "rust-target-roots", "");
3139            self.crate_targets
3140                .borrow_mut()
3141                .insert(crate_root.clone(), resolved.clone());
3142            resolved
3143        }?;
3144        if targets.lib_root.as_ref() == Some(&caller.to_path_buf()) {
3145            return targets.lib_root;
3146        }
3147        targets
3148            .target_roots
3149            .into_iter()
3150            .filter(|root| {
3151                let default_main = *root == crate_root.join("src/main.rs");
3152                root.parent()
3153                    .is_some_and(|dir| caller == root || (!default_main && caller.starts_with(dir)))
3154            })
3155            .max_by_key(|root| {
3156                (
3157                    caller == root,
3158                    root.parent()
3159                        .map(|dir| dir.components().count())
3160                        .unwrap_or(0),
3161                )
3162            })
3163            .or(targets.lib_root)
3164    }
3165}
3166
3167fn read_rust_crate_targets(crate_root: &Path, facts: &FactPaths<'_>) -> Option<RustCrateTargets> {
3168    let manifest = crate_root.join("Cargo.toml");
3169    // A crate's targets come from `[lib] path`, the target tables and their
3170    // auto-discovery switches, so a change to any of them changes this
3171    // answer. Without these fields the read named no field, and only another
3172    // reader's unrelated field on the same file kept it from counting as
3173    // reading the whole file.
3174    facts.config_fact(&manifest, "disk.lib.path");
3175    facts.config_fact(&manifest, "disk.targets");
3176    let bytes = facts.attributed_bytes(&manifest)?;
3177    let cargo: toml::Value = toml::from_str(std::str::from_utf8(&bytes).ok()?).ok()?;
3178    let lib = cargo
3179        .get("lib")
3180        .and_then(|lib| lib.get("path"))
3181        .and_then(toml::Value::as_str)
3182        .map(|path| crate_root.join(path))
3183        .unwrap_or_else(|| crate_root.join("src/lib.rs"));
3184    let lib_root = facts
3185        .is_file(&lib)
3186        .then(|| facts.canonical(&lib).unwrap_or(lib));
3187    Some(RustCrateTargets {
3188        lib_root,
3189        target_roots: rust_target_roots(crate_root, &cargo, facts),
3190    })
3191}
3192
3193pub fn rust_crate_root_file_for_caller(
3194    project_root: &Path,
3195    caller_file: &Path,
3196    facts: &FactPaths<'_>,
3197    memo: &RustCrateRootMemo,
3198) -> Option<PathBuf> {
3199    memo.root_file(project_root, caller_file, facts)
3200}
3201
3202fn rust_module_base_for_caller(
3203    crate_info: &RustCrateInfo,
3204    caller_file: &Path,
3205) -> Option<RustModuleBase> {
3206    let caller = canonicalize_path(caller_file);
3207    if crate_info.lib_root.as_ref() == Some(&caller) {
3208        return rust_lib_module_base(crate_info);
3209    }
3210    crate_info
3211        .target_roots
3212        .iter()
3213        .filter_map(|root_file| {
3214            let src_dir = root_file.parent()?;
3215            let default_main = *root_file == crate_info.package_root.join("src/main.rs");
3216            (caller == *root_file || (!default_main && caller.starts_with(src_dir))).then(|| {
3217                RustModuleBase {
3218                    src_dir: src_dir.to_path_buf(),
3219                    root_file: root_file.clone(),
3220                }
3221            })
3222        })
3223        .max_by_key(|base| (caller == base.root_file, base.src_dir.components().count()))
3224        .or_else(|| rust_lib_module_base(crate_info))
3225}
3226
3227fn rust_lib_module_base(crate_info: &RustCrateInfo) -> Option<RustModuleBase> {
3228    let root_file = crate_info.lib_root.clone()?;
3229    let src_dir = root_file.parent()?.to_path_buf();
3230    Some(RustModuleBase { src_dir, root_file })
3231}
3232
3233fn resolve_rust_module_segments(base: &RustModuleBase, segments: &[String]) -> Option<PathBuf> {
3234    if segments.is_empty() {
3235        return Some(base.root_file.clone());
3236    }
3237
3238    let module_base = segments
3239        .iter()
3240        .fold(base.src_dir.clone(), |path, segment| path.join(segment));
3241    let file_path = module_base.with_extension("rs");
3242    if file_path.is_file() {
3243        return Some(canonicalize_path(&file_path));
3244    }
3245
3246    let mod_path = module_base.join("mod.rs");
3247    if mod_path.is_file() {
3248        return Some(canonicalize_path(&mod_path));
3249    }
3250
3251    None
3252}
3253
3254fn rust_module_segments_for_file(base: &RustModuleBase, file: &Path) -> Option<Vec<String>> {
3255    let src_dir = canonicalize_path(&base.src_dir);
3256    let file = canonicalize_path(file);
3257    if file == canonicalize_path(&base.root_file) {
3258        return Some(Vec::new());
3259    }
3260    let rel = file.strip_prefix(&src_dir).ok()?;
3261    let mut parts: Vec<String> = rel
3262        .components()
3263        .filter_map(|component| component.as_os_str().to_str().map(ToOwned::to_owned))
3264        .collect();
3265    if parts.is_empty() {
3266        return None;
3267    }
3268
3269    let last = parts.pop()?;
3270    if last == "lib.rs" || last == "main.rs" {
3271        return Some(Vec::new());
3272    }
3273    if last == "mod.rs" {
3274        return Some(parts);
3275    }
3276    let stem = Path::new(&last).file_stem()?.to_str()?.to_string();
3277    parts.push(stem);
3278    Some(parts)
3279}
3280
3281fn rust_workspace_crates(from_dir: &Path) -> Option<HashMap<String, RustCrateInfo>> {
3282    let workspace_root =
3283        find_rust_workspace_root(from_dir).or_else(|| find_rust_crate_root(from_dir))?;
3284    let workspace_root = canonicalize_path(&workspace_root);
3285
3286    if let Some(cached) = RUST_WORKSPACE_CRATE_CACHE
3287        .read()
3288        .ok()
3289        .and_then(|cache| cache.get(&workspace_root).cloned())
3290    {
3291        return Some(cached);
3292    }
3293
3294    let mut crates = HashMap::new();
3295    for member in rust_workspace_member_dirs(&workspace_root) {
3296        if let Some(info) = rust_crate_info(&member) {
3297            if info.lib_root.is_some() {
3298                crates.insert(info.lib_name.clone(), info);
3299            }
3300        }
3301    }
3302    if let Some(info) = rust_crate_info(&workspace_root) {
3303        if info.lib_root.is_some() {
3304            crates.insert(info.lib_name.clone(), info);
3305        }
3306    }
3307
3308    if let Ok(mut cache) = RUST_WORKSPACE_CRATE_CACHE.write() {
3309        cache.insert(workspace_root, crates.clone());
3310    }
3311    Some(crates)
3312}
3313
3314fn find_rust_workspace_root(from_dir: &Path) -> Option<PathBuf> {
3315    let mut current = Some(from_dir);
3316    while let Some(dir) = current {
3317        let cargo = dir.join("Cargo.toml");
3318        if rust_manifest_value(&cargo)
3319            .and_then(|value| value.get("workspace").cloned())
3320            .is_some()
3321        {
3322            return Some(canonicalize_path(dir));
3323        }
3324        current = dir.parent();
3325    }
3326    None
3327}
3328
3329fn rust_workspace_member_dirs(workspace_root: &Path) -> Vec<PathBuf> {
3330    let Some(cargo) = rust_manifest_value(&workspace_root.join("Cargo.toml")) else {
3331        return Vec::new();
3332    };
3333    let Some(members) = cargo
3334        .get("workspace")
3335        .and_then(|workspace| workspace.get("members"))
3336        .and_then(|members| members.as_array())
3337    else {
3338        return Vec::new();
3339    };
3340
3341    let mut dirs = Vec::new();
3342    for member in members.iter().filter_map(|member| member.as_str()) {
3343        dirs.extend(expand_rust_workspace_member(workspace_root, member));
3344    }
3345    dirs.sort();
3346    dirs.dedup();
3347    dirs
3348}
3349
3350fn expand_rust_workspace_member(workspace_root: &Path, member: &str) -> Vec<PathBuf> {
3351    let member = member.trim();
3352    if member.is_empty() {
3353        return Vec::new();
3354    }
3355
3356    if member.contains('*') || member.contains('?') || member.contains('[') {
3357        let pattern = workspace_root.join(member).to_string_lossy().to_string();
3358        return crate::walk_boundary::expand_glob_same_file_system(&pattern)
3359            .unwrap_or_default()
3360            .into_iter()
3361            .filter(|path| path.join("Cargo.toml").is_file())
3362            .map(|path| canonicalize_path(&path))
3363            .collect();
3364    }
3365
3366    let path = workspace_root.join(member);
3367    if path.join("Cargo.toml").is_file() {
3368        vec![canonicalize_path(&path)]
3369    } else {
3370        Vec::new()
3371    }
3372}
3373
3374test_support_visibility! {
3375fn canonicalize_path(path: &Path) -> PathBuf {
3376    std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
3377}
3378}
3379
3380fn resolve_tsconfig_path(
3381    from_dir: &Path,
3382    module_path: &str,
3383    memo: Option<&ModuleResolutionMemo>,
3384    facts: &FactPaths<'_>,
3385) -> Option<PathBuf> {
3386    let tsconfig_dir = find_tsconfig_dir(from_dir, facts)?;
3387    let tsconfig = package_json_like_value(&tsconfig_dir.join("tsconfig.json"), memo, facts);
3388    facts.config_field(&tsconfig_dir, "tsconfig.json", "compilerOptions.paths");
3389    let tsconfig = tsconfig?;
3390    let compiler_options = tsconfig.get("compilerOptions")?;
3391    let paths = compiler_options.get("paths")?.as_object()?;
3392    facts.config_field(&tsconfig_dir, "tsconfig.json", "baseUrl");
3393    let base_url = compiler_options
3394        .get("baseUrl")
3395        .and_then(Value::as_str)
3396        .unwrap_or(".");
3397    let base_dir = tsconfig_dir.join(base_url);
3398
3399    for (alias, targets) in paths {
3400        let Some(capture) = ts_path_capture(alias, module_path) else {
3401            continue;
3402        };
3403        let Some(targets) = targets.as_array() else {
3404            continue;
3405        };
3406        for target in targets.iter().filter_map(Value::as_str) {
3407            let target = if target.contains('*') {
3408                target.replace('*', capture)
3409            } else {
3410                target.to_string()
3411            };
3412            if let Some(path) = resolve_file_like_path(&base_dir.join(target), facts) {
3413                return Some(path);
3414            }
3415        }
3416    }
3417
3418    None
3419}
3420
3421fn find_tsconfig_dir(from_dir: &Path, facts: &FactPaths<'_>) -> Option<PathBuf> {
3422    let mut current = Some(from_dir);
3423    while let Some(dir) = current {
3424        if facts.is_file(&dir.join("tsconfig.json")) {
3425            return Some(dir.to_path_buf());
3426        }
3427        current = dir.parent();
3428    }
3429    None
3430}
3431
3432fn ts_path_capture<'a>(alias: &str, module_path: &'a str) -> Option<&'a str> {
3433    if let Some(star_index) = alias.find('*') {
3434        let (prefix, suffix_with_star) = alias.split_at(star_index);
3435        let suffix = &suffix_with_star[1..];
3436        if module_path.starts_with(prefix) && module_path.ends_with(suffix) {
3437            return Some(&module_path[prefix.len()..module_path.len() - suffix.len()]);
3438        }
3439        return None;
3440    }
3441
3442    (alias == module_path).then_some("")
3443}
3444
3445fn split_package_import(module_path: &str) -> Option<(String, Option<String>)> {
3446    let mut parts = module_path.split('/');
3447    let first = parts.next()?;
3448    if first.is_empty() {
3449        return None;
3450    }
3451
3452    if first.starts_with('@') {
3453        let second = parts.next()?;
3454        if second.is_empty() {
3455            return None;
3456        }
3457        let package_name = format!("{first}/{second}");
3458        let subpath = parts.collect::<Vec<_>>().join("/");
3459        let subpath = (!subpath.is_empty()).then_some(subpath);
3460        Some((package_name, subpath))
3461    } else {
3462        let package_name = first.to_string();
3463        let subpath = parts.collect::<Vec<_>>().join("/");
3464        let subpath = (!subpath.is_empty()).then_some(subpath);
3465        Some((package_name, subpath))
3466    }
3467}
3468
3469fn find_package_root_for_import(
3470    from_dir: &Path,
3471    package_name: &str,
3472    memo: Option<&ModuleResolutionMemo>,
3473    facts: &FactPaths<'_>,
3474) -> Option<PathBuf> {
3475    let mut current = Some(from_dir);
3476    while let Some(dir) = current {
3477        if package_json_name(dir, memo, facts).as_deref() == Some(package_name) {
3478            return Some(facts.canonical(dir).unwrap_or_else(|| dir.to_path_buf()));
3479        }
3480        current = dir.parent();
3481    }
3482
3483    find_workspace_root(from_dir, memo, facts).and_then(|workspace_root| {
3484        resolve_workspace_package(&workspace_root, package_name, memo, facts)
3485    })
3486}
3487
3488fn find_workspace_root(
3489    from_dir: &Path,
3490    memo: Option<&ModuleResolutionMemo>,
3491    facts: &FactPaths<'_>,
3492) -> Option<PathBuf> {
3493    let mut current = Some(from_dir);
3494    while let Some(dir) = current {
3495        if is_workspace_root(dir, memo, facts) {
3496            return Some(facts.canonical(dir).unwrap_or_else(|| dir.to_path_buf()));
3497        }
3498        current = dir.parent();
3499    }
3500    None
3501}
3502
3503fn is_workspace_root(
3504    dir: &Path,
3505    memo: Option<&ModuleResolutionMemo>,
3506    facts: &FactPaths<'_>,
3507) -> bool {
3508    facts.config_field(dir, "package.json", "workspaces");
3509    package_json_value(dir, memo, facts)
3510        .map(|value| !workspace_patterns(&value).is_empty())
3511        .unwrap_or(false)
3512        || !pnpm_workspace_patterns(dir, facts).is_empty()
3513}
3514
3515/// Drop the workspace and crate caches for one project root only. The caches
3516/// are process-wide and the daemon serves dozens of roots that bind about ten
3517/// times a minute; clearing everything on each configure gave the caches a
3518/// lifetime of seconds, so every Tier-2 rescan re-walked every workspace under
3519/// every root. A configure is a signal about its own root's manifests, and
3520/// the keys are canonical paths, so containment is the right scope.
3521pub fn clear_workspace_package_cache_under(root: &Path) {
3522    let root = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
3523    if let Ok(mut cache) = WORKSPACE_PACKAGE_CACHE.write() {
3524        cache.retain(|(workspace, _), _| !workspace.starts_with(&root));
3525    }
3526    if let Ok(mut cache) = WORKSPACE_MEMBER_DIRS_CACHE.write() {
3527        cache.retain(|workspace, _| !workspace.starts_with(&root));
3528    }
3529    if let Ok(mut cache) = RUST_CRATE_INFO_CACHE.write() {
3530        cache.retain(|dir, _| !dir.starts_with(&root));
3531    }
3532    if let Ok(mut cache) = RUST_WORKSPACE_CRATE_CACHE.write() {
3533        cache.retain(|workspace, _| !workspace.starts_with(&root));
3534    }
3535}
3536
3537pub fn clear_workspace_package_cache() {
3538    if let Ok(mut cache) = WORKSPACE_PACKAGE_CACHE.write() {
3539        cache.clear();
3540    }
3541    if let Ok(mut cache) = WORKSPACE_MEMBER_DIRS_CACHE.write() {
3542        cache.clear();
3543    }
3544    if let Ok(mut cache) = RUST_CRATE_INFO_CACHE.write() {
3545        cache.clear();
3546    }
3547    if let Ok(mut cache) = RUST_WORKSPACE_CRATE_CACHE.write() {
3548        cache.clear();
3549    }
3550}
3551
3552fn resolve_workspace_package(
3553    workspace_root: &Path,
3554    package_name: &str,
3555    memo: Option<&ModuleResolutionMemo>,
3556    facts: &FactPaths<'_>,
3557) -> Option<PathBuf> {
3558    let workspace_root = facts
3559        .canonical(workspace_root)
3560        .unwrap_or_else(|| workspace_root.to_path_buf());
3561    let cache_key = (workspace_root.clone(), package_name.to_string());
3562
3563    // The memo is a bounded per-pass layer; the process-wide cache is the
3564    // durable one. Both are consulted whenever present: several call sites
3565    // resolve with a memo that lives for a single import, and a memo alone
3566    // turned every bare package import in a workspace monorepo into a full
3567    // member-directory walk (realpath per directory) because the miss never
3568    // reached the cache that already held the answer. Two daemon threads sat
3569    // at 70% each in that walk during one-file Tier-2 rescans across roots.
3570    if let Some(memo) = memo {
3571        if let Some(cached) = memo.workspace_package(&cache_key) {
3572            facts
3573                .facts
3574                .memo_replay(&workspace_root, "package", package_name);
3575            return cached;
3576        }
3577    }
3578    if facts.facts.records_config_facts() {
3579        if let Some(cached) = facts.facts.workspace_package(&workspace_root, package_name) {
3580            facts
3581                .facts
3582                .memo_replay(&workspace_root, "package", package_name);
3583            return cached;
3584        }
3585    } else if let Ok(cache) = WORKSPACE_PACKAGE_CACHE.read() {
3586        if let Some(cached) = cache.get(&cache_key) {
3587            if let Some(memo) = memo {
3588                memo.remember_workspace_package(cache_key, cached.clone());
3589            }
3590            facts
3591                .facts
3592                .memo_replay(&workspace_root, "package", package_name);
3593            return cached.clone();
3594        }
3595    }
3596
3597    facts
3598        .facts
3599        .memo_start(&workspace_root, "package", package_name);
3600    // A recorder that keeps every read with its answer records the name's key
3601    // instead of the member walk and the names it read: the walk is the same
3602    // for every reader, and kept in each it was most of a monorepo's stored
3603    // call graph. `js_workspace_package_map` sets the key when the name's
3604    // member changes.
3605    let keyed = facts.facts.records_answers();
3606    if keyed {
3607        facts
3608            .facts
3609            .record_domain(&crate::callgraph_store::join::js_package_key(
3610                &checkout_relative(facts, &workspace_root),
3611                package_name,
3612            ));
3613        facts.facts.pause_recording();
3614    }
3615    let resolved = workspace_package_member(&workspace_root, package_name, memo, facts);
3616    if keyed {
3617        facts.facts.resume_recording();
3618    }
3619
3620    facts
3621        .facts
3622        .memo_finish(&workspace_root, "package", package_name);
3623    if let Some(memo) = memo {
3624        memo.remember_workspace_package(cache_key.clone(), resolved.clone());
3625    }
3626    if facts.facts.records_config_facts() {
3627        facts
3628            .facts
3629            .remember_workspace_package(&workspace_root, package_name, resolved.clone());
3630    } else if let Ok(mut cache) = WORKSPACE_PACKAGE_CACHE.write() {
3631        cache.insert(cache_key, resolved.clone());
3632    }
3633
3634    resolved
3635}
3636
3637/// The member of the workspace at `workspace_root` whose `package.json` names
3638/// `package_name`, resolved: the first in member order when several do.
3639fn workspace_package_member(
3640    workspace_root: &Path,
3641    package_name: &str,
3642    memo: Option<&ModuleResolutionMemo>,
3643    facts: &FactPaths<'_>,
3644) -> Option<PathBuf> {
3645    cached_workspace_member_dirs(workspace_root, memo, facts)
3646        .iter()
3647        .find(|dir| package_json_name(dir, memo, facts).as_deref() == Some(package_name))
3648        .map(|dir| facts.canonical(dir).unwrap_or_else(|| dir.clone()))
3649}
3650
3651/// `path` relative to the checkout root of `facts`, with `/` separators.
3652fn checkout_relative(facts: &FactPaths<'_>, path: &Path) -> String {
3653    path.strip_prefix(facts.root)
3654        .unwrap_or(path)
3655        .to_string_lossy()
3656        .replace('\\', "/")
3657}
3658
3659/// Each JavaScript workspace package's resolved member folder, by the key a
3660/// reader records for looking its name up ([`js_package_key`]), for each of
3661/// `candidates` that is a workspace root. A name several members share maps
3662/// to the member [`resolve_workspace_package`] finds. Read through `facts`
3663/// without a memo, so a map built before and after a change compares what
3664/// the resolver would find in each.
3665///
3666/// [`js_package_key`]: crate::callgraph_store::join::js_package_key
3667pub fn js_workspace_package_map(
3668    facts: &FactPaths<'_>,
3669    candidates: impl IntoIterator<Item = PathBuf>,
3670) -> HashMap<String, String> {
3671    let mut map = HashMap::new();
3672    for candidate in candidates {
3673        if !is_workspace_root(&candidate, None, facts) {
3674            continue;
3675        }
3676        let root = facts
3677            .canonical(&candidate)
3678            .unwrap_or_else(|| candidate.clone());
3679        let relative = checkout_relative(facts, &root);
3680        for dir in workspace_member_dirs(&root, None, facts) {
3681            let Some(name) = package_json_name(&dir, None, facts) else {
3682                continue;
3683            };
3684            let key = crate::callgraph_store::join::js_package_key(&relative, &name);
3685            map.entry(key).or_insert_with(|| {
3686                let resolved = facts.canonical(&dir).unwrap_or(dir);
3687                resolved.to_string_lossy().into_owned()
3688            });
3689        }
3690    }
3691    map
3692}
3693
3694/// The member list for a workspace root, walked at most once per cache
3695/// lifetime. `workspace_root` is already canonical here (the caller keys on
3696/// it), so alias spellings cannot split the entry.
3697fn cached_workspace_member_dirs(
3698    workspace_root: &Path,
3699    memo: Option<&ModuleResolutionMemo>,
3700    facts: &FactPaths<'_>,
3701) -> Arc<Vec<PathBuf>> {
3702    if facts.facts.records_config_facts() {
3703        if let Some(members) = facts.facts.workspace_members(workspace_root) {
3704            facts.facts.memo_replay(workspace_root, "members", "");
3705            return members;
3706        }
3707    } else {
3708        let cell = WORKSPACE_MEMBER_DIRS_CACHE
3709            .write()
3710            .expect("workspace member cache poisoned")
3711            .entry(workspace_root.to_path_buf())
3712            .or_default()
3713            .clone();
3714        let mut populated = false;
3715        let members = cell.get_or_init(|| {
3716            populated = true;
3717            facts.facts.memo_start(workspace_root, "members", "");
3718            let members = Arc::new(workspace_member_dirs(workspace_root, memo, facts));
3719            facts.facts.memo_finish(workspace_root, "members", "");
3720            members
3721        });
3722        if !populated {
3723            facts.facts.memo_replay(workspace_root, "members", "");
3724        }
3725        return Arc::clone(members);
3726    }
3727    facts.facts.memo_start(workspace_root, "members", "");
3728    let members = Arc::new(workspace_member_dirs(workspace_root, memo, facts));
3729    facts.facts.memo_finish(workspace_root, "members", "");
3730    if facts.facts.records_config_facts() {
3731        facts
3732            .facts
3733            .remember_workspace_members(workspace_root, Arc::clone(&members));
3734    }
3735    members
3736}
3737
3738fn workspace_member_dirs(
3739    workspace_root: &Path,
3740    memo: Option<&ModuleResolutionMemo>,
3741    facts: &FactPaths<'_>,
3742) -> Vec<PathBuf> {
3743    facts.config_field(workspace_root, "package.json", "workspaces");
3744    let mut patterns = package_json_value(workspace_root, memo, facts)
3745        .map(|package_json| workspace_patterns(&package_json))
3746        .unwrap_or_default();
3747    patterns.extend(pnpm_workspace_patterns(workspace_root, facts));
3748
3749    expand_workspace_patterns(workspace_root, &patterns, facts)
3750}
3751
3752pub fn workspace_patterns(package_json: &Value) -> Vec<String> {
3753    match package_json.get("workspaces") {
3754        Some(Value::Array(items)) => items
3755            .iter()
3756            .filter_map(non_empty_workspace_pattern)
3757            .collect(),
3758        Some(Value::Object(map)) => map
3759            .get("packages")
3760            .and_then(Value::as_array)
3761            .map(|items| {
3762                items
3763                    .iter()
3764                    .filter_map(non_empty_workspace_pattern)
3765                    .collect()
3766            })
3767            .unwrap_or_default(),
3768        _ => Vec::new(),
3769    }
3770}
3771
3772fn non_empty_workspace_pattern(value: &Value) -> Option<String> {
3773    let pattern = value.as_str()?.trim();
3774    (!pattern.is_empty()).then(|| pattern.to_string())
3775}
3776
3777fn pnpm_workspace_patterns(workspace_root: &Path, facts: &FactPaths<'_>) -> Vec<String> {
3778    facts.config_field(workspace_root, "pnpm-workspace.yaml", "packages");
3779    let Some(bytes) = facts.attributed_bytes(&workspace_root.join("pnpm-workspace.yaml")) else {
3780        return Vec::new();
3781    };
3782
3783    parse_pnpm_workspace_patterns(&bytes)
3784}
3785
3786pub fn parse_pnpm_workspace_patterns(bytes: &[u8]) -> Vec<String> {
3787    let Ok(source) = std::str::from_utf8(bytes) else {
3788        return Vec::new();
3789    };
3790    let mut patterns = Vec::new();
3791    let mut in_packages = false;
3792    for line in source.lines() {
3793        let without_comment = line.split('#').next().unwrap_or("").trim_end();
3794        let trimmed = without_comment.trim();
3795        if trimmed.is_empty() {
3796            continue;
3797        }
3798        if trimmed == "packages:" {
3799            in_packages = true;
3800            continue;
3801        }
3802        if !trimmed.starts_with('-') && !line.starts_with(' ') && !line.starts_with('\t') {
3803            in_packages = false;
3804        }
3805        if in_packages {
3806            if let Some(pattern) = trimmed.strip_prefix('-') {
3807                let pattern = pattern.trim().trim_matches('"').trim_matches('\'');
3808                if !pattern.is_empty() {
3809                    patterns.push(pattern.to_string());
3810                }
3811            }
3812        }
3813    }
3814    patterns
3815}
3816
3817test_support_visibility! {
3818fn expand_workspace_patterns(
3819    workspace_root: &Path,
3820    patterns: &[String],
3821    facts: &FactPaths<'_>,
3822) -> Vec<PathBuf> {
3823    let positive_patterns: Vec<&str> = patterns
3824        .iter()
3825        .map(|pattern| pattern.trim())
3826        .filter(|pattern| !pattern.is_empty() && !pattern.starts_with('!'))
3827        .collect();
3828    if positive_patterns.is_empty() {
3829        return Vec::new();
3830    }
3831
3832    let positives = build_glob_set(&positive_patterns);
3833    let negative_patterns: Vec<&str> = patterns
3834        .iter()
3835        .map(|pattern| pattern.trim())
3836        .filter_map(|pattern| pattern.strip_prefix('!'))
3837        .map(str::trim)
3838        .filter(|pattern| !pattern.is_empty())
3839        .collect();
3840    let negatives = build_glob_set(&negative_patterns);
3841
3842    // Workspace membership is manifest-defined, not gitignore-defined: a
3843    // manifest can intentionally name an ignored vendor directory. In addition
3844    // to the existing excluded names and filesystem boundary, prune branches
3845    // outside every positive pattern's literal directory prefix.
3846    // Keep wildcard matching unchanged (including '*' matching separators).
3847    let prefixes: Vec<_> = positive_patterns
3848        .iter()
3849        .map(|pattern| {
3850            if pattern.contains('\\') {
3851                return (PathBuf::new(), true);
3852            }
3853            match pattern.find(['*', '?', '[', '{']) {
3854                Some(first_glob) => {
3855                    let end = pattern[..first_glob].rfind('/').unwrap_or(0);
3856                    (PathBuf::from(&pattern[..end]), true)
3857                }
3858                None => (PathBuf::from(pattern), false),
3859            }
3860        })
3861        .collect();
3862
3863    let mut members = Vec::new();
3864    collect_workspace_member_dirs(
3865        workspace_root,
3866        workspace_root,
3867        &positives,
3868        &negatives,
3869        &prefixes,
3870        &mut members,
3871        facts,
3872    );
3873    members
3874}
3875}
3876
3877test_support_visibility! {
3878fn build_glob_set(patterns: &[&str]) -> GlobSet {
3879    let mut builder = GlobSetBuilder::new();
3880    for pattern in patterns {
3881        if let Ok(glob) = Glob::new(pattern) {
3882            builder.add(glob);
3883        }
3884    }
3885    builder
3886        .build()
3887        .unwrap_or_else(|_| GlobSetBuilder::new().build().unwrap())
3888}
3889}
3890
3891fn collect_workspace_member_dirs(
3892    workspace_root: &Path,
3893    dir: &Path,
3894    positives: &GlobSet,
3895    negatives: &GlobSet,
3896    prefixes: &[(PathBuf, bool)],
3897    members: &mut Vec<PathBuf>,
3898    facts: &FactPaths<'_>,
3899) {
3900    #[cfg(any(test, feature = "test-support"))]
3901    crate::callgraph_store::work_counts::note_workspace_directory(dir);
3902    for entry in facts.list_dir(dir) {
3903        if entry.kind != EntryKind::Directory {
3904            continue;
3905        }
3906        let path = dir.join(byte_path(&entry.name));
3907        let name = String::from_utf8_lossy(&entry.name);
3908        if matches!(
3909            name.as_ref(),
3910            "node_modules" | ".git" | "target" | "dist" | "build"
3911        ) {
3912            continue;
3913        }
3914
3915        let Ok(rel) = path.strip_prefix(workspace_root) else {
3916            continue;
3917        };
3918        if !prefixes.iter().any(|(prefix, recursive)| {
3919            prefix.starts_with(rel) || (*recursive && rel.starts_with(prefix))
3920        }) {
3921            continue;
3922        }
3923        let candidate = rel.to_string_lossy().replace('\\', "/");
3924        if positives.is_match(&candidate)
3925            && !negatives.is_match(&candidate)
3926            && facts.is_file(&path.join("package.json"))
3927        {
3928            members.push(path.clone());
3929        }
3930
3931        if prefixes.iter().any(|(prefix, recursive)| {
3932            (prefix != rel && prefix.starts_with(rel)) || (*recursive && rel.starts_with(prefix))
3933        }) {
3934            collect_workspace_member_dirs(
3935                workspace_root,
3936                &path,
3937                positives,
3938                negatives,
3939                prefixes,
3940                members,
3941                facts,
3942            );
3943        }
3944    }
3945}
3946
3947fn package_json_value(
3948    dir: &Path,
3949    memo: Option<&ModuleResolutionMemo>,
3950    facts: &FactPaths<'_>,
3951) -> Option<Arc<Value>> {
3952    package_json_like_value(&dir.join("package.json"), memo, facts)
3953}
3954
3955fn package_json_like_value(
3956    path: &Path,
3957    memo: Option<&ModuleResolutionMemo>,
3958    facts: &FactPaths<'_>,
3959) -> Option<Arc<Value>> {
3960    if let Some(memo) = memo {
3961        return memo.json_value(path, facts);
3962    }
3963    let json = facts.attributed_bytes(path)?;
3964    serde_json::from_slice(&json).ok().map(Arc::new)
3965}
3966
3967fn package_json_name(
3968    dir: &Path,
3969    memo: Option<&ModuleResolutionMemo>,
3970    facts: &FactPaths<'_>,
3971) -> Option<String> {
3972    facts.config_field(dir, "package.json", "name");
3973    package_json_value(dir, memo, facts)?
3974        .get("name")?
3975        .as_str()
3976        .map(ToOwned::to_owned)
3977}
3978
3979fn resolve_package_entry(
3980    package_root: &Path,
3981    subpath: &Option<String>,
3982    memo: Option<&ModuleResolutionMemo>,
3983    facts: &FactPaths<'_>,
3984) -> Option<PathBuf> {
3985    let package_json =
3986        package_json_value(package_root, memo, facts).unwrap_or_else(|| Arc::new(Value::Null));
3987
3988    facts.config_field(package_root, "package.json", "exports");
3989    if let Some(exports) = package_json.get("exports") {
3990        if let Some(target) = export_target_for_subpath(exports, subpath.as_deref()) {
3991            if let Some(path) = resolve_package_target(package_root, &target, facts) {
3992                return Some(path);
3993            }
3994        }
3995    }
3996
3997    if subpath.is_none() {
3998        for field in ["module", "main"] {
3999            facts.config_field(package_root, "package.json", field);
4000            if let Some(target) = package_json.get(field).and_then(Value::as_str) {
4001                if let Some(path) = resolve_package_target(package_root, target, facts) {
4002                    return Some(path);
4003                }
4004            }
4005        }
4006    }
4007
4008    resolve_package_fallback(package_root, subpath.as_deref(), facts)
4009}
4010
4011fn export_target_for_subpath(exports: &Value, subpath: Option<&str>) -> Option<String> {
4012    let key = subpath
4013        .map(|value| format!("./{value}"))
4014        .unwrap_or_else(|| ".".to_string());
4015
4016    match exports {
4017        Value::String(target) if key == "." => Some(target.clone()),
4018        Value::Object(map) => {
4019            if let Some(target) = map.get(&key).and_then(export_condition_target) {
4020                return Some(target);
4021            }
4022
4023            if let Some(target) = wildcard_export_target(map, &key) {
4024                return Some(target);
4025            }
4026
4027            if key == "." && !map.contains_key(".") && !map.keys().any(|k| k.starts_with("./")) {
4028                return export_condition_target(exports);
4029            }
4030
4031            None
4032        }
4033        _ => None,
4034    }
4035}
4036
4037fn wildcard_export_target(map: &serde_json::Map<String, Value>, key: &str) -> Option<String> {
4038    for (pattern, target) in map {
4039        let Some(star_index) = pattern.find('*') else {
4040            continue;
4041        };
4042        let (prefix, suffix_with_star) = pattern.split_at(star_index);
4043        let suffix = &suffix_with_star[1..];
4044        if !key.starts_with(prefix) || !key.ends_with(suffix) {
4045            continue;
4046        }
4047        let matched = &key[prefix.len()..key.len() - suffix.len()];
4048        if let Some(target_pattern) = export_condition_target(target) {
4049            return Some(target_pattern.replace('*', matched));
4050        }
4051    }
4052    None
4053}
4054
4055fn export_condition_target(value: &Value) -> Option<String> {
4056    match value {
4057        Value::String(target) => Some(target.clone()),
4058        Value::Object(map) => ["source", "import", "module", "default", "types"]
4059            .into_iter()
4060            .find_map(|field| map.get(field).and_then(export_condition_target)),
4061        _ => None,
4062    }
4063}
4064
4065fn resolve_package_target(
4066    package_root: &Path,
4067    target: &str,
4068    facts: &FactPaths<'_>,
4069) -> Option<PathBuf> {
4070    let target = target.strip_prefix("./").unwrap_or(target);
4071    // Prefer source over compiled bundle when both exist: the callgraph
4072    // walks source files and cannot extract symbols from a built JS bundle.
4073    if let Some(src_relative) = target.strip_prefix("dist/") {
4074        if let Some(path) =
4075            resolve_file_like_path(&package_root.join("src").join(src_relative), facts)
4076        {
4077            return Some(path);
4078        }
4079    }
4080
4081    resolve_file_like_path(&package_root.join(target), facts)
4082}
4083
4084fn resolve_package_fallback(
4085    package_root: &Path,
4086    subpath: Option<&str>,
4087    facts: &FactPaths<'_>,
4088) -> Option<PathBuf> {
4089    match subpath {
4090        Some(subpath) => resolve_file_like_path(&package_root.join(subpath), facts)
4091            .or_else(|| resolve_file_like_path(&package_root.join("src").join(subpath), facts)),
4092        None => resolve_file_like_path(&package_root.join("src").join("index"), facts)
4093            .or_else(|| resolve_file_like_path(&package_root.join("index"), facts)),
4094    }
4095}
4096
4097pub fn resolve_reexported_symbol_target<F, D>(
4098    file: &Path,
4099    symbol_name: &str,
4100    file_exports_symbol: &mut F,
4101    file_default_export_symbol: &mut D,
4102) -> Option<(PathBuf, String)>
4103where
4104    F: FnMut(&Path, &str) -> bool,
4105    D: FnMut(&Path) -> Option<String>,
4106{
4107    resolve_reexported_symbol(
4108        file,
4109        symbol_name,
4110        file_exports_symbol,
4111        file_default_export_symbol,
4112    )
4113    .map(|target| (target.file, target.symbol))
4114}
4115
4116test_support_visibility! {
4117fn resolve_reexported_symbol<F, D>(
4118    file: &Path,
4119    symbol_name: &str,
4120    file_exports_symbol: &mut F,
4121    file_default_export_symbol: &mut D,
4122) -> Option<ResolvedSymbol>
4123where
4124    F: FnMut(&Path, &str) -> bool,
4125    D: FnMut(&Path) -> Option<String>,
4126{
4127    let mut visited = HashSet::new();
4128    resolve_reexported_symbol_inner(
4129        file,
4130        symbol_name,
4131        file_exports_symbol,
4132        file_default_export_symbol,
4133        &mut visited,
4134    )
4135}
4136}
4137
4138#[cfg(any(test, feature = "test-support"))]
4139thread_local! {
4140    pub static REEXPORT_PARSE_COUNT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4141}
4142
4143fn parse_reexport_source(
4144    source: &str,
4145    lang: LangId,
4146) -> Result<tree_sitter::Tree, crate::error::AftError> {
4147    #[cfg(any(test, feature = "test-support"))]
4148    REEXPORT_PARSE_COUNT.with(|count| count.set(count.get() + 1));
4149    crate::parser::FileParser::parse_source(Path::new("<reexport-source>"), source, lang)
4150}
4151
4152fn resolve_reexported_symbol_inner<F, D>(
4153    file: &Path,
4154    symbol_name: &str,
4155    file_exports_symbol: &mut F,
4156    file_default_export_symbol: &mut D,
4157    visited: &mut HashSet<(PathBuf, String)>,
4158) -> Option<ResolvedSymbol>
4159where
4160    F: FnMut(&Path, &str) -> bool,
4161    D: FnMut(&Path) -> Option<String>,
4162{
4163    let canon = std::fs::canonicalize(file).unwrap_or_else(|_| file.to_path_buf());
4164    if !visited.insert((canon.clone(), symbol_name.to_string())) {
4165        return None;
4166    }
4167
4168    let source = crate::project_content::read_to_string(&canon).ok()?;
4169    let lang = detect_language(&canon)?;
4170    if !matches!(lang, LangId::TypeScript | LangId::Tsx | LangId::JavaScript) {
4171        if symbol_name == "default" {
4172            return file_default_export_symbol(&canon).map(|symbol| ResolvedSymbol {
4173                file: canon,
4174                symbol,
4175            });
4176        }
4177        return file_exports_symbol(&canon, symbol_name).then(|| ResolvedSymbol {
4178            file: canon,
4179            symbol: symbol_name.to_string(),
4180        });
4181    }
4182
4183    let tree = parse_reexport_source(&source, lang).ok()?;
4184    let from_dir = canon.parent().unwrap_or_else(|| Path::new("."));
4185
4186    let mut cursor = tree.root_node().walk();
4187    if !cursor.goto_first_child() {
4188        return None;
4189    }
4190
4191    loop {
4192        let node = cursor.node();
4193        if node.kind() == "export_statement" {
4194            if let Some(target) = resolve_reexport_statement(
4195                &source,
4196                node,
4197                from_dir,
4198                symbol_name,
4199                file_exports_symbol,
4200                file_default_export_symbol,
4201                visited,
4202            ) {
4203                return Some(target);
4204            }
4205        }
4206
4207        if !cursor.goto_next_sibling() {
4208            break;
4209        }
4210    }
4211
4212    if symbol_name == "default" {
4213        if let Some(symbol) = file_default_export_symbol(&canon) {
4214            return Some(ResolvedSymbol {
4215                file: canon,
4216                symbol,
4217            });
4218        }
4219    }
4220
4221    if let Some(symbol) = resolve_local_export_alias(&source, tree.root_node(), symbol_name) {
4222        return Some(ResolvedSymbol {
4223            file: canon,
4224            symbol,
4225        });
4226    }
4227
4228    if file_exports_symbol(&canon, symbol_name) {
4229        let symbol = symbol_name.to_string();
4230        return Some(ResolvedSymbol {
4231            file: canon,
4232            symbol,
4233        });
4234    }
4235
4236    None
4237}
4238
4239fn resolve_reexport_statement<F, D>(
4240    source: &str,
4241    node: tree_sitter::Node,
4242    from_dir: &Path,
4243    symbol_name: &str,
4244    file_exports_symbol: &mut F,
4245    file_default_export_symbol: &mut D,
4246    visited: &mut HashSet<(PathBuf, String)>,
4247) -> Option<ResolvedSymbol>
4248where
4249    F: FnMut(&Path, &str) -> bool,
4250    D: FnMut(&Path) -> Option<String>,
4251{
4252    let source_node = node
4253        .child_by_field_name("source")
4254        .or_else(|| find_child_by_kind(node, "string"))?;
4255    let module_path = string_literal_content(source, source_node)?;
4256    let target_file = resolve_module_path(from_dir, &module_path)?;
4257    let raw_export = node_text(node, source);
4258
4259    if let Some(source_symbol) = reexport_clause_source_symbol(&raw_export, symbol_name) {
4260        return resolve_reexported_symbol_inner(
4261            &target_file,
4262            &source_symbol,
4263            file_exports_symbol,
4264            file_default_export_symbol,
4265            visited,
4266        )
4267        .or(Some(ResolvedSymbol {
4268            file: target_file,
4269            symbol: source_symbol,
4270        }));
4271    }
4272
4273    if raw_export.contains('*') {
4274        return resolve_reexported_symbol_inner(
4275            &target_file,
4276            symbol_name,
4277            file_exports_symbol,
4278            file_default_export_symbol,
4279            visited,
4280        );
4281    }
4282
4283    None
4284}
4285
4286fn resolve_local_export_alias(
4287    source: &str,
4288    root: tree_sitter::Node,
4289    requested_export: &str,
4290) -> Option<String> {
4291    let mut cursor = root.walk();
4292    if !cursor.goto_first_child() {
4293        return None;
4294    }
4295
4296    loop {
4297        let node = cursor.node();
4298        if node.kind() == "export_statement" && node.child_by_field_name("source").is_none() {
4299            let raw_export = node_text(node, source);
4300            if let Some(source_symbol) =
4301                reexport_clause_source_symbol(&raw_export, requested_export)
4302            {
4303                return Some(source_symbol);
4304            }
4305        }
4306
4307        if !cursor.goto_next_sibling() {
4308            break;
4309        }
4310    }
4311
4312    None
4313}
4314
4315fn reexport_clause_source_symbol(raw_export: &str, requested_export: &str) -> Option<String> {
4316    let start = raw_export.find('{')? + 1;
4317    let end = raw_export[start..].find('}')? + start;
4318    for specifier in raw_export[start..end].split(',') {
4319        let specifier = specifier.trim();
4320        if specifier.is_empty() {
4321            continue;
4322        }
4323        let specifier = specifier.strip_prefix("type ").unwrap_or(specifier).trim();
4324        if let Some((imported, exported)) = specifier.split_once(" as ") {
4325            if exported.trim() == requested_export {
4326                return Some(imported.trim().to_string());
4327            }
4328        } else if specifier == requested_export {
4329            return Some(requested_export.to_string());
4330        }
4331    }
4332    None
4333}
4334
4335fn string_literal_content(source: &str, node: tree_sitter::Node) -> Option<String> {
4336    let raw = source[node.byte_range()].trim();
4337    let quote = raw.chars().next()?;
4338    if quote != '\'' && quote != '"' {
4339        return None;
4340    }
4341    raw.strip_prefix(quote)
4342        .and_then(|value| value.strip_suffix(quote))
4343        .map(ToOwned::to_owned)
4344}
4345
4346/// Find an index file in a directory.
4347fn find_index_file(dir: &Path, facts: &FactPaths<'_>) -> Option<PathBuf> {
4348    for name in JS_TS_INDEX_FILES {
4349        let p = dir.join(name);
4350        if facts.is_file(&p) {
4351            return Some(facts.canonical(&p).unwrap_or(p));
4352        }
4353    }
4354    None
4355}
4356
4357/// Resolve an aliased import: `import { foo as bar } from './utils'`
4358/// where `local_name` is "bar". Returns `(original_name, resolved_file_path)`.
4359fn resolve_aliased_import(
4360    local_name: &str,
4361    import_block: &ImportBlock,
4362    caller_dir: &Path,
4363) -> Option<(String, PathBuf)> {
4364    for imp in &import_block.imports {
4365        // Parse the raw text to find "as <alias>" patterns
4366        // This handles: import { foo as bar, baz as qux } from './mod'
4367        if let Some(original) = find_alias_original(&imp.raw_text, local_name) {
4368            if let Some(resolved_path) = resolve_module_path(caller_dir, &imp.module_path) {
4369                return Some((original, resolved_path));
4370            }
4371        }
4372    }
4373    None
4374}
4375
4376test_support_visibility! {
4377/// Parse import raw text to find the original name for an alias.
4378/// Given raw text like `import { foo as bar, baz } from './utils'` and
4379/// local_name "bar", returns Some("foo").
4380fn find_alias_original(raw_import: &str, local_name: &str) -> Option<String> {
4381    // Look for pattern: <original> as <alias>
4382    // This is a simple text-based search; handles the common TS/JS pattern
4383    let search = format!(" as {}", local_name);
4384    if let Some(pos) = raw_import.find(&search) {
4385        // Walk backwards from `pos` to find the original name
4386        let before = &raw_import[..pos];
4387        // The original name is the last word-like token before " as "
4388        let original = before
4389            .rsplit(|c: char| c == '{' || c == ',' || c.is_whitespace())
4390            .find(|s| !s.is_empty())?;
4391        return Some(original.to_string());
4392    }
4393    None
4394}
4395}
4396
4397// ---------------------------------------------------------------------------
4398// Worktree file discovery
4399// ---------------------------------------------------------------------------
4400
4401/// Directories the callgraph walk always skips, whatever .gitignore says.
4402const WALK_EXCLUDED_DIR_NAMES: [&str; 9] = [
4403    "node_modules",
4404    "target",
4405    "venv",
4406    ".venv",
4407    ".git",
4408    "__pycache__",
4409    ".tox",
4410    "dist",
4411    "build",
4412];
4413
4414/// Walk project files respecting .gitignore, excluding common non-source dirs.
4415///
4416/// Returns an iterator of file paths for supported source file types.
4417pub fn walk_project_files(
4418    root: &Path,
4419    access: crate::project_walk::IgnoreFileAccess,
4420) -> impl Iterator<Item = PathBuf> {
4421    walk_project_files_filtered(root, access, |_| true)
4422}
4423
4424/// Walk the requested project subtrees, stopping before the next raw walker
4425/// advance when the caller's budget expires.
4426/// Starting at the project root preserves ignored-parent and nested ignore
4427/// rules; pruning before descent avoids traversing unrelated subtrees.
4428pub fn walk_project_files_in_scope_while(
4429    root: &Path,
4430    access: crate::project_walk::IgnoreFileAccess,
4431    scope_roots: &[PathBuf],
4432    keep_walking: impl Fn() -> bool + Send + Sync + 'static,
4433) -> impl Iterator<Item = PathBuf> {
4434    let roots = scope_roots.to_vec();
4435    walk_project_files_filtered_while(
4436        root,
4437        access,
4438        move |path| {
4439            roots
4440                .iter()
4441                .any(|root| path.starts_with(root) || root.starts_with(path))
4442        },
4443        keep_walking,
4444    )
4445}
4446
4447test_support_visibility! {
4448fn walk_project_files_filtered(
4449    root: &Path,
4450    access: crate::project_walk::IgnoreFileAccess,
4451    include: impl Fn(&Path) -> bool + Send + Sync + 'static,
4452) -> impl Iterator<Item = PathBuf> {
4453    walk_project_files_filtered_while(root, access, include, || true)
4454}
4455}
4456
4457/// Stop before advancing the directory iterator, not just between source files.
4458/// Unsupported files and directories still consume a caller's walk budget.
4459pub fn walk_project_files_while(
4460    root: &Path,
4461    access: crate::project_walk::IgnoreFileAccess,
4462    keep_walking: impl Fn() -> bool + Send + Sync + 'static,
4463) -> impl Iterator<Item = PathBuf> {
4464    walk_project_files_filtered_while(root, access, |_| true, keep_walking)
4465}
4466
4467#[cfg(any(test, feature = "test-support"))]
4468#[test]
4469fn audit01_walk_cancellation_observes_unsupported_entries() {
4470    let root = tempfile::tempdir().unwrap();
4471    for name in ["one.unsupported", "two.unsupported", "three.unsupported"] {
4472        std::fs::write(root.path().join(name), "").unwrap();
4473    }
4474    let checks = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
4475    let observed = checks.clone();
4476    let files = walk_project_files_while(
4477        root.path(),
4478        crate::project_walk::IgnoreFileAccess::Allowed,
4479        move || {
4480            observed.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
4481            false
4482        },
4483    )
4484    .collect::<Vec<_>>();
4485    assert!(files.is_empty());
4486    assert_eq!(
4487        checks.load(std::sync::atomic::Ordering::SeqCst),
4488        1,
4489        "cancellation must run before source-file filtering"
4490    );
4491}
4492
4493/// Walk all non-excluded files under a root, using the same bounded iterator
4494/// and ignore rules as the source-file census. Caller-excluded paths are pruned
4495/// before descent.
4496pub fn walk_project_paths_while(
4497    root: &Path,
4498    access: crate::project_walk::IgnoreFileAccess,
4499    include: impl Fn(&Path) -> bool + Send + Sync + 'static,
4500    keep_walking: impl Fn() -> bool + Send + Sync + 'static,
4501) -> impl Iterator<Item = PathBuf> {
4502    walk_project_paths_filtered_while_with_builder(root, access, include, keep_walking, |_| {})
4503}
4504
4505fn walk_project_files_filtered_while(
4506    root: &Path,
4507    access: crate::project_walk::IgnoreFileAccess,
4508    include: impl Fn(&Path) -> bool + Send + Sync + 'static,
4509    keep_walking: impl Fn() -> bool + Send + Sync + 'static,
4510) -> impl Iterator<Item = PathBuf> {
4511    walk_project_files_filtered_while_with_builder(root, access, include, keep_walking, |_| {})
4512}
4513
4514#[cfg(any(test, feature = "test-support"))]
4515pub fn walk_project_files_while_sorted_for_test(
4516    root: &Path,
4517    access: crate::project_walk::IgnoreFileAccess,
4518    keep_walking: impl Fn() -> bool + Send + Sync + 'static,
4519) -> impl Iterator<Item = PathBuf> {
4520    walk_project_files_filtered_while_with_builder(
4521        root,
4522        access,
4523        |_| true,
4524        keep_walking,
4525        |builder| {
4526            builder.sort_by_file_name(|left, right| left.cmp(right));
4527        },
4528    )
4529}
4530
4531fn walk_project_files_filtered_while_with_builder(
4532    root: &Path,
4533    access: crate::project_walk::IgnoreFileAccess,
4534    include: impl Fn(&Path) -> bool + Send + Sync + 'static,
4535    keep_walking: impl Fn() -> bool + Send + Sync + 'static,
4536    configure_builder: impl FnOnce(&mut ignore::WalkBuilder),
4537) -> impl Iterator<Item = PathBuf> {
4538    walk_project_paths_filtered_while_with_builder(
4539        root,
4540        access,
4541        include,
4542        keep_walking,
4543        configure_builder,
4544    )
4545    .filter(|path| {
4546        crate::parser::detect_language_any(path, cfg!(feature = "wasm-grammars")).is_some()
4547    })
4548}
4549
4550fn walk_project_paths_filtered_while_with_builder(
4551    root: &Path,
4552    access: crate::project_walk::IgnoreFileAccess,
4553    include: impl Fn(&Path) -> bool + Send + Sync + 'static,
4554    keep_walking: impl Fn() -> bool + Send + Sync + 'static,
4555    configure_builder: impl FnOnce(&mut ignore::WalkBuilder),
4556) -> impl Iterator<Item = PathBuf> {
4557    use ignore::WalkBuilder;
4558
4559    // A disappearing child mount can make ReadDir::drop panic on ENXIO and abort
4560    // the daemon, so never open directories outside this walk root's filesystem.
4561    let mut builder = WalkBuilder::new(root);
4562    builder.same_file_system(true).hidden(true); // skip hidden files/dirs
4563                                                 // .gitignore (also outside a git repository), global excludes,
4564                                                 // .git/info/exclude and .aftignore (e.g. submodules).
4565    configure_builder(&mut builder);
4566    let filter_keep_walking = std::sync::Arc::new(keep_walking);
4567    let filter_budget = std::sync::Arc::clone(&filter_keep_walking);
4568    // Skip nested linked worktrees of this repository: their files are indexed
4569    // under their own roots. The walk root itself is always admitted (depth 0).
4570    let worktrees = crate::project_content::NestedWorktreeBoundary::for_root(root);
4571    let mut walker = crate::project_walk::apply_project_ignore_rules(&mut builder, root, access)
4572        .filter_entry(move |entry| {
4573            #[cfg(any(test, feature = "test-support"))]
4574            crate::walk_profile::entry();
4575            #[cfg(any(test, feature = "test-support"))]
4576            PROJECT_WALK_FILTER_ENTRIES
4577                .with(|entries| entries.borrow_mut().push(entry.path().to_path_buf()));
4578            // The ignore crate filters hidden and ignored entries before this hook.
4579            // Once the budget expires, it prevents descent and yielding, but
4580            // the current Walk::next() can still finish this directory. The
4581            // remaining worst case is one directory listing.
4582            if !filter_budget() {
4583                return false;
4584            }
4585            #[cfg(any(test, feature = "test-support"))]
4586            {
4587                PROJECT_WALK_ENTRIES.with(|count| count.set(count.get() + 1));
4588                PROJECT_WALK_ACCEPTED_FILTER_ENTRIES
4589                    .with(|entries| entries.borrow_mut().push(entry.path().to_path_buf()));
4590            }
4591            include(entry.path()) && project_walk_entry_is_included(entry, &worktrees)
4592        })
4593        .build();
4594    // Filtering to source paths first can hide arbitrarily many directory/file
4595    // visits inside a single next() call. Check before each raw walker advance.
4596    let walk_budget = std::sync::Arc::clone(&filter_keep_walking);
4597    std::iter::from_fn(move || walk_budget().then(|| walker.next()).flatten())
4598        .fuse()
4599        .filter_map(|entry| entry.ok())
4600        .filter(|entry| entry.file_type().map_or(false, |ft| ft.is_file()))
4601        .map(|entry| entry.into_path())
4602}
4603
4604pub fn project_walk_entry_is_included(
4605    entry: &ignore::DirEntry,
4606    worktrees: &crate::project_content::NestedWorktreeBoundary,
4607) -> bool {
4608    let file_type = entry.file_type();
4609    if crate::project_content::is_excluded_with_file_type(entry.path(), file_type.as_ref())
4610        || crate::project_walk::is_nested_worktree_entry(entry, worktrees)
4611    {
4612        return false;
4613    }
4614    if file_type.as_ref().is_some_and(std::fs::FileType::is_dir) {
4615        return !WALK_EXCLUDED_DIR_NAMES.contains(&entry.file_name().to_string_lossy().as_ref());
4616    }
4617    !crate::os_metadata::is_os_metadata_file_name(entry.file_name())
4618}
4619
4620#[cfg(any(test, feature = "test-support"))]
4621thread_local! {
4622    pub static PROJECT_WALK_ENTRIES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4623    pub static PROJECT_WALK_FILTER_ENTRIES: std::cell::RefCell<Vec<PathBuf>> = const { std::cell::RefCell::new(Vec::new()) };
4624    pub static PROJECT_WALK_ACCEPTED_FILTER_ENTRIES: std::cell::RefCell<Vec<PathBuf>> = const { std::cell::RefCell::new(Vec::new()) };
4625}
4626
4627/// Whether [`walk_project_files`] can yield the file at this root-relative
4628/// path (`/` or `\` separators), judged from the path alone: a supported
4629/// source type, no hidden component, no always-excluded directory and no OS
4630/// metadata file name. Ignore files are not consulted; callers pass paths
4631/// that an ignore-respecting walk has already produced.
4632pub fn walk_could_include(relative: &str) -> bool {
4633    let components: Vec<&str> = relative
4634        .split(['/', '\\'])
4635        .filter(|component| !component.is_empty())
4636        .collect();
4637    let Some((file_name, directories)) = components.split_last() else {
4638        return false;
4639    };
4640    if components
4641        .iter()
4642        .any(|component| component.starts_with('.'))
4643    {
4644        return false;
4645    }
4646    if directories
4647        .iter()
4648        .any(|directory| WALK_EXCLUDED_DIR_NAMES.contains(directory))
4649    {
4650        return false;
4651    }
4652    if crate::os_metadata::is_os_metadata_file_name(std::ffi::OsStr::new(file_name)) {
4653        return false;
4654    }
4655    crate::parser::detect_language_any(Path::new(file_name), cfg!(feature = "wasm-grammars"))
4656        .is_some()
4657}
4658
4659// ---------------------------------------------------------------------------
4660// Tests
4661// ---------------------------------------------------------------------------
4662
4663#[cfg(any(test, feature = "test-support"))]
4664fn symbol_query_candidates(file_data: &FileCallData, symbol_name: &str) -> Vec<String> {
4665    let mut seen = HashSet::new();
4666    let mut candidates = Vec::new();
4667    let qualified_query = symbol_name.contains("::");
4668    let mut consider = |candidate: &str| {
4669        let matches = if qualified_query {
4670            candidate == symbol_name
4671        } else {
4672            candidate == symbol_name || symbol_unqualified_name(candidate) == symbol_name
4673        };
4674        if matches && seen.insert(candidate.to_string()) {
4675            candidates.push(candidate.to_string());
4676        }
4677    };
4678    for candidate in file_data.symbol_metadata.keys() {
4679        consider(candidate);
4680    }
4681    for candidate in file_data.calls_by_symbol.keys() {
4682        consider(candidate);
4683    }
4684    for candidate in &file_data.exported_symbols {
4685        consider(candidate);
4686    }
4687    candidates.sort();
4688    candidates
4689}
4690
4691#[cfg(any(test, feature = "test-support"))]
4692pub fn resolve_symbol_query_in_data(
4693    file_data: &FileCallData,
4694    file: &Path,
4695    symbol_name: &str,
4696) -> Result<String, AftError> {
4697    let candidates = symbol_query_candidates(file_data, symbol_name);
4698    match candidates.as_slice() {
4699        [candidate] => Ok(candidate.clone()),
4700        [] => Err(AftError::SymbolNotFound {
4701            name: symbol_name.to_string(),
4702            file: file.display().to_string(),
4703        }),
4704        _ => Err(AftError::AmbiguousSymbol {
4705            name: symbol_name.to_string(),
4706            candidates,
4707        }),
4708    }
4709}
4710
4711#[cfg(test)]
4712mod rust_use_regressions {
4713    use super::*;
4714    #[test]
4715    fn rust_use_tree_expansion_preserves_depth_first_entry_order() {
4716        let mut entries = Vec::new();
4717        expand_rust_use_tree(
4718            "root::{first, branch::{self, nested::{Leaf as Renamed, *, {}}, after}, self, *, {}, last as Tail}",
4719            &mut entries,
4720        );
4721        let actual: Vec<_> = entries
4722            .iter()
4723            .map(|entry| {
4724                let imported = match &entry.kind {
4725                    RustUseKind::Item { imported_name } => Some(imported_name.as_str()),
4726                    RustUseKind::Module => None,
4727                };
4728                (
4729                    entry.module_path.as_str(),
4730                    entry.local_name.as_str(),
4731                    imported,
4732                )
4733            })
4734            .collect();
4735        assert_eq!(
4736            actual,
4737            [
4738                ("root", "first", Some("first")),
4739                ("root::first", "first", None),
4740                ("root::branch", "branch", None),
4741                ("root::branch::nested", "Renamed", Some("Leaf")),
4742                ("root::branch::nested::Leaf", "Renamed", None),
4743                ("root::branch", "after", Some("after")),
4744                ("root::branch::after", "after", None),
4745                ("root", "root", None),
4746                ("root", "Tail", Some("last")),
4747                ("root::last", "Tail", None),
4748            ]
4749        );
4750    }
4751}