Skip to main content

aft_parse/callgraph_store/
mod.rs

1//! Shared call-graph resolution and query contracts.
2//!
3//! The index store binds extracted facts through this resolver and implements
4//! the reader contract used by navigation commands. The retired SQLite store
5//! no longer owns builds, generations, readers, or refresh workers here.
6
7pub mod access;
8mod dispatch_type_hints;
9use dispatch_type_hints::*;
10pub mod disk_facts;
11pub mod fact_answers;
12pub mod facts;
13test_support_visibility! {
14    mod go_dispatch;
15}
16pub mod join;
17test_support_visibility! {
18    mod luau;
19}
20pub mod method_call_facts;
21#[cfg(target_os = "macos")]
22mod readiness_watch_macos;
23pub mod resolution_facts;
24use facts::{byte_path, EntryKind, FactPaths, ProjectFacts};
25#[cfg(any(test, feature = "test-support"))]
26use std::sync::Mutex;
27#[cfg(any(test, feature = "test-support"))]
28use std::time::{Duration, Instant};
29
30use crate::callgraph::{self, FileCallData, TraceToSymbolCandidate};
31use crate::error::AftError;
32use crate::imports::{ImportForm, ImportGroup, ImportKind, ImportStatement};
33use crate::parser::{parse_source_with_cached_parser, LangId};
34use crate::symbols::SymbolKind;
35use join::syntax_index::{Direct, Nav};
36use std::cell::RefCell;
37use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};
38use std::fmt;
39use std::path::{Path, PathBuf};
40use std::rc::Rc;
41use std::sync::{Arc, OnceLock};
42use std::time::{SystemTime, UNIX_EPOCH};
43use tree_sitter::Node;
44
45pub const PROVENANCE_TREESITTER: &str = "treesitter+resolver";
46pub const PROVENANCE_NAME_MATCH: &str = "name_match";
47pub const PROVENANCE_TYPE_MATCH: &str = "type_match";
48pub const PROVENANCE_VALUE_REF: &str = "value_ref";
49/// Ref kind for a call written directly in a `macro_rules!` template; the
50/// macro name is stored in `local_name`. Never resolved into an edge.
51pub const MACRO_BODY_CALL_REF_KIND: &str = "macro_body_call";
52/// Ref kind for an identifier inside a Rust macro token tree that could not be
53/// parsed as Rust. Never resolved into an edge.
54pub const MACRO_MENTION_REF_KIND: &str = "macro_mention";
55pub const TOP_LEVEL_SYMBOL: &str = "<top-level>";
56const JS_TS_EXTENSIONS: &[&str] = &["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"];
57
58/// Work counters for measurement tests: source parses by the store and
59/// resolution-config reads (`package.json`, `tsconfig.json`, `Cargo.toml`).
60/// They are keyed by absolute path because the work runs on build-pool
61/// threads, and tests running in parallel must each count only the files
62/// under their own fixture root.
63pub mod dead_code_projection;
64
65test_support_visibility! {
66    mod rust_bindings;
67}
68pub use dead_code_projection::{
69    ProjectionCostEstimates, ProjectionKind, ProjectionVerdict, MAX_DELTA_BYTES,
70};
71
72#[derive(Debug)]
73pub enum CallGraphStoreError {
74    Io(std::io::Error),
75    Sqlite(rusqlite::Error),
76    Json(serde_json::Error),
77    Aft(AftError),
78    Lock(crate::fs_lock::AcquireError),
79    MissingCallerData {
80        file: String,
81    },
82    Unavailable(String),
83    PathIdentityMismatch {
84        path: PathBuf,
85        project_root: PathBuf,
86    },
87    Suspended(crate::build_state::BuildSuspension),
88    Superseded,
89    CorpusSnapshotMissing(PathBuf),
90    CorpusInventoryChanged(Option<PathBuf>),
91    StaleFiles(Vec<String>),
92    /// The data layer's call graph is still building or catching up with
93    /// edits; a reader retries.
94    Building,
95}
96
97impl CallGraphStoreError {
98    /// SQLite reported the database busy or locked. A view reader opens
99    /// without a busy wait, so this is a moment of contention (a publication
100    /// checkpointing the database it reads), not a failure: commands report it
101    /// as a retryable `callgraph_building`.
102    pub fn is_transient_lock_contention(&self) -> bool {
103        matches!(
104            self,
105            Self::Sqlite(rusqlite::Error::SqliteFailure(error, _))
106                if matches!(
107                    error.code,
108                    rusqlite::ErrorCode::DatabaseBusy | rusqlite::ErrorCode::DatabaseLocked
109                )
110        )
111    }
112}
113
114impl fmt::Display for CallGraphStoreError {
115    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
116        match self {
117            Self::Io(error) => write!(formatter, "I/O error: {error}"),
118            Self::Sqlite(error) => write!(formatter, "sqlite error: {error}"),
119            Self::Json(error) => write!(formatter, "json error: {error}"),
120            Self::Aft(error) => write!(formatter, "callgraph extraction error: {error}"),
121            Self::Lock(error) => write!(formatter, "callgraph writer lease error: {error}"),
122            Self::MissingCallerData { file } => {
123                write!(formatter, "missing extracted caller data for {file}")
124            }
125            Self::Unavailable(message) => {
126                write!(formatter, "callgraph store unavailable: {message}")
127            }
128            Self::PathIdentityMismatch { path, project_root } => write!(
129                formatter,
130                "callgraph path identity mismatch: {} is not under project root {}",
131                path.display(),
132                project_root.display()
133            ),
134            Self::Suspended(suspension) => write!(
135                formatter,
136                "callgraph build suspended for {} after {} deaths ({})",
137                suspension.domain.as_str(),
138                suspension.death_count,
139                suspension.reason
140            ),
141            Self::Superseded => {
142                write!(formatter, "callgraph store build superseded before publish")
143            }
144            Self::Building => write!(formatter, "the call graph is still building"),
145            Self::CorpusSnapshotMissing(path) => write!(
146                formatter,
147                "callgraph corpus snapshot lookup invariant failed: {} was not admitted",
148                path.display()
149            ),
150            Self::CorpusInventoryChanged(path) => {
151                write!(
152                    formatter,
153                    "callgraph corpus inventory changed after admission"
154                )?;
155                if let Some(path) = path {
156                    write!(formatter, ": {} was added", path.display())?;
157                }
158                Ok(())
159            }
160            Self::StaleFiles(files) => {
161                write!(
162                    formatter,
163                    "callgraph store has stale files: {}",
164                    files.join(", ")
165                )
166            }
167        }
168    }
169}
170
171impl std::error::Error for CallGraphStoreError {}
172
173impl From<std::io::Error> for CallGraphStoreError {
174    fn from(error: std::io::Error) -> Self {
175        Self::Io(error)
176    }
177}
178
179impl From<rusqlite::Error> for CallGraphStoreError {
180    fn from(error: rusqlite::Error) -> Self {
181        Self::Sqlite(error)
182    }
183}
184
185impl From<serde_json::Error> for CallGraphStoreError {
186    fn from(error: serde_json::Error) -> Self {
187        Self::Json(error)
188    }
189}
190
191impl From<AftError> for CallGraphStoreError {
192    fn from(error: AftError) -> Self {
193        Self::Aft(error)
194    }
195}
196
197impl From<crate::fs_lock::AcquireError> for CallGraphStoreError {
198    fn from(error: crate::fs_lock::AcquireError) -> Self {
199        Self::Lock(error)
200    }
201}
202
203pub type Result<T> = std::result::Result<T, CallGraphStoreError>;
204
205type WorkspaceCratePrefixes = HashMap<String, String>;
206
207#[derive(Clone, Debug, Default)]
208pub struct WorkspaceCratePrefixCache(
209    Arc<OnceLock<WorkspaceCratePrefixes>>,
210    Arc<OnceLock<HashMap<String, String>>>,
211);
212
213pub fn refresh_lease_release_event(event: &notify::Event, lease: &Path) -> bool {
214    use notify::{event::ModifyKind, EventKind};
215    let Some(directory) = lease.parent() else {
216        return false;
217    };
218    let same_directory = |path: &Path| {
219        path == directory
220            || match (fs_canonicalize(path), fs_canonicalize(directory)) {
221                (Ok(path), Ok(directory)) => path == directory,
222                _ => false,
223            }
224    };
225    let named_release = matches!(
226        event.kind,
227        EventKind::Remove(_) | EventKind::Modify(ModifyKind::Name(_))
228    ) && event.paths.iter().any(|path| {
229        path.file_name() == lease.file_name() && path.parent().is_some_and(&same_directory)
230    });
231    // Native watchers can coalesce a deletion into directory/sidecar activity,
232    // and spell the watched directory through an alias (/var vs /private/var).
233    // Activity is a hint only when the lease is gone; the worker still checks
234    // writer liveness before reopening the store.
235    let sibling_change = matches!(
236        event.kind,
237        EventKind::Any | EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_)
238    ) && !lease.exists()
239        && event
240            .paths
241            .iter()
242            .any(|path| same_directory(path) || path.parent().is_some_and(&same_directory));
243    named_release || sibling_change
244}
245
246/// Readiness notifications for one cache directory. macOS uses a vnode watch
247/// so unlinking a lease wakes the waiter even if FSEvents coalesces it away.
248/// Windows uses AFT's directory watcher to avoid re-arming notify reads on
249/// closed handles. Other platforms keep notify's watcher.
250#[cfg(not(any(windows, target_os = "macos")))]
251pub type ReadinessWatcher = notify::RecommendedWatcher;
252#[cfg(windows)]
253pub type ReadinessWatcher = Box<dyn ReadinessWatcherHandle>;
254#[cfg(target_os = "macos")]
255pub type ReadinessWatcher = readiness_watch_macos::DirectoryWatch;
256
257/// Watches `dir`, without its subdirectories, and hands every event to
258/// `handler` until the returned watcher is dropped.
259pub fn watch_readiness_directory<F>(
260    dir: &Path,
261    handler: F,
262    #[cfg(windows)] factory: &dyn ReadinessWatcherFactory,
263) -> notify::Result<ReadinessWatcher>
264where
265    F: FnMut(notify::Result<notify::Event>) + Send + 'static,
266{
267    #[cfg(not(any(windows, target_os = "macos")))]
268    {
269        use notify::{RecursiveMode, Watcher};
270        let mut watcher = notify::recommended_watcher(handler)?;
271        watcher.watch(dir, RecursiveMode::NonRecursive)?;
272        Ok(watcher)
273    }
274    #[cfg(windows)]
275    {
276        factory.watch(dir, Box::new(handler))
277    }
278    #[cfg(target_os = "macos")]
279    {
280        readiness_watch_macos::DirectoryWatch::start(dir, handler)
281    }
282}
283
284/// An owned readiness subscription; dropping the handle stops its watcher.
285#[cfg(windows)]
286pub trait ReadinessWatcherHandle: Send {}
287
288/// Constructs the native readiness watcher for the application.
289#[cfg(windows)]
290pub trait ReadinessWatcherFactory {
291    fn watch(
292        &self,
293        dir: &Path,
294        handler: Box<dyn FnMut(notify::Result<notify::Event>) + Send>,
295    ) -> notify::Result<Box<dyn ReadinessWatcherHandle>>;
296}
297
298/// Bound the work spent counting unresolved possible callers.
299pub const UNRESOLVED_CALL_SITE_COUNT_LIMIT: usize = 1_000;
300
301pub trait CallGraphRead {
302    fn project_root(&self) -> &Path;
303    fn project_key(&self) -> &str;
304    fn sqlite_path(&self) -> &Path;
305    fn is_current(&self) -> bool;
306    fn edge_snapshot(&self) -> Result<BTreeSet<StoredEdge>>;
307    fn indexed_file_count(&self) -> Result<usize>;
308    fn node_for(&self, file_rel: &Path, symbol: &str) -> Result<StoreNode>;
309    fn nodes_for(&self, file_rel: &Path, symbol: &str) -> Result<Vec<StoreNode>>;
310    /// `nodes_for` for a file path this store returned (store-relative and
311    /// already resolved), without resolving it against the filesystem again.
312    /// Graph walks call this once per visited node.
313    fn nodes_for_stored(&self, file: &str, symbol: &str) -> Result<Vec<StoreNode>> {
314        self.nodes_for(Path::new(file), symbol)
315    }
316    /// The indexed content hash for a path returned by this store, or `None`
317    /// when unknown. Compare before pairing stored positions with live text.
318    fn stored_content_hash(&self, _file: &str) -> Result<Option<String>> {
319        Ok(None)
320    }
321    fn nodes_matching(&self, symbol: &str) -> Result<Vec<StoreNode>>;
322    fn direct_callers_of(&self, file_rel: &Path, symbol: &str) -> Result<Vec<StoreCallSite>>;
323    fn direct_callers_for_symbols(
324        &self,
325        targets: &[(String, String)],
326    ) -> Result<HashMap<(String, String), Vec<StoreCallSite>>> {
327        targets
328            .iter()
329            .cloned()
330            .map(|target| {
331                let callers = self.direct_callers_of(Path::new(&target.0), &target.1)?;
332                Ok((target, callers))
333            })
334            .collect()
335    }
336    fn direct_caller_counts_of(
337        &self,
338        targets: &[(String, String)],
339    ) -> Result<HashMap<(String, String), usize>>;
340    /// Fetch at most `limit` caller sites, reporting whether more were found.
341    /// Stop in the edge iterator, before constructing a site beyond the limit.
342    fn direct_callers_bounded(
343        &self,
344        targets: &[(String, String)],
345        limit: usize,
346    ) -> Result<(HashMap<(String, String), Vec<StoreCallSite>>, bool, usize)>;
347    fn outgoing_calls_for_symbols(
348        &self,
349        sources: &[(String, String)],
350    ) -> Result<HashMap<(String, String), Vec<StoreCallSite>>>;
351    fn callers_of(&self, file_rel: &Path, symbol: &str, depth: usize)
352        -> Result<StoreCallersResult>;
353    fn impact_of(&self, file_rel: &Path, symbol: &str, depth: usize) -> Result<StoreImpactResult>;
354    fn outgoing_calls_of(&self, node: &StoreNode) -> Result<Vec<StoreCallSite>>;
355    fn resolved_self_calls_of(&self, node: &StoreNode) -> Result<Vec<StoreCallSite>>;
356    fn unresolved_calls_of(&self, node: &StoreNode) -> Result<Vec<StoreUnresolvedCall>>;
357    /// Raw ref rows of `kind` whose short name is `short_name`, resolved or
358    /// not, at most `limit` of them in file and line order. `callers` uses it
359    /// to find macro invocations and macro facts by name. Stores that keep no
360    /// such rows answer with none.
361    fn ref_sites_named(
362        &self,
363        kind: &str,
364        short_name: &str,
365        limit: usize,
366    ) -> Result<Vec<StoreRefSite>> {
367        let _ = (kind, short_name, limit);
368        Ok(Vec::new())
369    }
370    /// The calls written inside the `macro_rules!` template that `node`, a
371    /// macro owner (`name!`), defines, resolved or not, in source order.
372    /// `call_tree` and `trace_to_symbol` follow them by name, as `callers`
373    /// lists them. Stores that keep no such rows answer with none.
374    fn macro_template_calls_of(&self, node: &StoreNode) -> Result<Vec<StoreUnresolvedCall>> {
375        let _ = node;
376        Ok(Vec::new())
377    }
378    /// Unbound receiver calls of the written member name, excluding sites that
379    /// already have a supplemental edge. An empty reverse graph cannot prove
380    /// these calls do not reach the queried method.
381    fn unresolved_method_sites_named(
382        &self,
383        name: &str,
384        language: LangId,
385    ) -> Result<Vec<StoreRefSite>> {
386        let _ = (name, language);
387        Ok(Vec::new())
388    }
389    /// Count all unresolved invocation spans with this name and return up to
390    /// `limit` locations, ordered by file and source position. Unlike the
391    /// general warning count, this total is exact and respects the test filter.
392    fn unresolved_call_sites_named(
393        &self,
394        name: &str,
395        language: LangId,
396        include_tests: bool,
397        limit: usize,
398    ) -> Result<(usize, Vec<StoreRefSite>)> {
399        let _ = (name, language, include_tests, limit);
400        Ok((0, Vec::new()))
401    }
402    /// Count unresolved invocation sites, stopping at `UNRESOLVED_CALL_SITE_COUNT_LIMIT`.
403    /// A count at the limit is a lower bound, not an exact total.
404    fn unresolved_call_site_count(&self, language: LangId, include_tests: bool) -> Result<usize> {
405        let _ = (language, include_tests);
406        Ok(0)
407    }
408    /// Count distinct (caller file, byte start, byte end) spans with this short
409    /// name, including bare imported calls. The test filter and SQL count limit
410    /// match the unnamed count.
411    fn unresolved_call_site_count_named(
412        &self,
413        name: &str,
414        language: LangId,
415        include_tests: bool,
416    ) -> Result<usize> {
417        let _ = (name, language, include_tests);
418        Ok(0)
419    }
420    fn call_tree(
421        &self,
422        file_rel: &Path,
423        symbol: &str,
424        depth: usize,
425    ) -> Result<callgraph::CallTreeNode>;
426    fn trace_to(
427        &self,
428        file_rel: &Path,
429        symbol: &str,
430        max_depth: usize,
431    ) -> Result<callgraph::TraceToResult>;
432    fn trace_to_symbol_candidates(&self, to_symbol: &str) -> Result<Vec<TraceToSymbolCandidate>>;
433    fn trace_to_symbol(
434        &self,
435        file_rel: &Path,
436        symbol: &str,
437        to_symbol: &str,
438        to_file: Option<&Path>,
439        max_depth: usize,
440    ) -> Result<callgraph::TraceToSymbolResult>;
441}
442
443#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
444pub struct StoredEdge {
445    pub source_file: String,
446    pub source_symbol: String,
447    pub target_file: String,
448    pub target_symbol: String,
449    pub kind: String,
450    pub line: u32,
451}
452
453#[derive(Debug, Clone, PartialEq, Eq)]
454pub struct StoreNode {
455    node_id: String,
456    pub file: String,
457    pub symbol: String,
458    pub name: String,
459    pub kind: String,
460    pub line: u32,
461    pub end_line: u32,
462    pub signature: Option<String>,
463    pub exported: bool,
464    /// The store's own entry-point guess. `trace_to` and `impact` label the
465    /// roots they reach from [`StoreNode::entry`] instead.
466    pub is_entry_point: bool,
467    pub lang: LangId,
468    /// What extraction recorded about execution starting at this symbol.
469    pub entry: EntryFacts,
470}
471
472/// What extraction recorded about where execution can start at a symbol.
473/// `trace_to` and `impact` label the roots they reach with these facts.
474/// The data layer's call graph records them; today's database does not,
475/// so its nodes carry the defaults.
476#[derive(Debug, Clone, Default, PartialEq, Eq)]
477pub struct EntryFacts {
478    /// Whether the symbol is test code (a `#[test]` or `#[cfg(test)]`
479    /// item); `None` when extraction could not tell.
480    pub is_test: Option<bool>,
481    /// Whether the program starts here, as the language defines it. For
482    /// Rust this is `fn main` at the top of its file, and the file must also
483    /// be a binary target's root.
484    pub program_start: bool,
485    /// The entry attribute or decorator recorded on the symbol, such as
486    /// `no_mangle` or `tauri::command`.
487    pub entry_attribute: Option<String>,
488    /// Whether the symbol is its module's default export.
489    pub default_export: bool,
490}
491
492impl StoreNode {
493    /// The positional node identity, for request-local memo keys.
494    pub fn node_id(&self) -> &str {
495        &self.node_id
496    }
497
498    /// This node with `entry` as its entry facts.
499    #[must_use]
500    pub fn with_entry(mut self, entry: EntryFacts) -> Self {
501        self.entry = entry;
502        self
503    }
504
505    /// A node from its fields, for stores that do not keep database rows.
506    #[expect(clippy::too_many_arguments, reason = "one argument per node field")]
507    pub fn from_parts(
508        node_id: String,
509        file: String,
510        symbol: String,
511        name: String,
512        kind: String,
513        line: u32,
514        end_line: u32,
515        signature: Option<String>,
516        exported: bool,
517        is_entry_point: bool,
518        lang: LangId,
519    ) -> Self {
520        Self {
521            node_id,
522            file,
523            symbol,
524            name,
525            kind,
526            line,
527            end_line,
528            signature,
529            exported,
530            is_entry_point,
531            lang,
532            entry: EntryFacts::default(),
533        }
534    }
535}
536
537#[cfg(any(test, feature = "test-support"))]
538impl StoreNode {
539    pub fn for_test(file: &str, symbol: &str, is_entry_point: bool) -> Self {
540        Self {
541            node_id: format!("{file}:{symbol}"),
542            file: file.to_string(),
543            symbol: symbol.to_string(),
544            name: symbol.to_string(),
545            kind: "function".to_string(),
546            line: 1,
547            end_line: 1,
548            signature: None,
549            exported: is_entry_point,
550            is_entry_point,
551            lang: LangId::TypeScript,
552            entry: EntryFacts::default(),
553        }
554    }
555}
556
557#[derive(Debug, Clone, PartialEq, Eq)]
558pub struct StoreCallSite {
559    pub kind: String,
560    pub caller_is_test: Option<bool>,
561    pub caller: StoreNode,
562    pub target_file: String,
563    pub target_symbol: String,
564    pub target: Option<StoreNode>,
565    pub line: u32,
566    pub byte_start: usize,
567    pub byte_end: usize,
568    pub resolved: bool,
569    pub provenance: String,
570}
571
572impl StoreCallSite {
573    pub fn approximate(&self) -> bool {
574        self.provenance == PROVENANCE_NAME_MATCH
575    }
576
577    pub fn resolved_by(&self) -> &str {
578        &self.provenance
579    }
580
581    pub fn supplemental_resolution(&self) -> Option<&str> {
582        match self.provenance.as_str() {
583            PROVENANCE_NAME_MATCH | PROVENANCE_TYPE_MATCH => Some(self.provenance.as_str()),
584            "dispatch" => Some("possible_target (dispatch)"),
585            _ => None,
586        }
587    }
588}
589
590#[derive(Debug, Clone, PartialEq, Eq)]
591pub struct StoreUnresolvedCall {
592    pub caller: StoreNode,
593    pub symbol: String,
594    pub full_ref: Option<String>,
595    pub line: u32,
596    pub byte_start: usize,
597    pub byte_end: usize,
598}
599
600/// One raw ref row located by name; see `CallGraphRead::ref_sites_named`.
601#[derive(Debug, Clone, PartialEq, Eq)]
602pub struct StoreRefSite {
603    pub is_test: Option<bool>,
604    pub file: String,
605    /// Scoped name of the symbol containing the ref, when it has a node.
606    pub caller_symbol: Option<String>,
607    pub line: u32,
608    /// For macro-template call refs, the macro (`name!`) making the call.
609    pub local_name: Option<String>,
610}
611
612#[derive(Debug, Clone, PartialEq, Eq)]
613pub struct StoreCallersResult {
614    pub target: StoreNode,
615    pub callers: Vec<StoreCallSite>,
616    pub scanned_files: usize,
617    pub depth_limited: bool,
618    pub truncated: usize,
619}
620
621#[derive(Debug, Clone, PartialEq, Eq)]
622pub struct StoreImpactCaller {
623    pub site: StoreCallSite,
624    pub signature: Option<String>,
625    pub is_entry_point: bool,
626    pub call_expression: Option<String>,
627    pub parameters: Vec<String>,
628}
629
630#[derive(Debug, Clone, PartialEq, Eq)]
631pub struct StoreImpactResult {
632    pub target: StoreNode,
633    pub parameters: Vec<String>,
634    pub callers: Vec<StoreImpactCaller>,
635    pub depth_limited: bool,
636    pub truncated: usize,
637}
638
639#[derive(Debug, Clone)]
640struct FileExtract {
641    rel_path: String,
642    lang: LangId,
643    data: FileCallData,
644    nodes: Vec<NodeRecord>,
645    raw_refs: Vec<RawRef>,
646}
647
648#[derive(Debug, Clone)]
649struct NodeRecord {
650    id: String,
651    name: String,
652    scoped_name: String,
653    kind: String,
654}
655
656test_support_visibility! {
657#[derive(Debug, Clone)]
658struct RawRef {
659    ref_id: String,
660    caller_symbol: Option<String>,
661    caller_file: String,
662    kind: String,
663    short_name: Option<String>,
664    full_ref: Option<String>,
665    module_path: Option<String>,
666    import_kind: Option<String>,
667    local_name: Option<String>,
668    requested_name: Option<String>,
669    namespace_alias: Option<String>,
670    wildcard: bool,
671    line: u32,
672    byte_start: usize,
673    byte_end: usize,
674    dependencies: BTreeSet<String>,
675}
676}
677
678#[derive(Debug, Clone)]
679struct ResolvedRef {
680    target_file: Option<String>,
681    target_symbol: Option<String>,
682    dependencies: BTreeSet<String>,
683}
684
685impl DbFileIndex {
686    /// The modules this file declares, each with the file it names.
687    pub fn declared_module_targets(&self) -> &HashMap<String, Option<String>> {
688        &self.declared_module_targets
689    }
690}
691
692#[derive(Debug, Clone)]
693pub struct DbFileIndex {
694    #[cfg(any(test, feature = "test-support"))]
695    pub lang: Option<LangId>,
696    #[cfg(not(any(test, feature = "test-support")))]
697    lang: Option<LangId>,
698    #[cfg(any(test, feature = "test-support"))]
699    pub exports: HashSet<String>,
700    #[cfg(not(any(test, feature = "test-support")))]
701    exports: HashSet<String>,
702    #[cfg(any(test, feature = "test-support"))]
703    pub default_export: Option<String>,
704    #[cfg(not(any(test, feature = "test-support")))]
705    default_export: Option<String>,
706    #[cfg(any(test, feature = "test-support"))]
707    pub export_aliases: HashMap<String, String>,
708    #[cfg(not(any(test, feature = "test-support")))]
709    export_aliases: HashMap<String, String>,
710    #[cfg(any(test, feature = "test-support"))]
711    pub node_by_scoped: HashMap<String, String>,
712    #[cfg(not(any(test, feature = "test-support")))]
713    node_by_scoped: HashMap<String, String>,
714    #[cfg(any(test, feature = "test-support"))]
715    pub node_by_bare: HashMap<String, String>,
716    #[cfg(not(any(test, feature = "test-support")))]
717    node_by_bare: HashMap<String, String>,
718    #[cfg(any(test, feature = "test-support"))]
719    pub node_kind_by_id: HashMap<String, String>,
720    #[cfg(not(any(test, feature = "test-support")))]
721    node_kind_by_id: HashMap<String, String>,
722    #[cfg(any(test, feature = "test-support"))]
723    pub module_targets: HashMap<String, Option<String>>,
724    #[cfg(not(any(test, feature = "test-support")))]
725    module_targets: HashMap<String, Option<String>>,
726    #[cfg(any(test, feature = "test-support"))]
727    pub declared_module_targets: HashMap<String, Option<String>>,
728    #[cfg(not(any(test, feature = "test-support")))]
729    declared_module_targets: HashMap<String, Option<String>>,
730    #[cfg(any(test, feature = "test-support"))]
731    pub macro_use_module_targets: BTreeSet<String>,
732    #[cfg(not(any(test, feature = "test-support")))]
733    macro_use_module_targets: BTreeSet<String>,
734    #[cfg(any(test, feature = "test-support"))]
735    pub reexports: Vec<ReexportIndex>,
736    #[cfg(not(any(test, feature = "test-support")))]
737    reexports: Vec<ReexportIndex>,
738}
739
740#[derive(Debug, Clone)]
741pub struct ReexportIndex {
742    #[cfg(any(test, feature = "test-support"))]
743    pub target_file: Option<String>,
744    #[cfg(not(any(test, feature = "test-support")))]
745    target_file: Option<String>,
746    #[cfg(any(test, feature = "test-support"))]
747    pub named: HashMap<String, String>,
748    #[cfg(not(any(test, feature = "test-support")))]
749    named: HashMap<String, String>,
750    #[cfg(any(test, feature = "test-support"))]
751    pub wildcard: bool,
752    #[cfg(not(any(test, feature = "test-support")))]
753    wildcard: bool,
754}
755
756aft_store::heap_bytes_of_fields!(DbFileIndex {
757    lang,
758    exports,
759    default_export,
760    export_aliases,
761    node_by_scoped,
762    node_by_bare,
763    node_kind_by_id,
764    module_targets,
765    declared_module_targets,
766    macro_use_module_targets,
767    reexports,
768});
769aft_store::heap_bytes_of_fields!(ReexportIndex {
770    target_file,
771    named,
772    wildcard,
773});
774
775#[derive(Clone)]
776pub struct ProjectIndex<'a> {
777    #[cfg(any(test, feature = "test-support"))]
778    pub facts: Rc<dyn ProjectFacts + 'a>,
779    #[cfg(not(any(test, feature = "test-support")))]
780    facts: Rc<dyn ProjectFacts + 'a>,
781    #[cfg(any(test, feature = "test-support"))]
782    pub project_root: PathBuf,
783    #[cfg(not(any(test, feature = "test-support")))]
784    project_root: PathBuf,
785    #[cfg(any(test, feature = "test-support"))]
786    /// Shared, so several resolver threads can each wrap the same bound
787    /// surfaces in their own index with their own memos.
788    pub files: Arc<HashMap<String, DbFileIndex>>,
789    #[cfg(not(any(test, feature = "test-support")))]
790    /// Shared, so several resolver threads can each wrap the same bound
791    /// surfaces in their own index with their own memos.
792    files: Arc<HashMap<String, DbFileIndex>>,
793    #[cfg(any(test, feature = "test-support"))]
794    pub caller_data: HashMap<String, &'a FileCallData>,
795    #[cfg(not(any(test, feature = "test-support")))]
796    caller_data: HashMap<String, &'a FileCallData>,
797    #[cfg(any(test, feature = "test-support"))]
798    /// File indexes loaded on demand: the legacy store's rows, for an
799    /// incremental refresh, or the data layer's files bound on first use.
800    /// Files in `files` take precedence over it.
801    pub lazy: Option<Rc<dyn LoadedFileIndexes + 'a>>,
802    #[cfg(not(any(test, feature = "test-support")))]
803    /// File indexes loaded on demand: the legacy store's rows, for an
804    /// incremental refresh, or the data layer's files bound on first use.
805    /// Files in `files` take precedence over it.
806    lazy: Option<Rc<dyn LoadedFileIndexes + 'a>>,
807    #[cfg(any(test, feature = "test-support"))]
808    /// Root-scoped maps shared by successive refresh-worker batches. Cargo.toml
809    /// and go.mod watcher events replace them before another batch resolves refs.
810    /// Cold/direct refreshes use a private cache so each refresh builds and uses
811    /// its own workspace mapping.
812    pub workspace_crate_prefixes: WorkspaceCratePrefixCache,
813    #[cfg(not(any(test, feature = "test-support")))]
814    /// Root-scoped maps shared by successive refresh-worker batches. Cargo.toml
815    /// and go.mod watcher events replace them before another batch resolves refs.
816    /// Cold/direct refreshes use a private cache so each refresh builds and uses
817    /// its own workspace mapping.
818    workspace_crate_prefixes: WorkspaceCratePrefixCache,
819    #[cfg(any(test, feature = "test-support"))]
820    pub rust_crate_roots: callgraph::RustCrateRootMemo,
821    #[cfg(not(any(test, feature = "test-support")))]
822    rust_crate_roots: callgraph::RustCrateRootMemo,
823    #[cfg(any(test, feature = "test-support"))]
824    /// Crate-wide lookups derived from `files`, built on first use and never
825    /// rebuilt. Only an index with every file in memory (`lazy` is `None`)
826    /// uses it. Such an index's file set is fixed when it is constructed: a
827    /// changed file set means a new `ProjectIndex`, which starts empty.
828    pub crate_scans: std::cell::OnceCell<CrateScanMemo>,
829    #[cfg(not(any(test, feature = "test-support")))]
830    /// Crate-wide lookups derived from `files`, built on first use and never
831    /// rebuilt. Only an index with every file in memory (`lazy` is `None`)
832    /// uses it. Such an index's file set is fixed when it is constructed: a
833    /// changed file set means a new `ProjectIndex`, which starts empty.
834    crate_scans: std::cell::OnceCell<CrateScanMemo>,
835    #[cfg(any(test, feature = "test-support"))]
836    /// The lazy index overlays fresh caller extracts on stored rows. Its parent
837    /// map and caller paths belong to that immutable snapshot, not the worker.
838    pub lazy_module_parents: std::cell::OnceCell<Arc<ModuleParents>>,
839    #[cfg(not(any(test, feature = "test-support")))]
840    /// The lazy index overlays fresh caller extracts on stored rows. Its parent
841    /// map and caller paths belong to that immutable snapshot, not the worker.
842    lazy_module_parents: std::cell::OnceCell<Arc<ModuleParents>>,
843    #[cfg(any(test, feature = "test-support"))]
844    pub lazy_inline_candidates: std::cell::OnceCell<RustInlineCandidates>,
845    #[cfg(not(any(test, feature = "test-support")))]
846    lazy_inline_candidates: std::cell::OnceCell<RustInlineCandidates>,
847    #[cfg(any(test, feature = "test-support"))]
848    pub rust_caller_paths: RefCell<HashMap<String, Vec<String>>>,
849    #[cfg(not(any(test, feature = "test-support")))]
850    rust_caller_paths: RefCell<HashMap<String, Vec<String>>>,
851    #[cfg(any(test, feature = "test-support"))]
852    pub go_packages: RefCell<GoPackageMemo>,
853    #[cfg(not(any(test, feature = "test-support")))]
854    go_packages: RefCell<GoPackageMemo>,
855    #[cfg(any(test, feature = "test-support"))]
856    pub local_symbols: RefCell<CallerSymbolMemo>,
857    #[cfg(not(any(test, feature = "test-support")))]
858    local_symbols: RefCell<CallerSymbolMemo>,
859}
860
861test_support_visibility! {
862/// Symbol-query answers for the active caller. Resolution visits references in
863/// caller order, so retaining only one file avoids a corpus-sized name cache.
864/// The caller's symbol set is immutable for the lifetime of a resolver index.
865#[derive(Clone, Default)]
866struct CallerSymbolMemo {
867    #[cfg(any(test, feature = "test-support"))]
868    pub file: Option<String>,
869    #[cfg(not(any(test, feature = "test-support")))]
870    file: Option<String>,
871    symbols: HashMap<String, Option<String>>,
872    #[cfg(any(test, feature = "test-support"))]
873    pub builds: usize,
874}
875}
876
877impl CallerSymbolMemo {
878    fn resolve(&mut self, file: &str, data: &FileCallData, query: &str) -> Option<String> {
879        if self.file.as_deref() != Some(file) {
880            self.symbols.clear();
881            for symbol in data
882                .symbol_metadata
883                .keys()
884                .chain(data.calls_by_symbol.keys())
885                .chain(data.exported_symbols.iter())
886            {
887                // Qualified queries require an exact match; bare queries must
888                // remain ambiguous even when one candidate is file-level.
889                if symbol.contains("::") {
890                    self.symbols.insert(symbol.clone(), Some(symbol.clone()));
891                }
892                if symbol.starts_with("@object:") {
893                    continue;
894                }
895                let bare = symbol.rsplit("::").next().unwrap_or(symbol);
896                self.symbols
897                    .entry(bare.to_string())
898                    .and_modify(|existing| {
899                        if existing.as_ref() != Some(symbol) {
900                            *existing = None;
901                        }
902                    })
903                    .or_insert_with(|| Some(symbol.clone()));
904            }
905            self.file = Some(file.to_string());
906            #[cfg(any(test, feature = "test-support"))]
907            {
908                self.builds += 1;
909            }
910        }
911        self.symbols.get(query).cloned().flatten()
912    }
913}
914
915#[cfg(any(test, feature = "test-support"))]
916thread_local! {
917    /// Lets a measurement compare the memoized lookups with the scans on one
918    /// real corpus, in the same process.
919    pub static SCAN_WITHOUT_CRATE_MEMO: std::cell::Cell<bool> =
920        const { std::cell::Cell::new(false) };
921}
922
923test_support_visibility! {
924/// Answers to the two Rust lookups that otherwise scan every indexed file on
925/// each call (`module_parent`, `inline_scoped_target`), precomputed from an
926/// in-memory file set. Lookups return exactly what the scans return.
927#[derive(Clone, Debug, Default)]
928struct CrateScanMemo {
929    /// Module prefixes derived from Rust source-file paths, in scan order.
930    inline_candidates: RustInlineCandidates,
931    /// For each declared module target, the smallest `(declaring file,
932    /// module name)` pair, which is the scan's first match after sorting.
933    module_parents: HashMap<String, (String, String)>,
934}
935}
936
937impl CrateScanMemo {
938    fn build(files: &HashMap<String, DbFileIndex>) -> Self {
939        let mut rust_files = files
940            .iter()
941            .filter(|(_, index)| index.lang == Some(LangId::Rust))
942            .map(|(path, _)| path.clone())
943            .collect::<Vec<_>>();
944        rust_files.sort();
945        let mut module_parents = HashMap::<String, (String, String)>::new();
946        for (file, index) in files {
947            Self::note_module_parents(&mut module_parents, file, index);
948        }
949        Self {
950            inline_candidates: RustInlineCandidates::build(&rust_files),
951            module_parents,
952        }
953    }
954
955    fn note_module_parents(
956        parents: &mut HashMap<String, (String, String)>,
957        file: &str,
958        index: &DbFileIndex,
959    ) {
960        for (module, target) in &index.declared_module_targets {
961            let Some(target) = target else {
962                continue;
963            };
964            let candidate = (file.to_string(), module.clone());
965            let best = parents
966                .entry(target.clone())
967                .or_insert_with(|| candidate.clone());
968            if candidate < *best {
969                *best = candidate;
970            }
971        }
972    }
973}
974
975/// Resolution reads symbols and exports through one interface. Incremental
976/// refreshes use the in-memory index, while cold builds query only the rows
977/// needed by the active caller from SQLite.
978pub trait ResolverIndex {
979    fn luau_config(&self, file: &str) -> Option<Arc<[u8]>>;
980    fn macro_use_modules(&self, file: &str) -> Vec<String>;
981    fn go_package_files(&self, caller_file: &str, module: Option<&str>) -> Vec<String>;
982    // Enumerate package files without building or reading a cached package
983    // index. Cached adapters override this to avoid rebuilding oversized
984    // indexes during symbol scans and to allow independent membership checks.
985    fn uncached_go_package_files(&self, caller_file: &str, module: Option<&str>) -> Vec<String> {
986        self.go_package_files(caller_file, module)
987    }
988    fn go_symbol_target(
989        &self,
990        caller_file: &str,
991        module: Option<&str>,
992        symbol: &str,
993    ) -> Option<String> {
994        go_symbol_target_by_scan(self, caller_file, module, symbol)
995    }
996    fn caller_data(&self, file: &str) -> Option<&FileCallData>;
997    fn local_symbol(&self, file: &str, data: &FileCallData, query: &str) -> Option<String>;
998    fn lang_for(&self, file: &str) -> Option<LangId>;
999    fn module_target(&self, caller_file: &str, module_path: &str) -> Option<String>;
1000    fn module_parent(&self, target_file: &str) -> Option<(String, String)>;
1001    fn rust_caller_module_segments(&self, caller_file: &str) -> Vec<String> {
1002        rust_caller_module_segments_uncached(self, caller_file)
1003    }
1004    /// The module names each `use` in `data` binds, one entry per import in
1005    /// order. Resolution asks for them once per qualified reference, so an
1006    /// index that resolves one file's references can keep them.
1007    fn rust_module_aliases(&self, data: &FileCallData) -> std::rc::Rc<[RustModuleAliases]> {
1008        rust_module_aliases_of(data)
1009    }
1010    fn reexports_for(&self, file: &str) -> Vec<ReexportIndex>;
1011    fn node_for_symbol(&self, file: &str, symbol: &str) -> Option<String>;
1012    fn node_is_callable(&self, file: &str, node_id: &str) -> bool;
1013    fn export_alias(&self, file: &str, symbol: &str) -> Option<String>;
1014    fn has_export(&self, file: &str, symbol: &str) -> bool;
1015    fn default_export(&self, file: &str) -> Option<String>;
1016    fn contains_file(&self, file: &str) -> bool;
1017    fn crate_src_prefix(&self, crate_name: &str) -> Option<String>;
1018    fn rust_crate_root_file(&self, caller_file: &str) -> Option<String>;
1019    fn inline_scoped_target(
1020        &self,
1021        caller_file: &str,
1022        module_segments: &[String],
1023        short_name: &str,
1024    ) -> Option<(String, String)>;
1025}
1026
1027impl ResolverIndex for ProjectIndex<'_> {
1028    fn luau_config(&self, file: &str) -> Option<Arc<[u8]>> {
1029        luau::config(self, file)
1030    }
1031    fn macro_use_modules(&self, file: &str) -> Vec<String> {
1032        self.file_index(file)
1033            .map(|index| index.macro_use_module_targets.iter().cloned().collect())
1034            .unwrap_or_default()
1035    }
1036    fn go_package_files(&self, caller_file: &str, module: Option<&str>) -> Vec<String> {
1037        let paths = FactPaths {
1038            root: &self.project_root,
1039            facts: self.facts.as_ref(),
1040        };
1041        if let Some(package) = self.go_package(&paths, caller_file, module) {
1042            return package.files_for(caller_file);
1043        }
1044        self.uncached_go_package_files(caller_file, module)
1045    }
1046    fn uncached_go_package_files(&self, caller_file: &str, module: Option<&str>) -> Vec<String> {
1047        let paths = FactPaths {
1048            root: &self.project_root,
1049            facts: self.facts.as_ref(),
1050        };
1051        go_package_files(&paths, &self.workspace_crate_prefixes, caller_file, module)
1052            .into_iter()
1053            .filter(|file| self.contains_file(file))
1054            .collect()
1055    }
1056    fn go_symbol_target(
1057        &self,
1058        caller_file: &str,
1059        module: Option<&str>,
1060        symbol: &str,
1061    ) -> Option<String> {
1062        let paths = FactPaths {
1063            root: &self.project_root,
1064            facts: self.facts.as_ref(),
1065        };
1066        if let Some(package) = self.go_package(&paths, caller_file, module) {
1067            return package.target(caller_file, module.is_some(), symbol);
1068        }
1069        go_symbol_target_by_scan(self, caller_file, module, symbol)
1070    }
1071    fn caller_data(&self, file: &str) -> Option<&FileCallData> {
1072        self.caller_data.get(file).copied()
1073    }
1074
1075    fn local_symbol(&self, file: &str, data: &FileCallData, query: &str) -> Option<String> {
1076        self.local_symbols.borrow_mut().resolve(file, data, query)
1077    }
1078
1079    fn lang_for(&self, file: &str) -> Option<LangId> {
1080        self.lang_for(file)
1081    }
1082
1083    fn module_target(&self, caller_file: &str, module_path: &str) -> Option<String> {
1084        self.module_target(caller_file, module_path)
1085    }
1086
1087    fn module_parent(&self, target_file: &str) -> Option<(String, String)> {
1088        #[cfg(any(test, feature = "test-support"))]
1089        let _timing = rust_module_work::Timing::parent();
1090        if self.lazy.is_some() {
1091            #[cfg(any(test, feature = "test-support"))]
1092            if rust_module_work::disabled() {
1093                return self.module_parent_by_scan(target_file);
1094            }
1095            return self.lazy_module_parents().get(target_file).cloned();
1096        }
1097        match self.crate_scans() {
1098            Some(memo) => memo.module_parents.get(target_file).cloned(),
1099            None => self.module_parent_by_scan(target_file),
1100        }
1101    }
1102
1103    fn rust_caller_module_segments(&self, caller_file: &str) -> Vec<String> {
1104        #[cfg(any(test, feature = "test-support"))]
1105        if rust_module_work::disabled() {
1106            return rust_caller_module_segments_uncached(self, caller_file);
1107        }
1108        if let Some(path) = self.rust_caller_paths.borrow().get(caller_file) {
1109            return path.clone();
1110        }
1111        let path = rust_caller_module_segments_uncached(self, caller_file);
1112        self.rust_caller_paths
1113            .borrow_mut()
1114            .insert(caller_file.to_string(), path.clone());
1115        path
1116    }
1117
1118    fn reexports_for(&self, file: &str) -> Vec<ReexportIndex> {
1119        self.reexports_for(file)
1120    }
1121
1122    fn node_for_symbol(&self, file: &str, symbol: &str) -> Option<String> {
1123        self.node_for_symbol(file, symbol)
1124    }
1125
1126    fn node_is_callable(&self, file: &str, node_id: &str) -> bool {
1127        self.node_is_callable(file, node_id)
1128    }
1129
1130    fn export_alias(&self, file: &str, symbol: &str) -> Option<String> {
1131        self.file_index(file)
1132            .and_then(|item| item.export_aliases.get(symbol).cloned())
1133    }
1134
1135    fn has_export(&self, file: &str, symbol: &str) -> bool {
1136        self.file_index(file)
1137            .is_some_and(|item| item.exports.contains(symbol))
1138    }
1139
1140    fn default_export(&self, file: &str) -> Option<String> {
1141        self.file_index(file)
1142            .and_then(|item| item.default_export.clone())
1143    }
1144
1145    fn contains_file(&self, file: &str) -> bool {
1146        self.files.contains_key(file)
1147            || self
1148                .lazy
1149                .as_ref()
1150                .is_some_and(|lazy| lazy.contains_file(file))
1151    }
1152
1153    fn crate_src_prefix(&self, crate_name: &str) -> Option<String> {
1154        // The map reads every workspace Cargo.toml. Readers record its domain
1155        // key and the requested crate-name key, so their dependencies do not
1156        // depend on which reader built the map.
1157        self.facts.record_domain(join::VIEW_RUST_CRATES_DOMAIN);
1158        self.facts.record_domain(&join::rust_crate_key(crate_name));
1159        self.workspace_crate_prefixes
1160            .0
1161            .get_or_init(|| {
1162                self.facts.pause_recording();
1163                let prefixes = build_workspace_crate_prefixes(
1164                    &self.project_root,
1165                    &FactPaths {
1166                        root: &self.project_root,
1167                        facts: self.facts.as_ref(),
1168                    },
1169                );
1170                self.facts.resume_recording();
1171                prefixes
1172            })
1173            .get(crate_name)
1174            .cloned()
1175    }
1176
1177    fn rust_crate_root_file(&self, caller_file: &str) -> Option<String> {
1178        let paths = FactPaths {
1179            root: &self.project_root,
1180            facts: self.facts.as_ref(),
1181        };
1182        callgraph::rust_crate_root_file_for_caller(
1183            &self.project_root,
1184            &self.project_root.join(caller_file),
1185            &paths,
1186            &self.rust_crate_roots,
1187        )
1188        .map(|path| relative_path(&self.project_root, &path))
1189    }
1190
1191    fn inline_scoped_target(
1192        &self,
1193        caller_file: &str,
1194        module_segments: &[String],
1195        short_name: &str,
1196    ) -> Option<(String, String)> {
1197        let candidates = match self.crate_scans() {
1198            Some(memo) => &memo.inline_candidates,
1199            None => {
1200                #[cfg(any(test, feature = "test-support"))]
1201                if SCAN_WITHOUT_CRATE_MEMO.with(std::cell::Cell::get) {
1202                    return self.inline_scoped_target_by_scan(
1203                        caller_file,
1204                        module_segments,
1205                        short_name,
1206                    );
1207                }
1208                self.lazy_inline_candidates.get_or_init(|| {
1209                    // Fresh caller extracts replace stored paths in this batch,
1210                    // including files whose language or module layout changed.
1211                    let mut paths = self.scan_paths(|lazy| lazy.rust_files());
1212                    paths.sort();
1213                    RustInlineCandidates::build(&paths)
1214                })
1215            }
1216        };
1217        self.inline_scoped_target_in(candidates, caller_file, module_segments, short_name)
1218    }
1219}
1220
1221impl ProjectIndex<'_> {
1222    fn lazy_module_parents(&self) -> &ModuleParents {
1223        self.lazy_module_parents.get_or_init(|| {
1224            // A loader that keeps the parents indexed answers for every
1225            // file it loads; an index with files of its own in memory scans,
1226            // since those replace the loader's.
1227            if self.files.is_empty() {
1228                if let Some(parents) = self.lazy.as_ref().and_then(|lazy| lazy.module_parents()) {
1229                    return parents;
1230                }
1231            }
1232            #[cfg(any(test, feature = "test-support"))]
1233            rust_module_work::note(|work| work.parent_scans += 1);
1234            let mut parents = HashMap::new();
1235            // scan_paths excludes stored rows replaced by this refresh's
1236            // extracts, including declarations that have just been removed.
1237            for file in self.scan_paths(|lazy| lazy.module_declaring_files()) {
1238                #[cfg(any(test, feature = "test-support"))]
1239                rust_module_work::note(|work| work.parent_file_visits += 1);
1240                if let Some(index) = self.file_index(&file) {
1241                    CrateScanMemo::note_module_parents(&mut parents, &file, &index);
1242                }
1243            }
1244            Arc::new(parents)
1245        })
1246    }
1247
1248    fn go_package(
1249        &self,
1250        paths: &FactPaths<'_>,
1251        caller: &str,
1252        module: Option<&str>,
1253    ) -> Option<Rc<GoPackage>> {
1254        // Builds that record configuration facts also track filesystem reads
1255        // and per-file symbol/export answers to invalidate reused results later.
1256        // Keep those reads observable instead of hiding them behind this memo.
1257        if self.facts.records_config_facts() {
1258            return None;
1259        }
1260        cached_go_package(
1261            paths,
1262            &self.workspace_crate_prefixes,
1263            &self.go_packages,
1264            caller,
1265            module,
1266            |file| self.contains_file(file),
1267            |file| self.file_index(file),
1268        )
1269    }
1270    /// The eager crate-wide memo. Lazy indexes build their parent map and
1271    /// inline candidate index separately from the current caller overlay.
1272    fn crate_scans(&self) -> Option<&CrateScanMemo> {
1273        #[cfg(any(test, feature = "test-support"))]
1274        if SCAN_WITHOUT_CRATE_MEMO.with(std::cell::Cell::get) {
1275            return None;
1276        }
1277        if self.lazy.is_some() {
1278            return None;
1279        }
1280        Some(
1281            self.crate_scans
1282                .get_or_init(|| CrateScanMemo::build(&self.files)),
1283        )
1284    }
1285
1286    test_support_visibility! {
1287    /// `module_parent` by scanning every indexed file: the smallest
1288        /// `(declaring file, module name)` pair whose declared target is
1289        /// `target_file`.
1290        fn module_parent_by_scan(&self, target_file: &str) -> Option<(String, String)> {
1291            #[cfg(any(test, feature = "test-support"))]
1292            rust_module_work::note(|work| work.parent_scans += 1);
1293            let mut parents = self
1294                .scan_paths(|lazy| lazy.module_declaring_files())
1295                .into_iter()
1296                .filter_map(|file| {
1297                    #[cfg(any(test, feature = "test-support"))]
1298                    rust_module_work::note(|work| work.parent_file_visits += 1);
1299                    let index = self.file_index(&file)?;
1300                    let modules = index
1301                        .declared_module_targets
1302                        .iter()
1303                        .filter(|(_, target)| target.as_deref() == Some(target_file))
1304                        .map(|(module, _)| (file.clone(), module.clone()))
1305                        .collect::<Vec<_>>();
1306                    Some(modules)
1307                })
1308                .flatten()
1309                .collect::<Vec<_>>();
1310            parents.sort();
1311            parents.into_iter().next()
1312        }
1313    }
1314
1315    /// Tries the caller first, then files whose path-derived module segments
1316    /// prefix the requested module, in global path order. The candidate index
1317    /// belongs to this eager or lazy resolver snapshot.
1318    fn inline_scoped_target_in(
1319        &self,
1320        memo: &RustInlineCandidates,
1321        caller_file: &str,
1322        module_segments: &[String],
1323        short_name: &str,
1324    ) -> Option<(String, String)> {
1325        let caller = memo
1326            .by_path
1327            .get(caller_file)
1328            .map(|ordinal| &memo.files[*ordinal]);
1329        let fallback_prefix;
1330        let src_prefix = if let Some(file) = caller {
1331            file.src_prefix.as_str()
1332        } else {
1333            fallback_prefix = rust_src_prefix(caller_file);
1334            &fallback_prefix
1335        };
1336        let check = |file: &RustInlineFile| {
1337            #[cfg(any(test, feature = "test-support"))]
1338            rust_module_work::note(|work| work.inline_file_visits += 1);
1339            if file.src_prefix != src_prefix
1340                || !module_segments.starts_with(&file.module_segments)
1341                || self.lang_for(&file.path) != Some(LangId::Rust)
1342            {
1343                return None;
1344            }
1345            let scoped_segments = &module_segments[file.module_segments.len()..];
1346            if scoped_segments.is_empty() {
1347                return None;
1348            }
1349            let scoped_symbol = format!("{}::{short_name}", scoped_segments.join("::"));
1350            self.node_for_symbol(&file.path, &scoped_symbol)
1351                .map(|_| (file.path.clone(), scoped_symbol))
1352        };
1353        caller.and_then(check).or_else(|| {
1354            memo.eligible_files(src_prefix, module_segments)
1355                .into_iter()
1356                .map(|ordinal| &memo.files[ordinal])
1357                .filter(|file| file.path != caller_file)
1358                .find_map(check)
1359        })
1360    }
1361
1362    /// `inline_scoped_target` by sorting and scanning every indexed path.
1363    #[cfg(any(test, feature = "test-support"))]
1364    pub fn inline_scoped_target_by_scan(
1365        &self,
1366        caller_file: &str,
1367        module_segments: &[String],
1368        short_name: &str,
1369    ) -> Option<(String, String)> {
1370        let src_prefix = rust_src_prefix(caller_file);
1371        // Stored files outside `files` are limited to Rust ones up front; the
1372        // language check below still applies to every path.
1373        let mut file_paths = self.scan_paths(|lazy| lazy.rust_files());
1374        file_paths.sort();
1375        if let Some(position) = file_paths.iter().position(|file| file == caller_file) {
1376            let caller = file_paths.remove(position);
1377            file_paths.insert(0, caller);
1378        }
1379        for file_path in file_paths {
1380            rust_module_work::note(|work| work.inline_file_visits += 1);
1381            // Path checks come before the language check so that a stored
1382            // file's index is loaded only when its module path can match.
1383            if rust_src_prefix(&file_path) != src_prefix {
1384                continue;
1385            }
1386            let file_module_segments = rust_module_segments_for_rel(&file_path);
1387            if !module_segments.starts_with(&file_module_segments)
1388                || self.lang_for(&file_path) != Some(LangId::Rust)
1389            {
1390                continue;
1391            }
1392            let scoped_segments = &module_segments[file_module_segments.len()..];
1393            if scoped_segments.is_empty() {
1394                continue;
1395            }
1396            let scoped_symbol = format!("{}::{short_name}", scoped_segments.join("::"));
1397            if self.node_for_symbol(&file_path, &scoped_symbol).is_some() {
1398                return Some((file_path, scoped_symbol));
1399            }
1400        }
1401        None
1402    }
1403}
1404
1405#[derive(Clone, Debug)]
1406struct RustInlineFile {
1407    path: String,
1408    src_prefix: String,
1409    module_segments: Vec<String>,
1410}
1411
1412impl RustInlineFile {
1413    fn new(path: &str) -> Self {
1414        Self {
1415            path: path.to_string(),
1416            src_prefix: rust_src_prefix(path),
1417            module_segments: rust_module_segments_for_rel(path),
1418        }
1419    }
1420}
1421
1422test_support_visibility! {
1423#[derive(Clone, Debug, Default)]
1424struct RustInlineCandidates {
1425    files: Vec<RustInlineFile>,
1426    by_path: HashMap<String, usize>,
1427    by_prefix: HashMap<String, HashMap<Vec<String>, Vec<usize>>>,
1428}
1429}
1430
1431impl RustInlineCandidates {
1432    fn build(paths: &[String]) -> Self {
1433        let mut index = Self::default();
1434        for path in paths {
1435            let file = RustInlineFile::new(path);
1436            let ordinal = index.files.len();
1437            index.by_path.insert(path.clone(), ordinal);
1438            index
1439                .by_prefix
1440                .entry(file.src_prefix.clone())
1441                .or_default()
1442                .entry(file.module_segments.clone())
1443                .or_default()
1444                .push(ordinal);
1445            index.files.push(file);
1446        }
1447        index
1448    }
1449
1450    fn eligible_files(&self, src_prefix: &str, module_segments: &[String]) -> Vec<usize> {
1451        let mut files = Vec::new();
1452        if let Some(prefixes) = self.by_prefix.get(src_prefix) {
1453            // An equal physical path has no inline suffix and is left to the
1454            // module-file fallback. Only proper prefixes can contain the target.
1455            for len in 0..module_segments.len() {
1456                if let Some(ordinals) = prefixes.get(&module_segments[..len]) {
1457                    files.extend_from_slice(ordinals);
1458                }
1459            }
1460        }
1461        // Prefix depth must not change the old global path-order preference.
1462        files.sort_unstable();
1463        files
1464    }
1465}
1466
1467impl<T: CallGraphRead + ?Sized> CallGraphRead for Arc<T> {
1468    fn stored_content_hash(&self, file: &str) -> Result<Option<String>> {
1469        (**self).stored_content_hash(file)
1470    }
1471    fn project_root(&self) -> &Path {
1472        (**self).project_root()
1473    }
1474    fn project_key(&self) -> &str {
1475        (**self).project_key()
1476    }
1477    fn sqlite_path(&self) -> &Path {
1478        (**self).sqlite_path()
1479    }
1480    fn is_current(&self) -> bool {
1481        (**self).is_current()
1482    }
1483    fn edge_snapshot(&self) -> Result<BTreeSet<StoredEdge>> {
1484        (**self).edge_snapshot()
1485    }
1486    fn indexed_file_count(&self) -> Result<usize> {
1487        (**self).indexed_file_count()
1488    }
1489    fn node_for(&self, file_rel: &Path, symbol: &str) -> Result<StoreNode> {
1490        (**self).node_for(file_rel, symbol)
1491    }
1492    fn nodes_for(&self, file_rel: &Path, symbol: &str) -> Result<Vec<StoreNode>> {
1493        (**self).nodes_for(file_rel, symbol)
1494    }
1495    fn nodes_for_stored(&self, file: &str, symbol: &str) -> Result<Vec<StoreNode>> {
1496        (**self).nodes_for_stored(file, symbol)
1497    }
1498    fn nodes_matching(&self, symbol: &str) -> Result<Vec<StoreNode>> {
1499        (**self).nodes_matching(symbol)
1500    }
1501    fn direct_callers_of(&self, file_rel: &Path, symbol: &str) -> Result<Vec<StoreCallSite>> {
1502        (**self).direct_callers_of(file_rel, symbol)
1503    }
1504    fn direct_callers_for_symbols(
1505        &self,
1506        targets: &[(String, String)],
1507    ) -> Result<HashMap<(String, String), Vec<StoreCallSite>>> {
1508        (**self).direct_callers_for_symbols(targets)
1509    }
1510    fn direct_caller_counts_of(
1511        &self,
1512        targets: &[(String, String)],
1513    ) -> Result<HashMap<(String, String), usize>> {
1514        (**self).direct_caller_counts_of(targets)
1515    }
1516
1517    fn direct_callers_bounded(
1518        &self,
1519        targets: &[(String, String)],
1520        limit: usize,
1521    ) -> Result<(HashMap<(String, String), Vec<StoreCallSite>>, bool, usize)> {
1522        (**self).direct_callers_bounded(targets, limit)
1523    }
1524    fn callers_of(
1525        &self,
1526        file_rel: &Path,
1527        symbol: &str,
1528        depth: usize,
1529    ) -> Result<StoreCallersResult> {
1530        (**self).callers_of(file_rel, symbol, depth)
1531    }
1532    fn impact_of(&self, file_rel: &Path, symbol: &str, depth: usize) -> Result<StoreImpactResult> {
1533        (**self).impact_of(file_rel, symbol, depth)
1534    }
1535    fn outgoing_calls_of(&self, node: &StoreNode) -> Result<Vec<StoreCallSite>> {
1536        (**self).outgoing_calls_of(node)
1537    }
1538    fn outgoing_calls_for_symbols(
1539        &self,
1540        sources: &[(String, String)],
1541    ) -> Result<HashMap<(String, String), Vec<StoreCallSite>>> {
1542        (**self).outgoing_calls_for_symbols(sources)
1543    }
1544    fn resolved_self_calls_of(&self, node: &StoreNode) -> Result<Vec<StoreCallSite>> {
1545        (**self).resolved_self_calls_of(node)
1546    }
1547    fn unresolved_calls_of(&self, node: &StoreNode) -> Result<Vec<StoreUnresolvedCall>> {
1548        (**self).unresolved_calls_of(node)
1549    }
1550    fn ref_sites_named(
1551        &self,
1552        kind: &str,
1553        short_name: &str,
1554        limit: usize,
1555    ) -> Result<Vec<StoreRefSite>> {
1556        (**self).ref_sites_named(kind, short_name, limit)
1557    }
1558    fn macro_template_calls_of(&self, node: &StoreNode) -> Result<Vec<StoreUnresolvedCall>> {
1559        (**self).macro_template_calls_of(node)
1560    }
1561    fn unresolved_method_sites_named(
1562        &self,
1563        name: &str,
1564        language: LangId,
1565    ) -> Result<Vec<StoreRefSite>> {
1566        (**self).unresolved_method_sites_named(name, language)
1567    }
1568    fn unresolved_call_site_count(&self, language: LangId, include_tests: bool) -> Result<usize> {
1569        (**self).unresolved_call_site_count(language, include_tests)
1570    }
1571    fn unresolved_call_sites_named(
1572        &self,
1573        name: &str,
1574        language: LangId,
1575        include_tests: bool,
1576        limit: usize,
1577    ) -> Result<(usize, Vec<StoreRefSite>)> {
1578        (**self).unresolved_call_sites_named(name, language, include_tests, limit)
1579    }
1580    fn unresolved_call_site_count_named(
1581        &self,
1582        name: &str,
1583        language: LangId,
1584        include_tests: bool,
1585    ) -> Result<usize> {
1586        (**self).unresolved_call_site_count_named(name, language, include_tests)
1587    }
1588    fn call_tree(
1589        &self,
1590        file_rel: &Path,
1591        symbol: &str,
1592        depth: usize,
1593    ) -> Result<callgraph::CallTreeNode> {
1594        (**self).call_tree(file_rel, symbol, depth)
1595    }
1596    fn trace_to(
1597        &self,
1598        file_rel: &Path,
1599        symbol: &str,
1600        max_depth: usize,
1601    ) -> Result<callgraph::TraceToResult> {
1602        (**self).trace_to(file_rel, symbol, max_depth)
1603    }
1604    fn trace_to_symbol_candidates(&self, to_symbol: &str) -> Result<Vec<TraceToSymbolCandidate>> {
1605        (**self).trace_to_symbol_candidates(to_symbol)
1606    }
1607    fn trace_to_symbol(
1608        &self,
1609        file_rel: &Path,
1610        symbol: &str,
1611        to_symbol: &str,
1612        to_file: Option<&Path>,
1613        max_depth: usize,
1614    ) -> Result<callgraph::TraceToSymbolResult> {
1615        (**self).trace_to_symbol(file_rel, symbol, to_symbol, to_file, max_depth)
1616    }
1617}
1618
1619/// A node's id: its class prefix and the first 64 bits of a BLAKE3 digest of
1620/// its file, kind and scoped name, as 16 hex digits.
1621///
1622/// Node ids are repeated in every ref, edge and index that names a caller or a
1623/// target, so their length is a large share of the store. 64 bits keep them
1624/// unique in practice; the store's insert and update triggers refuse two
1625/// different symbols with the same id (`initialize_schema`) rather than merging
1626/// them. Hex digits of a prefix sort as the full digest does, so ordering by id
1627/// is unchanged.
1628fn node_id(rel_path: &str, kind: &str, scoped_name: &str) -> String {
1629    if scoped_name == TOP_LEVEL_SYMBOL {
1630        return format!("top:{}", short_hash_hex(blake3::hash(rel_path.as_bytes())));
1631    }
1632    // Length-delimited fields avoid aliasing paths or names containing colons.
1633    let mut hash = blake3::Hasher::new();
1634    for field in [rel_path, kind, scoped_name] {
1635        hash.update(&(field.len() as u64).to_le_bytes());
1636        hash.update(field.as_bytes());
1637    }
1638    format!("pos:symbol:{}", short_hash_hex(hash.finalize()))
1639}
1640
1641/// A views store's node id: `vp` plus 16 hex digits for a symbol, `vt` plus
1642/// 16 hex digits for a file's top level.
1643///
1644/// The digests are `node_id`'s. Views stores never hold `node_id`'s longer
1645/// spellings, so the short class letters only have to keep the two classes
1646/// apart and in the same order: symbol ids still sort before top-level ids, and
1647/// ids of one class still sort by digest.
1648pub fn view_node_id(rel_path: &str, kind: &str, scoped_name: &str) -> String {
1649    let id = node_id(rel_path, kind, scoped_name);
1650    match (id.strip_prefix("pos:symbol:"), id.strip_prefix("top:")) {
1651        (Some(digest), _) => format!("vp{digest}"),
1652        (_, Some(digest)) => format!("vt{digest}"),
1653        _ => unreachable!("node_id returns a symbol or top-level id"),
1654    }
1655}
1656
1657fn build_import_refs(
1658    project_root: &Path,
1659    abs_path: &Path,
1660    rel_path: &str,
1661    imports: &[ImportStatement],
1662    line_index: &LineIndex,
1663    memo: &callgraph::ModuleResolutionMemo,
1664    facts: &FactPaths<'_>,
1665) -> Vec<RawRef> {
1666    let mut refs = Vec::new();
1667    for (index, import) in imports.iter().enumerate() {
1668        let import_kind = import_kind_label(import.kind).to_string();
1669        let local_name = import_local_names(import).join(",");
1670        let requested_name = import_requested_names(import).join(",");
1671        let ref_id = ref_id(&[
1672            rel_path,
1673            "import",
1674            &import.byte_range.start.to_string(),
1675            &import.byte_range.end.to_string(),
1676            &import.module_path,
1677            &index.to_string(),
1678        ]);
1679        refs.push(RawRef {
1680            ref_id,
1681            caller_symbol: None,
1682            caller_file: rel_path.to_string(),
1683            kind: "import".to_string(),
1684            short_name: None,
1685            full_ref: Some(import.raw_text.clone()),
1686            module_path: Some(import.module_path.clone()),
1687            import_kind: Some(import_kind),
1688            local_name: empty_to_none(local_name),
1689            requested_name: empty_to_none(requested_name),
1690            namespace_alias: import.namespace_import.clone(),
1691            wildcard: import_is_wildcard(import),
1692            line: line_index.byte_to_line(import.byte_range.start),
1693            byte_start: import.byte_range.start,
1694            byte_end: import.byte_range.end,
1695            dependencies: module_dependencies_with_memo(
1696                project_root,
1697                abs_path,
1698                &import.module_path,
1699                memo,
1700                facts,
1701            ),
1702        });
1703    }
1704    refs
1705}
1706
1707fn rust_declared_module_target(
1708    project_root: &Path,
1709    caller_file: &str,
1710    module_name: &str,
1711    memo: &callgraph::ModuleResolutionMemo,
1712    facts: &FactPaths<'_>,
1713) -> Option<String> {
1714    memo.rust_declared_module_target(caller_file, module_name, || {
1715        rust_declared_module_targets(project_root, caller_file, facts)
1716    })
1717}
1718
1719fn rust_declared_module_targets(
1720    project_root: &Path,
1721    caller_file: &str,
1722    facts: &FactPaths<'_>,
1723) -> HashMap<String, Option<String>> {
1724    let declaring_file = project_root.join(caller_file);
1725    let Ok(source) = crate::project_content::read_to_string(&declaring_file) else {
1726        return HashMap::new();
1727    };
1728    let Ok(tree) = parse_source_with_cached_parser(&declaring_file, &source, LangId::Rust) else {
1729        return HashMap::new();
1730    };
1731    let mut targets = HashMap::new();
1732    let mut stack = vec![tree.root_node()];
1733    while let Some(node) = stack.pop() {
1734        if node.kind() == "mod_item"
1735            && node
1736                .named_children(&mut node.walk())
1737                .all(|child| child.kind() != "declaration_list")
1738        {
1739            if let Some(name) = node.child_by_field_name("name") {
1740                let module_name = node_text(name, &source);
1741                let target = rust_external_module_target(
1742                    &declaring_file,
1743                    rust_module_path_override(&source, node),
1744                    module_name,
1745                    facts,
1746                )
1747                .map(|target| {
1748                    relative_path(
1749                        project_root,
1750                        &facts.canonical(&target).unwrap_or(target.clone()),
1751                    )
1752                });
1753                targets.entry(module_name.to_string()).or_insert(target);
1754            }
1755        }
1756        let mut cursor = node.walk();
1757        if cursor.goto_first_child() {
1758            loop {
1759                stack.push(cursor.node());
1760                if !cursor.goto_next_sibling() {
1761                    break;
1762                }
1763            }
1764        }
1765    }
1766    targets
1767}
1768
1769fn rust_external_module_target(
1770    declaring_file: &Path,
1771    path_override: Option<&str>,
1772    module_name: &str,
1773    facts: &FactPaths<'_>,
1774) -> Option<PathBuf> {
1775    let parent = declaring_file.parent()?;
1776    if let Some(path) = path_override {
1777        let candidate = parent.join(path);
1778        return facts.is_file(&candidate).then_some(candidate);
1779    }
1780
1781    let stem = declaring_file.file_stem().and_then(|stem| stem.to_str())?;
1782    let declaring_file = facts
1783        .canonical(declaring_file)
1784        .unwrap_or_else(|| declaring_file.to_path_buf());
1785    let is_crate_root = callgraph::rust_crate_root_file_for_caller(
1786        facts.root,
1787        &declaring_file,
1788        facts,
1789        &callgraph::RustCrateRootMemo::default(),
1790    )
1791    .as_ref()
1792        == Some(&declaring_file);
1793    let module_dir = if matches!(stem, "lib" | "main" | "mod") || is_crate_root {
1794        parent.to_path_buf()
1795    } else {
1796        parent.join(stem)
1797    };
1798    [
1799        module_dir.join(format!("{module_name}.rs")),
1800        module_dir.join(module_name).join("mod.rs"),
1801    ]
1802    .into_iter()
1803    .find(|candidate| facts.is_file(candidate))
1804}
1805
1806fn rust_module_path_override<'a>(source: &'a str, module: Node<'_>) -> Option<&'a str> {
1807    rust_module_path_override_with(source, module, Direct)
1808}
1809
1810/// The `#[path = "../../../aft/src/callgraph_store/..."]` attribute before a `mod` declaration.
1811fn rust_module_path_override_with<'a, 'tree>(
1812    source: &'a str,
1813    module: Node<'tree>,
1814    nav: impl Nav<'tree>,
1815) -> Option<&'a str> {
1816    let mut previous = nav.prev_sibling(module);
1817    while let Some(attribute) = previous {
1818        if nav.kind(attribute) != "attribute_item" {
1819            break;
1820        }
1821        if let Some(path) = rust_path_attribute(source.get(attribute.byte_range())?) {
1822            return Some(path);
1823        }
1824        previous = nav.prev_sibling(attribute);
1825    }
1826    None
1827}
1828
1829pub(super) fn rust_module_has_macro_use(source: &str, module: Node<'_>) -> bool {
1830    rust_module_has_macro_use_with(source, module, Direct)
1831}
1832
1833/// Whether a `#[macro_use]` attribute precedes a `mod` declaration.
1834fn rust_module_has_macro_use_with<'tree>(
1835    source: &str,
1836    module: Node<'tree>,
1837    nav: impl Nav<'tree>,
1838) -> bool {
1839    let mut previous = nav.prev_sibling(module);
1840    while let Some(attribute) = previous {
1841        if matches!(nav.kind(attribute), "line_comment" | "block_comment") {
1842            previous = nav.prev_sibling(attribute);
1843            continue;
1844        }
1845        if nav.kind(attribute) != "attribute_item" {
1846            break;
1847        }
1848        if node_text(attribute, source)
1849            .trim()
1850            .strip_prefix("#[")
1851            .and_then(|body| body.strip_suffix(']'))
1852            .is_some_and(|body| body.trim() == "macro_use")
1853        {
1854            return true;
1855        }
1856        previous = nav.prev_sibling(attribute);
1857    }
1858    false
1859}
1860
1861fn rust_path_attribute(attribute: &str) -> Option<&str> {
1862    let body = attribute.trim().strip_prefix("#[")?.strip_suffix(']')?;
1863    let (name, value) = body.split_once('=')?;
1864    (name.trim() == "path")
1865        .then(|| value.trim().trim_matches('"'))
1866        .filter(|path| !path.is_empty())
1867}
1868
1869fn extend_rust_imports_from_tree(source: &str, root: Node<'_>, data: &mut FileCallData) {
1870    let mut seen = HashSet::new();
1871    let mut nested_imports = Vec::new();
1872    collect_rust_use_imports(source, root, &mut seen, &mut nested_imports);
1873    if nested_imports.is_empty() {
1874        return;
1875    }
1876
1877    // Replace use declarations with their leaf bindings once, at extraction.
1878    // Other import forms retain their original representation.
1879    data.import_block
1880        .imports
1881        .retain(|import| !seen.contains(&(import.byte_range.start, import.byte_range.end)));
1882    data.import_block.imports.extend(nested_imports);
1883    data.import_block
1884        .imports
1885        .sort_by_key(|import| import.byte_range.start);
1886    data.import_block.byte_range = import_byte_range_from_imports(&data.import_block.imports);
1887}
1888
1889/// Like [`extend_rust_imports_from_tree`], given the tree's
1890/// `use_declaration` nodes in preorder instead of walking it for them.
1891fn extend_rust_imports_from_uses<'tree>(
1892    source: &str,
1893    uses: impl Iterator<Item = Node<'tree>>,
1894    data: &mut FileCallData,
1895) {
1896    let mut seen = HashSet::new();
1897    let mut nested_imports = Vec::new();
1898    for node in uses {
1899        collect_rust_use_import(source, node, &mut seen, &mut nested_imports);
1900    }
1901    if nested_imports.is_empty() {
1902        return;
1903    }
1904    data.import_block
1905        .imports
1906        .retain(|import| !seen.contains(&(import.byte_range.start, import.byte_range.end)));
1907    data.import_block.imports.extend(nested_imports);
1908    data.import_block
1909        .imports
1910        .sort_by_key(|import| import.byte_range.start);
1911    data.import_block.byte_range = import_byte_range_from_imports(&data.import_block.imports);
1912}
1913
1914fn collect_rust_use_imports(
1915    source: &str,
1916    node: Node<'_>,
1917    seen: &mut HashSet<(usize, usize)>,
1918    imports: &mut Vec<ImportStatement>,
1919) {
1920    if node.kind() == "use_declaration" {
1921        collect_rust_use_import(source, node, seen, imports);
1922    }
1923
1924    let mut cursor = node.walk();
1925    if !cursor.goto_first_child() {
1926        return;
1927    }
1928    loop {
1929        collect_rust_use_imports(source, cursor.node(), seen, imports);
1930        if !cursor.goto_next_sibling() {
1931            break;
1932        }
1933    }
1934}
1935
1936/// The imports one `use` declaration binds: one per leaf of its use tree.
1937fn collect_rust_use_import(
1938    source: &str,
1939    node: Node<'_>,
1940    seen: &mut HashSet<(usize, usize)>,
1941    imports: &mut Vec<ImportStatement>,
1942) {
1943    let range = node.byte_range();
1944    if !seen.insert((range.start, range.end)) {
1945        return;
1946    }
1947    let Some(import) = rust_import_from_use_node(source, node) else {
1948        return;
1949    };
1950    let paths = node
1951        .child_by_field_name("argument")
1952        .map(|argument| rust_use_leaf_paths(source, argument))
1953        .unwrap_or_default();
1954    if paths.is_empty() {
1955        imports.push(import);
1956        return;
1957    }
1958    for (path, range) in paths {
1959        let mut leaf = import.clone();
1960        leaf.byte_range = range;
1961        leaf.module_path = path.clone();
1962        leaf.raw_text = format!(
1963            "{}use {path};",
1964            leaf.default_import
1965                .as_ref()
1966                .map(|v| format!("{v} "))
1967                .unwrap_or_default()
1968        );
1969        leaf.names = Vec::new();
1970        if let ImportForm::RustUse { named, .. } = &mut leaf.form {
1971            named.clear();
1972        }
1973        imports.push(leaf);
1974    }
1975}
1976
1977test_support_visibility! {
1978fn rust_import_from_use_node(source: &str, node: Node<'_>) -> Option<ImportStatement> {
1979    let raw_text = source[node.byte_range()].to_string();
1980    let body = rust_use_body(&raw_text)?.to_string();
1981    let visibility = rust_use_visibility(&raw_text);
1982    let names = rust_use_list_names(&body);
1983    let group = classify_rust_import_group(&body);
1984    let byte_range = node.byte_range();
1985
1986    Some(ImportStatement {
1987        module_path: body,
1988        names: names.clone(),
1989        default_import: visibility.clone(),
1990        namespace_import: None,
1991        kind: ImportKind::Value,
1992        group,
1993        byte_range,
1994        raw_text,
1995        form: ImportForm::RustUse {
1996            visibility,
1997            named: names,
1998        },
1999    })
2000}
2001}
2002
2003/// The leaf paths a `use` tree imports, each with the byte range of its
2004/// leaf. Paths and nested lists can be as deep as the source writes them, so
2005/// both walks are loops over heap state rather than recursion: a stack
2006/// overflow would abort the process.
2007fn rust_use_leaf_paths(source: &str, root: Node<'_>) -> Vec<(String, std::ops::Range<usize>)> {
2008    /// The text of a path, its segments joined by `::`; a segment the
2009    /// syntax tree lacks reads as empty.
2010    fn path_text(source: &str, node: Node<'_>) -> String {
2011        // `a::b::c` nests to the left: collect the names from the last
2012        // segment inward, then join them from the innermost path out.
2013        let mut names = Vec::new();
2014        let mut current = Some(node);
2015        while let Some(path) = current.filter(|path| path.kind() == "scoped_identifier") {
2016            names.push(
2017                path.child_by_field_name("name")
2018                    .map(|name| node_text(name, source))
2019                    .unwrap_or_default(),
2020            );
2021            current = path.child_by_field_name("path");
2022        }
2023        let mut text = current
2024            .map(|innermost| node_text(innermost, source).to_string())
2025            .unwrap_or_default();
2026        for name in names.iter().rev() {
2027            text.push_str("::");
2028            text.push_str(name);
2029        }
2030        text
2031    }
2032    let mut paths = Vec::new();
2033    // Use trees still to visit, each with the path prefix of the lists
2034    // around it. Children are pushed in reverse so paths come out in
2035    // source order.
2036    let mut pending = vec![(root, String::new())];
2037    while let Some((node, prefix)) = pending.pop() {
2038        if node.kind() == "scoped_use_list" {
2039            let path = node
2040                .child_by_field_name("path")
2041                .map(|path| path_text(source, path))
2042                .unwrap_or_default();
2043            let joined = if prefix.is_empty() {
2044                path
2045            } else {
2046                format!("{prefix}::{path}")
2047            };
2048            if let Some(list) = node.child_by_field_name("list") {
2049                pending.push((list, joined));
2050            }
2051        } else if node.kind() == "use_list" {
2052            let start = pending.len();
2053            for child in node.named_children(&mut node.walk()) {
2054                if !matches!(child.kind(), "line_comment" | "block_comment") {
2055                    pending.push((child, prefix.clone()));
2056                }
2057            }
2058            pending[start..].reverse();
2059        } else {
2060            let (path, alias) = if node.kind() == "use_as_clause" {
2061                (
2062                    node.child_by_field_name("path")
2063                        .map(|p| path_text(source, p))
2064                        .unwrap_or_default(),
2065                    node.child_by_field_name("alias")
2066                        .map(|a| node_text(a, source)),
2067                )
2068            } else {
2069                (path_text(source, node), None)
2070            };
2071            let mut joined = if path == "self" && !prefix.is_empty() {
2072                prefix
2073            } else if prefix.is_empty() {
2074                path
2075            } else {
2076                format!("{prefix}::{path}")
2077            };
2078            if let Some(alias) = alias {
2079                joined.push_str(" as ");
2080                joined.push_str(alias);
2081            }
2082            if !joined.is_empty() {
2083                paths.push((joined, node.byte_range()));
2084            }
2085        }
2086    }
2087    paths
2088}
2089
2090fn import_byte_range_from_imports(imports: &[ImportStatement]) -> Option<std::ops::Range<usize>> {
2091    let start = imports.iter().map(|import| import.byte_range.start).min()?;
2092    let end = imports.iter().map(|import| import.byte_range.end).max()?;
2093    Some(start..end)
2094}
2095
2096test_support_visibility! {
2097fn rust_use_visibility(raw_text: &str) -> Option<String> {
2098    let use_pos = raw_text.find("use ")?;
2099    let prefix = raw_text[..use_pos].trim();
2100    if prefix.is_empty() {
2101        None
2102    } else {
2103        Some(prefix.to_string())
2104    }
2105}
2106}
2107
2108test_support_visibility! {
2109fn rust_use_body(raw_text: &str) -> Option<&str> {
2110    let use_pos = raw_text.find("use ")?;
2111    Some(raw_text[use_pos + 4..].trim().trim_end_matches(';').trim())
2112}
2113}
2114
2115test_support_visibility! {
2116fn rust_use_list_names(body: &str) -> Vec<String> {
2117    let Some(open) = body.find("::{") else {
2118        return Vec::new();
2119    };
2120    let Some(close) = body[open + 3..].find('}').map(|offset| open + 3 + offset) else {
2121        return Vec::new();
2122    };
2123    body[open + 3..close]
2124        .split(',')
2125        .filter_map(|spec| {
2126            let spec = spec.trim();
2127            if spec.is_empty() {
2128                None
2129            } else {
2130                Some(spec.to_string())
2131            }
2132        })
2133        .collect()
2134}
2135}
2136
2137fn classify_rust_import_group(body: &str) -> ImportGroup {
2138    let first = body
2139        .split("::")
2140        .next()
2141        .unwrap_or(body)
2142        .split_whitespace()
2143        .next()
2144        .unwrap_or(body);
2145    match first.trim() {
2146        "std" | "core" | "alloc" => ImportGroup::Stdlib,
2147        "crate" | "self" | "super" => ImportGroup::Internal,
2148        _ => ImportGroup::External,
2149    }
2150}
2151
2152#[derive(Debug, Clone)]
2153struct ReexportRefs {
2154    raw_refs: Vec<RawRef>,
2155}
2156
2157fn collect_reexport_refs_with_line_index(
2158    project_root: &Path,
2159    abs_path: &Path,
2160    rel_path: &str,
2161    source: &str,
2162    lang: LangId,
2163    memo: &callgraph::ModuleResolutionMemo,
2164    facts: &FactPaths<'_>,
2165    line_index: &LineIndex,
2166    python_root: Option<Node<'_>>,
2167) -> ReexportRefs {
2168    if lang == LangId::Python {
2169        // Reuse the caller's syntax tree when the source has already been parsed.
2170        let exports = if let Some(root) = python_root {
2171            callgraph::python::reexports(source, root)
2172        } else {
2173            let Ok(tree) = parse_source_with_cached_parser(abs_path, source, LangId::Python) else {
2174                return ReexportRefs {
2175                    raw_refs: Vec::new(),
2176                };
2177            };
2178            callgraph::python::reexports(source, tree.root_node())
2179        };
2180        let mut raw_refs = build_import_refs(
2181            project_root,
2182            abs_path,
2183            rel_path,
2184            &exports,
2185            line_index,
2186            memo,
2187            facts,
2188        );
2189        for raw in &mut raw_refs {
2190            let names = raw
2191                .local_name
2192                .as_deref()
2193                .unwrap_or_default()
2194                .split(',')
2195                .zip(raw.requested_name.as_deref().unwrap_or_default().split(','))
2196                .map(|(local, source)| format!("{source} as {local}"))
2197                .collect::<Vec<_>>()
2198                .join(", ");
2199            let statement = format!("export {{ {names} }}");
2200            raw.ref_id = ref_id(&["python_reexport", &raw.ref_id]);
2201            raw.kind = "reexport".to_string();
2202            raw.import_kind = Some("reexport".to_string());
2203            raw.full_ref = Some(statement.clone());
2204        }
2205        return ReexportRefs { raw_refs };
2206    }
2207    let mut raw_refs = Vec::new();
2208    let mut search_start = 0usize;
2209    let mut ordinal = 0usize;
2210    while let Some(export_offset) = source[search_start..].find("export") {
2211        let start = search_start + export_offset;
2212        let Some(statement_end_offset) = source[start..].find(';') else {
2213            break;
2214        };
2215        let end = start + statement_end_offset + 1;
2216        let statement = &source[start..end];
2217        search_start = end;
2218        if !statement.contains(" from ") || !statement.contains(['\'', '"']) {
2219            continue;
2220        }
2221        let Some(module_path) = quoted_module_path(statement) else {
2222            continue;
2223        };
2224        ordinal += 1;
2225        let wildcard = statement.contains('*');
2226        let line = line_index.byte_to_line(start);
2227        let ref_id = ref_id(&[
2228            rel_path,
2229            "reexport",
2230            &start.to_string(),
2231            &end.to_string(),
2232            &module_path,
2233            &ordinal.to_string(),
2234        ]);
2235        raw_refs.push(RawRef {
2236            ref_id,
2237            caller_symbol: None,
2238            caller_file: rel_path.to_string(),
2239            kind: "reexport".to_string(),
2240            short_name: None,
2241            full_ref: Some(statement.to_string()),
2242            module_path: Some(module_path.clone()),
2243            import_kind: Some("reexport".to_string()),
2244            local_name: None,
2245            requested_name: None,
2246            namespace_alias: None,
2247            wildcard,
2248            line,
2249            byte_start: start,
2250            byte_end: end,
2251            dependencies: module_dependencies_with_memo(
2252                project_root,
2253                abs_path,
2254                &module_path,
2255                memo,
2256                facts,
2257            ),
2258        });
2259    }
2260    ReexportRefs { raw_refs }
2261}
2262
2263fn collect_rust_pub_use_reexport_refs(
2264    project_root: &Path,
2265    abs_path: &Path,
2266    rel_path: &str,
2267    imports: &[ImportStatement],
2268    line_index: &LineIndex,
2269    facts: &FactPaths<'_>,
2270) -> ReexportRefs {
2271    let mut raw_refs = Vec::new();
2272    let mut ordinal = 0usize;
2273    let module_memo = callgraph::ModuleResolutionMemo::default();
2274
2275    for import in imports {
2276        let Some(visibility) = &import.default_import else {
2277            continue;
2278        };
2279        if !visibility.starts_with("pub") {
2280            continue;
2281        }
2282        let Some((module_path, named, wildcard)) = rust_pub_use_reexport_parts(import) else {
2283            continue;
2284        };
2285        ordinal += 1;
2286        let ref_id = ref_id(&[
2287            rel_path,
2288            "rust_reexport",
2289            &import.byte_range.start.to_string(),
2290            &import.byte_range.end.to_string(),
2291            &module_path,
2292            &ordinal.to_string(),
2293        ]);
2294        raw_refs.push(RawRef {
2295            ref_id,
2296            caller_symbol: None,
2297            caller_file: rel_path.to_string(),
2298            kind: "reexport".to_string(),
2299            short_name: None,
2300            full_ref: Some(rust_reexport_statement_for_index(&named, &import.raw_text)),
2301            module_path: Some(module_path.clone()),
2302            import_kind: Some("reexport".to_string()),
2303            local_name: None,
2304            requested_name: None,
2305            namespace_alias: None,
2306            wildcard,
2307            line: line_index.byte_to_line(import.byte_range.start),
2308            byte_start: import.byte_range.start,
2309            byte_end: import.byte_range.end,
2310            dependencies: rust_module_dependencies(
2311                project_root,
2312                abs_path,
2313                &module_path,
2314                &module_memo,
2315                facts,
2316            ),
2317        });
2318    }
2319
2320    ReexportRefs { raw_refs }
2321}
2322
2323test_support_visibility! {
2324fn rust_pub_use_reexport_parts(
2325    import: &ImportStatement,
2326) -> Option<(String, HashMap<String, String>, bool)> {
2327    let body = rust_use_body(&import.raw_text).unwrap_or(import.module_path.as_str());
2328    let body = body.trim();
2329    if let Some(module_path) = body.strip_suffix("::*") {
2330        return Some((module_path.trim().to_string(), HashMap::new(), true));
2331    }
2332
2333    if let Some(brace_start) = body.find("::{") {
2334        rust_use_group_close(body)?;
2335        let module_path = body.get(..brace_start)?.trim().to_string();
2336        // Validate a real group, but retain the existing range, including
2337        // trailing comments, for output compatibility.
2338        let specs = body.get(brace_start + 3..body.rfind('}')?)?;
2339        let names = rust_reexport_names_from_specs(specs);
2340        if names.is_empty() {
2341            return None;
2342        }
2343        return Some((module_path, names, false));
2344    }
2345
2346    let (module_path, spec) = body.rsplit_once("::")?;
2347    let names = rust_reexport_names_from_specs(spec);
2348    if names.is_empty() {
2349        return None;
2350    }
2351    Some((module_path.trim().to_string(), names, false))
2352}
2353}
2354
2355test_support_visibility! {
2356fn rust_use_group_close(body: &str) -> Option<usize> {
2357    let bytes = body.as_bytes();
2358    let mut pos = 0;
2359    let mut depth: usize = 0;
2360    while let Some(&byte) = bytes.get(pos) {
2361        let rest = bytes.get(pos..)?;
2362        if rest.starts_with(b"//") {
2363            pos += rest.iter().position(|&b| b == b'\n').unwrap_or(rest.len());
2364            continue;
2365        }
2366        if rest.starts_with(b"/*") {
2367            pos += 2;
2368            let mut comments = 1;
2369            while comments > 0 {
2370                let rest = bytes.get(pos..)?;
2371                if rest.starts_with(b"/*") {
2372                    comments += 1;
2373                    pos += 2;
2374                } else if rest.starts_with(b"*/") {
2375                    comments -= 1;
2376                    pos += 2;
2377                } else {
2378                    bytes.get(pos)?;
2379                    pos += 1;
2380                }
2381            }
2382            continue;
2383        }
2384        // Raw strings may also have byte or C prefixes; scanning reaches their
2385        // `r` after the prefix without interpreting their contents as code.
2386        if byte == b'r' {
2387            let hashes = rest[1..].iter().take_while(|&&b| b == b'#').count();
2388            if rest.get(1 + hashes) == Some(&b'"') {
2389                pos += 2 + hashes;
2390                loop {
2391                    let &next = bytes.get(pos)?;
2392                    pos += 1;
2393                    if next == b'"' && bytes.get(pos..pos + hashes)?.iter().all(|&b| b == b'#') {
2394                        pos += hashes;
2395                        break;
2396                    }
2397                }
2398                continue;
2399            }
2400        }
2401        if byte == b'"' || (byte == b'\'' && rust_use_char_literal(body.get(pos..)?)) {
2402            pos += 1;
2403            loop {
2404                let &next = bytes.get(pos)?;
2405                pos += 1;
2406                if next == b'\\' {
2407                    bytes.get(pos)?;
2408                    pos += 1;
2409                } else if next == byte {
2410                    break;
2411                }
2412            }
2413            continue;
2414        }
2415        if depth == 0 && rest.starts_with(b"::{") {
2416            depth = 1;
2417            pos += 3;
2418            continue;
2419        }
2420        if depth > 0 {
2421            if byte == b'{' {
2422                depth += 1;
2423            } else if byte == b'}' {
2424                depth -= 1;
2425                if depth == 0 {
2426                    return Some(pos);
2427                }
2428            }
2429        }
2430        pos += 1;
2431    }
2432    None
2433}
2434}
2435
2436fn rust_use_char_literal(rest: &str) -> bool {
2437    // Apostrophes also introduce lifetimes. A character has either an escape or
2438    // one UTF-8 character followed by its closing quote.
2439    if rest.as_bytes().get(1) == Some(&b'\\') {
2440        return true;
2441    }
2442    rest.strip_prefix('\'')
2443        .and_then(|text| text.chars().next())
2444        .is_some_and(|ch| rest.as_bytes().get(1 + ch.len_utf8()) == Some(&b'\''))
2445}
2446
2447test_support_visibility! {
2448fn rust_reexport_names_from_specs(specs: &str) -> HashMap<String, String> {
2449    let mut names = HashMap::new();
2450    for spec in specs.split(',') {
2451        let spec = spec.trim();
2452        if spec.is_empty() || spec == "self" {
2453            continue;
2454        }
2455        if let Some((source, local)) = spec.split_once(" as ") {
2456            let source = source.trim();
2457            let local = local.trim();
2458            if !source.is_empty() && !local.is_empty() && source != "self" {
2459                names.insert(local.to_string(), source.to_string());
2460            }
2461        } else {
2462            names.insert(spec.to_string(), spec.to_string());
2463        }
2464    }
2465    names
2466}
2467}
2468
2469fn rust_reexport_statement_for_index(named: &HashMap<String, String>, fallback: &str) -> String {
2470    if named.is_empty() {
2471        return fallback.to_string();
2472    }
2473    let mut specs = named
2474        .iter()
2475        .map(|(local, source)| {
2476            if local == source {
2477                source.clone()
2478            } else {
2479                format!("{source} as {local}")
2480            }
2481        })
2482        .collect::<Vec<_>>();
2483    specs.sort();
2484    format!("pub use {{{}}};", specs.join(", "))
2485}
2486
2487test_support_visibility! {
2488fn quoted_module_path(statement: &str) -> Option<String> {
2489    let quote = match (statement.find('\''), statement.find('"')) {
2490        (Some(single), Some(double)) if single < double => '\'',
2491        (Some(_), Some(_)) => '"',
2492        (Some(_), None) => '\'',
2493        (None, Some(_)) => '"',
2494        (None, None) => return None,
2495    };
2496    let start = statement.find(quote)? + 1;
2497    let end = statement[start..].find(quote)? + start;
2498    Some(statement[start..end].to_string())
2499}
2500}
2501
2502#[derive(Debug, Clone)]
2503struct SourceLessExportRefs {
2504    raw_refs: Vec<RawRef>,
2505}
2506
2507fn collect_source_less_export_alias_refs_with_line_index(
2508    rel_path: &str,
2509    source: &str,
2510    line_index: &LineIndex,
2511) -> SourceLessExportRefs {
2512    let mut raw_refs = Vec::new();
2513    let mut search_start = 0usize;
2514    let mut ordinal = 0usize;
2515    while let Some(export_offset) = source[search_start..].find("export") {
2516        let start = search_start + export_offset;
2517        let Some(statement_end_offset) = source[start..].find(';') else {
2518            break;
2519        };
2520        let end = start + statement_end_offset + 1;
2521        let statement = &source[start..end];
2522        search_start = end;
2523        if statement.contains(" from ") || !statement.contains('{') || !statement.contains('}') {
2524            continue;
2525        }
2526        let aliases = parse_reexport_names(statement);
2527        if aliases.is_empty() {
2528            continue;
2529        }
2530        // Number the aliases in a fixed order: the ordinal is part of each ref
2531        // id and the parts feed the surface fingerprint, and hash-map order
2532        // differs between two extractions of the same file.
2533        let mut aliases = aliases.into_iter().collect::<Vec<_>>();
2534        aliases.sort();
2535        let line = line_index.byte_to_line(start);
2536        for (exported, source_symbol) in aliases {
2537            ordinal += 1;
2538            let ref_id = ref_id(&[
2539                rel_path,
2540                "export_alias",
2541                &start.to_string(),
2542                &end.to_string(),
2543                &exported,
2544                &source_symbol,
2545                &ordinal.to_string(),
2546            ]);
2547            raw_refs.push(RawRef {
2548                ref_id,
2549                caller_symbol: None,
2550                caller_file: rel_path.to_string(),
2551                kind: "export_alias".to_string(),
2552                short_name: None,
2553                full_ref: Some(statement.to_string()),
2554                module_path: None,
2555                import_kind: Some("export_alias".to_string()),
2556                local_name: Some(exported),
2557                requested_name: Some(source_symbol),
2558                namespace_alias: None,
2559                wildcard: false,
2560                line,
2561                byte_start: start,
2562                byte_end: end,
2563                dependencies: BTreeSet::new(),
2564            });
2565        }
2566    }
2567    SourceLessExportRefs { raw_refs }
2568}
2569
2570fn resolve_ref<I: ResolverIndex>(raw: RawRef, index: &I) -> Result<ResolvedRef> {
2571    #[cfg(any(test, feature = "test-support"))]
2572    rust_module_work::note(|work| {
2573        work.resolved_refs += 1;
2574        work.resolved_files.insert(raw.caller_file.clone());
2575    });
2576    if raw.kind == "import" && index.lang_for(&raw.caller_file) == Some(LangId::Luau) {
2577        let mut dependencies = raw.dependencies.clone();
2578        let target_file = raw
2579            .module_path
2580            .as_deref()
2581            .and_then(|path| luau::module(index, &raw.caller_file, path, &mut dependencies));
2582        return Ok(ResolvedRef {
2583            target_file,
2584            target_symbol: None,
2585            dependencies,
2586        });
2587    }
2588    if raw.kind == "import" && index.lang_for(&raw.caller_file) == Some(LangId::Go) {
2589        let files = raw
2590            .module_path
2591            .as_deref()
2592            .map(|module| index.go_package_files(&raw.caller_file, Some(module)))
2593            .unwrap_or_default();
2594        let target_file = files.first().cloned();
2595        let mut dependencies = raw.dependencies.clone();
2596        dependencies.extend(files);
2597        return Ok(ResolvedRef {
2598            target_file,
2599            target_symbol: None,
2600            dependencies,
2601        });
2602    }
2603    if !matches!(
2604        raw.kind.as_str(),
2605        "call" | "construction" | "callback_ref" | "value_ref" | MACRO_BODY_CALL_REF_KIND
2606    ) {
2607        return Ok(ResolvedRef {
2608            dependencies: raw.dependencies.clone(),
2609            target_file: None,
2610            target_symbol: None,
2611        });
2612    }
2613
2614    let caller_file = raw.caller_file.clone();
2615    let caller_data =
2616        index
2617            .caller_data(&caller_file)
2618            .ok_or_else(|| CallGraphStoreError::MissingCallerData {
2619                file: caller_file.clone(),
2620            })?;
2621    let full_ref = raw.full_ref.as_deref().unwrap_or_default();
2622    let short_name = raw.short_name.as_deref().unwrap_or_default();
2623    let mut dependencies = raw.dependencies.clone();
2624
2625    let resolved = match index.lang_for(&caller_file) {
2626        Some(LangId::Luau) => luau::call(
2627            index,
2628            &caller_file,
2629            full_ref,
2630            short_name,
2631            caller_data,
2632            &mut dependencies,
2633        ),
2634        Some(LangId::Rust) => {
2635            resolve_rust_target(index, &caller_file, full_ref, short_name, caller_data, &raw)
2636        }
2637        Some(LangId::Go) => {
2638            resolve_go_target(index, &caller_file, full_ref, short_name, caller_data)
2639        }
2640        Some(LangId::Python) => resolve_python_target(
2641            index,
2642            &caller_file,
2643            full_ref,
2644            short_name,
2645            caller_data,
2646            &raw,
2647            &mut dependencies,
2648        ),
2649        Some(LangId::TypeScript | LangId::Tsx | LangId::JavaScript) => {
2650            resolve_js_ts_target(index, &caller_file, full_ref, short_name, caller_data)
2651        }
2652        _ => resolve_local_target(index, &caller_file, full_ref, short_name, caller_data),
2653    };
2654
2655    let Some((_, target_file, mut target_symbol)) = resolved else {
2656        return Ok(ResolvedRef {
2657            target_file: None,
2658            target_symbol: None,
2659            dependencies,
2660        });
2661    };
2662
2663    dependencies.insert(target_file.clone());
2664    if raw.kind == "construction" {
2665        let Some(node) = index.node_for_symbol(&target_file, &target_symbol) else {
2666            return Ok(ResolvedRef {
2667                target_file: None,
2668                target_symbol: None,
2669                dependencies,
2670            });
2671        };
2672        let constructor = format!("{target_symbol}::constructor");
2673        if index.node_is_callable(&target_file, &node) {
2674            // JavaScript functions can also be constructed; they remain callable targets.
2675        } else if index.node_for_symbol(&target_file, &constructor).is_some() {
2676            target_symbol = constructor;
2677        } else {
2678        }
2679    }
2680    let target_node = index.node_for_symbol(&target_file, &target_symbol);
2681    if matches!(raw.kind.as_str(), "value_ref" | "callback_ref")
2682        && index.lang_for(&caller_file) != Some(LangId::Go)
2683        && !target_node
2684            .as_deref()
2685            .is_some_and(|node_id| index.node_is_callable(&target_file, node_id))
2686    {
2687        return Ok(ResolvedRef {
2688            target_file: None,
2689            target_symbol: None,
2690            dependencies,
2691        });
2692    }
2693
2694    Ok(ResolvedRef {
2695        target_file: Some(target_file),
2696        target_symbol: Some(target_symbol),
2697        dependencies,
2698    })
2699}
2700
2701// Retain at most 8 MiB of conservatively charged package data per resolution
2702// pass, independently of the file-index memo. Evict whole packages, and use the
2703// original scan for oversized ones: never trim the resolver's candidates.
2704const GO_PACKAGE_MEMO_BYTES: usize = 8 * 1024 * 1024;
2705// Remember oversized package directories separately from cached indexes, using
2706// at most 64 KiB of conservatively charged path/set storage. If that fills up,
2707// stop building new indexes for this pass: otherwise an unremembered oversized
2708// directory could trigger the same failed construction on every reference.
2709const GO_PACKAGE_OVERSIZED_MEMO_BYTES: usize = 64 * 1024;
2710
2711test_support_visibility! {
2712#[derive(Clone, Default)]
2713struct GoPackageMemo {
2714    packages: HashMap<PathBuf, Rc<GoPackage>>,
2715    order: VecDeque<(PathBuf, usize)>,
2716    bytes: usize,
2717    oversized_dirs: HashSet<PathBuf>,
2718    oversized_bytes: usize,
2719}
2720}
2721
2722impl GoPackageMemo {
2723    fn mark_oversized(&mut self, dir: PathBuf) {
2724        if self.oversized_dirs.contains(&dir) {
2725            return;
2726        }
2727        let bytes = dir.as_os_str().len() + 4 * std::mem::size_of::<PathBuf>() + 32;
2728        if self.oversized_bytes + bytes > GO_PACKAGE_OVERSIZED_MEMO_BYTES {
2729            self.oversized_bytes = GO_PACKAGE_OVERSIZED_MEMO_BYTES;
2730            return;
2731        }
2732        self.oversized_bytes += bytes;
2733        self.oversized_dirs.insert(dir);
2734    }
2735
2736    fn insert(&mut self, dir: PathBuf, package: Rc<GoPackage>) {
2737        while self.bytes + package.bytes > GO_PACKAGE_MEMO_BYTES {
2738            let (oldest, bytes) = self.order.pop_front().expect("nonempty package memo");
2739            self.packages.remove(&oldest);
2740            self.bytes -= bytes;
2741        }
2742        self.bytes += package.bytes;
2743        self.order.push_back((dir.clone(), package.bytes));
2744        self.packages.insert(dir, package);
2745    }
2746}
2747
2748#[derive(Default)]
2749struct GoPackage {
2750    files: Vec<String>,
2751    symbols: HashMap<String, GoSymbolTargets>,
2752    bytes: usize,
2753}
2754
2755#[derive(Default)]
2756struct GoSymbolTargets {
2757    // Slot 0 excludes _test.go files; slot 1 includes them. `exported` also
2758    // requires the symbol to be exported, as an imported package lookup does.
2759    // None means no matching file; usize::MAX means multiple matching files.
2760    local: [Option<usize>; 2],
2761    exported: [Option<usize>; 2],
2762}
2763
2764impl GoPackage {
2765    fn files_for(&self, caller: &str) -> Vec<String> {
2766        self.files
2767            .iter()
2768            .filter(|file| caller.ends_with("_test.go") || !file.ends_with("_test.go"))
2769            .cloned()
2770            .collect()
2771    }
2772
2773    fn target(&self, caller: &str, imported: bool, symbol: &str) -> Option<String> {
2774        let targets = self.symbols.get(symbol)?;
2775        let candidates = if imported {
2776            &targets.exported
2777        } else {
2778            &targets.local
2779        };
2780        self.files
2781            .get(candidates[usize::from(caller.ends_with("_test.go"))]?)
2782            .cloned()
2783    }
2784
2785    fn add_symbols(&mut self, file: usize, index: &DbFileIndex) -> bool {
2786        let test_only = self.files[file].ends_with("_test.go");
2787        for symbol in index.node_by_scoped.keys().chain(
2788            index
2789                .node_by_bare
2790                .keys()
2791                .filter(|symbol| !index.node_by_scoped.contains_key(*symbol)),
2792        ) {
2793            if !self.symbols.contains_key(symbol) {
2794                // Charge spare hash buckets and string allocation overhead as
2795                // well as payload, so tiny symbols/packages are bounded too.
2796                self.bytes += symbol.len() + 4 * std::mem::size_of::<(String, GoSymbolTargets)>();
2797                if self.bytes > GO_PACKAGE_MEMO_BYTES {
2798                    return false;
2799                }
2800            }
2801            let targets = self.symbols.entry(symbol.clone()).or_default();
2802            for variant in usize::from(test_only)..2 {
2803                let add = |slot: &mut Option<usize>| {
2804                    *slot = Some(if slot.is_none() { file } else { usize::MAX });
2805                };
2806                add(&mut targets.local[variant]);
2807                if index.exports.contains(symbol) {
2808                    add(&mut targets.exported[variant]);
2809                }
2810            }
2811        }
2812        true
2813    }
2814}
2815
2816fn cached_go_package<T: std::ops::Deref<Target = DbFileIndex>>(
2817    facts: &FactPaths<'_>,
2818    modules: &WorkspaceCratePrefixCache,
2819    memo: &RefCell<GoPackageMemo>,
2820    caller: &str,
2821    module: Option<&str>,
2822    contains: impl Fn(&str) -> bool,
2823    load: impl Fn(&str) -> Option<T>,
2824) -> Option<Rc<GoPackage>> {
2825    let Some(dir) = go_package_dir(facts, modules, caller, module) else {
2826        return Some(Rc::new(GoPackage::default()));
2827    };
2828    if let Some(package) = memo.borrow().packages.get(&dir) {
2829        return Some(Rc::clone(package));
2830    }
2831    if memo.borrow().oversized_bytes >= GO_PACKAGE_OVERSIZED_MEMO_BYTES
2832        || memo.borrow().oversized_dirs.contains(&dir)
2833    {
2834        return None;
2835    }
2836    #[cfg(any(test, feature = "test-support"))]
2837    work_counts::note_go_package_build(&dir);
2838    let files = go_files_in_dir(facts, &dir, true)
2839        .into_iter()
2840        .filter(|file| contains(file))
2841        .collect::<Vec<_>>();
2842    let bytes = 512
2843        + 2 * dir.as_os_str().len()
2844        + files.capacity() * std::mem::size_of::<String>()
2845        + files.iter().map(|file| file.capacity() + 32).sum::<usize>();
2846    if bytes > GO_PACKAGE_MEMO_BYTES {
2847        memo.borrow_mut().mark_oversized(dir);
2848        return None;
2849    }
2850    let mut package = GoPackage {
2851        files,
2852        bytes,
2853        ..Default::default()
2854    };
2855    for file in 0..package.files.len() {
2856        if let Some(index) = load(&package.files[file]) {
2857            if !package.add_symbols(file, &index) {
2858                memo.borrow_mut().mark_oversized(dir);
2859                return None;
2860            }
2861        }
2862    }
2863    let package = Rc::new(package);
2864    memo.borrow_mut().insert(dir, Rc::clone(&package));
2865    Some(package)
2866}
2867
2868fn go_symbol_target_by_scan<I: ResolverIndex + ?Sized>(
2869    index: &I,
2870    caller_file: &str,
2871    module: Option<&str>,
2872    symbol: &str,
2873) -> Option<String> {
2874    let mut targets = index
2875        .uncached_go_package_files(caller_file, module)
2876        .into_iter()
2877        .filter(|file| {
2878            index.node_for_symbol(file, symbol).is_some()
2879                && (module.is_none() || index.has_export(file, symbol))
2880        });
2881    let target = targets.next()?;
2882    targets.next().is_none().then_some(target)
2883}
2884
2885fn go_package_files(
2886    facts: &FactPaths<'_>,
2887    cache: &WorkspaceCratePrefixCache,
2888    caller_file: &str,
2889    module: Option<&str>,
2890) -> Vec<String> {
2891    let Some(dir) = go_package_dir(facts, cache, caller_file, module) else {
2892        return Vec::new();
2893    };
2894    go_files_in_dir(facts, &dir, caller_file.ends_with("_test.go"))
2895}
2896
2897/// The Go module map: each `go.mod`'s module path, by the folder it names,
2898/// from a walk of every folder of the checkout. Every reader of a Go import
2899/// path depends on it as a whole, through its domain key.
2900pub fn go_module_map(facts: &FactPaths<'_>) -> HashMap<String, String> {
2901    let mut modules = HashMap::new();
2902    let mut stack = vec![facts.root.to_path_buf()];
2903    while let Some(dir) = stack.pop() {
2904        if matches!(
2905            dir.file_name().and_then(|s| s.to_str()),
2906            Some("target" | "node_modules" | ".git")
2907        ) {
2908            continue;
2909        }
2910        let manifest = dir.join("go.mod");
2911        facts.config_fact(&manifest, "module");
2912        if let Some(bytes) = facts.attributed_bytes(&manifest) {
2913            if let Ok(text) = std::str::from_utf8(&bytes) {
2914                for line in text.lines() {
2915                    let mut words = line.split_whitespace();
2916                    if words.next() == Some("module") {
2917                        if let Some(name) = words.next() {
2918                            modules.insert(
2919                                name.trim_matches('"').to_string(),
2920                                relative_path(facts.root, &dir),
2921                            );
2922                        }
2923                    }
2924                }
2925            }
2926        }
2927        for entry in facts.list_dir(&dir) {
2928            if entry.kind == EntryKind::Directory {
2929                stack.push(dir.join(byte_path(&entry.name)));
2930            }
2931        }
2932    }
2933    modules
2934}
2935
2936/// The Rust crate map: each workspace crate's name, by the prefix of its
2937/// source folder, from every `Cargo.toml` of the checkout. Every reader of a
2938/// crate path depends on it as a whole, through its domain key.
2939pub fn rust_crate_map(facts: &FactPaths<'_>) -> HashMap<String, String> {
2940    build_workspace_crate_prefixes(facts.root, facts)
2941}
2942
2943fn go_package_dir(
2944    facts: &FactPaths<'_>,
2945    cache: &WorkspaceCratePrefixCache,
2946    caller_file: &str,
2947    module: Option<&str>,
2948) -> Option<PathBuf> {
2949    Some(if let Some(module) = module {
2950        // The module map is built once per index by walking every directory
2951        // for its go.mod. A reader records the map's domain key, not the walk:
2952        // the walk names every directory, and which reader happened to build
2953        // the map must not change what any reader records.
2954        facts.facts.record_domain(join::VIEW_GO_MODULES_DOMAIN);
2955        let modules = cache.1.get_or_init(|| {
2956            facts.facts.pause_recording();
2957            let modules = go_module_map(facts);
2958            facts.facts.resume_recording();
2959            modules
2960        });
2961        let Some((prefix, dir)) = modules
2962            .iter()
2963            .filter(|(prefix, _)| {
2964                module == prefix.as_str()
2965                    || module
2966                        .strip_prefix(prefix.as_str())
2967                        .is_some_and(|rest| rest.starts_with('/'))
2968            })
2969            .max_by_key(|(prefix, _)| prefix.len())
2970        else {
2971            return None;
2972        };
2973        facts
2974            .root
2975            .join(dir)
2976            .join(module[prefix.len()..].trim_start_matches('/'))
2977    } else {
2978        facts
2979            .root
2980            .join(caller_file)
2981            .parent()
2982            .unwrap_or(facts.root)
2983            .to_path_buf()
2984    })
2985}
2986
2987fn go_files_in_dir(facts: &FactPaths<'_>, dir: &Path, include_tests: bool) -> Vec<String> {
2988    let mut files = facts
2989        .list_dir(&dir)
2990        .into_iter()
2991        .filter_map(|entry| {
2992            let path = dir.join(byte_path(&entry.name));
2993            (entry.kind == EntryKind::Regular
2994                && path.extension().and_then(|s| s.to_str()) == Some("go")
2995                && (include_tests || !path.to_string_lossy().ends_with("_test.go")))
2996            .then(|| relative_path(facts.root, &path))
2997        })
2998        .collect::<Vec<_>>();
2999    files.sort();
3000    files
3001}
3002
3003fn resolve_go_target<I: ResolverIndex>(
3004    index: &I,
3005    caller_file: &str,
3006    full_ref: &str,
3007    short_name: &str,
3008    caller_data: &FileCallData,
3009) -> Option<(String, String, String)> {
3010    let module = if let Some((alias, member)) = full_ref.split_once('.') {
3011        if member != short_name || member.contains('.') {
3012            return None;
3013        }
3014        // An object selector is not a package-level symbol lookup. Leave
3015        // it for receiver-aware dispatch rather than binding its bare name.
3016        let import = caller_data.import_block.imports.iter().find(|import| {
3017            let raw_alias = import.raw_text.split('"').next().unwrap_or("").trim();
3018            import.default_import.as_deref().unwrap_or_else(|| {
3019                if !raw_alias.is_empty() {
3020                    raw_alias
3021                } else {
3022                    import.module_path.rsplit('/').next().unwrap_or("")
3023                }
3024            }) == alias
3025        })?;
3026        Some(import.module_path.as_str())
3027    } else {
3028        None
3029    };
3030    let target = index.go_symbol_target(caller_file, module, short_name)?;
3031    Some(("resolved".to_string(), target, short_name.to_string()))
3032}
3033
3034fn resolve_python_target<I: ResolverIndex>(
3035    index: &I,
3036    caller_file: &str,
3037    full_ref: &str,
3038    short_name: &str,
3039    caller_data: &FileCallData,
3040    raw: &RawRef,
3041    dependencies: &mut BTreeSet<String>,
3042) -> Option<(String, String, String)> {
3043    if let Ok(binding_index) = caller_data
3044        .python_bindings
3045        .binary_search_by_key(&(raw.byte_start, raw.byte_end), |binding| {
3046            (binding.byte_start, binding.byte_end)
3047        })
3048    {
3049        let binding = &caller_data.python_bindings[binding_index];
3050        let (module, symbol) = binding.target.as_ref()?;
3051        let target_file = if module.is_empty() {
3052            caller_file.to_string()
3053        } else {
3054            index.module_target(caller_file, module)?
3055        };
3056        let (file, symbol) = resolve_python_symbol(index, &target_file, symbol, dependencies)?;
3057        return Some(("resolved".to_string(), file, symbol));
3058    }
3059    resolve_local_target(index, caller_file, full_ref, short_name, caller_data)
3060}
3061
3062fn resolve_python_symbol<I: ResolverIndex>(
3063    index: &I,
3064    file: &str,
3065    symbol: &str,
3066    dependencies: &mut BTreeSet<String>,
3067) -> Option<(String, String)> {
3068    let mut file = file.to_string();
3069    let mut symbol = symbol.to_string();
3070    let mut visited = HashSet::new();
3071    loop {
3072        dependencies.insert(file.clone());
3073        if !visited.insert((file.clone(), symbol.clone())) {
3074            return None;
3075        }
3076        if let Some(node) = index.node_for_symbol(&file, &symbol) {
3077            // Python index lookups require an exact scoped name, so a bare
3078            // import cannot select a class method with the same name.
3079            if index.node_is_callable(&file, &node) {
3080                return Some((file, symbol));
3081            }
3082            let initializer = format!("{symbol}::__init__");
3083            let init_node = index.node_for_symbol(&file, &initializer)?;
3084            return index
3085                .node_is_callable(&file, &init_node)
3086                .then_some((file, initializer));
3087        }
3088        let mut targets = BTreeSet::new();
3089        for export in index.reexports_for(&file) {
3090            if let (Some(source), Some(target)) = (export.named.get(&symbol), export.target_file) {
3091                targets.insert((target, source.clone()));
3092            }
3093        }
3094        if targets.len() != 1 {
3095            return None;
3096        }
3097        (file, symbol) = targets.into_iter().next()?;
3098    }
3099}
3100
3101fn resolve_js_ts_target<I: ResolverIndex>(
3102    index: &I,
3103    caller_file: &str,
3104    full_ref: &str,
3105    short_name: &str,
3106    caller_data: &FileCallData,
3107) -> Option<(String, String, String)> {
3108    if let Some((namespace, member)) = full_ref.split_once('.') {
3109        for import in &caller_data.import_block.imports {
3110            if import.namespace_import.as_deref() == Some(namespace) {
3111                if let Some(target_file) = index.module_target(caller_file, &import.module_path) {
3112                    if let Some((file, symbol)) =
3113                        resolve_exported_symbol(index, &target_file, member, 0)
3114                    {
3115                        return Some(("resolved".to_string(), file, symbol));
3116                    }
3117                }
3118            }
3119        }
3120    }
3121
3122    for import in &caller_data.import_block.imports {
3123        for spec in &import.names {
3124            if crate::imports::specifier_local_name(spec) == short_name {
3125                if let Some(target_file) = index.module_target(caller_file, &import.module_path) {
3126                    let requested = crate::imports::specifier_imported_name(spec);
3127                    let (file, symbol) = resolve_exported_symbol(index, &target_file, requested, 0)
3128                        .unwrap_or_else(|| (target_file, requested.to_string()));
3129                    return Some(("resolved".to_string(), file, symbol));
3130                }
3131            }
3132        }
3133
3134        if import.default_import.as_deref() == Some(short_name) {
3135            if let Some(target_file) = index.module_target(caller_file, &import.module_path) {
3136                let (file, symbol) = resolve_exported_symbol(index, &target_file, "default", 0)
3137                    .or_else(|| {
3138                        index
3139                            .default_export(&target_file)
3140                            .map(|symbol| (target_file.clone(), symbol))
3141                    })
3142                    .unwrap_or_else(|| {
3143                        let file_name = Path::new(&target_file)
3144                            .file_name()
3145                            .and_then(|name| name.to_str())
3146                            .unwrap_or("unknown")
3147                            .to_string();
3148                        (target_file, format!("<default:{file_name}>"))
3149                    });
3150                return Some(("resolved".to_string(), file, symbol));
3151            }
3152        }
3153    }
3154
3155    for import in &caller_data.import_block.imports {
3156        if let Some(target_file) = index.module_target(caller_file, &import.module_path) {
3157            if index.has_export(&target_file, short_name) {
3158                return Some(("resolved".to_string(), target_file, short_name.to_string()));
3159            }
3160        }
3161    }
3162
3163    resolve_local_target(index, caller_file, full_ref, short_name, caller_data)
3164}
3165
3166test_support_visibility! {
3167fn resolve_exported_symbol<I: ResolverIndex>(
3168    index: &I,
3169    file: &str,
3170    requested: &str,
3171    depth: usize,
3172) -> Option<(String, String)> {
3173    let mut visited = std::collections::HashMap::new();
3174    resolve_exported_symbol_inner(index, file, requested, depth, &mut visited)
3175}
3176}
3177
3178/// Re-export graphs are frequently cyclic (barrel files re-exporting each
3179/// other, `pub use` cycles). The depth cap alone bounds path LENGTH, not path
3180/// COUNT: with wildcard fan-out the walk explores branching^depth paths and a
3181/// single resolution can burn CPU-minutes. The memo prunes re-visits of a
3182/// (file, symbol) pair — but only when the earlier visit had at least as much
3183/// remaining depth budget (a shallower re-visit can reach leaves the deeper
3184/// first visit had to cut off at the cap, so plain visited-set pruning would
3185/// lose resolutions the capped walk finds).
3186fn resolve_exported_symbol_inner<I: ResolverIndex>(
3187    index: &I,
3188    file: &str,
3189    requested: &str,
3190    depth: usize,
3191    visited: &mut std::collections::HashMap<(String, String), usize>,
3192) -> Option<(String, String)> {
3193    if depth > 16 {
3194        return None;
3195    }
3196    if requested != "default" {
3197        if let Some(source_symbol) = index.export_alias(file, requested) {
3198            if index.lang_for(file) != Some(LangId::Rust)
3199                || index.node_for_symbol(file, &source_symbol).is_some()
3200            {
3201                return Some((file.to_string(), source_symbol));
3202            }
3203        }
3204        if index.has_export(file, requested) {
3205            // A Rust use can export a name without declaring it in this module.
3206            // Follow the re-export rather than claiming this file defines the name.
3207            if index.lang_for(file) != Some(LangId::Rust)
3208                || index.node_for_symbol(file, requested).is_some()
3209            {
3210                return Some((file.to_string(), requested.to_string()));
3211            }
3212        }
3213    } else if let Some(default) = index.default_export(file) {
3214        return Some((file.to_string(), default));
3215    }
3216
3217    // Memo check sits after the local-export fast paths: the common direct
3218    // hit never allocates the key, and a hit through the memo would have
3219    // returned above anyway.
3220    match visited.entry((file.to_string(), requested.to_string())) {
3221        std::collections::hash_map::Entry::Occupied(mut seen) => {
3222            if *seen.get() <= depth {
3223                return None;
3224            }
3225            seen.insert(depth);
3226        }
3227        std::collections::hash_map::Entry::Vacant(slot) => {
3228            slot.insert(depth);
3229        }
3230    }
3231
3232    for reexport in index.reexports_for(file) {
3233        let mut next_requested = requested.to_string();
3234        let matches = if reexport.wildcard {
3235            true
3236        } else if let Some(source_name) = reexport.named.get(requested) {
3237            next_requested = source_name.clone();
3238            true
3239        } else {
3240            false
3241        };
3242        if !matches {
3243            continue;
3244        }
3245        if let Some(target_file) = &reexport.target_file {
3246            if let Some(target) = resolve_exported_symbol_inner(
3247                index,
3248                target_file,
3249                &next_requested,
3250                depth + 1,
3251                visited,
3252            ) {
3253                return Some(target);
3254            }
3255        }
3256    }
3257    None
3258}
3259
3260fn resolve_rust_target<I: ResolverIndex>(
3261    index: &I,
3262    caller_file: &str,
3263    full_ref: &str,
3264    short_name: &str,
3265    caller_data: &FileCallData,
3266    raw: &RawRef,
3267) -> Option<(String, String, String)> {
3268    // A self call is bound by its enclosing declaration, including trait
3269    // defaults and trait impls whose scope contains both trait and type names.
3270    if let Some(member) = full_ref.strip_prefix("self.") {
3271        if let Some(owner) = raw
3272            .caller_symbol
3273            .as_deref()
3274            .and_then(|s| s.rsplit_once("::"))
3275        {
3276            for scope in std::iter::once(owner.0) {
3277                let symbol = format!("{scope}::{member}");
3278                if caller_data
3279                    .symbol_metadata
3280                    .get(&symbol)
3281                    .is_some_and(|meta| {
3282                        meta.kind == SymbolKind::Method
3283                            && meta
3284                                .signature
3285                                .as_deref()
3286                                .and_then(signature_parameter_text)
3287                                .and_then(|parameters| {
3288                                    split_top_level_commas(parameters).first().copied()
3289                                })
3290                                .and_then(|parameter| {
3291                                    rust_parameter_name(
3292                                        parameter.split(':').next().unwrap_or(parameter),
3293                                    )
3294                                })
3295                                == Some("self")
3296                    })
3297                    && index.node_for_symbol(caller_file, &symbol).is_some()
3298                {
3299                    return Some((
3300                        "resolved_local".to_string(),
3301                        caller_file.to_string(),
3302                        symbol,
3303                    ));
3304                }
3305            }
3306        }
3307    }
3308    if full_ref.contains('.') {
3309        return None;
3310    }
3311    if short_name.ends_with('!') && !full_ref.contains("::") {
3312        if index.node_for_symbol(caller_file, short_name).is_some() {
3313            return Some((
3314                "resolved_local".to_string(),
3315                caller_file.to_string(),
3316                short_name.to_string(),
3317            ));
3318        }
3319        if let Some(file) = rust_macro_use_target(index, caller_file, short_name) {
3320            return Some(("resolved".to_string(), file, short_name.to_string()));
3321        }
3322    }
3323    if full_ref.contains("::") {
3324        if let Some((file, symbol)) =
3325            rust_associated_target(index, caller_file, full_ref, caller_data, raw)
3326        {
3327            return Some(("resolved".to_string(), file, symbol));
3328        }
3329        if let Some((owner, _)) = full_ref.rsplit_once("::") {
3330            if !matches!(owner, "Self" | "self" | "super" | "crate") {
3331                if let Some((file, symbol)) =
3332                    rust_type_binding(index, caller_file, owner, caller_data, raw)
3333                {
3334                    if index
3335                        .node_for_symbol(&file, &symbol)
3336                        .is_some_and(|node| !index.node_is_callable(&file, &node))
3337                    {
3338                        return None;
3339                    }
3340                }
3341            }
3342        }
3343        // Self names the enclosing impl or trait, not a module on disk. Keep
3344        // private associated helpers in the same graph as their public callers.
3345        if let Some(member) = full_ref.strip_prefix("Self::") {
3346            if let Some(caller) = raw.caller_symbol.as_deref().filter(|caller| {
3347                caller_data
3348                    .symbol_metadata
3349                    .get(*caller)
3350                    .is_some_and(|meta| meta.kind == SymbolKind::Method)
3351            }) {
3352                if let Some((owner, _)) = caller.rsplit_once("::") {
3353                    let symbol = format!("{owner}::{member}");
3354                    if index.node_for_symbol(caller_file, &symbol).is_some() {
3355                        return Some((
3356                            "resolved_local".to_string(),
3357                            caller_file.to_string(),
3358                            symbol,
3359                        ));
3360                    }
3361                }
3362            }
3363        }
3364        if let Some((target_file, target_symbol)) =
3365            rust_target_for_qualified(index, caller_file, full_ref, short_name, caller_data, raw)
3366        {
3367            return Some(("resolved".to_string(), target_file, target_symbol));
3368        }
3369        // An unresolved qualifier must not bind an unrelated unqualified import
3370        // that happens to share the final function name.
3371        return None;
3372    }
3373
3374    // A file-level function of the caller's own file wins over imports. Rust
3375    // rejects a file-level `use` that binds the same name as a file-level item,
3376    // so any import of this name sits in a nested scope (typically
3377    // `mod tests { use super::{..}; }`); applying it to the whole file
3378    // resolved ordinary same-file calls through the wrong module.
3379    if let Some(local) =
3380        rust_unique_file_level_function(index, caller_file, full_ref, short_name, caller_data)
3381    {
3382        return Some(local);
3383    }
3384
3385    for import in &caller_data.import_block.imports {
3386        if let Some((target_file, target_symbol)) =
3387            rust_target_for_use(index, caller_file, import, short_name, caller_data, raw)
3388        {
3389            return Some(("resolved".to_string(), target_file, target_symbol));
3390        }
3391    }
3392
3393    resolve_local_target(index, caller_file, full_ref, short_name, caller_data)
3394}
3395
3396fn rust_associated_target<I: ResolverIndex>(
3397    index: &I,
3398    caller_file: &str,
3399    full_ref: &str,
3400    caller_data: &FileCallData,
3401    raw: &RawRef,
3402) -> Option<(String, String)> {
3403    let (owner, member) = full_ref.rsplit_once("::")?;
3404    if matches!(owner, "Self" | "self" | "super" | "crate") {
3405        return None;
3406    }
3407    let binding = rust_type_binding(index, caller_file, owner, caller_data, raw)?;
3408    // Follow the imported type before appending its member: the module
3409    // re-exports `Backend`, not a free function named `new`.
3410    index.node_for_symbol(&binding.0, &binding.1)?;
3411    let symbol = format!("{}::{member}", binding.1);
3412    index.node_for_symbol(&binding.0, &symbol)?;
3413    Some((binding.0, symbol))
3414}
3415
3416fn rust_type_binding<I: ResolverIndex>(
3417    index: &I,
3418    caller_file: &str,
3419    owner: &str,
3420    caller_data: &FileCallData,
3421    raw: &RawRef,
3422) -> Option<(String, String)> {
3423    if owner.contains("::") {
3424        rust_target_for_qualified(
3425            index,
3426            caller_file,
3427            owner,
3428            owner.rsplit("::").next()?,
3429            caller_data,
3430            raw,
3431        )
3432    } else {
3433        let modules = rust_reference_module_segments(index, caller_file, caller_data, raw);
3434        if let Some(target) = rust_inline_scoped_target(index, caller_file, &modules, owner) {
3435            if index
3436                .node_for_symbol(&target.0, &target.1)
3437                .is_some_and(|node| !index.node_is_callable(&target.0, &node))
3438            {
3439                return Some(target);
3440            }
3441        }
3442        if caller_data.symbol_metadata.contains_key(owner) {
3443            return Some((caller_file.to_string(), owner.to_string()));
3444        }
3445        caller_data
3446            .import_block
3447            .imports
3448            .iter()
3449            .filter(|import| rust_import_is_visible_to_call(import, raw))
3450            .find_map(|import| {
3451                rust_target_for_use(index, caller_file, import, owner, caller_data, raw)
3452            })
3453    }
3454}
3455
3456fn rust_macro_use_target<I: ResolverIndex>(
3457    index: &I,
3458    caller_file: &str,
3459    name: &str,
3460) -> Option<String> {
3461    let mut scope = Some(caller_file.to_string());
3462    let mut visited_scopes = BTreeSet::new();
3463    while let Some(file) = scope {
3464        if !visited_scopes.insert(file.clone()) {
3465            break;
3466        }
3467        let mut queue = index.macro_use_modules(&file);
3468        let mut visited_modules = BTreeSet::new();
3469        let mut targets = BTreeSet::new();
3470        while let Some(module) = queue.pop() {
3471            if !visited_modules.insert(module.clone()) {
3472                continue;
3473            }
3474            if index.node_for_symbol(&module, name).is_some() {
3475                targets.insert(module.clone());
3476            }
3477            queue.extend(index.macro_use_modules(&module));
3478        }
3479        if targets.len() == 1 {
3480            return targets.into_iter().next();
3481        }
3482        if !targets.is_empty() {
3483            return None;
3484        }
3485        scope = index.module_parent(&file).map(|(parent, _)| parent);
3486    }
3487    None
3488}
3489
3490test_support_visibility! {
3491fn rust_unique_file_level_function<I: ResolverIndex>(
3492    _index: &I,
3493    caller_file: &str,
3494    full_ref: &str,
3495    short_name: &str,
3496    caller_data: &FileCallData,
3497) -> Option<(String, String, String)> {
3498    if full_ref.contains("::") || !callgraph::is_bare_callee(full_ref, short_name) {
3499        return None;
3500    }
3501    // Another free function can shadow a bare call; associated functions
3502    // cannot. Keep trait members behind their declaring trait or type.
3503    let symbol = short_name.to_string();
3504    // Declaration metadata proves the local binding without probing indexed
3505    // nodes for primitive return types or other non-function receiver names.
3506    let is_file_level_function = caller_data
3507        .symbol_metadata
3508        .get(short_name)
3509        .is_some_and(|meta| meta.kind == SymbolKind::Function)
3510        && !caller_data.symbol_metadata.iter().any(|(name, meta)| {
3511            name != short_name
3512                && last_name_segment(name) == short_name
3513                && meta.kind == SymbolKind::Function
3514        });
3515    is_file_level_function.then(|| {
3516        (
3517            "resolved_local".to_string(),
3518            caller_file.to_string(),
3519            symbol,
3520        )
3521    })
3522}
3523}
3524
3525fn rust_target_for_qualified<I: ResolverIndex>(
3526    index: &I,
3527    caller_file: &str,
3528    full_ref: &str,
3529    short_name: &str,
3530    caller_data: &FileCallData,
3531    raw: &RawRef,
3532) -> Option<(String, String)> {
3533    let mut segments: Vec<&str> = full_ref.split("::").collect();
3534    if segments.len() < 2 {
3535        return None;
3536    }
3537    segments.pop();
3538    let requested_symbol = rust_target_symbol(full_ref, short_name);
3539
3540    for path in rust_module_path_candidates(index, &segments, caller_data, raw) {
3541        let path_refs = path.iter().map(String::as_str).collect::<Vec<_>>();
3542        if !matches!(path_refs.first().copied(), Some("crate" | "self" | "super")) {
3543            if let Some(target_file) = rust_workspace_file_for_segments(index, &path_refs) {
3544                return Some(rust_resolve_reexport_if_symbol_missing(
3545                    index,
3546                    target_file,
3547                    requested_symbol.clone(),
3548                ));
3549            }
3550        }
3551
3552        // A path that does not resolve under one reading may under another, and
3553        // a later alias candidate may still match, so try them all in order.
3554        for module_segments in rust_resolve_segment_candidates_from(
3555            rust_reference_module_segments(index, caller_file, caller_data, raw),
3556            &path_refs,
3557        ) {
3558            if let Some(target) =
3559                rust_inline_scoped_target(index, caller_file, &module_segments, &requested_symbol)
3560            {
3561                return Some(target);
3562            }
3563            if let Some(target_file) = rust_file_for_segments(index, caller_file, &module_segments)
3564            {
3565                return Some(rust_resolve_reexport_if_symbol_missing(
3566                    index,
3567                    target_file,
3568                    requested_symbol.clone(),
3569                ));
3570            }
3571        }
3572    }
3573    None
3574}
3575
3576fn rust_target_symbol(full_ref: &str, short_name: &str) -> String {
3577    full_ref
3578        .rsplit("::")
3579        .next()
3580        .filter(|name| !name.is_empty())
3581        .unwrap_or(short_name)
3582        .to_string()
3583}
3584
3585fn rust_resolve_reexport_if_symbol_missing<I: ResolverIndex>(
3586    index: &I,
3587    target_file: String,
3588    target_symbol: String,
3589) -> (String, String) {
3590    if index
3591        .node_for_symbol(&target_file, &target_symbol)
3592        .is_some()
3593    {
3594        return (target_file, target_symbol);
3595    }
3596    if let Some(resolved) = resolve_exported_symbol(index, &target_file, &target_symbol, 0) {
3597        resolved
3598    } else {
3599        (target_file, target_symbol)
3600    }
3601}
3602
3603fn rust_module_path_candidates<I: ResolverIndex + ?Sized>(
3604    index: &I,
3605    segments: &[&str],
3606    caller_data: &FileCallData,
3607    raw: &RawRef,
3608) -> Vec<Vec<String>> {
3609    let mut candidates = Vec::new();
3610    if let Some(first) = segments.first().copied() {
3611        let aliases = index.rust_module_aliases(caller_data);
3612        for (import, aliases) in caller_data.import_block.imports.iter().zip(aliases.iter()) {
3613            if !rust_import_is_visible_to_call(import, raw) {
3614                continue;
3615            }
3616            for (local_name, path_segments) in aliases {
3617                if local_name == first {
3618                    let mut path_segments = path_segments.clone();
3619                    path_segments
3620                        .extend(segments[1..].iter().map(|segment| (*segment).to_string()));
3621                    rust_push_unique_path_candidate(&mut candidates, path_segments);
3622                }
3623            }
3624        }
3625    }
3626    rust_push_unique_path_candidate(
3627        &mut candidates,
3628        segments
3629            .iter()
3630            .map(|segment| (*segment).to_string())
3631            .collect(),
3632    );
3633    candidates
3634}
3635
3636fn rust_push_unique_path_candidate(candidates: &mut Vec<Vec<String>>, candidate: Vec<String>) {
3637    if !candidates.iter().any(|existing| existing == &candidate) {
3638        candidates.push(candidate);
3639    }
3640}
3641
3642fn rust_import_is_visible_to_call(import: &ImportStatement, raw: &RawRef) -> bool {
3643    import.byte_range.start <= raw.byte_start
3644}
3645
3646/// What [`rust_module_alias_segments`] returns for one import: each local
3647/// module name it binds, with the path it names.
3648pub type RustModuleAliases = Vec<(String, Vec<String>)>;
3649
3650/// [`rust_module_alias_segments`] for each import of `data`, in order.
3651pub fn rust_module_aliases_of(data: &FileCallData) -> std::rc::Rc<[RustModuleAliases]> {
3652    data.import_block
3653        .imports
3654        .iter()
3655        .map(rust_module_alias_segments)
3656        .collect()
3657}
3658
3659/// Module names a `use` declaration binds: `use a::b;` / `use a::b as c;`
3660/// bind one, and a use list binds `self` (the prefix module itself, as in
3661/// `use crate::cache_freshness::{self, FileFreshness};`). Conservative module
3662/// candidates use the imported item's spelling, not the alias's capitalization.
3663fn rust_module_alias_segments(import: &ImportStatement) -> Vec<(String, Vec<String>)> {
3664    let path = rust_use_body(&import.raw_text)
3665        .unwrap_or(&import.module_path)
3666        .trim()
3667        .trim_end_matches(';')
3668        .trim();
3669    if path.contains('*') {
3670        return Vec::new();
3671    }
3672    let split_path = |path: &str| {
3673        path.split("::")
3674            .map(str::trim)
3675            .filter(|segment| !segment.is_empty())
3676            .map(str::to_string)
3677            .collect::<Vec<_>>()
3678    };
3679    let is_module_name = |name: &str| {
3680        !name.is_empty() && name != "_" && !name.chars().next().is_some_and(char::is_uppercase)
3681    };
3682    if let Some((prefix, rest)) = path.split_once("::{") {
3683        if rest.contains('{') {
3684            return Vec::new();
3685        }
3686        let prefix_segments = split_path(prefix);
3687        return rest
3688            .trim_end_matches('}')
3689            .split(',')
3690            .filter_map(|specifier| {
3691                let specifier = specifier.trim();
3692                let (path_without_alias, alias) = specifier
3693                    .split_once(" as ")
3694                    .map(|(left, right)| (left.trim(), Some(right.trim())))
3695                    .unwrap_or((specifier, None));
3696                let segments = if path_without_alias == "self" {
3697                    prefix_segments.clone()
3698                } else {
3699                    let mut segments = prefix_segments.clone();
3700                    segments.extend(split_path(path_without_alias));
3701                    segments
3702                };
3703                let local_name = alias
3704                    .map(str::to_string)
3705                    .or_else(|| segments.last().cloned())?;
3706                segments
3707                    .last()
3708                    .is_some_and(|name| is_module_name(name))
3709                    .then_some((local_name, segments))
3710            })
3711            .collect();
3712    }
3713    if path.contains('{') {
3714        return Vec::new();
3715    }
3716    let (path_without_alias, alias) = path
3717        .split_once(" as ")
3718        .map(|(left, right)| (left.trim(), Some(right.trim())))
3719        .unwrap_or((path, None));
3720    let segments = split_path(path_without_alias);
3721    let Some(local_name) = alias
3722        .map(str::to_string)
3723        .or_else(|| segments.last().cloned())
3724    else {
3725        return Vec::new();
3726    };
3727    if !segments.last().is_some_and(|name| is_module_name(name)) {
3728        return Vec::new();
3729    }
3730    vec![(local_name, segments)]
3731}
3732
3733fn rust_inline_scoped_target<I: ResolverIndex>(
3734    index: &I,
3735    caller_file: &str,
3736    module_segments: &[String],
3737    short_name: &str,
3738) -> Option<(String, String)> {
3739    index.inline_scoped_target(caller_file, module_segments, short_name)
3740}
3741
3742fn rust_target_for_use<I: ResolverIndex>(
3743    index: &I,
3744    caller_file: &str,
3745    import: &ImportStatement,
3746    short_name: &str,
3747    caller_data: &FileCallData,
3748    raw: &RawRef,
3749) -> Option<(String, String)> {
3750    let imports = &caller_data.import_block.imports;
3751    let path = rust_use_body(&import.raw_text)
3752        .unwrap_or(&import.module_path)
3753        .trim()
3754        .trim_end_matches(';');
3755    if let Some(module) = path.strip_suffix("::*") {
3756        if let Some((file, symbol)) = rust_target_for_qualified(
3757            index,
3758            caller_file,
3759            &format!("{module}::{short_name}"),
3760            short_name,
3761            caller_data,
3762            raw,
3763        ) {
3764            return index.has_export(&file, &symbol).then_some((file, symbol));
3765        }
3766        let segments = module.split("::").collect::<Vec<_>>();
3767        let file = rust_use_module_file(index, caller_file, &segments, imports)?;
3768        let (file, symbol) =
3769            rust_resolve_reexport_if_symbol_missing(index, file, short_name.to_string());
3770        return index.has_export(&file, &symbol).then_some((file, symbol));
3771    }
3772    if let Some(brace_start) = path.find("::{") {
3773        let prefix = &path[..brace_start];
3774        // `use m::{f as g};` binds `g`; resolve the imported `f`.
3775        let imported = import.names.iter().find_map(|name| {
3776            (crate::imports::specifier_local_name(name) == short_name)
3777                .then(|| crate::imports::specifier_imported_name(name).to_string())
3778        });
3779        if let Some(imported) = imported {
3780            if let Some(target) = rust_target_for_qualified(
3781                index,
3782                caller_file,
3783                &format!("{prefix}::{imported}"),
3784                &imported,
3785                caller_data,
3786                raw,
3787            ) {
3788                return Some(target);
3789            }
3790            let prefix_segments: Vec<&str> = prefix.split("::").collect();
3791            let inline_segments = prefix_segments
3792                .iter()
3793                .map(|s| s.to_string())
3794                .collect::<Vec<_>>();
3795            if let Some(target) =
3796                index.inline_scoped_target(caller_file, &inline_segments, &imported)
3797            {
3798                return Some(target);
3799            }
3800            let file = rust_use_module_file(index, caller_file, &prefix_segments, imports)?;
3801            // The module may only re-export the item (`pub use inner::{f};`);
3802            // follow that to the definition, as qualified paths already do.
3803            return Some(rust_resolve_reexport_if_symbol_missing(
3804                index, file, imported,
3805            ));
3806        }
3807        return None;
3808    }
3809
3810    let (path_without_alias, alias) = path
3811        .split_once(" as ")
3812        .map(|(left, right)| (left.trim(), Some(right.trim())))
3813        .unwrap_or((path, None));
3814    let segments: Vec<&str> = path_without_alias.split("::").collect();
3815    let imported = alias.or_else(|| segments.last().copied())?;
3816    if imported != short_name {
3817        return None;
3818    }
3819    if segments.len() < 2 {
3820        return None;
3821    }
3822    if let Some(target) = rust_target_for_qualified(
3823        index,
3824        caller_file,
3825        path_without_alias,
3826        segments.last().copied().unwrap_or(short_name),
3827        caller_data,
3828        raw,
3829    ) {
3830        return Some(target);
3831    }
3832    let module_segments = segments[..segments.len() - 1]
3833        .iter()
3834        .map(|s| s.to_string())
3835        .collect::<Vec<_>>();
3836    if let Some(target) = index.inline_scoped_target(
3837        caller_file,
3838        &module_segments,
3839        segments.last().copied().unwrap_or(short_name),
3840    ) {
3841        return Some(target);
3842    }
3843    let file = rust_use_module_file(index, caller_file, &segments[..segments.len() - 1], imports)?;
3844    Some(rust_resolve_reexport_if_symbol_missing(
3845        index,
3846        file,
3847        segments.last().unwrap_or(&short_name).to_string(),
3848    ))
3849}
3850
3851/// The file of the module a `use` path names. A path may start with another
3852/// workspace crate (`use aft::callgraph_store::{..}` in an integration test or
3853/// a binary), which is checked first, as qualified call paths do. It may also
3854/// start with a module another `use` in the same file brought into scope
3855/// (`use aft::search::{paging};` then `use paging::{build};`).
3856fn rust_use_module_file<I: ResolverIndex>(
3857    index: &I,
3858    caller_file: &str,
3859    module_segments: &[&str],
3860    imports: &[ImportStatement],
3861) -> Option<String> {
3862    if let Some(file) = rust_use_module_file_direct(index, caller_file, module_segments) {
3863        return Some(file);
3864    }
3865    let (first, rest) = module_segments.split_first()?;
3866    imports
3867        .iter()
3868        .flat_map(rust_module_alias_segments)
3869        .filter(|(local_name, _)| local_name == first)
3870        .find_map(|(_, mut alias_segments)| {
3871            alias_segments.extend(rest.iter().map(|segment| (*segment).to_string()));
3872            let alias_refs = alias_segments
3873                .iter()
3874                .map(String::as_str)
3875                .collect::<Vec<_>>();
3876            rust_use_module_file_direct(index, caller_file, &alias_refs)
3877        })
3878}
3879
3880fn rust_use_module_file_direct<I: ResolverIndex>(
3881    index: &I,
3882    caller_file: &str,
3883    module_segments: &[&str],
3884) -> Option<String> {
3885    // Local declarations, including #[path] modules in integration-test
3886    // harnesses, take precedence over reconstructing a library-relative path.
3887    if let Some((first, rest)) = module_segments.split_first() {
3888        if !matches!(*first, "crate" | "self" | "super") {
3889            if let Some(mut file) = index
3890                .module_target(caller_file, first)
3891                .filter(|file| file != caller_file)
3892            {
3893                for segment in rest {
3894                    file = index.module_target(&file, segment)?;
3895                }
3896                return Some(file);
3897            }
3898        }
3899    }
3900    if !matches!(
3901        module_segments.first().copied(),
3902        Some("crate" | "self" | "super") | None
3903    ) {
3904        if let Some(file) = rust_workspace_file_for_segments(index, module_segments) {
3905            return Some(file);
3906        }
3907    }
3908    let resolved = rust_resolve_segments_with_index(index, caller_file, module_segments)?;
3909    rust_file_for_segments(index, caller_file, &resolved)
3910}
3911
3912fn rust_workspace_file_for_segments<I: ResolverIndex>(
3913    index: &I,
3914    segments: &[&str],
3915) -> Option<String> {
3916    let crate_name = segments.first().copied()?;
3917    let src_prefix = index.crate_src_prefix(crate_name)?;
3918    let module_segments = segments[1..]
3919        .iter()
3920        .map(|segment| segment.to_string())
3921        .collect::<Vec<_>>();
3922    rust_file_for_src_prefix(index, &src_prefix, &module_segments)
3923}
3924
3925#[cfg(any(test, feature = "test-support"))]
3926static WORKSPACE_CRATE_PREFIX_BUILD_COUNTS: OnceLock<Mutex<HashMap<PathBuf, usize>>> =
3927    OnceLock::new();
3928
3929#[cfg(any(test, feature = "test-support"))]
3930fn note_workspace_crate_prefix_build(project_root: &Path) {
3931    let mut counts = WORKSPACE_CRATE_PREFIX_BUILD_COUNTS
3932        .get_or_init(|| Mutex::new(HashMap::new()))
3933        .lock()
3934        .expect("workspace crate prefix build counts mutex poisoned");
3935    *counts.entry(project_root.to_path_buf()).or_default() += 1;
3936}
3937
3938#[cfg(not(any(test, feature = "test-support")))]
3939fn note_workspace_crate_prefix_build(_project_root: &Path) {}
3940
3941/// Walk the project tree once and map every Rust crate name (package name with
3942/// `-` normalized to `_`, plus any explicit `[lib] name`) to its `src` prefix.
3943/// Replaces the previous per-ref tree walk: resolving 600k+ qualified refs no
3944/// longer re-walks the filesystem once per ref.
3945fn build_workspace_crate_prefixes(
3946    project_root: &Path,
3947    facts: &FactPaths<'_>,
3948) -> HashMap<String, String> {
3949    build_workspace_crate_prefixes_with_manifests(project_root, facts, |_| {})
3950}
3951
3952fn build_workspace_crate_prefixes_with_manifests(
3953    project_root: &Path,
3954    facts: &FactPaths<'_>,
3955    mut visit_manifest: impl FnMut(&Path),
3956) -> HashMap<String, String> {
3957    note_workspace_crate_prefix_build(project_root);
3958    let mut prefixes = HashMap::new();
3959    let mut stack = vec![project_root.to_path_buf()];
3960    while let Some(dir) = stack.pop() {
3961        let name = dir.file_name().and_then(|name| name.to_str()).unwrap_or("");
3962        if matches!(name, "target" | "node_modules" | ".git") {
3963            continue;
3964        }
3965        let manifest = dir.join("Cargo.toml");
3966        if facts.is_file(&manifest) {
3967            visit_manifest(&manifest);
3968            let crate_names = rust_manifest_crate_names(&manifest, facts);
3969            if !crate_names.is_empty() {
3970                let src_prefix = relative_path(
3971                    project_root,
3972                    &facts
3973                        .canonical(&dir.join("src"))
3974                        .unwrap_or_else(|| dir.join("src")),
3975                );
3976                for crate_name in crate_names {
3977                    prefixes
3978                        .entry(crate_name)
3979                        .or_insert_with(|| src_prefix.clone());
3980                }
3981            }
3982        }
3983        for entry in facts.list_dir(&dir) {
3984            if entry.kind == EntryKind::Directory {
3985                stack.push(dir.join(byte_path(&entry.name)));
3986            }
3987        }
3988    }
3989    prefixes
3990}
3991
3992/// Extract the crate names a manifest defines: the normalized package name
3993/// (`-` -> `_`) and any explicit `[lib] name`. Returns both so a crate is
3994/// reachable by either spelling, matching the previous match semantics.
3995fn rust_manifest_crate_names(manifest: &Path, facts: &FactPaths<'_>) -> Vec<String> {
3996    facts.config_fact(manifest, "manifest.name");
3997    facts.config_fact(manifest, "manifest.lib.name");
3998    let Some(bytes) = facts.attributed_bytes(manifest) else {
3999        return Vec::new();
4000    };
4001    let (package_name, lib_name) = rust_manifest_name_fields(&bytes);
4002    let mut names = Vec::new();
4003    if let Some(lib) = lib_name {
4004        names.push(lib);
4005    }
4006    if let Some(package) = package_name {
4007        let normalized = package.replace('-', "_");
4008        if !names.contains(&normalized) {
4009            names.push(normalized);
4010        }
4011    }
4012    names
4013}
4014
4015/// Preserve the manifest resolver's line-oriented extraction, including its
4016/// first non-lib name and last lib name semantics; this is not a TOML parser.
4017pub fn rust_manifest_name_fields(bytes: &[u8]) -> (Option<String>, Option<String>) {
4018    let Ok(source) = std::str::from_utf8(bytes) else {
4019        return (None, None);
4020    };
4021    let mut in_lib = false;
4022    let mut package_name = None;
4023    let mut lib_name = None;
4024    for line in source.lines() {
4025        let trimmed = line.trim();
4026        if trimmed.starts_with('[') {
4027            in_lib = trimmed == "[lib]";
4028            continue;
4029        }
4030        let Some((key, value)) = trimmed.split_once('=') else {
4031            continue;
4032        };
4033        let key = key.trim();
4034        let value = value.trim().trim_matches('"');
4035        if in_lib && key == "name" {
4036            lib_name = Some(value.to_string());
4037        } else if !in_lib && key == "name" && package_name.is_none() {
4038            package_name = Some(value.to_string());
4039        }
4040    }
4041    (package_name, lib_name)
4042}
4043
4044fn rust_resolve_segments_with_index<I: ResolverIndex>(
4045    index: &I,
4046    caller_file: &str,
4047    segments: &[&str],
4048) -> Option<Vec<String>> {
4049    rust_resolve_segments_from(rust_caller_module_segments(index, caller_file), segments)
4050}
4051
4052test_support_visibility! {
4053fn rust_caller_module_segments<I: ResolverIndex>(index: &I, caller_file: &str) -> Vec<String> {
4054    #[cfg(any(test, feature = "test-support"))]
4055    let _timing = rust_module_work::Timing::caller();
4056    index.rust_caller_module_segments(caller_file)
4057}
4058}
4059
4060test_support_visibility! {
4061fn rust_caller_module_segments_uncached<I: ResolverIndex + ?Sized>(
4062    index: &I,
4063    caller_file: &str,
4064) -> Vec<String> {
4065    #[cfg(any(test, feature = "test-support"))]
4066    rust_module_work::note(|work| work.caller_walks += 1);
4067    if index.rust_crate_root_file(caller_file).as_deref() == Some(caller_file) {
4068        Vec::new()
4069    } else {
4070        rust_registered_module_segments(index, caller_file)
4071            .unwrap_or_else(|| rust_module_segments_for_rel(caller_file))
4072    }
4073}
4074}
4075
4076fn rust_reference_module_segments<I: ResolverIndex>(
4077    index: &I,
4078    caller_file: &str,
4079    caller_data: &FileCallData,
4080    raw: &RawRef,
4081) -> Vec<String> {
4082    let mut modules = rust_caller_module_segments(index, caller_file);
4083    let Some(caller) = raw.caller_symbol.as_deref() else {
4084        return modules;
4085    };
4086    let mut scope = caller.split("::").collect::<Vec<_>>();
4087    scope.pop();
4088    if caller_data
4089        .symbol_metadata
4090        .get(caller)
4091        .is_some_and(|meta| meta.kind == SymbolKind::Method)
4092    {
4093        scope.pop();
4094    }
4095    // Scoped names include inline modules as well as enclosing functions and
4096    // impl owners. Only the module prefix changes the meaning of self/super.
4097    for (position, segment) in scope.iter().enumerate() {
4098        if caller_data
4099            .symbol_metadata
4100            .contains_key(&scope[..=position].join("::"))
4101        {
4102            break;
4103        }
4104        modules.push((*segment).to_string());
4105    }
4106    modules
4107}
4108
4109/// A bare path is relative to the current module; try its child modules before
4110/// the sibling-module interpretation retained for imported paths.
4111fn rust_resolve_segment_candidates_from(
4112    caller_segments: Vec<String>,
4113    segments: &[&str],
4114) -> Vec<Vec<String>> {
4115    let mut candidates = Vec::new();
4116    if segments
4117        .first()
4118        .is_some_and(|first| !matches!(*first, "crate" | "self" | "super"))
4119    {
4120        let mut child = caller_segments.clone();
4121        child.extend(segments.iter().map(|item| item.to_string()));
4122        candidates.push(child);
4123    }
4124    if let Some(resolved) = rust_resolve_segments_from(caller_segments, segments) {
4125        rust_push_unique_path_candidate(&mut candidates, resolved);
4126    }
4127    candidates
4128}
4129
4130fn rust_resolve_segments(caller_file: &str, segments: &[&str]) -> Option<Vec<String>> {
4131    rust_resolve_segments_from(rust_module_segments_for_rel(caller_file), segments)
4132}
4133
4134fn rust_resolve_segments_from(
4135    caller_segments: Vec<String>,
4136    segments: &[&str],
4137) -> Option<Vec<String>> {
4138    if segments.is_empty() {
4139        return Some(Vec::new());
4140    }
4141    match segments[0] {
4142        "crate" => Some(segments[1..].iter().map(|item| item.to_string()).collect()),
4143        "self" => {
4144            let mut resolved = caller_segments;
4145            resolved.extend(segments[1..].iter().map(|item| item.to_string()));
4146            Some(resolved)
4147        }
4148        "super" => {
4149            let mut resolved = caller_segments;
4150            let parents = segments
4151                .iter()
4152                .take_while(|segment| **segment == "super")
4153                .count();
4154            for _ in 0..parents {
4155                resolved.pop()?;
4156            }
4157            resolved.extend(segments[parents..].iter().map(|item| item.to_string()));
4158            Some(resolved)
4159        }
4160        _ => {
4161            let mut resolved = caller_segments;
4162            resolved.pop();
4163            resolved.extend(segments.iter().map(|item| item.to_string()));
4164            Some(resolved)
4165        }
4166    }
4167}
4168
4169fn rust_registered_module_segments<I: ResolverIndex + ?Sized>(
4170    index: &I,
4171    caller_file: &str,
4172) -> Option<Vec<String>> {
4173    let mut current = caller_file.to_string();
4174    let mut segments = Vec::new();
4175    let mut seen = HashSet::new();
4176    while seen.insert(current.clone()) {
4177        let Some((parent, module)) = index.module_parent(&current) else {
4178            break;
4179        };
4180        segments.push(module);
4181        current = parent;
4182    }
4183    if segments.is_empty() {
4184        None
4185    } else {
4186        segments.reverse();
4187        Some(segments)
4188    }
4189}
4190
4191fn rust_file_for_segments<I: ResolverIndex>(
4192    index: &I,
4193    caller_file: &str,
4194    segments: &[String],
4195) -> Option<String> {
4196    let src_prefix = rust_src_prefix(caller_file);
4197    if let Some(target) =
4198        rust_file_from_module_declarations(index, caller_file, &src_prefix, segments)
4199    {
4200        return Some(target);
4201    }
4202    rust_file_for_src_prefix(index, &src_prefix, segments)
4203}
4204
4205fn rust_file_from_module_declarations<I: ResolverIndex>(
4206    index: &I,
4207    caller_file: &str,
4208    src_prefix: &str,
4209    segments: &[String],
4210) -> Option<String> {
4211    let mut current = index.rust_crate_root_file(caller_file).or_else(|| {
4212        [
4213            format!("{src_prefix}/lib.rs"),
4214            format!("{src_prefix}/main.rs"),
4215        ]
4216        .into_iter()
4217        .find(|candidate| index.contains_file(candidate))
4218    })?;
4219    for segment in segments {
4220        current = index.module_target(&current, segment)?;
4221    }
4222    Some(current)
4223}
4224
4225fn rust_file_for_src_prefix<I: ResolverIndex>(
4226    index: &I,
4227    src_prefix: &str,
4228    segments: &[String],
4229) -> Option<String> {
4230    let candidate = if segments.is_empty() {
4231        [src_prefix, "lib.rs"].join("/")
4232    } else {
4233        format!("{}/{}.rs", src_prefix, segments.join("/"))
4234    };
4235    if index.contains_file(&candidate) {
4236        return Some(candidate);
4237    }
4238    if !segments.is_empty() {
4239        let mod_candidate = format!("{}/{}/mod.rs", src_prefix, segments.join("/"));
4240        if index.contains_file(&mod_candidate) {
4241            return Some(mod_candidate);
4242        }
4243    }
4244    None
4245}
4246
4247fn rust_src_prefix(rel_path: &str) -> String {
4248    rel_path
4249        .split_once("/src/")
4250        .map(|(prefix, _)| format!("{prefix}/src"))
4251        .unwrap_or_else(|| "src".to_string())
4252}
4253
4254fn rust_module_segments_for_rel(rel_path: &str) -> Vec<String> {
4255    let after_src = rel_path
4256        .split_once("/src/")
4257        .map(|(_, rest)| rest)
4258        .or_else(|| rel_path.strip_prefix("src/"))
4259        .unwrap_or(rel_path);
4260    if matches!(after_src, "lib.rs" | "main.rs") {
4261        return Vec::new();
4262    }
4263    if let Some(prefix) = after_src.strip_suffix("/mod.rs") {
4264        return prefix.split('/').map(|item| item.to_string()).collect();
4265    }
4266    after_src
4267        .strip_suffix(".rs")
4268        .unwrap_or(after_src)
4269        .split('/')
4270        .map(|item| item.to_string())
4271        .collect()
4272}
4273
4274fn resolve_local_target<I: ResolverIndex>(
4275    index: &I,
4276    caller_file: &str,
4277    full_ref: &str,
4278    short_name: &str,
4279    caller_data: &FileCallData,
4280) -> Option<(String, String, String)> {
4281    if !callgraph::is_bare_callee(full_ref, short_name) {
4282        return None;
4283    }
4284    index
4285        .local_symbol(caller_file, caller_data, short_name)
4286        .map(|symbol| {
4287            (
4288                "resolved_local".to_string(),
4289                caller_file.to_string(),
4290                symbol,
4291            )
4292        })
4293}
4294
4295impl<'a> ProjectIndex<'a> {
4296    test_support_visibility! {
4297    fn from_parts(
4298            project_root: &Path,
4299            files: HashMap<String, DbFileIndex>,
4300            caller_data: HashMap<String, &'a FileCallData>,
4301            workspace_crate_prefixes: WorkspaceCratePrefixCache,
4302            facts: Rc<dyn ProjectFacts + 'a>,
4303        ) -> Self {
4304            Self::from_shared(
4305                project_root,
4306                Arc::new(files),
4307                caller_data,
4308                workspace_crate_prefixes,
4309                facts,
4310            )
4311        }
4312    }
4313
4314    /// An index whose every file index comes from `loaded`, on first use.
4315    pub fn from_loaded(
4316        project_root: &Path,
4317        loaded: Rc<dyn LoadedFileIndexes + 'a>,
4318        workspace_crate_prefixes: WorkspaceCratePrefixCache,
4319        facts: Rc<dyn ProjectFacts + 'a>,
4320    ) -> Self {
4321        let mut index = Self::from_parts(
4322            project_root,
4323            HashMap::new(),
4324            HashMap::new(),
4325            workspace_crate_prefixes,
4326            facts,
4327        );
4328        index.lazy = Some(loaded);
4329        index
4330    }
4331
4332    /// An index over bound surfaces another index or thread also holds.
4333    pub fn from_shared(
4334        project_root: &Path,
4335        files: Arc<HashMap<String, DbFileIndex>>,
4336        caller_data: HashMap<String, &'a FileCallData>,
4337        workspace_crate_prefixes: WorkspaceCratePrefixCache,
4338        facts: Rc<dyn ProjectFacts + 'a>,
4339    ) -> Self {
4340        Self {
4341            facts,
4342            project_root: project_root.to_path_buf(),
4343            files,
4344            caller_data,
4345            lazy: None,
4346            workspace_crate_prefixes,
4347            rust_crate_roots: callgraph::RustCrateRootMemo::default(),
4348            crate_scans: std::cell::OnceCell::new(),
4349            lazy_module_parents: std::cell::OnceCell::new(),
4350            lazy_inline_candidates: std::cell::OnceCell::new(),
4351            rust_caller_paths: RefCell::default(),
4352            go_packages: RefCell::default(),
4353            local_symbols: RefCell::default(),
4354        }
4355    }
4356
4357    /// The index of one file: the in-memory entry when there is one (every
4358    /// file of an eagerly built index, or a file this refresh re-resolves),
4359    /// otherwise the stored rows, loaded on first use.
4360    fn file_index(&self, rel_path: &str) -> Option<FileIndexRef<'_>> {
4361        if let Some(index) = self.files.get(rel_path) {
4362            return Some(FileIndexRef::Borrowed(index));
4363        }
4364        self.lazy
4365            .as_ref()
4366            .and_then(|lazy| lazy.file_index(rel_path))
4367            .map(FileIndexRef::Loaded)
4368    }
4369
4370    fn lang_for(&self, rel_path: &str) -> Option<LangId> {
4371        self.file_index(rel_path).and_then(|file| file.lang)
4372    }
4373
4374    fn module_target(&self, caller_file: &str, module_path: &str) -> Option<String> {
4375        self.file_index(caller_file)
4376            .and_then(|file| file.module_targets.get(module_path).cloned().flatten())
4377    }
4378
4379    fn reexports_for(&self, rel_path: &str) -> Vec<ReexportIndex> {
4380        self.file_index(rel_path)
4381            .map(|file| file.reexports.clone())
4382            .unwrap_or_default()
4383    }
4384
4385    fn node_for_symbol(&self, rel_path: &str, symbol: &str) -> Option<String> {
4386        self.file_index(rel_path).and_then(|file| {
4387            file.node_by_scoped.get(symbol).cloned().or_else(|| {
4388                (file.lang != Some(LangId::Python))
4389                    .then(|| file.node_by_bare.get(symbol).cloned())
4390                    .flatten()
4391            })
4392        })
4393    }
4394
4395    fn node_is_callable(&self, rel_path: &str, node_id: &str) -> bool {
4396        self.file_index(rel_path)
4397            .and_then(|file| file.node_kind_by_id.get(node_id).cloned())
4398            .is_some_and(|kind| matches!(kind.as_str(), "function" | "kernel" | "method"))
4399    }
4400
4401    /// Every indexed file path an index-wide scan must consider, in no order:
4402    /// the in-memory entries plus the stored files `stored` lists that have no
4403    /// in-memory entry (an in-memory entry replaces the stored rows).
4404    fn scan_paths(
4405        &self,
4406        stored: impl FnOnce(&dyn LoadedFileIndexes) -> Vec<String>,
4407    ) -> Vec<String> {
4408        let mut paths = self.files.keys().cloned().collect::<Vec<_>>();
4409        if let Some(lazy) = &self.lazy {
4410            paths.extend(
4411                stored(lazy.as_ref())
4412                    .into_iter()
4413                    .filter(|path| !self.files.contains_key(path)),
4414            );
4415        }
4416        paths
4417    }
4418}
4419
4420/// A file index borrowed from an in-memory map or loaded on demand.
4421enum FileIndexRef<'a> {
4422    Borrowed(&'a DbFileIndex),
4423    Loaded(LoadedIndex),
4424}
4425
4426impl std::ops::Deref for FileIndexRef<'_> {
4427    type Target = DbFileIndex;
4428
4429    fn deref(&self) -> &DbFileIndex {
4430        match self {
4431            Self::Borrowed(index) => index,
4432            Self::Loaded(index) => index,
4433        }
4434    }
4435}
4436
4437/// A file index loaded on demand and shared across resolver threads.
4438#[derive(Clone)]
4439pub enum LoadedIndex {
4440    Shared(Arc<DbFileIndex>),
4441}
4442
4443impl std::ops::Deref for LoadedIndex {
4444    type Target = DbFileIndex;
4445
4446    fn deref(&self) -> &DbFileIndex {
4447        match self {
4448            Self::Shared(index) => index,
4449        }
4450    }
4451}
4452
4453/// File indexes a [`ProjectIndex`] loads when resolution first reaches
4454/// them, rather than binding every file eagerly.
4455pub trait LoadedFileIndexes {
4456    /// Whether `rel_path` is an indexed file.
4457    fn contains_file(&self, rel_path: &str) -> bool;
4458    /// `rel_path`'s index, or `None` when it is not an indexed file.
4459    fn file_index(&self, rel_path: &str) -> Option<LoadedIndex>;
4460    /// Every indexed Rust file, in no order.
4461    fn rust_files(&self) -> Vec<String>;
4462    /// Every indexed file that declares a module, in no order.
4463    fn module_declaring_files(&self) -> Vec<String>;
4464    /// For each declared module target, its parent: the smallest
4465    /// `(declaring file, module name)` pair over every module-declaring
4466    /// file, as [`note_module_parents`] keeps it. `None` when the loader
4467    /// does not keep them, and the index binds every module-declaring file
4468    /// to find them.
4469    fn module_parents(&self) -> Option<Arc<ModuleParents>> {
4470        None
4471    }
4472}
4473
4474/// Each declared module target's parent, `(declaring file, module name)`.
4475pub type ModuleParents = HashMap<String, (String, String)>;
4476
4477/// Notes in `parents` every module `index`, the index of `file`, declares
4478/// with a target, keeping each target's smallest parent.
4479pub fn note_module_parents(parents: &mut ModuleParents, file: &str, index: &DbFileIndex) {
4480    CrateScanMemo::note_module_parents(parents, file, index);
4481}
4482
4483impl DbFileIndex {
4484    fn from_extract(project_root: &Path, extract: &FileExtract, facts: &FactPaths<'_>) -> Self {
4485        let module_memo = callgraph::ModuleResolutionMemo::default();
4486        let mut node_by_scoped = HashMap::new();
4487        let mut node_by_bare = HashMap::new();
4488        for node in &extract.nodes {
4489            node_by_scoped.insert(node.scoped_name.clone(), node.id.clone());
4490            node_by_bare
4491                .entry(node.name.clone())
4492                .or_insert(node.id.clone());
4493        }
4494        let node_kind_by_id = extract
4495            .nodes
4496            .iter()
4497            .map(|node| (node.id.clone(), node.kind.clone()))
4498            .collect();
4499        let mut export_aliases = HashMap::new();
4500        for raw_ref in &extract.raw_refs {
4501            if raw_ref.kind == "export_alias" {
4502                if let (Some(exported), Some(source_symbol)) =
4503                    (&raw_ref.local_name, &raw_ref.requested_name)
4504                {
4505                    export_aliases.insert(exported.clone(), source_symbol.clone());
4506                }
4507            }
4508        }
4509        let mut module_targets: HashMap<String, Option<String>> = HashMap::new();
4510        let mut declared_module_targets = HashMap::<String, Option<String>>::new();
4511        let mut macro_use_module_targets = BTreeSet::new();
4512        let mut reexports = Vec::new();
4513        for raw_ref in &extract.raw_refs {
4514            if !matches!(raw_ref.kind.as_str(), "import" | "reexport" | "module") {
4515                continue;
4516            }
4517            let Some(module_path) = &raw_ref.module_path else {
4518                continue;
4519            };
4520            // An import and its re-export select the same Python module.
4521            let target_file = if extract.lang == LangId::Python {
4522                if module_targets.contains_key(module_path) {
4523                    module_targets.get(module_path).cloned().flatten()
4524                } else {
4525                    // Python packages take precedence over same-named module
4526                    // files, unlike the lexical order of dependency candidates.
4527                    module_ref_target(
4528                        project_root,
4529                        &extract.rel_path,
4530                        &raw_ref.kind,
4531                        module_path,
4532                        &module_memo,
4533                        facts,
4534                        |file| facts.is_file(&project_root.join(file)),
4535                    )
4536                }
4537            } else if extract.lang == LangId::Rust && raw_ref.kind == "reexport" {
4538                // Parsed module refs remain available when immutable facts do
4539                // not contain raw source for reparsing module declarations.
4540                // Dependency sets include parent-module candidates. Their lexical
4541                // order is not Rust resolution order: retain the most-specific
4542                // module target for each flattened re-export leaf.
4543                declared_module_targets
4544                    .get(module_path)
4545                    .cloned()
4546                    .flatten()
4547                    .or_else(|| {
4548                        module_ref_target(
4549                            project_root,
4550                            &extract.rel_path,
4551                            &raw_ref.kind,
4552                            module_path,
4553                            &module_memo,
4554                            facts,
4555                            |file| facts.is_file(&project_root.join(file)),
4556                        )
4557                    })
4558            } else {
4559                module_target_from_dependencies(project_root, &raw_ref.dependencies, facts)
4560            };
4561            module_targets
4562                .entry(module_path.clone())
4563                .or_insert_with(|| target_file.clone());
4564            if raw_ref.kind == "module" {
4565                if raw_ref
4566                    .full_ref
4567                    .as_deref()
4568                    .is_some_and(|text| text.starts_with("#[macro_use]"))
4569                {
4570                    macro_use_module_targets.extend(target_file.iter().cloned());
4571                }
4572                declared_module_targets
4573                    .entry(module_path.clone())
4574                    .or_insert_with(|| target_file.clone());
4575            }
4576            if raw_ref.kind == "reexport" {
4577                reexports.push(reexport_index_from_raw(raw_ref, target_file));
4578            }
4579        }
4580        Self {
4581            lang: Some(extract.lang),
4582            exports: extract.data.exported_symbols.iter().cloned().collect(),
4583            default_export: extract.data.default_export_symbol.clone(),
4584            export_aliases,
4585            node_by_scoped,
4586            node_by_bare,
4587            node_kind_by_id,
4588            module_targets,
4589            declared_module_targets,
4590            macro_use_module_targets,
4591            reexports,
4592        }
4593    }
4594}
4595
4596#[cfg(any(test, feature = "test-support"))]
4597thread_local! {
4598    pub static STALE_PATH_CENSUS_BUILDS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4599}
4600
4601/// The indexed file that an `import`, `reexport` or Rust `module` ref names.
4602///
4603/// Cold builds and incremental refreshes both answer this through this one
4604/// function, so a store gives the same answer however it was built. The
4605/// answer comes from the module resolver itself, not from the file's
4606/// dependency set: that set also holds candidate paths recorded only so that
4607/// creating one of them invalidates the importer, and picking the first
4608/// existing member can name a file the import never refers to.
4609///
4610/// Rust `use` paths are not handled by the JS/TS resolver; for Rust callers
4611/// the first indexed file among the module's Rust path candidates is used.
4612/// No other file is ever substituted: an import the resolver cannot place
4613/// (`bun:test`, `node:fs`, an npm package) has no target.
4614fn module_ref_target(
4615    project_root: &Path,
4616    caller_file: &str,
4617    kind: &str,
4618    module_path: &str,
4619    memo: &callgraph::ModuleResolutionMemo,
4620    facts: &FactPaths<'_>,
4621    is_indexed: impl Fn(&str) -> bool,
4622) -> Option<String> {
4623    if kind == "module" {
4624        return rust_declared_module_target(project_root, caller_file, module_path, memo, facts);
4625    }
4626    let caller_path = project_root.join(caller_file);
4627    if caller_path.extension().and_then(|ext| ext.to_str()) == Some("py") {
4628        return python_module_candidates(project_root, &caller_path, module_path)
4629            .into_iter()
4630            .find(|candidate| facts.is_file(candidate))
4631            .map(|path| relative_path(project_root, &path))
4632            .filter(|path| is_indexed(path));
4633    }
4634    if Path::new(caller_file)
4635        .extension()
4636        .and_then(|ext| ext.to_str())
4637        == Some("rs")
4638    {
4639        // `pub use cli::{..}` in a file that declares `mod cli;` names that
4640        // module (Rust 2018 paths start from names in scope), wherever the
4641        // path candidates below would look.
4642        if let Some(target) =
4643            rust_declared_module_path_target(project_root, caller_file, module_path, memo, facts)
4644                .filter(|target| is_indexed(target))
4645        {
4646            return Some(target);
4647        }
4648        return rust_module_candidates(project_root, &caller_path, module_path, memo, facts)
4649            .into_iter()
4650            .find(|candidate| is_indexed(candidate));
4651    }
4652    let caller_dir = caller_path.parent()?;
4653    let resolved = callgraph::resolve_module_path_with_memo(caller_dir, module_path, memo, facts)?;
4654    let rel_path = relative_path(project_root, &resolved);
4655    is_indexed(&rel_path).then_some(rel_path)
4656}
4657
4658/// The file a Rust `use` path reaches by following `mod` declarations from
4659/// `caller_file`: its first segment (after an optional `self::`) must be a
4660/// module the caller declares, and each further segment that the reached file
4661/// declares as a module is followed too. The remaining segments name items.
4662fn rust_declared_module_path_target(
4663    project_root: &Path,
4664    caller_file: &str,
4665    module_path: &str,
4666    memo: &callgraph::ModuleResolutionMemo,
4667    facts: &FactPaths<'_>,
4668) -> Option<String> {
4669    let path = rust_module_path_without_alias_or_use_list(module_path);
4670    let path = path.strip_prefix("self::").unwrap_or(path);
4671    let mut segments = path
4672        .split("::")
4673        .map(str::trim)
4674        .filter(|segment| !segment.is_empty());
4675    let first = segments.next()?;
4676    let mut current = rust_declared_module_target(project_root, caller_file, first, memo, facts)?;
4677    for segment in segments {
4678        match rust_declared_module_target(project_root, &current, segment, memo, facts) {
4679            Some(next) => current = next,
4680            None => break,
4681        }
4682    }
4683    Some(current)
4684}
4685
4686fn module_target_from_dependencies(
4687    project_root: &Path,
4688    dependencies: &BTreeSet<String>,
4689    facts: &FactPaths<'_>,
4690) -> Option<String> {
4691    dependencies.iter().find_map(|dep| {
4692        let path = project_root.join(dep);
4693        if facts.is_file(&path) {
4694            Some(relative_path(
4695                project_root,
4696                &facts.canonical(&path).unwrap_or(path.clone()),
4697            ))
4698        } else {
4699            None
4700        }
4701    })
4702}
4703
4704fn reexport_index_from_raw(raw_ref: &RawRef, target_file: Option<String>) -> ReexportIndex {
4705    let mut named = HashMap::new();
4706    if let Some(full_ref) = &raw_ref.full_ref {
4707        named = parse_reexport_names(full_ref);
4708    }
4709    ReexportIndex {
4710        target_file,
4711        named,
4712        wildcard: raw_ref.wildcard,
4713    }
4714}
4715
4716test_support_visibility! {
4717fn parse_reexport_names(statement: &str) -> HashMap<String, String> {
4718    let mut names = HashMap::new();
4719    let Some(open) = statement.find('{') else {
4720        return names;
4721    };
4722    let Some(close) = statement[open + 1..]
4723        .find('}')
4724        .map(|offset| open + 1 + offset)
4725    else {
4726        return names;
4727    };
4728    for spec in statement[open + 1..close].split(',') {
4729        let spec = spec.trim();
4730        if spec.is_empty() {
4731            continue;
4732        }
4733        if let Some((source, local)) = spec.split_once(" as ") {
4734            names.insert(local.trim().to_string(), source.trim().to_string());
4735        } else {
4736            names.insert(spec.to_string(), spec.to_string());
4737        }
4738    }
4739    names
4740}
4741}
4742
4743fn module_dependencies(
4744    project_root: &Path,
4745    abs_path: &Path,
4746    module_path: &str,
4747    facts: &FactPaths<'_>,
4748) -> BTreeSet<String> {
4749    module_dependencies_with_memo(
4750        project_root,
4751        abs_path,
4752        module_path,
4753        &callgraph::ModuleResolutionMemo::default(),
4754        facts,
4755    )
4756}
4757
4758fn module_dependencies_with_memo(
4759    project_root: &Path,
4760    abs_path: &Path,
4761    module_path: &str,
4762    memo: &callgraph::ModuleResolutionMemo,
4763    facts: &FactPaths<'_>,
4764) -> BTreeSet<String> {
4765    if abs_path.extension().and_then(|ext| ext.to_str()) == Some("py") {
4766        // Keep missing candidates too, so creating a module rebinds its importers.
4767        return python_module_candidates(project_root, abs_path, module_path)
4768            .into_iter()
4769            .map(|path| relative_path(project_root, &path))
4770            .collect();
4771    }
4772    let mut deps = rust_module_dependencies(project_root, abs_path, module_path, memo, facts);
4773    let caller_dir = abs_path.parent().unwrap_or(project_root);
4774    if let Some(resolved) =
4775        callgraph::resolve_module_path_with_memo(caller_dir, module_path, memo, facts)
4776    {
4777        deps.insert(relative_path(project_root, &resolved));
4778    }
4779    if module_path.starts_with('.') {
4780        let base = caller_dir.join(module_path);
4781        for candidate in relative_module_candidates(&base) {
4782            deps.insert(relative_path(project_root, &candidate));
4783        }
4784    }
4785    deps
4786}
4787
4788/// Absolute Python imports start at the analyzed project root. Relative dots
4789/// walk package directories; neither form searches arbitrary same-named files
4790/// or guesses runtime changes to sys.path.
4791fn python_module_candidates(project_root: &Path, caller: &Path, module: &str) -> Vec<PathBuf> {
4792    let dots = module.bytes().take_while(|byte| *byte == b'.').count();
4793    let mut base = if dots == 0 {
4794        project_root.to_path_buf()
4795    } else {
4796        let Some(parent) = caller.parent() else {
4797            return Vec::new();
4798        };
4799        parent.to_path_buf()
4800    };
4801    for _ in 1..dots {
4802        let Some(parent) = base.parent() else {
4803            return Vec::new();
4804        };
4805        base = parent.to_path_buf();
4806    }
4807    if !base.starts_with(project_root) || (dots > 0 && base == project_root) {
4808        return Vec::new();
4809    }
4810    let rest = &module[dots..];
4811    if !rest.is_empty() {
4812        for segment in rest.split('.') {
4813            if segment.is_empty() || !segment.chars().all(|c| c == '_' || c.is_alphanumeric()) {
4814                return Vec::new();
4815            }
4816            base.push(segment);
4817        }
4818    } else if dots == 0 {
4819        return Vec::new();
4820    }
4821    // A regular package takes precedence over a sibling module, as in Python.
4822    vec![base.join("__init__.py"), base.with_extension("py")]
4823}
4824
4825fn rust_module_dependencies(
4826    project_root: &Path,
4827    abs_path: &Path,
4828    module_path: &str,
4829    memo: &callgraph::ModuleResolutionMemo,
4830    facts: &FactPaths<'_>,
4831) -> BTreeSet<String> {
4832    rust_module_candidates(project_root, abs_path, module_path, memo, facts)
4833        .into_iter()
4834        .collect()
4835}
4836
4837/// Existing files a Rust `use` path can name, most specific first: the file for
4838/// the full path (`a/b.rs`, `a/b/mod.rs`), then the file for its parent module,
4839/// which is where an item such as `a::b::Item` lives.
4840fn rust_module_candidates(
4841    project_root: &Path,
4842    abs_path: &Path,
4843    module_path: &str,
4844    memo: &callgraph::ModuleResolutionMemo,
4845    facts: &FactPaths<'_>,
4846) -> Vec<String> {
4847    let mut candidates = Vec::new();
4848    let rel_path = relative_path(
4849        project_root,
4850        &facts
4851            .canonical(abs_path)
4852            .unwrap_or_else(|| abs_path.to_path_buf()),
4853    );
4854    // A manifest can put a crate root outside src/, as ripgrep's binary does.
4855    // Resolve use paths from that target's directory, not from a guessed src/.
4856    let root_dir = memo
4857        .rust_crate_root_file(project_root, abs_path, facts)
4858        .and_then(|root| root.parent().map(Path::to_path_buf));
4859    let (src_prefix, path_segments) = if let Some(root_dir) = root_dir {
4860        let caller_rel = relative_path(
4861            &root_dir,
4862            &facts
4863                .canonical(abs_path)
4864                .unwrap_or_else(|| abs_path.to_path_buf()),
4865        );
4866        let path = rust_module_path_without_alias_or_use_list(module_path);
4867        let segments = path
4868            .split("::")
4869            .map(str::trim)
4870            .filter(|part| !part.is_empty())
4871            .collect::<Vec<_>>();
4872        if segments.is_empty() || matches!(segments[0], "std" | "core" | "alloc") {
4873            return candidates;
4874        }
4875        (
4876            relative_path(project_root, &root_dir),
4877            rust_resolve_segments_from(rust_module_segments_for_rel(&caller_rel), &segments),
4878        )
4879    } else {
4880        (
4881            rust_src_prefix(&rel_path),
4882            rust_module_dependency_segments(&rel_path, module_path),
4883        )
4884    };
4885    let Some(path_segments) = path_segments else {
4886        return candidates;
4887    };
4888    rust_push_module_dependency_candidate(
4889        project_root,
4890        &mut candidates,
4891        &src_prefix,
4892        &path_segments,
4893        facts,
4894    );
4895    if !path_segments.is_empty() {
4896        rust_push_module_dependency_candidate(
4897            project_root,
4898            &mut candidates,
4899            &src_prefix,
4900            &path_segments[..path_segments.len() - 1],
4901            facts,
4902        );
4903    }
4904    candidates
4905}
4906
4907fn rust_module_dependency_segments(rel_path: &str, module_path: &str) -> Option<Vec<String>> {
4908    let path = rust_module_path_without_alias_or_use_list(module_path);
4909    let segments = path
4910        .split("::")
4911        .map(str::trim)
4912        .filter(|segment| !segment.is_empty())
4913        .collect::<Vec<_>>();
4914    if segments.is_empty() || matches!(segments[0], "std" | "core" | "alloc") {
4915        return None;
4916    }
4917    rust_resolve_segments(rel_path, &segments)
4918}
4919
4920fn rust_module_path_without_alias_or_use_list(module_path: &str) -> &str {
4921    let path = module_path
4922        .trim()
4923        .trim_end_matches(';')
4924        .split_once(" as ")
4925        .map(|(left, _)| left.trim())
4926        .unwrap_or_else(|| module_path.trim().trim_end_matches(';'));
4927    path.find("::{").map(|brace| &path[..brace]).unwrap_or(path)
4928}
4929
4930fn rust_push_module_dependency_candidate(
4931    project_root: &Path,
4932    deps: &mut Vec<String>,
4933    src_prefix: &str,
4934    segments: &[String],
4935    facts: &FactPaths<'_>,
4936) {
4937    let prefix = if src_prefix.is_empty() {
4938        String::new()
4939    } else {
4940        format!("{src_prefix}/")
4941    };
4942    let candidates = if segments.is_empty() {
4943        vec![format!("{prefix}lib.rs"), format!("{prefix}main.rs")]
4944    } else {
4945        vec![
4946            format!("{}{}.rs", prefix, segments.join("/")),
4947            format!("{}{}/mod.rs", prefix, segments.join("/")),
4948        ]
4949    };
4950    for candidate in candidates {
4951        if facts.is_file(&project_root.join(&candidate)) && !deps.contains(&candidate) {
4952            deps.push(candidate);
4953        }
4954    }
4955}
4956
4957fn relative_module_candidates(base: &Path) -> Vec<PathBuf> {
4958    let mut candidates = Vec::new();
4959    if base.extension().is_some() {
4960        candidates.push(base.to_path_buf());
4961        return candidates;
4962    }
4963    for ext in JS_TS_EXTENSIONS {
4964        candidates.push(base.with_extension(ext));
4965    }
4966    for ext in JS_TS_EXTENSIONS {
4967        candidates.push(base.join(format!("index.{ext}")));
4968    }
4969    candidates
4970}
4971
4972fn import_local_names(import: &ImportStatement) -> Vec<String> {
4973    let mut names = Vec::new();
4974    if let Some(default) = &import.default_import {
4975        names.push(default.clone());
4976    }
4977    if let Some(namespace) = &import.namespace_import {
4978        names.push(namespace.clone());
4979    }
4980    for name in &import.names {
4981        names.push(crate::imports::specifier_local_name(name).to_string());
4982    }
4983    names
4984}
4985
4986fn import_requested_names(import: &ImportStatement) -> Vec<String> {
4987    import
4988        .names
4989        .iter()
4990        .map(|name| crate::imports::specifier_imported_name(name).to_string())
4991        .collect()
4992}
4993
4994fn import_is_wildcard(import: &ImportStatement) -> bool {
4995    import.namespace_import.is_some() || import.raw_text.contains('*')
4996}
4997
4998fn import_kind_label(kind: ImportKind) -> &'static str {
4999    match kind {
5000        ImportKind::Value => "value",
5001        ImportKind::Type => "type",
5002        ImportKind::SideEffect => "side_effect",
5003    }
5004}
5005
5006pub fn lang_label(lang: LangId) -> &'static str {
5007    match lang {
5008        LangId::TypeScript => "typescript",
5009        LangId::Tsx => "tsx",
5010        LangId::JavaScript => "javascript",
5011        LangId::Python => "python",
5012        LangId::Rust => "rust",
5013        LangId::Go => "go",
5014        LangId::C => "c",
5015        LangId::Cpp => "cpp",
5016        LangId::Cuda => "cuda",
5017        LangId::Metal => "metal",
5018        LangId::Zig => "zig",
5019        LangId::CSharp => "csharp",
5020        LangId::Bash => "bash",
5021        LangId::Html => "html",
5022        LangId::Markdown => "markdown",
5023        LangId::Solidity => "solidity",
5024        LangId::Scss => "scss",
5025        LangId::Vue => "vue",
5026        LangId::Json => "json",
5027        LangId::Scala => "scala",
5028        LangId::Java => "java",
5029        LangId::Ruby => "ruby",
5030        LangId::Kotlin => "kotlin",
5031        LangId::Swift => "swift",
5032        LangId::Php => "php",
5033        LangId::Lua => "lua",
5034        LangId::Luau => "luau",
5035        LangId::Perl => "perl",
5036        LangId::Yaml => "yaml",
5037        LangId::Pascal => "pascal",
5038        LangId::R => "r",
5039        LangId::Groovy => "groovy",
5040        LangId::ObjC => "objc",
5041        LangId::Toml => "toml",
5042    }
5043}
5044
5045pub fn lang_from_label(label: &str) -> Option<LangId> {
5046    match label {
5047        "typescript" => Some(LangId::TypeScript),
5048        "tsx" => Some(LangId::Tsx),
5049        "javascript" => Some(LangId::JavaScript),
5050        "python" => Some(LangId::Python),
5051        "rust" => Some(LangId::Rust),
5052        "go" => Some(LangId::Go),
5053        "c" => Some(LangId::C),
5054        "cpp" => Some(LangId::Cpp),
5055        "cuda" => Some(LangId::Cuda),
5056        "metal" => Some(LangId::Metal),
5057        "zig" => Some(LangId::Zig),
5058        "csharp" => Some(LangId::CSharp),
5059        "bash" => Some(LangId::Bash),
5060        "html" => Some(LangId::Html),
5061        "markdown" => Some(LangId::Markdown),
5062        "solidity" => Some(LangId::Solidity),
5063        "scss" => Some(LangId::Scss),
5064        "vue" => Some(LangId::Vue),
5065        "json" => Some(LangId::Json),
5066        "scala" => Some(LangId::Scala),
5067        "java" => Some(LangId::Java),
5068        "ruby" => Some(LangId::Ruby),
5069        "kotlin" => Some(LangId::Kotlin),
5070        "swift" => Some(LangId::Swift),
5071        "php" => Some(LangId::Php),
5072        "lua" => Some(LangId::Lua),
5073        "perl" => Some(LangId::Perl),
5074        "yaml" => Some(LangId::Yaml),
5075        "pascal" => Some(LangId::Pascal),
5076        "r" => Some(LangId::R),
5077        "groovy" => Some(LangId::Groovy),
5078        "objc" => Some(LangId::ObjC),
5079        "toml" => Some(LangId::Toml),
5080        _ => None,
5081    }
5082}
5083
5084pub fn normalize_file_path(project_root: &Path, path: &Path) -> Result<PathBuf> {
5085    let full_path = if path.is_relative() {
5086        project_root.join(path)
5087    } else {
5088        path.to_path_buf()
5089    };
5090    Ok(canonicalize_path(&full_path))
5091}
5092
5093#[cfg(any(test, feature = "test-support"))]
5094thread_local! {
5095    pub static CANONICALIZE_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5096}
5097
5098/// `std::fs::canonicalize`, counted in tests. Each call is a `realpath`, which
5099/// on macOS costs one `getattrlist` per path component.
5100fn fs_canonicalize(path: &Path) -> std::io::Result<PathBuf> {
5101    #[cfg(any(test, feature = "test-support"))]
5102    CANONICALIZE_CALLS.with(|calls| calls.set(calls.get() + 1));
5103    #[cfg(any(test, feature = "test-support"))]
5104    work_counts::note_realpath(path);
5105    std::fs::canonicalize(path)
5106}
5107
5108test_support_visibility! {
5109/// Canonicalize an existing path or the deepest existing ancestor of a deleted
5110/// one. This keeps watcher deletion events in the same identity domain as the
5111/// files indexed before the deletion.
5112///
5113/// Uncached resolver probes also call this (`tsconfig.json` in each ancestor
5114/// directory, `index.ts` beside each import), and most name a missing file.
5115fn canonicalize_path(path: &Path) -> PathBuf {
5116    #[cfg(any(test, feature = "test-support"))]
5117    work_counts::note_canonical_path(path);
5118    if let Ok(canonical) = fs_canonicalize(path) {
5119        return canonical;
5120    }
5121    canonicalize_missing_absolute_path(path).unwrap_or_else(|| canonicalize_missing_path(path))
5122}
5123}
5124
5125/// The deepest-existing-ancestor form of an absolute path made only of normal
5126/// components, found by walking up from the parent. A missing probe usually
5127/// sits in an existing directory, so this costs one more `canonicalize`; the
5128/// component-by-component walk in [`canonicalize_missing_path`] costs one per
5129/// component, each of them a full `realpath` from the root.
5130///
5131/// It returns what that walk returns: canonicalizing an ancestor also resolves
5132/// every ancestor above it, so the first ancestor that canonicalizes is the
5133/// deepest one the walk would reach. `None` hands paths with `..`, relative
5134/// paths or no parent to the walk. A Windows drive or verbatim prefix before
5135/// the root is allowed, since `canonicalize` returns such paths there.
5136fn canonicalize_missing_absolute_path(path: &Path) -> Option<PathBuf> {
5137    let mut components = path.components().peekable();
5138    if matches!(components.peek(), Some(std::path::Component::Prefix(_))) {
5139        components.next();
5140    }
5141    if components.next() != Some(std::path::Component::RootDir) {
5142        return None;
5143    }
5144    let names = components
5145        .map(|component| match component {
5146            std::path::Component::Normal(name) => Some(name),
5147            _ => None,
5148        })
5149        .collect::<Option<Vec<_>>>()?;
5150    let (existing, canonical) =
5151        path.ancestors()
5152            .skip(1)
5153            .enumerate()
5154            .find_map(|(depth_above, ancestor)| {
5155                fs_canonicalize(ancestor)
5156                    .ok()
5157                    .map(|canonical| (names.len() - 1 - depth_above, canonical))
5158            })?;
5159    // The walk checks the first missing component the same way: a name that
5160    // exists but cannot be resolved (a dangling symlink, a file used as a
5161    // directory) leaves the whole path as given.
5162    match std::fs::symlink_metadata(canonical.join(names[existing])) {
5163        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
5164            let mut resolved = canonical;
5165            resolved.extend(&names[existing..]);
5166            Some(resolved)
5167        }
5168        _ => Some(path.to_path_buf()),
5169    }
5170}
5171
5172test_support_visibility! {
5173/// Resolve a missing path component by component, keeping the unresolved tail
5174/// and applying `..` to it lexically.
5175fn canonicalize_missing_path(path: &Path) -> PathBuf {
5176    let mut resolved = PathBuf::new();
5177    let mut missing = Vec::new();
5178    for component in path.components() {
5179        match component {
5180            std::path::Component::Prefix(_) | std::path::Component::RootDir => {
5181                resolved.push(component.as_os_str());
5182                if let Ok(canonical) = fs_canonicalize(&resolved) {
5183                    resolved = canonical;
5184                }
5185            }
5186            std::path::Component::CurDir => {}
5187            std::path::Component::ParentDir => {
5188                if missing.pop().is_none() {
5189                    if !resolved.as_os_str().is_empty() && !resolved.is_dir() {
5190                        return path.to_path_buf();
5191                    }
5192                    resolved.pop();
5193                }
5194            }
5195            std::path::Component::Normal(name) => {
5196                if missing.is_empty() {
5197                    let candidate = resolved.join(name);
5198                    match fs_canonicalize(&candidate) {
5199                        Ok(canonical) => resolved = canonical,
5200                        Err(_) => match std::fs::symlink_metadata(&candidate) {
5201                            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
5202                                missing.push(name.to_owned());
5203                            }
5204                            _ => return path.to_path_buf(),
5205                        },
5206                    }
5207                } else {
5208                    missing.push(name.to_owned());
5209                }
5210            }
5211        }
5212    }
5213    resolved.extend(missing);
5214    resolved
5215}
5216}
5217
5218pub fn relative_path(project_root: &Path, path: &Path) -> String {
5219    if let Ok(stripped) = path.strip_prefix(project_root) {
5220        return stripped.to_string_lossy().replace('\\', "/");
5221    }
5222    let canon_root = canonicalize_path(project_root);
5223    let canon_path = canonicalize_path(path);
5224    if let Ok(stripped) = canon_path.strip_prefix(&canon_root) {
5225        return stripped.to_string_lossy().replace('\\', "/");
5226    }
5227    canon_path.to_string_lossy().replace('\\', "/")
5228}
5229
5230fn ref_id(parts: &[&str]) -> String {
5231    let joined = parts.join("\0");
5232    hash_to_hex(blake3::hash(joined.as_bytes()))
5233}
5234
5235fn hash_to_hex(hash: blake3::Hash) -> String {
5236    hash.to_hex().to_string()
5237}
5238
5239/// The first 64 bits of a digest as 16 hex digits.
5240fn short_hash_hex(hash: blake3::Hash) -> String {
5241    hash.to_hex()[..16].to_string()
5242}
5243
5244#[derive(Debug, Clone)]
5245pub struct LineIndex {
5246    starts: Vec<usize>,
5247    ends: Vec<usize>,
5248    source_len: usize,
5249}
5250
5251impl LineIndex {
5252    pub fn new(source: &str) -> Self {
5253        #[cfg(any(test, feature = "test-support"))]
5254        join::extraction_work::note(|work| work.position_bytes += source.len());
5255        let mut starts = vec![0];
5256        let mut ends = Vec::new();
5257        for (offset, byte) in source.bytes().enumerate() {
5258            if byte == b'\n' {
5259                // Call attribution clamps columns before CRLF terminators;
5260                // blob ranges retain the older inclusive segment convention.
5261                ends.push(if offset > 0 && source.as_bytes()[offset - 1] == b'\r' {
5262                    offset - 1
5263                } else {
5264                    offset
5265                });
5266                starts.push(offset + 1);
5267            }
5268        }
5269        ends.push(source.len());
5270        Self {
5271            starts,
5272            ends,
5273            source_len: source.len(),
5274        }
5275    }
5276
5277    test_support_visibility! {
5278    fn byte_to_line(&self, byte_offset: usize) -> u32 {
5279            let byte_offset = byte_offset.min(self.source_len);
5280            self.starts.partition_point(|start| *start <= byte_offset) as u32
5281        }
5282    }
5283
5284    pub fn byte_offset(&self, line: u32, column: u32) -> usize {
5285        let Some(&start) = self.starts.get(line as usize) else {
5286            return self.source_len;
5287        };
5288        start + (column as usize).min(self.ends[line as usize] - start)
5289    }
5290
5291    test_support_visibility! {
5292    fn inclusive_byte_offset(&self, line: u32, column: u32) -> usize {
5293            let Some(&start) = self.starts.get(line as usize) else {
5294                return self.source_len;
5295            };
5296            let end = self
5297                .starts
5298                .get(line as usize + 1)
5299                .copied()
5300                .unwrap_or(self.source_len);
5301            start + (column as usize).min(end - start)
5302        }
5303
5304    }
5305}
5306
5307fn empty_to_none(value: String) -> Option<String> {
5308    if value.is_empty() {
5309        None
5310    } else {
5311        Some(value)
5312    }
5313}
5314
5315pub fn unix_millis_now() -> u64 {
5316    SystemTime::now()
5317        .duration_since(UNIX_EPOCH)
5318        .unwrap_or_default()
5319        .as_millis()
5320        .min(u128::from(u64::MAX)) as u64
5321}
5322
5323#[cfg(any(test, feature = "test-support"))]
5324impl DbFileIndex {
5325    pub fn empty(lang: Option<LangId>) -> Self {
5326        Self {
5327            lang,
5328            exports: HashSet::new(),
5329            default_export: None,
5330            export_aliases: HashMap::new(),
5331            node_by_scoped: HashMap::new(),
5332            node_by_bare: HashMap::new(),
5333            node_kind_by_id: HashMap::new(),
5334            module_targets: HashMap::new(),
5335            declared_module_targets: HashMap::new(),
5336            macro_use_module_targets: BTreeSet::new(),
5337            reexports: Vec::new(),
5338        }
5339    }
5340}
5341#[cfg(any(test, feature = "test-support"))]
5342pub mod work_counts {
5343    use std::collections::HashMap;
5344    use std::path::{Path, PathBuf};
5345    use std::sync::{Mutex, OnceLock};
5346
5347    static PARSES: OnceLock<Mutex<HashMap<PathBuf, usize>>> = OnceLock::new();
5348    static FINGERPRINT_READS: OnceLock<Mutex<HashMap<PathBuf, usize>>> = OnceLock::new();
5349    static CONFIG_READS: OnceLock<Mutex<HashMap<PathBuf, usize>>> = OnceLock::new();
5350    static STAGING_READS: OnceLock<Mutex<HashMap<PathBuf, usize>>> = OnceLock::new();
5351    static DIRECTORY_READS: OnceLock<Mutex<HashMap<PathBuf, usize>>> = OnceLock::new();
5352    static GO_PACKAGE_BUILDS: OnceLock<Mutex<HashMap<PathBuf, usize>>> = OnceLock::new();
5353    static CANONICAL_PATHS: OnceLock<Mutex<HashMap<PathBuf, usize>>> = OnceLock::new();
5354    static REALPATHS: OnceLock<Mutex<HashMap<PathBuf, usize>>> = OnceLock::new();
5355    static WORKSPACE_DIRECTORIES: OnceLock<Mutex<HashMap<PathBuf, usize>>> = OnceLock::new();
5356    static CORPUS_LOOKUPS: OnceLock<Mutex<HashMap<PathBuf, (usize, usize, u128)>>> =
5357        OnceLock::new();
5358
5359    fn note(map: &OnceLock<Mutex<HashMap<PathBuf, usize>>>, path: &Path) {
5360        *map.get_or_init(Default::default)
5361            .lock()
5362            .expect("work counter mutex poisoned")
5363            .entry(path.to_path_buf())
5364            .or_default() += 1;
5365    }
5366
5367    fn under(
5368        map: &OnceLock<Mutex<HashMap<PathBuf, usize>>>,
5369        root: &Path,
5370        file_name: Option<&str>,
5371    ) -> usize {
5372        map.get_or_init(Default::default)
5373            .lock()
5374            .expect("work counter mutex poisoned")
5375            .iter()
5376            .filter(|(path, _)| path.starts_with(root))
5377            .filter(|(path, _)| {
5378                file_name.is_none_or(|name| path.file_name().is_some_and(|file| file == name))
5379            })
5380            .map(|(_, count)| *count)
5381            .sum()
5382    }
5383
5384    pub fn note_config_read(path: &Path) {
5385        note(&CONFIG_READS, path);
5386    }
5387
5388    pub fn note_directory_read(path: &Path) {
5389        note(&DIRECTORY_READS, path);
5390    }
5391
5392    pub fn directory_reads_under(root: &Path) -> usize {
5393        under(&DIRECTORY_READS, root, None)
5394    }
5395
5396    pub fn note_canonical_path(path: &Path) {
5397        note(&CANONICAL_PATHS, path);
5398    }
5399
5400    pub fn note_realpath(path: &Path) {
5401        note(&REALPATHS, path);
5402    }
5403
5404    pub fn note_workspace_directory(path: &Path) {
5405        note(&WORKSPACE_DIRECTORIES, path);
5406    }
5407
5408    pub fn filesystem_counts(root: &Path) -> (usize, usize, usize, usize) {
5409        let paths = CANONICAL_PATHS
5410            .get_or_init(Default::default)
5411            .lock()
5412            .unwrap();
5413        let unique = paths.keys().filter(|path| path.starts_with(root)).count();
5414        let calls = paths
5415            .iter()
5416            .filter(|(path, _)| path.starts_with(root))
5417            .map(|(_, count)| count)
5418            .sum();
5419        (
5420            calls,
5421            unique,
5422            under(&WORKSPACE_DIRECTORIES, root, None),
5423            directory_reads_under(root),
5424        )
5425    }
5426
5427    pub fn note_go_package_build(path: &Path) {
5428        note(&GO_PACKAGE_BUILDS, path);
5429    }
5430
5431    pub fn reset_under(root: &Path) {
5432        CORPUS_LOOKUPS
5433            .get_or_init(Default::default)
5434            .lock()
5435            .unwrap()
5436            .retain(|path, _| !path.starts_with(root));
5437        for map in [
5438            &PARSES,
5439            &FINGERPRINT_READS,
5440            &CONFIG_READS,
5441            &STAGING_READS,
5442            &DIRECTORY_READS,
5443            &GO_PACKAGE_BUILDS,
5444            &CANONICAL_PATHS,
5445            &REALPATHS,
5446            &WORKSPACE_DIRECTORIES,
5447        ] {
5448            map.get_or_init(Default::default)
5449                .lock()
5450                .expect("work counter mutex poisoned")
5451                .retain(|path, _| !path.starts_with(root));
5452        }
5453    }
5454}
5455#[cfg(any(test, feature = "test-support"))]
5456pub mod rust_module_work {
5457    use super::*;
5458
5459    #[derive(Debug, Default)]
5460    pub(super) struct Work {
5461        pub resolved_refs: usize,
5462        pub resolved_files: BTreeSet<String>,
5463        pub parent_lookups: usize,
5464        pub parent_scans: usize,
5465        pub parent_file_visits: usize,
5466        pub inline_file_visits: usize,
5467        pub caller_requests: usize,
5468        pub caller_walks: usize,
5469        pub parent_time: Duration,
5470        pub caller_time: Duration,
5471    }
5472
5473    thread_local! {
5474        static ACTIVE: RefCell<Option<Work>> = const { RefCell::new(None) };
5475        static DISABLED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
5476    }
5477
5478    pub(super) fn disabled() -> bool {
5479        DISABLED.with(std::cell::Cell::get)
5480    }
5481
5482    pub(super) fn note(update: impl FnOnce(&mut Work)) {
5483        ACTIVE.with(|active| {
5484            if let Some(work) = active.borrow_mut().as_mut() {
5485                update(work);
5486            }
5487        });
5488    }
5489
5490    pub(super) struct Timing {
5491        started: Option<Instant>,
5492        parent: bool,
5493    }
5494
5495    impl Timing {
5496        pub fn parent() -> Self {
5497            note(|work| work.parent_lookups += 1);
5498            Self::start(true)
5499        }
5500
5501        pub fn caller() -> Self {
5502            note(|work| work.caller_requests += 1);
5503            Self::start(false)
5504        }
5505
5506        fn start(parent: bool) -> Self {
5507            Self {
5508                started: ACTIVE.with(|active| active.borrow().is_some().then(Instant::now)),
5509                parent,
5510            }
5511        }
5512    }
5513
5514    impl Drop for Timing {
5515        fn drop(&mut self) {
5516            if let Some(started) = self.started {
5517                let elapsed = started.elapsed();
5518                note(|work| {
5519                    if self.parent {
5520                        work.parent_time += elapsed;
5521                    } else {
5522                        work.caller_time += elapsed;
5523                    }
5524                });
5525            }
5526        }
5527    }
5528}