Skip to main content

aft_parse/callgraph_store/
join.rs

1//! Path-free callgraph extraction and checkout-backed reference resolution.
2//!
3//! The index store keeps immutable parse payloads. Binding a payload to its
4//! checkout path and resolving cross-file references uses the checkout's
5//! [`ProjectFacts`], not a separate manifest or artifact store.
6
7use std::borrow::Cow;
8use std::collections::{BTreeMap, BTreeSet};
9use std::fmt;
10
11#[path = "dispatch.rs"]
12pub mod dispatch;
13#[path = "join_record.rs"]
14pub mod record;
15
16#[cfg(any(test, feature = "test-support"))]
17#[path = "extraction_work.rs"]
18pub mod extraction_work;
19
20#[cfg(any(test, feature = "test-support"))]
21pub use extraction_work::CountingParser as Parser;
22use serde::{Deserialize, Serialize};
23#[cfg(not(any(test, feature = "test-support")))]
24use tree_sitter::Parser;
25
26test_support_visibility! {
27#[path = "extraction_index.rs"]
28mod extraction_index;
29}
30
31#[path = "single_walk.rs"]
32pub mod single_walk;
33
34#[path = "syntax_index.rs"]
35pub mod syntax_index;
36
37use super::facts::{BlobKey, FactPaths, NoProjectFacts, ProjectFacts};
38use crate::callgraph::{self, FileCallData, SymbolMeta};
39use crate::imports::{ImportBlock, ImportForm, ImportGroup, ImportKind, ImportStatement};
40use crate::parser::LangId;
41use crate::symbols::SymbolKind;
42use std::collections::HashMap;
43use std::path::Path;
44use std::rc::Rc;
45use std::sync::Arc;
46
47const TOP_LEVEL_SYMBOL: &str = "<top-level>";
48
49/// The reason a view publication fence gives when it refuses a publication
50/// because the checkout's view owner was superseded. A cancelled join
51/// ([`ManifestJoinError::Cancelled`]) reports the same text.
52pub const SUPERSEDED_PUBLISH: &str = "checkout view owner superseded; publication refused";
53
54/// An error raised while decoding parse payloads or resolving checkout references.
55#[derive(Clone, Debug, Eq, PartialEq)]
56pub enum ManifestJoinError {
57    GrammarParseTimeout {
58        path: String,
59        language: String,
60        timeout_ms: u64,
61    },
62    GrammarUnavailable(crate::grammar::GrammarUnavailable),
63    Cancelled,
64    UnsupportedLanguage(String),
65    Parse(String),
66    InvalidBlob(String),
67}
68
69impl fmt::Display for ManifestJoinError {
70    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
71        match self {
72            Self::GrammarParseTimeout {
73                path, timeout_ms, ..
74            } => write!(
75                formatter,
76                "grammar parse exceeded {timeout_ms} ms for {path}"
77            ),
78            Self::GrammarUnavailable(error) => formatter.write_str(&error.message),
79            Self::Cancelled => formatter.write_str(SUPERSEDED_PUBLISH),
80            Self::UnsupportedLanguage(language) => {
81                write!(formatter, "unsupported callgraph blob language {language}")
82            }
83            Self::Parse(reason) => write!(formatter, "callgraph blob parse failed: {reason}"),
84            Self::InvalidBlob(reason) => write!(formatter, "invalid callgraph blob: {reason}"),
85        }
86    }
87}
88
89impl std::error::Error for ManifestJoinError {}
90
91/// Keep grammar availability typed across the index-store extraction boundary;
92/// it is neither a malformed source file nor a successful empty record.
93pub fn extraction_error(error: crate::error::AftError) -> ManifestJoinError {
94    match error {
95        crate::error::AftError::GrammarParseTimeout {
96            path,
97            language,
98            timeout_ms,
99        } => ManifestJoinError::GrammarParseTimeout {
100            path,
101            language,
102            timeout_ms,
103        },
104        crate::error::AftError::GrammarUnavailable {
105            language,
106            state,
107            message,
108            cause,
109            retry_after_ms,
110        } => ManifestJoinError::GrammarUnavailable(crate::grammar::GrammarUnavailable {
111            language,
112            state,
113            message,
114            cause,
115            retry_after_ms,
116        }),
117        other => ManifestJoinError::Parse(other.to_string()),
118    }
119}
120
121/// Tree-sitter node position in canonical pre-order traversal order.
122#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
123pub struct AstPreorderNode {
124    pub ordinal: u32,
125    /// Grammar names are static during extraction; legacy payload decoding owns
126    /// the same text.
127    pub kind: Cow<'static, str>,
128    pub byte_start: usize,
129    pub byte_end: usize,
130}
131
132/// A symbol captured by extraction.  Its ordinal is the source AST node's
133/// pre-order position, not a per-path or database-generated identifier.
134#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
135pub struct BlobSymbol {
136    #[serde(default)]
137    pub is_test: Option<bool>,
138    pub ordinal: u32,
139    pub name: String,
140    pub scoped_name: String,
141    pub kind: String,
142    pub exported: bool,
143    pub is_default_export: bool,
144    pub start_line: u32,
145    pub start_col: u32,
146    pub end_line: u32,
147    pub end_col: u32,
148    pub signature: Option<String>,
149    /// Whether the program starts here, as the symbol's language defines it
150    /// (`SymbolMeta::program_start`).
151    #[serde(default)]
152    pub program_start: bool,
153    /// The entry attribute extraction recorded for the symbol
154    /// (`SymbolMeta::entry_point_attribute`), such as `no_mangle`.
155    #[serde(default)]
156    pub entry_attribute: Option<String>,
157}
158
159/// The parse-level class of a reference.  No target path is present in a blob.
160#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
161#[serde(rename_all = "snake_case")]
162pub enum BlobRefKind {
163    Construction,
164    CallbackRef,
165    Call,
166    ValueRef,
167    Import,
168    Module,
169    Reexport,
170    ExportAlias,
171    /// A name inside a Rust macro whose tokens tree-sitter could not parse:
172    /// a call there is invisible to the graph, so callers of that name note
173    /// where it occurs. Never resolved.
174    MacroMention,
175}
176
177/// An unresolved reference extracted from one source blob.
178#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
179pub struct BlobRef {
180    /// Canonical tree-sitter AST pre-order position of this reference.
181    pub ordinal: u32,
182    pub kind: BlobRefKind,
183    pub caller_symbol: Option<String>,
184    pub short_name: Option<String>,
185    pub full_ref: Option<String>,
186    pub module_path: Option<String>,
187    pub line: u32,
188    pub byte_start: usize,
189    pub byte_end: usize,
190    pub path_override: Option<String>,
191    pub local_name: Option<String>,
192    pub requested_name: Option<String>,
193    pub namespace_alias: Option<String>,
194    pub wildcard: bool,
195    pub import_kind: Option<String>,
196}
197
198/// A parsed import retained in the blob so binding can resolve aliases without
199/// re-reading source text.
200#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
201pub struct BlobImport {
202    pub ordinal: u32,
203    pub module_path: String,
204    pub names: Vec<String>,
205    pub default_import: Option<String>,
206    pub namespace_import: Option<String>,
207    pub byte_start: usize,
208    pub byte_end: usize,
209    pub raw_text: String,
210    pub type_only: bool,
211    pub side_effect: bool,
212}
213
214/// Path-free parse output stored for a regular source file.
215#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
216pub struct ParseBlob {
217    pub entry_point_symbols: Vec<String>,
218    #[serde(default)]
219    pub dispatch: dispatch::DispatchFacts,
220    pub extractor_version: String,
221    pub language: String,
222    /// Extraction uses node spans to assign ordinals. All later readers use the
223    /// ordinals already copied into symbols, imports, references and dispatch.
224    /// Keep accepting older payloads, but do not persist the temporary index.
225    #[serde(skip_serializing, default)]
226    pub ast_nodes: Vec<AstPreorderNode>,
227    pub symbols: Vec<BlobSymbol>,
228    pub default_export_symbol: Option<String>,
229    pub exported_symbols: Vec<String>,
230    pub callable_symbols: Vec<String>,
231    pub imports: Vec<BlobImport>,
232    #[serde(default)]
233    pub python_bindings: Vec<callgraph::python::CallBinding>,
234    pub refs: Vec<BlobRef>,
235}
236
237/// Raw source is retained only for configuration files and ignore-list members.
238/// These blobs are parsed during joining because their interpretation depends on
239/// the manifest view they configure.
240#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
241pub struct ConfigBlob {
242    pub extractor_version: String,
243    pub language: String,
244    pub source: Vec<u8>,
245}
246
247/// The immutable callgraph blob payload.  A regular source blob has parse output
248/// only; a configuration blob is intentionally raw so its manifest-scoped
249/// resolver settings can be interpreted during assembly.
250#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
251#[serde(tag = "kind", rename_all = "snake_case")]
252pub enum CallgraphBlob {
253    Parse(ParseBlob),
254    Config(ConfigBlob),
255}
256
257impl CallgraphBlob {
258    /// Extracts path-free callgraph parse output from source bytes and the
259    /// extractor version that names the corresponding content key.
260    pub fn extract(
261        source: &str,
262        language: &str,
263        extractor_version: impl Into<String>,
264    ) -> Result<Self, ManifestJoinError> {
265        single_walk::extract(source, language, extractor_version.into())
266    }
267
268    /// [`Self::extract_tree`], also returning the file's symbols as the
269    /// parser extracts them for outline: the same table, from the same walk,
270    /// before the call graph qualifies, adds or merges any.
271    pub fn extract_tree_with_outline(
272        source: &str,
273        language: &str,
274        extractor_version: impl Into<String>,
275        tree: &tree_sitter::Tree,
276    ) -> Result<(Self, Vec<crate::symbols::Symbol>), ManifestJoinError> {
277        let mut outline = Vec::new();
278        let blob = single_walk::extract_tree(
279            source,
280            language,
281            extractor_version.into(),
282            tree,
283            Some(&mut outline),
284        )?;
285        Ok((blob, outline))
286    }
287
288    /// The extractor before the single walk: the same passes, each walking
289    /// the tree itself and asking tree-sitter for parents and siblings. It
290    /// stays only so the extraction gate (`data_layer::extract_gate`) can
291    /// check both give the same output.
292    pub fn extract_reference(
293        source: &str,
294        language: &str,
295        extractor_version: impl Into<String>,
296    ) -> Result<Self, ManifestJoinError> {
297        let lang = language_id(language)
298            .ok_or_else(|| ManifestJoinError::UnsupportedLanguage(language.to_string()))?;
299        let extractor_version = extractor_version.into();
300        let tree = match crate::parser::cached_header_tree(source, lang) {
301            Some(tree) => tree,
302            None if crate::parser::markdown_too_deep_to_parse(lang, source) => {
303                return Err(ManifestJoinError::Parse(
304                    crate::parser::MARKDOWN_TOO_DEEP.to_string(),
305                ));
306            }
307            None => {
308                let mut parser = Parser::new();
309                crate::parser::initialize_parser(&mut parser, lang).map_err(extraction_error)?;
310                #[cfg(any(test, feature = "test-support"))]
311                parser.note_parse();
312                crate::parser::parse_with_parser(
313                    &mut parser,
314                    Path::new("<reference-content>"),
315                    source,
316                    lang,
317                    None,
318                )
319                .map_err(extraction_error)?
320            }
321        };
322        let root = tree.root_node();
323        let ast_nodes = ast_preorder_nodes(root);
324        let line_index = super::LineIndex::new(source);
325        let mut data = callgraph::build_file_data_from_tree(
326            std::path::Path::new("__callgraph_blob__"),
327            source,
328            lang,
329            &tree,
330            &line_index,
331        )
332        .map_err(|error| ManifestJoinError::Parse(error.to_string()))?;
333        if lang == LangId::Rust {
334            super::extend_rust_imports_from_tree(source, root, &mut data);
335        }
336        let mut symbols = blob_symbols(&data);
337        let mut imports = blob_imports(&data);
338        let mut refs = blob_refs(&line_index, &data);
339        refs.extend(rust_module_refs(source, lang, root));
340        let paths = FactPaths {
341            root: Path::new("/"),
342            facts: &NoProjectFacts,
343        };
344        let file = Path::new("/__callgraph_blob__");
345        let mut structural = super::collect_reexport_refs_with_line_index(
346            paths.root,
347            file,
348            "__callgraph_blob__",
349            source,
350            lang,
351            &crate::callgraph::ModuleResolutionMemo::default(),
352            &paths,
353            &line_index,
354            Some(root),
355        )
356        .raw_refs;
357        structural.extend(
358            super::collect_source_less_export_alias_refs_with_line_index(
359                "__callgraph_blob__",
360                source,
361                &line_index,
362            )
363            .raw_refs,
364        );
365        if lang == LangId::Rust {
366            structural.extend(
367                super::collect_rust_pub_use_reexport_refs(
368                    paths.root,
369                    file,
370                    "__callgraph_blob__",
371                    &data.import_block.imports,
372                    &line_index,
373                    &paths,
374                )
375                .raw_refs,
376            );
377        }
378        refs.extend(structural.into_iter().map(structural_ref));
379        assign_ordinals(
380            &ast_nodes,
381            &line_index,
382            &mut symbols,
383            &mut imports,
384            &mut refs,
385        );
386        let mut exported_symbols = data.exported_symbols.clone();
387        exported_symbols.sort();
388        let mut callable_symbols = data.calls_by_symbol.keys().cloned().collect::<Vec<_>>();
389        callable_symbols.sort();
390        refs.sort_by(|left, right| {
391            (
392                left.ordinal,
393                left.kind,
394                left.byte_start,
395                left.byte_end,
396                left.full_ref.as_deref(),
397                left.caller_symbol.as_deref(),
398            )
399                .cmp(&(
400                    right.ordinal,
401                    right.kind,
402                    right.byte_start,
403                    right.byte_end,
404                    right.full_ref.as_deref(),
405                    right.caller_symbol.as_deref(),
406                ))
407        });
408        refs.dedup_by(|left, right| {
409            left.ordinal == right.ordinal
410                && left.kind == right.kind
411                && left.byte_start == right.byte_start
412                && left.byte_end == right.byte_end
413                && left.full_ref == right.full_ref
414                && left.caller_symbol == right.caller_symbol
415        });
416
417        let mut parse = ParseBlob {
418            entry_point_symbols: data
419                .symbol_metadata
420                .iter()
421                .filter(|(_, meta)| meta.entry_point_attribute.is_some())
422                .map(|(name, _)| name.clone())
423                .collect(),
424            dispatch: dispatch::DispatchFacts::default(),
425            extractor_version,
426            language: language.to_string(),
427            ast_nodes,
428            symbols,
429            default_export_symbol: data.default_export_symbol,
430            exported_symbols,
431            callable_symbols,
432            imports,
433            python_bindings: data.python_bindings,
434            refs,
435        };
436        parse.entry_point_symbols.sort();
437        parse.dispatch = dispatch::extract(source, lang, root, &mut parse)?;
438        Ok(Self::Parse(parse))
439    }
440
441    /// Builds a manifest configuration input. The caller keys it with the
442    /// file's configuration language (plain `config`, or `config-<grammar>`
443    /// when the record also holds TODO markers read in that grammar; see
444    /// `data_layer::content::is_config_language`) and the same extractor
445    /// version stored here. The blob itself always names plain `config`:
446    /// it holds the file's bytes whole, which do not depend on the grammar,
447    /// and readers take the language from the path record, not from here.
448    pub fn config(source: impl Into<Vec<u8>>, extractor_version: impl Into<String>) -> Self {
449        Self::Config(ConfigBlob {
450            extractor_version: extractor_version.into(),
451            language: "config".to_string(),
452            source: source.into(),
453        })
454    }
455
456    /// Uses one canonical JSON encoding for the immutable payload bytes.
457    pub fn to_bytes(&self) -> Result<Vec<u8>, ManifestJoinError> {
458        serde_json::to_vec(self).map_err(|error| ManifestJoinError::InvalidBlob(error.to_string()))
459    }
460
461    /// Decodes a payload after the blob store has verified its digest and schema.
462    pub fn from_bytes(bytes: &[u8]) -> Result<Self, ManifestJoinError> {
463        serde_json::from_slice(bytes)
464            .map_err(|error| ManifestJoinError::InvalidBlob(error.to_string()))
465    }
466
467    pub fn parse(&self) -> Option<&ParseBlob> {
468        match self {
469            Self::Parse(blob) => Some(blob),
470            Self::Config(_) => None,
471        }
472    }
473
474    pub fn config_source(&self) -> Option<&ConfigBlob> {
475        match self {
476            Self::Parse(_) => None,
477            Self::Config(blob) => Some(blob),
478        }
479    }
480}
481
482/// The stable identity of one bound blob reference.  The path breaks ties when
483/// identical content is bound at more than one manifest path.
484#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
485pub struct CallerRefKey {
486    pub caller_blob_key: String,
487    pub ref_ordinal: u32,
488    pub caller_path: Vec<u8>,
489}
490
491/// The manifest-derived resolution state for one reference.
492#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
493pub enum ResolutionStatus {
494    Resolved,
495    Unresolved,
496}
497
498/// A logical derived row.  It is intentionally independent of SQLite rowids and
499/// other physical database details.
500#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
501pub struct DerivedRow {
502    pub caller_blob_key: String,
503    pub ref_ordinal: u32,
504    pub caller_path: Vec<u8>,
505    pub kind: BlobRefKind,
506    pub status: ResolutionStatus,
507    pub target_path: Option<Vec<u8>>,
508    pub target_symbol: Option<String>,
509}
510
511impl DerivedRow {
512    pub fn ref_key(&self) -> CallerRefKey {
513        CallerRefKey {
514            caller_blob_key: self.caller_blob_key.clone(),
515            ref_ordinal: self.ref_ordinal,
516            caller_path: self.caller_path.clone(),
517        }
518    }
519}
520
521pub fn language_id(language: &str) -> Option<LangId> {
522    Some(match language {
523        "typescript" => LangId::TypeScript,
524        "tsx" => LangId::Tsx,
525        "javascript" => LangId::JavaScript,
526        "python" => LangId::Python,
527        "rust" => LangId::Rust,
528        "go" => LangId::Go,
529        "c" => LangId::C,
530        "cpp" => LangId::Cpp,
531        "cuda" => LangId::Cuda,
532        "metal" => LangId::Metal,
533        "zig" => LangId::Zig,
534        "csharp" => LangId::CSharp,
535        "bash" => LangId::Bash,
536        "html" => LangId::Html,
537        "markdown" => LangId::Markdown,
538        "solidity" => LangId::Solidity,
539        "scss" => LangId::Scss,
540        "vue" => LangId::Vue,
541        "json" => LangId::Json,
542        "scala" => LangId::Scala,
543        "java" => LangId::Java,
544        "ruby" => LangId::Ruby,
545        "kotlin" => LangId::Kotlin,
546        "swift" => LangId::Swift,
547        "php" => LangId::Php,
548        "lua" => LangId::Lua,
549        "perl" => LangId::Perl,
550        "yaml" => LangId::Yaml,
551        "pascal" => LangId::Pascal,
552        "r" => LangId::R,
553        "groovy" => LangId::Groovy,
554        "objc" => LangId::ObjC,
555        "toml" => LangId::Toml,
556        _ => return crate::grammar::extractor_language(language),
557    })
558}
559
560fn ast_preorder_nodes(root: tree_sitter::Node<'_>) -> Vec<AstPreorderNode> {
561    let mut nodes = Vec::new();
562    for node in extraction_index::preorder(root) {
563        let kind = Cow::Borrowed(node.kind());
564        #[cfg(any(test, feature = "test-support"))]
565        extraction_work::note(|work| {
566            work.kind_copies += usize::from(matches!(kind, Cow::Owned(_)))
567        });
568        nodes.push(AstPreorderNode {
569            ordinal: nodes.len() as u32,
570            kind,
571            byte_start: node.start_byte(),
572            byte_end: node.end_byte(),
573        });
574    }
575    nodes
576}
577
578test_support_visibility! {
579fn blob_symbols(data: &FileCallData) -> Vec<BlobSymbol> {
580    data.symbol_metadata
581        .iter()
582        .map(|(scoped_name, meta)| blob_symbol(scoped_name, meta, &data.default_export_symbol))
583        .collect()
584}
585}
586
587fn sort_blob_symbols(symbols: &mut [BlobSymbol]) {
588    symbols.sort_by(|left, right| {
589        (
590            left.ordinal,
591            left.start_line,
592            left.start_col,
593            left.scoped_name.as_str(),
594        )
595            .cmp(&(
596                right.ordinal,
597                right.start_line,
598                right.start_col,
599                right.scoped_name.as_str(),
600            ))
601    });
602}
603
604fn blob_symbol(
605    scoped_name: &str,
606    meta: &SymbolMeta,
607    default_export: &Option<String>,
608) -> BlobSymbol {
609    BlobSymbol {
610        is_test: meta.is_test,
611        ordinal: 0,
612        name: unqualified_symbol_name(scoped_name).to_string(),
613        scoped_name: scoped_name.to_string(),
614        kind: symbol_kind_name(&meta.kind).to_string(),
615        exported: meta.exported,
616        is_default_export: default_export.as_deref() == Some(scoped_name),
617        start_line: meta.range.start_line,
618        start_col: meta.range.start_col,
619        end_line: meta.range.end_line,
620        end_col: meta.range.end_col,
621        signature: meta.signature.clone(),
622        program_start: meta.program_start,
623        entry_attribute: meta.entry_point_attribute.clone(),
624    }
625}
626
627test_support_visibility! {
628fn blob_imports(data: &FileCallData) -> Vec<BlobImport> {
629    data.import_block
630        .imports
631        .iter()
632        .map(|import| BlobImport {
633            ordinal: 0,
634            module_path: import.module_path.clone(),
635            names: import.names.clone(),
636            default_import: import.default_import.clone(),
637            namespace_import: import.namespace_import.clone(),
638            byte_start: import.byte_range.start,
639            byte_end: import.byte_range.end,
640            raw_text: import.raw_text.clone(),
641            type_only: import.kind == ImportKind::Type,
642            side_effect: import.kind == ImportKind::SideEffect,
643        })
644        .collect()
645}
646}
647
648test_support_visibility! {
649fn blob_refs(line_index: &super::LineIndex, data: &FileCallData) -> Vec<BlobRef> {
650    let mut refs = Vec::new();
651    for (caller_symbol, calls) in ordered_symbol_sites(&data.calls_by_symbol) {
652        for call in calls {
653            refs.push(call_ref(caller_symbol, call, BlobRefKind::Call));
654        }
655    }
656    for (caller_symbol, calls) in ordered_symbol_sites(&data.value_refs_by_symbol) {
657        for call in calls {
658            refs.push(call_ref(caller_symbol, call, BlobRefKind::ValueRef));
659        }
660    }
661    for (caller_symbol, calls) in ordered_symbol_sites(&data.macro_body_calls_by_macro) {
662        for call in calls {
663            refs.push(call_ref(caller_symbol, call, BlobRefKind::Call));
664        }
665    }
666    for (caller_symbol, mentions) in ordered_symbol_sites(&data.macro_mentions_by_symbol) {
667        for mention in mentions {
668            refs.push(call_ref(caller_symbol, mention, BlobRefKind::MacroMention));
669        }
670    }
671    for import in &data.import_block.imports {
672        refs.push(BlobRef {
673            ordinal: 0,
674            kind: BlobRefKind::Import,
675            caller_symbol: None,
676            short_name: None,
677            full_ref: Some(import.module_path.clone()),
678            module_path: Some(import.module_path.clone()),
679            line: line_index.byte_to_line(import.byte_range.start),
680            byte_start: import.byte_range.start,
681            byte_end: import.byte_range.end,
682            path_override: None,
683            local_name: None,
684            requested_name: None,
685            namespace_alias: import.namespace_import.clone(),
686            wildcard: super::import_is_wildcard(import),
687            import_kind: None,
688        });
689    }
690    refs
691}
692}
693
694test_support_visibility! {
695/// Reference construction must not depend on a hash map's randomized order.
696/// One source call can belong to several enclosing symbols, and each caller is
697/// distinct evidence even when the call's AST range is identical.
698fn ordered_symbol_sites(
699    sites: &HashMap<String, Vec<callgraph::CallSite>>,
700) -> Vec<(&str, &[callgraph::CallSite])> {
701    let mut ordered = sites
702        .iter()
703        .map(|(caller, calls)| (caller.as_str(), calls.as_slice()))
704        .collect::<Vec<_>>();
705    ordered.sort_unstable_by_key(|(caller, _)| *caller);
706    ordered
707}
708}
709
710fn call_ref(caller_symbol: &str, call: &callgraph::CallSite, kind: BlobRefKind) -> BlobRef {
711    BlobRef {
712        ordinal: 0,
713        kind: match call.kind {
714            callgraph::CallSiteKind::Construction => BlobRefKind::Construction,
715            callgraph::CallSiteKind::CallbackReference => BlobRefKind::CallbackRef,
716            callgraph::CallSiteKind::Call => kind,
717        },
718        caller_symbol: Some(caller_symbol.to_string()),
719        short_name: Some(call.callee_name.clone()),
720        full_ref: Some(call.full_callee.clone()),
721        module_path: None,
722        line: call.line,
723        byte_start: call.byte_start,
724        byte_end: call.byte_end,
725        path_override: None,
726        local_name: None,
727        requested_name: None,
728        namespace_alias: None,
729        wildcard: false,
730        import_kind: None,
731    }
732}
733
734fn rust_module_refs(source: &str, lang: LangId, root: tree_sitter::Node<'_>) -> Vec<BlobRef> {
735    if lang != LangId::Rust {
736        return Vec::new();
737    }
738    let mut refs = Vec::new();
739    for node in extraction_index::preorder(root) {
740        if node.kind() == "mod_item"
741            && node
742                .named_children(&mut node.walk())
743                .all(|child| child.kind() != "declaration_list")
744        {
745            if let Some(name) = node.child_by_field_name("name") {
746                let module_name = source[name.byte_range()].to_string();
747                refs.push(BlobRef {
748                    ordinal: 0,
749                    kind: BlobRefKind::Module,
750                    caller_symbol: None,
751                    short_name: Some(module_name.clone()),
752                    full_ref: Some(if super::rust_module_has_macro_use(source, node) {
753                        format!("#[macro_use] mod {module_name};")
754                    } else {
755                        module_name.clone()
756                    }),
757                    module_path: Some(module_name),
758                    line: node.start_position().row as u32 + 1,
759                    byte_start: node.start_byte(),
760                    byte_end: node.end_byte(),
761                    path_override: super::rust_module_path_override(source, node)
762                        .map(str::to_string),
763                    local_name: None,
764                    requested_name: None,
765                    namespace_alias: None,
766                    wildcard: false,
767                    import_kind: None,
768                });
769            }
770        }
771    }
772    refs
773}
774
775test_support_visibility! {
776fn assign_ordinals(
777    ast_nodes: &[AstPreorderNode],
778    lines: &super::LineIndex,
779    symbols: &mut [BlobSymbol],
780    imports: &mut [BlobImport],
781    refs: &mut [BlobRef],
782) {
783    let ranges = ast_nodes
784        .iter()
785        .map(|n| (n.byte_start, n.byte_end))
786        .collect::<Vec<_>>();
787    let queries = symbols
788        .iter()
789        .map(|symbol| {
790            let start = lines.inclusive_byte_offset(symbol.start_line, symbol.start_col);
791            let end = lines
792                .inclusive_byte_offset(symbol.end_line, symbol.end_col)
793                .max(start);
794            (start, end)
795        })
796        .chain(imports.iter().map(|i| (i.byte_start, i.byte_end)))
797        .chain(refs.iter().map(|r| (r.byte_start, r.byte_end)))
798        .collect::<Vec<_>>();
799    let ordinals =
800        extraction_index::range_minima(&ranges, &queries, extraction_index::LookupWork::Ordinal);
801    for (ordinal, target) in ordinals.into_iter().zip(
802        symbols
803            .iter_mut()
804            .map(|s| &mut s.ordinal)
805            .chain(imports.iter_mut().map(|i| &mut i.ordinal))
806            .chain(refs.iter_mut().map(|r| &mut r.ordinal)),
807    ) {
808        *target = ordinal.map(|i| ast_nodes[i].ordinal).unwrap_or(0);
809    }
810    sort_blob_symbols(symbols);
811    imports.sort_by(|left, right| {
812        (left.ordinal, left.module_path.as_str()).cmp(&(right.ordinal, right.module_path.as_str()))
813    });
814}
815}
816
817fn symbol_kind_name(kind: &SymbolKind) -> &'static str {
818    match kind {
819        SymbolKind::Function => "function",
820        SymbolKind::Kernel => "kernel",
821        SymbolKind::Class => "class",
822        SymbolKind::Method => "method",
823        SymbolKind::Struct => "struct",
824        SymbolKind::Interface => "interface",
825        SymbolKind::Enum => "enum",
826        SymbolKind::TypeAlias => "type_alias",
827        SymbolKind::Variable => "variable",
828        SymbolKind::Heading => "heading",
829        SymbolKind::FileSummary => "file_summary",
830    }
831}
832
833fn unqualified_symbol_name(scoped_name: &str) -> &str {
834    if scoped_name == TOP_LEVEL_SYMBOL {
835        return scoped_name;
836    }
837    scoped_name.rsplit("::").next().unwrap_or(scoped_name)
838}
839
840test_support_visibility! {
841fn structural_ref(raw: super::RawRef) -> BlobRef {
842    BlobRef {
843        ordinal: 0,
844        kind: if raw.kind == "export_alias" {
845            BlobRefKind::ExportAlias
846        } else {
847            BlobRefKind::Reexport
848        },
849        caller_symbol: raw.caller_symbol,
850        short_name: raw.short_name,
851        full_ref: raw.full_ref,
852        module_path: raw.module_path,
853        line: raw.line,
854        byte_start: raw.byte_start,
855        byte_end: raw.byte_end,
856        path_override: None,
857        local_name: raw.local_name,
858        requested_name: raw.requested_name,
859        namespace_alias: raw.namespace_alias,
860        wildcard: raw.wildcard,
861        import_kind: raw.import_kind,
862    }
863}
864}
865
866fn bound_name(name: &str, path: &str) -> String {
867    name.replace(
868        "<default:__callgraph_blob__>",
869        &format!(
870            "<default:{}>",
871            Path::new(path)
872                .file_name()
873                .unwrap_or_default()
874                .to_string_lossy()
875        ),
876    )
877}
878
879impl ParseBlob {
880    /// Bind Python dispatch hints to the same keys as their call references.
881    /// Nested bodies retain each enclosing caller, so their hints must use
882    /// caller-specific keys rather than the shared syntax ordinal.
883    pub fn iter_bound_dispatch_sites(&self) -> impl Iterator<Item = dispatch::SiteHint> + '_ {
884        let keys = (self.language == "python").then(|| {
885            self.refs
886                .iter()
887                .zip(self.reference_keys())
888                .filter(|(reference, _)| reference.kind == BlobRefKind::Call)
889                .map(|(reference, key)| {
890                    ((reference.ordinal, reference.caller_symbol.as_deref()), key)
891                })
892                .collect::<HashMap<_, _>>()
893        });
894        self.dispatch.sites.iter().cloned().map(move |mut site| {
895            if let Some(key) = keys
896                .as_ref()
897                .and_then(|keys| keys.get(&(site.ordinal, site.caller.as_deref())))
898            {
899                site.ordinal = *key;
900            }
901            site
902        })
903    }
904
905    pub fn bound_dispatch_sites(&self) -> Vec<dispatch::SiteHint> {
906        self.iter_bound_dispatch_sites().collect()
907    }
908
909    /// AST ordinals stay intact in the blob. When several facts occupy one
910    /// ordinal, their bound keys must also distinguish source span and caller.
911    /// Singleton references retain their historical key; collision suffixes
912    /// hash only stable, path-free source facts, never map order or rowids.
913    pub fn reference_keys(&self) -> Vec<u32> {
914        let mut groups: BTreeMap<u32, Vec<usize>> = BTreeMap::new();
915        for (position, reference) in self.refs.iter().enumerate() {
916            groups.entry(reference.ordinal).or_default().push(position);
917        }
918        let mut used = groups.keys().copied().collect::<BTreeSet<_>>();
919        let mut keys = self.refs.iter().map(|r| r.ordinal).collect::<Vec<_>>();
920        for (ordinal, positions) in groups {
921            if positions.len() < 2 {
922                continue;
923            }
924            let calls = positions
925                .iter()
926                .copied()
927                .filter(|p| self.refs[*p].kind == BlobRefKind::Call)
928                .collect::<Vec<_>>();
929            let primary = if calls.len() == 1 {
930                calls[0]
931            } else {
932                positions[0]
933            };
934            for position in positions {
935                if position == primary {
936                    continue;
937                }
938                let reference = &self.refs[position];
939                let bytes = serde_json::to_vec(&(
940                    "bound-reference-v2",
941                    ordinal,
942                    reference.kind,
943                    reference.byte_start,
944                    reference.byte_end,
945                    &reference.caller_symbol,
946                    &reference.full_ref,
947                    &reference.module_path,
948                    &reference.local_name,
949                    &reference.requested_name,
950                ))
951                .expect("source facts serialize");
952                let hash = blake3::hash(&bytes);
953                let mut key =
954                    u32::from_le_bytes(hash.as_bytes()[..4].try_into().expect("four hash bytes"));
955                while !used.insert(key) {
956                    key = key.wrapping_add(1);
957                }
958                keys[position] = key;
959            }
960        }
961        keys
962    }
963
964    pub(super) fn file_data(&self, path: &str) -> Result<FileCallData, ManifestJoinError> {
965        let lang = language_id(&self.language)
966            .ok_or_else(|| ManifestJoinError::UnsupportedLanguage(self.language.clone()))?;
967        let mut calls_by_symbol: HashMap<String, Vec<callgraph::CallSite>> = HashMap::new();
968        let mut value_refs_by_symbol: HashMap<String, Vec<callgraph::CallSite>> = HashMap::new();
969        let mut macro_body_calls_by_macro: HashMap<String, Vec<callgraph::CallSite>> =
970            HashMap::new();
971        let mut macro_mentions_by_symbol: HashMap<String, Vec<callgraph::CallSite>> =
972            HashMap::new();
973        for raw in &self.refs {
974            let map = match raw.kind {
975                BlobRefKind::Call
976                    if raw
977                        .caller_symbol
978                        .as_deref()
979                        .is_some_and(|s| s.ends_with('!')) =>
980                {
981                    &mut macro_body_calls_by_macro
982                }
983                BlobRefKind::Call | BlobRefKind::Construction => &mut calls_by_symbol,
984                BlobRefKind::ValueRef | BlobRefKind::CallbackRef => &mut value_refs_by_symbol,
985                BlobRefKind::MacroMention => &mut macro_mentions_by_symbol,
986                _ => continue,
987            };
988            let Some(caller) = &raw.caller_symbol else {
989                continue;
990            };
991            map.entry(bound_name(caller, path))
992                .or_default()
993                .push(callgraph::CallSite {
994                    kind: match raw.kind {
995                        BlobRefKind::Construction => callgraph::CallSiteKind::Construction,
996                        BlobRefKind::CallbackRef => callgraph::CallSiteKind::CallbackReference,
997                        _ => callgraph::CallSiteKind::Call,
998                    },
999                    callee_name: raw.short_name.clone().unwrap_or_default(),
1000                    full_callee: raw.full_ref.clone().unwrap_or_default(),
1001                    line: raw.line,
1002                    byte_start: raw.byte_start,
1003                    byte_end: raw.byte_end,
1004                });
1005        }
1006        for symbol in &self.callable_symbols {
1007            calls_by_symbol.entry(bound_name(symbol, path)).or_default();
1008        }
1009        let mut symbol_metadata = HashMap::new();
1010        for symbol in &self.symbols {
1011            let kind = match symbol.kind.as_str() {
1012                "function" => SymbolKind::Function,
1013                "method" => SymbolKind::Method,
1014                "class" => SymbolKind::Class,
1015                "struct" => SymbolKind::Struct,
1016                "interface" => SymbolKind::Interface,
1017                "enum" => SymbolKind::Enum,
1018                "type_alias" => SymbolKind::TypeAlias,
1019                "heading" => SymbolKind::Heading,
1020                "file_summary" => SymbolKind::FileSummary,
1021                _ => SymbolKind::Variable,
1022            };
1023            symbol_metadata.insert(
1024                bound_name(&symbol.scoped_name, path),
1025                SymbolMeta {
1026                    is_test: symbol.is_test,
1027                    kind,
1028                    exported: symbol.exported,
1029                    signature: symbol.signature.clone(),
1030                    line: symbol.start_line + 1,
1031                    range: crate::symbols::Range {
1032                        start_line: symbol.start_line,
1033                        start_col: symbol.start_col,
1034                        end_line: symbol.end_line,
1035                        end_col: symbol.end_col,
1036                    },
1037                    entry_point_attribute: self
1038                        .entry_point_symbols
1039                        .contains(&symbol.scoped_name)
1040                        .then(|| "initializer_or_attribute".to_string()),
1041                    program_start: symbol.program_start,
1042                },
1043            );
1044        }
1045        let imports = self
1046            .imports
1047            .iter()
1048            .map(|import| ImportStatement {
1049                module_path: import.module_path.clone(),
1050                names: import.names.clone(),
1051                default_import: import.default_import.clone(),
1052                namespace_import: import.namespace_import.clone(),
1053                kind: if import.type_only {
1054                    ImportKind::Type
1055                } else if import.side_effect {
1056                    ImportKind::SideEffect
1057                } else {
1058                    ImportKind::Value
1059                },
1060                group: ImportGroup::Internal,
1061                byte_range: import.byte_start..import.byte_end,
1062                raw_text: import.raw_text.clone(),
1063                form: if lang == LangId::Rust {
1064                    ImportForm::RustUse {
1065                        visibility: import.default_import.clone(),
1066                        named: import.names.clone(),
1067                    }
1068                } else {
1069                    ImportForm::Es {
1070                        default_import: import.default_import.clone(),
1071                        namespace_import: import.namespace_import.clone(),
1072                        named: import.names.clone(),
1073                        type_only: import.type_only,
1074                        side_effect: import.side_effect,
1075                        attribute_clause: None,
1076                        attribute_type: None,
1077                    }
1078                },
1079            })
1080            .collect::<Vec<_>>();
1081        Ok(FileCallData {
1082            calls_by_symbol,
1083            value_refs_by_symbol,
1084            macro_body_calls_by_macro,
1085            macro_mentions_by_symbol,
1086            symbol_metadata,
1087            exported_symbols: self
1088                .exported_symbols
1089                .iter()
1090                .map(|s| bound_name(s, path))
1091                .collect(),
1092            default_export_symbol: self
1093                .default_export_symbol
1094                .as_ref()
1095                .map(|s| bound_name(s, path)),
1096            import_block: ImportBlock {
1097                imports,
1098                byte_range: None,
1099            },
1100            python_bindings: self.python_bindings.clone(),
1101            lang,
1102        })
1103    }
1104
1105    fn bind_with_dependencies(
1106        &self,
1107        path: &str,
1108        facts: &FactPaths<'_>,
1109        cached: Option<&BTreeMap<u32, BTreeSet<String>>>,
1110    ) -> Result<super::FileExtract, ManifestJoinError> {
1111        let data = self.file_data(path)?;
1112        // A node id names the file, the scoped name, and which symbol of that
1113        // name it is (overloads share one). It leaves out the AST position, so
1114        // an edit that only moves code keeps every id, and resolutions that
1115        // recorded a node answer stay valid.
1116        let mut occurrences = HashMap::<String, usize>::new();
1117        let nodes = self
1118            .symbols
1119            .iter()
1120            .map(|symbol| {
1121                let scoped_name = bound_name(&symbol.scoped_name, path);
1122                let occurrence = occurrences.entry(scoped_name.clone()).or_default();
1123                let id = format!("{path}:{occurrence}:{scoped_name}");
1124                *occurrence += 1;
1125                super::NodeRecord {
1126                    id,
1127                    name: bound_name(&symbol.name, path),
1128                    scoped_name,
1129                    kind: symbol.kind.clone(),
1130                }
1131            })
1132            .collect::<Vec<_>>();
1133        let abs = facts.root.join(path);
1134        let mut raw_refs = Vec::new();
1135        // A module path's dependencies are computed once per file and reused
1136        // by every reference that names it (imports also produce re-export
1137        // rows). The result is a function of the file, the module path and
1138        // the checkout, and every read the computation makes is recorded for
1139        // this file the first time, so a reuse records nothing new. Each
1140        // computation keeps its own memo: a memo shared between module paths
1141        // returns cached targets without the candidate paths the dependency
1142        // set lists.
1143        let mut module_dependencies = HashMap::new();
1144        for (position, (raw, reference_key)) in
1145            self.refs.iter().zip(self.reference_keys()).enumerate()
1146        {
1147            let position = u32::try_from(position).expect("reference vector fits u32");
1148            let dependencies = if let Some(dependencies) =
1149                cached.and_then(|cache| cache.get(&position))
1150            {
1151                dependencies.clone()
1152            } else if raw.kind == BlobRefKind::Module {
1153                super::rust_external_module_target(
1154                    &abs,
1155                    raw.path_override.as_deref(),
1156                    raw.module_path.as_deref().unwrap_or_default(),
1157                    facts,
1158                )
1159                .and_then(|p| facts.canonical(&p))
1160                .map(|p| super::relative_path(facts.root, &p))
1161                .into_iter()
1162                .collect()
1163            } else if let Some(module) = &raw.module_path {
1164                module_dependencies
1165                    .entry(module.clone())
1166                    .or_insert_with(|| super::module_dependencies(facts.root, &abs, module, facts))
1167                    .clone()
1168            } else {
1169                BTreeSet::new()
1170            };
1171            let caller_symbol = raw
1172                .caller_symbol
1173                .as_ref()
1174                .map(|name| bound_name(name, path));
1175            raw_refs.push(super::RawRef {
1176                ref_id: format!("{path}:{reference_key}:{:?}", raw.kind),
1177                caller_symbol,
1178                caller_file: path.to_string(),
1179                kind: match raw.kind {
1180                    BlobRefKind::Call
1181                        if raw
1182                            .caller_symbol
1183                            .as_deref()
1184                            .is_some_and(|s| s.ends_with('!')) =>
1185                    {
1186                        super::MACRO_BODY_CALL_REF_KIND
1187                    }
1188                    BlobRefKind::Call => "call",
1189                    BlobRefKind::Construction => "construction",
1190                    BlobRefKind::CallbackRef => "callback_ref",
1191                    BlobRefKind::ValueRef => "value_ref",
1192                    BlobRefKind::Import => "import",
1193                    BlobRefKind::Module => "module",
1194                    BlobRefKind::Reexport => "reexport",
1195                    BlobRefKind::ExportAlias => "export_alias",
1196                    BlobRefKind::MacroMention => super::MACRO_MENTION_REF_KIND,
1197                }
1198                .to_string(),
1199                short_name: raw.short_name.clone(),
1200                full_ref: raw.full_ref.clone(),
1201                module_path: raw.module_path.clone(),
1202                import_kind: raw.import_kind.clone(),
1203                local_name: raw.local_name.clone(),
1204                requested_name: raw.requested_name.clone(),
1205                namespace_alias: raw.namespace_alias.clone(),
1206                wildcard: raw.wildcard,
1207                line: raw.line,
1208                byte_start: raw.byte_start,
1209                byte_end: raw.byte_end,
1210                dependencies,
1211            });
1212        }
1213        Ok(super::FileExtract {
1214            rel_path: path.to_string(),
1215            lang: data.lang,
1216            data,
1217            nodes,
1218            raw_refs,
1219        })
1220    }
1221}
1222
1223/// The receiver type names of one file that method-call resolution may
1224/// look up through ordinary Rust path binding: declared types and their bases,
1225/// method owners and traits, field and return types, and each call site's
1226/// receiver with any field or return-value wrapper removed.
1227pub(super) fn dispatch_type_names(parse: &ParseBlob) -> BTreeSet<String> {
1228    let mut names = BTreeSet::new();
1229    for ty in &parse.dispatch.types {
1230        names.insert(ty.name.clone());
1231        names.extend(ty.bases.iter().cloned());
1232    }
1233    for method in &parse.dispatch.methods {
1234        names.insert(method.owner.clone());
1235        names.extend(method.trait_name.iter().cloned());
1236    }
1237    for field in &parse.dispatch.fields {
1238        let mut name = field.ty.as_str();
1239        while let Some((_, outer, inner)) = dispatch::smart_pointer::parts(name) {
1240            names.insert(outer.to_string());
1241            name = inner;
1242        }
1243        names.insert(name.to_string());
1244    }
1245    names.extend(parse.dispatch.returns.iter().map(|r| r.ty.clone()));
1246    for site in &parse.dispatch.sites {
1247        if let Some(receiver) = &site.receiver {
1248            // A self call in a macro template names its target already;
1249            // there is no type name to bind.
1250            if receiver.starts_with(dispatch::TEMPLATE_SELF_RECEIVER) {
1251                continue;
1252            }
1253            let mut name = receiver.as_str();
1254            while let Some(expression) = name.strip_prefix("@field:") {
1255                name = expression
1256                    .rsplit_once('|')
1257                    .map(|(base, _)| base)
1258                    .unwrap_or(expression);
1259            }
1260            names.insert(name.strip_prefix("@return:").unwrap_or(name).to_string());
1261        }
1262    }
1263    names
1264}
1265
1266/// Bind receiver names through ordinary language import resolution. Rust names
1267/// also retain lexical call contexts; different bindings remain ambiguous.
1268pub(super) fn resolve_dispatch_type_names<I: super::ResolverIndex>(
1269    index: &I,
1270    file: &str,
1271    parse: &ParseBlob,
1272    data: &FileCallData,
1273) -> BTreeMap<String, (String, String)> {
1274    if parse.language != "rust" {
1275        let mut targets = BTreeMap::new();
1276        for name in dispatch_type_names(parse) {
1277            if name.starts_with('@')
1278                || !parse.imports.iter().any(|import| {
1279                    !import.type_only
1280                        && (import.default_import.as_deref() == Some(&name)
1281                            || import
1282                                .names
1283                                .iter()
1284                                .any(|spec| crate::imports::specifier_local_name(spec) == name))
1285                })
1286            {
1287                continue;
1288            }
1289            if let Some((_, target_file, symbol)) =
1290                super::resolve_js_ts_target(index, file, &name, &name, data)
1291            {
1292                if super::ResolverIndex::node_for_symbol(index, &target_file, &symbol).is_some() {
1293                    targets.insert(name, (target_file, symbol));
1294                }
1295            }
1296        }
1297        if let Some(facts) = &parse.dispatch.static_facts {
1298            let candidates = facts.import_receivers().collect::<BTreeSet<_>>();
1299            for (name, module) in candidates {
1300                let Some(target) = index.module_target(file, module) else {
1301                    continue;
1302                };
1303                let requested = parse
1304                    .imports
1305                    .iter()
1306                    .filter(|import| import.module_path == module && !import.type_only)
1307                    .find_map(|import| {
1308                        if import.default_import.as_deref() == Some(name) {
1309                            Some("default")
1310                        } else {
1311                            import
1312                                .names
1313                                .iter()
1314                                .find(|spec| crate::imports::specifier_local_name(spec) == name)
1315                                .map(|spec| crate::imports::specifier_imported_name(spec))
1316                        }
1317                    });
1318                let bound = requested.and_then(|requested| {
1319                    super::resolve_exported_symbol(index, &target, requested, 0)
1320                });
1321                // A present module with no resolvable export is not an external package.
1322                targets.insert(
1323                    format!("{}{name}", dispatch::STATIC_IMPORT_PREFIX),
1324                    bound.unwrap_or((target, String::new())),
1325                );
1326            }
1327        }
1328        return targets;
1329    }
1330    let mut names = dispatch_type_names(parse);
1331    for import in &data.import_block.imports {
1332        names.extend(callgraph::rust_import_local_names(import));
1333    }
1334    let references = parse
1335        .refs
1336        .iter()
1337        .filter(|raw| matches!(raw.kind, BlobRefKind::Call | BlobRefKind::Construction))
1338        .map(|raw| (raw.ordinal, raw))
1339        .collect::<HashMap<_, _>>();
1340    // Path binding depends on the enclosing scope and the visible import prefix,
1341    // not on a call's identity. Resolve repeated uses in the same context once,
1342    // while retaining distinct inline modules, impl owners and import scopes.
1343    fn context_key<'a>(raw: &'a BlobRef, data: &FileCallData) -> (Option<(&'a str, bool)>, usize) {
1344        (
1345            raw.caller_symbol.as_deref().map(|caller| {
1346                (
1347                    caller.rsplit_once("::").map_or("", |(scope, _)| scope),
1348                    data.symbol_metadata
1349                        .get(caller)
1350                        .is_some_and(|meta| meta.kind == SymbolKind::Method),
1351                )
1352            }),
1353            data.import_block
1354                .imports
1355                .partition_point(|import| import.byte_range.start <= raw.byte_start),
1356        )
1357    }
1358    let mut contexts = HashMap::<_, BTreeMap<_, &BlobRef>>::new();
1359    for raw in references.values() {
1360        if let Some(name) = raw.full_ref.as_ref().filter(|name| names.contains(*name)) {
1361            contexts
1362                .entry(name.as_str())
1363                .or_default()
1364                .insert(context_key(raw, data), raw);
1365        }
1366    }
1367    for site in &parse.dispatch.sites {
1368        let (Some(receiver), Some(reference)) = (&site.receiver, references.get(&site.ordinal))
1369        else {
1370            continue;
1371        };
1372        let mut name = receiver.as_str();
1373        while let Some(expression) = name.strip_prefix("@field:") {
1374            name = expression
1375                .rsplit_once('|')
1376                .map(|(base, _)| base)
1377                .unwrap_or(expression);
1378        }
1379        name = name.strip_prefix("@return:").unwrap_or(name);
1380        contexts
1381            .entry(name)
1382            .or_default()
1383            .insert(context_key(reference, data), reference);
1384    }
1385    let mut targets = BTreeMap::new();
1386    for name in names {
1387        let short = name.rsplit("::").next().unwrap_or(&name);
1388        let sites = contexts
1389            .get(name.as_str())
1390            .map(|refs| refs.values().copied().map(Some).collect::<Vec<_>>())
1391            .unwrap_or_else(|| vec![None]);
1392        let mut bindings = BTreeSet::new();
1393        let mut incomplete = false;
1394        for site in sites {
1395            let raw = super::RawRef {
1396                ref_id: String::new(),
1397                caller_symbol: site.and_then(|raw| raw.caller_symbol.clone()),
1398                caller_file: file.to_string(),
1399                kind: "call".into(),
1400                short_name: Some(short.into()),
1401                full_ref: Some(name.clone()),
1402                module_path: None,
1403                import_kind: None,
1404                local_name: None,
1405                requested_name: None,
1406                namespace_alias: None,
1407                wildcard: false,
1408                line: site.map_or(0, |raw| raw.line),
1409                byte_start: site.map_or(0, |raw| raw.byte_start),
1410                byte_end: site.map_or(0, |raw| raw.byte_end),
1411                dependencies: BTreeSet::new(),
1412            };
1413            if let Some((_, target_file, symbol)) =
1414                super::resolve_rust_target(index, file, &name, short, data, &raw)
1415            {
1416                if super::ResolverIndex::node_for_symbol(index, &target_file, &symbol).is_some() {
1417                    bindings.insert((target_file, symbol));
1418                } else {
1419                    incomplete = true;
1420                }
1421            } else {
1422                incomplete = true;
1423            }
1424        }
1425        if !incomplete && bindings.len() == 1 {
1426            targets.insert(name, bindings.into_iter().next().unwrap());
1427        }
1428    }
1429    targets
1430}
1431
1432/// What resolving one Rust file's receiver type names consulted: every
1433/// resolver index answer it read, and every path whose presence it probed.
1434/// While each recorded answer is unchanged and no probed path was added or
1435/// removed, the file's receiver type targets are unchanged too, because the
1436/// file's own parse blob is the only other input.
1437#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
1438pub struct DispatchTypeTargetTrace {
1439    queries: Vec<(ViewSurfaceQuery, String)>,
1440    probes: BTreeSet<String>,
1441    /// Every checkout read with its answer, when answers were recorded.
1442    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1443    pub answers: super::fact_answers::FactAnswers,
1444}
1445
1446impl DispatchTypeTargetTrace {
1447    /// Paths and index domains whose change can alter a recorded answer or
1448    /// probe, so the owner knows which traces to check after a manifest diff.
1449    pub fn dependencies(&self) -> BTreeSet<String> {
1450        self.queries
1451            .iter()
1452            .flat_map(|(query, _)| query.dependencies())
1453            .chain(self.probes.iter().cloned())
1454            .collect()
1455    }
1456
1457    /// Every path whose presence this resolution probed.
1458    pub fn probes(&self) -> &BTreeSet<String> {
1459        &self.probes
1460    }
1461
1462    /// True when a path this resolution probed was added or removed.
1463    pub fn probes_any(&self, paths: &BTreeSet<String>) -> bool {
1464        !self.probes.is_disjoint(paths)
1465    }
1466
1467    /// True when every recorded answer that depends on one of `changed` is
1468    /// unchanged in `index`. An answer depending on nothing in `changed` reads
1469    /// only index entries that are the same as when it was recorded. Traces
1470    /// share queries (a crate's module parents, for one), so answers are kept
1471    /// in `answers` for the next trace checked against the same index. The
1472    /// memo owns its queries, so the traces checked need not outlive it.
1473    pub fn replays(
1474        &self,
1475        index: &impl super::ResolverIndex,
1476        changed: &BTreeSet<String>,
1477        answers: &mut BTreeMap<ViewSurfaceQuery, String>,
1478    ) -> bool {
1479        self.queries.iter().all(|(query, expected)| {
1480            !query.depends_on_any(changed) || answer_is(query, expected, index, answers)
1481        })
1482    }
1483
1484    /// True when every recorded surface answer is unchanged in `index`.
1485    pub fn all_answers_hold<'q>(
1486        &'q self,
1487        index: &impl super::ResolverIndex,
1488        answers: &mut BTreeMap<&'q ViewSurfaceQuery, String>,
1489    ) -> bool {
1490        self.queries.iter().all(|(query, expected)| {
1491            *answers.entry(query).or_insert_with(|| query.answer(index)) == *expected
1492        })
1493    }
1494}
1495
1496/// One Rust file's receiver type targets, keyed by the type name as written.
1497#[derive(Clone, Debug, Default, Eq, PartialEq)]
1498pub struct DispatchTypeTargets {
1499    pub targets: BTreeMap<String, (String, String)>,
1500    pub trace: DispatchTypeTargetTrace,
1501}
1502
1503/// Bound reference dependencies and resolver probes are generation-specific, unlike
1504/// parse blobs. The owner must invalidate these whenever a probed path changes.
1505#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
1506pub struct ViewBindingDependencies {
1507    // AST ordinals can collide for structural references. Vector positions are
1508    // unique and stable within the immutable caller blob used to validate reuse.
1509    pub references: BTreeMap<u32, BTreeSet<String>>,
1510    pub dependencies: BTreeSet<String>,
1511    #[serde(default)]
1512    pub consulted_facts: BTreeSet<(String, String)>,
1513    #[serde(default)]
1514    pub unattributed: bool,
1515    #[serde(default)]
1516    binding_facts: ConfigConsultations,
1517    #[serde(default)]
1518    resolution_facts: ConfigConsultations,
1519    binding_probes: BTreeSet<String>,
1520    resolved_dependencies: BTreeSet<String>,
1521    surface_queries: Vec<(ViewSurfaceQuery, String)>,
1522    /// Every checkout read binding made, with its answer, when answers were
1523    /// recorded (see [`super::fact_answers`]).
1524    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1525    pub binding_answers: super::fact_answers::FactAnswers,
1526    /// Likewise for resolution's reads beyond binding's.
1527    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1528    pub resolution_answers: super::fact_answers::FactAnswers,
1529    #[serde(skip)]
1530    surface: Option<ViewFileSurface>,
1531}
1532
1533impl ViewBindingDependencies {
1534    /// This binding without its bound file surface, which is not stored:
1535    /// binding computes it again from the file's own parse.
1536    pub fn without_surface(&self) -> Self {
1537        Self {
1538            surface: None,
1539            ..self.clone()
1540        }
1541    }
1542
1543    /// Drops the bound file surface in place, as a stored resolution never
1544    /// carries it. Resolution never reads it; whoever compares surfaces
1545    /// reads them from the bound file.
1546    pub fn clear_surface(&mut self) {
1547        self.surface = None;
1548    }
1549
1550    /// Whether binding gave this file the surface `other` recorded, so no
1551    /// other file's resolution can read a different answer from it.
1552    pub fn same_surface(&self, other: &Self) -> bool {
1553        self.surface == other.surface
1554    }
1555
1556    /// Keys for the answers this surface change can affect. External Rust
1557    /// module declarations have name-scoped readers, including failed
1558    /// lookups. Any other change, or one with no attributable name, keeps
1559    /// the whole-file invalidation used by every kind of surface reader.
1560    pub fn changed_surface_keys(&self, other: &Self, file: &str) -> BTreeSet<String> {
1561        if self.same_surface(other) {
1562            return BTreeSet::new();
1563        }
1564        if let (Some(before), Some(after)) = (&self.surface, &other.surface) {
1565            if before.language == "rust"
1566                && after.language == "rust"
1567                && before.without_declared_modules() == after.without_declared_modules()
1568            {
1569                let mut names = BTreeSet::new();
1570                for (old, new) in [
1571                    (&before.module_targets, &after.module_targets),
1572                    (
1573                        &before.declared_module_targets,
1574                        &after.declared_module_targets,
1575                    ),
1576                ] {
1577                    names.extend(
1578                        old.keys()
1579                            .chain(new.keys())
1580                            .filter(|name| old.get(*name) != new.get(*name))
1581                            .cloned(),
1582                    );
1583                }
1584                if !names.is_empty() {
1585                    return names
1586                        .iter()
1587                        .map(|name| rust_module_name_key(file, name))
1588                        .collect();
1589                }
1590            }
1591        }
1592        BTreeSet::from([file.to_string()])
1593    }
1594
1595    /// True when every surface query this resolution asked that depends on
1596    /// one of `changed` still has the answer it recorded in `index`. A query
1597    /// depending on nothing in `changed` reads only index entries that are
1598    /// unchanged. Answers are kept in `answers` for the next file replayed
1599    /// against the same index. The memo owns its queries, so the resolutions
1600    /// replayed need not outlive it.
1601    pub fn surface_replays(
1602        &self,
1603        index: &impl super::ResolverIndex,
1604        changed: &BTreeSet<String>,
1605        answers: &mut BTreeMap<ViewSurfaceQuery, String>,
1606    ) -> bool {
1607        self.surface_queries.iter().all(|(query, expected)| {
1608            !query.depends_on_any(changed) || answer_is(query, expected, index, answers)
1609        })
1610    }
1611
1612    /// Carries a resolution over from `old`, whose recorded answers replay,
1613    /// onto this file's new binding.
1614    pub fn reuse_resolution(&mut self, old: &Self) {
1615        self.resolved_dependencies = old.resolved_dependencies.clone();
1616        self.surface_queries = old.surface_queries.clone();
1617        self.resolution_facts = old.resolution_facts.clone();
1618        self.resolution_answers = old.resolution_answers.clone();
1619        finish_binding(self);
1620    }
1621
1622    /// The input keys binding recorded, before resolution added its own:
1623    /// what [`finish_binding`] gives a freshly bound file.
1624    pub fn binding_keys(&self) -> BTreeSet<String> {
1625        self.references
1626            .values()
1627            .flatten()
1628            .cloned()
1629            .chain(self.binding_probes.iter().cloned())
1630            .collect()
1631    }
1632
1633    /// Every checkout read binding and resolution made, with its answer.
1634    pub fn answers(
1635        &self,
1636    ) -> impl Iterator<
1637        Item = (
1638            &super::fact_answers::FactQuestion,
1639            &super::fact_answers::FactAnswer,
1640        ),
1641    > {
1642        self.binding_answers
1643            .iter()
1644            .chain(self.resolution_answers.iter())
1645    }
1646
1647    /// True when every surface query resolution asked still has its
1648    /// recorded answer in `index`, whatever changed.
1649    pub fn all_surface_answers_hold<'q>(
1650        &'q self,
1651        index: &impl super::ResolverIndex,
1652        answers: &mut BTreeMap<&'q ViewSurfaceQuery, String>,
1653    ) -> bool {
1654        self.surface_queries.iter().all(|(query, expected)| {
1655            *answers.entry(query).or_insert_with(|| query.answer(index)) == *expected
1656        })
1657    }
1658}
1659
1660/// Inputs that determine a reference's target, excluding call-site identity.
1661/// Rust qualified imports are visible only after their declaration; the count
1662/// of visible imports identifies that monotone prefix even across nested uses.
1663/// Python calls include the selected lexical target or an explicit unresolved binding.
1664#[derive(Hash, PartialEq, Eq)]
1665struct ViewResolutionBinding {
1666    kind: String,
1667    full_ref: Option<String>,
1668    short_name: Option<String>,
1669    visible_rust_imports: usize,
1670    // Distinguish no lexical binding from a binding that explicitly rejects resolution.
1671    python_binding: Option<Option<(String, String)>>,
1672}
1673
1674impl ViewResolutionBinding {
1675    fn new(raw: &super::RawRef, caller: &FileCallData) -> Self {
1676        Self {
1677            kind: raw.kind.clone(),
1678            full_ref: raw.full_ref.clone(),
1679            short_name: raw.short_name.clone(),
1680            python_binding: if caller.lang == LangId::Python {
1681                caller
1682                    .python_bindings
1683                    .binary_search_by_key(&(raw.byte_start, raw.byte_end), |binding| {
1684                        (binding.byte_start, binding.byte_end)
1685                    })
1686                    .ok()
1687                    .map(|position| caller.python_bindings[position].target.clone())
1688            } else {
1689                None
1690            },
1691            visible_rust_imports: if caller.lang == LangId::Rust {
1692                caller
1693                    .import_block
1694                    .imports
1695                    .partition_point(|import| import.byte_range.start <= raw.byte_start)
1696            } else {
1697                0
1698            },
1699        }
1700    }
1701}
1702
1703/// Compact, deterministic snapshot of one file's resolver index. It deliberately
1704/// excludes source, AST nodes, and call sites: only callers actually resolved need
1705/// those payloads. Membership probes invalidate module/reexport targets along with
1706/// bindings; source changes invalidate the snapshot through the manifest diff.
1707#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
1708struct ViewFileSurface {
1709    language: String,
1710    exports: BTreeSet<String>,
1711    default_export: Option<String>,
1712    export_aliases: BTreeMap<String, String>,
1713    node_by_scoped: BTreeMap<String, String>,
1714    node_by_bare: BTreeMap<String, String>,
1715    node_kind_by_id: BTreeMap<String, String>,
1716    module_targets: BTreeMap<String, Option<String>>,
1717    declared_module_targets: BTreeMap<String, Option<String>>,
1718    macro_use_module_targets: BTreeSet<String>,
1719    reexports: Vec<(Option<String>, BTreeMap<String, String>, bool)>,
1720}
1721
1722impl ViewFileSurface {
1723    /// The part answered by queries other than module-target lookups. Keep
1724    /// nodes, exports, macro-use and reexport state: changing any of them
1725    /// requires whole-file invalidation, not just a module-name key.
1726    fn without_declared_modules(&self) -> Self {
1727        let mut rest = self.clone();
1728        rest.module_targets
1729            .retain(|name, _| !self.declared_module_targets.contains_key(name));
1730        rest.declared_module_targets.clear();
1731        rest
1732    }
1733
1734    fn capture(language: &str, index: &super::DbFileIndex) -> Self {
1735        Self {
1736            language: language.into(),
1737            exports: index.exports.iter().cloned().collect(),
1738            default_export: index.default_export.clone(),
1739            export_aliases: index.export_aliases.clone().into_iter().collect(),
1740            node_by_scoped: index.node_by_scoped.clone().into_iter().collect(),
1741            node_by_bare: index.node_by_bare.clone().into_iter().collect(),
1742            node_kind_by_id: index.node_kind_by_id.clone().into_iter().collect(),
1743            module_targets: index.module_targets.clone().into_iter().collect(),
1744            declared_module_targets: index.declared_module_targets.clone().into_iter().collect(),
1745            macro_use_module_targets: index.macro_use_module_targets.clone(),
1746            reexports: index
1747                .reexports
1748                .iter()
1749                .map(|r| {
1750                    (
1751                        r.target_file.clone(),
1752                        r.named.clone().into_iter().collect(),
1753                        r.wildcard,
1754                    )
1755                })
1756                .collect(),
1757        }
1758    }
1759}
1760
1761/// Configuration files read by the manifest resolver's workspace/package and
1762/// tsconfig lookup (callgraph.rs), and Rust crate lookup (callgraph_store).
1763/// Directory discovery uses a compact membership domain for these names. Their
1764/// content changes invalidate only callers that consulted changed fields.
1765pub fn view_resolution_config(path: &[u8]) -> bool {
1766    matches!(
1767        path.rsplit(|byte| *byte == b'/').next(),
1768        Some(
1769            b"package.json" | b"tsconfig.json" | b"pnpm-workspace.yaml" | b"Cargo.toml" | b"go.mod"
1770        )
1771    )
1772}
1773
1774test_support_visibility! {
1775/// Field identities are generation-owned. Raw-read paths are transient validation
1776/// evidence, cleared after classifying a caller so memo-hit timing is not persisted.
1777#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
1778struct ConfigConsultations {
1779    facts: BTreeSet<(String, String)>,
1780    reads: BTreeSet<String>,
1781    unattributed: bool,
1782}
1783}
1784impl ConfigConsultations {
1785    fn extend(&mut self, other: &Self) {
1786        self.facts.extend(other.facts.iter().cloned());
1787        self.reads.extend(other.reads.iter().cloned());
1788        self.unattributed |= other.unattributed;
1789    }
1790    test_support_visibility! {
1791    fn unattributed(&self) -> bool {
1792            self.unattributed
1793                || self
1794                    .reads
1795                    .iter()
1796                    .any(|path| !self.facts.iter().any(|(input, _)| input == path))
1797        }
1798
1799    }
1800}
1801
1802#[derive(Clone, Default)]
1803struct ConsultationTrace {
1804    config: ConfigConsultations,
1805    probes: BTreeSet<String>,
1806    answers: super::fact_answers::FactAnswers,
1807}
1808type ConsultationMemoKey = (std::path::PathBuf, String, String);
1809
1810/// Memo answers and their provenance belong to one immutable manifest join.
1811/// Replaying provenance on hits keeps missing candidates and facts attributable.
1812pub struct ViewBindingFacts<'a> {
1813    inner: Rc<dyn ProjectFacts + 'a>,
1814    probes: std::cell::RefCell<BTreeSet<String>>,
1815    #[cfg(any(test, feature = "test-support"))]
1816    pub consultations: std::cell::RefCell<ConfigConsultations>,
1817    #[cfg(not(any(test, feature = "test-support")))]
1818    consultations: std::cell::RefCell<ConfigConsultations>,
1819    memo_stack: std::cell::RefCell<Vec<(ConsultationMemoKey, ConsultationTrace)>>,
1820    memo_traces: std::cell::RefCell<BTreeMap<ConsultationMemoKey, ConsultationTrace>>,
1821    workspace_packages:
1822        std::cell::RefCell<BTreeMap<(std::path::PathBuf, String), Option<std::path::PathBuf>>>,
1823    workspace_members:
1824        std::cell::RefCell<BTreeMap<std::path::PathBuf, Arc<Vec<std::path::PathBuf>>>>,
1825    canonical_cache: std::cell::RefCell<HashMap<Vec<u8>, Option<Vec<u8>>>>,
1826    file_cache: std::cell::RefCell<HashMap<Vec<u8>, bool>>,
1827    config_cache: std::cell::RefCell<HashMap<Vec<u8>, Option<Arc<[u8]>>>>,
1828    directory_cache: std::cell::RefCell<HashMap<Vec<u8>, Vec<super::facts::DirEntry>>>,
1829    /// Nonzero while a repository-wide structure is built: its reads are
1830    /// not the caller's inputs.
1831    paused: std::cell::Cell<u32>,
1832    /// Whether every read is also kept as a typed question with its answer
1833    /// (see [`super::fact_answers`]).
1834    typed: bool,
1835    answers: std::cell::RefCell<super::fact_answers::FactAnswers>,
1836    /// Every answer this recorder has computed. The checkout does not
1837    /// change while a recorder lives, so a read asked again, by any file,
1838    /// reuses its answer rather than reading (or parsing a config file)
1839    /// again.
1840    answer_cache: std::cell::RefCell<
1841        HashMap<super::fact_answers::FactQuestion, super::fact_answers::FactAnswer>,
1842    >,
1843}
1844
1845impl<'a> ViewBindingFacts<'a> {
1846    pub fn new(inner: Rc<dyn ProjectFacts + 'a>) -> Self {
1847        Self {
1848            inner,
1849            probes: Default::default(),
1850            consultations: Default::default(),
1851            memo_stack: Default::default(),
1852            memo_traces: Default::default(),
1853            workspace_packages: Default::default(),
1854            workspace_members: Default::default(),
1855            canonical_cache: Default::default(),
1856            file_cache: Default::default(),
1857            config_cache: Default::default(),
1858            directory_cache: Default::default(),
1859            paused: Default::default(),
1860            typed: false,
1861            answers: Default::default(),
1862            answer_cache: Default::default(),
1863        }
1864    }
1865
1866    /// Like [`Self::new`], and also keeps every read as a typed question
1867    /// with its answer, which [`Self::take_answers`] hands over.
1868    pub fn typed(inner: Rc<dyn ProjectFacts + 'a>) -> Self {
1869        Self {
1870            typed: true,
1871            ..Self::new(inner)
1872        }
1873    }
1874
1875    /// The questions read since the last call, with their answers.
1876    pub fn take_answers(&self) -> super::fact_answers::FactAnswers {
1877        std::mem::take(&mut *self.answers.borrow_mut())
1878    }
1879
1880    fn answered(
1881        &self,
1882        question: super::fact_answers::FactQuestion,
1883        answer: impl FnOnce() -> super::fact_answers::FactAnswer,
1884    ) {
1885        if !self.typed || self.paused.get() > 0 {
1886            return;
1887        }
1888        let cached = self.answer_cache.borrow().get(&question).cloned();
1889        let answer = cached.unwrap_or_else(|| {
1890            let answer = answer();
1891            self.answer_cache
1892                .borrow_mut()
1893                .insert(question.clone(), answer.clone());
1894            answer
1895        });
1896        for (_, trace) in self.memo_stack.borrow_mut().iter_mut() {
1897            trace.answers.insert(question.clone(), answer.clone());
1898        }
1899        self.answers.borrow_mut().insert(question, answer);
1900    }
1901
1902    fn file_fact(&self, rel: &[u8]) -> bool {
1903        if let Some(value) = self.file_cache.borrow().get(rel) {
1904            return *value;
1905        }
1906        let value = self.inner.is_file(rel);
1907        self.file_cache.borrow_mut().insert(rel.to_vec(), value);
1908        value
1909    }
1910
1911    fn record(&self, path: &[u8]) {
1912        if self.paused.get() > 0 {
1913            return;
1914        }
1915        // Directory discovery may probe thousands of missing package manifests.
1916        // One membership domain rechecks those bindings on config add/remove;
1917        // individual config content changes use the field consultations instead.
1918        // A typed recorder (the data layer) also keeps every probe, found or
1919        // missing, as a question with its answer, so a config file added or
1920        // removed reaches exactly the files whose answer it changes; it keeps
1921        // a found config file as a path like any other.
1922        if !self.typed && view_resolution_config(path) {
1923            self.record(VIEW_CONFIG_MEMBERSHIP_DOMAIN.as_bytes());
1924            return;
1925        }
1926        if let Ok(path) = std::str::from_utf8(path) {
1927            let mut parts = Vec::new();
1928            for part in path.split('/') {
1929                match part {
1930                    "" | "." => {}
1931                    ".." => {
1932                        parts.pop();
1933                    }
1934                    _ => parts.push(part),
1935                }
1936            }
1937            let path = parts.join("/");
1938            self.probes.borrow_mut().insert(path.clone());
1939            for (_, trace) in self.memo_stack.borrow_mut().iter_mut() {
1940                trace.probes.insert(path.clone());
1941            }
1942        }
1943    }
1944
1945    test_support_visibility! {
1946    fn take_config(&self) -> ConfigConsultations {
1947            let mut result = std::mem::take(&mut *self.consultations.borrow_mut());
1948            result.unattributed = result.unattributed();
1949            result.reads.clear();
1950            result
1951        }
1952    }
1953
1954    fn config_event(&self, path: &[u8], name: Option<&str>) {
1955        if self.paused.get() > 0 {
1956            return;
1957        }
1958        let Ok(path) = std::str::from_utf8(path) else {
1959            self.consultations.borrow_mut().unattributed = true;
1960            return;
1961        };
1962        let mut event = ConfigConsultations::default();
1963        if let Some(name) = name {
1964            event.facts.insert((path.into(), name.into()));
1965        } else {
1966            event.reads.insert(path.into());
1967        }
1968        self.consultations.borrow_mut().extend(&event);
1969        for (_, trace) in self.memo_stack.borrow_mut().iter_mut() {
1970            trace.config.extend(&event);
1971        }
1972    }
1973
1974    fn take(&self) -> BTreeSet<String> {
1975        std::mem::take(&mut *self.probes.borrow_mut())
1976    }
1977    /// A configuration file's bytes, read once and cached.
1978    fn config_value(&self, rel: &[u8]) -> Option<Arc<[u8]>> {
1979        let cached = self.config_cache.borrow().get(rel).cloned();
1980        cached.unwrap_or_else(|| {
1981            let value = self.inner.config_bytes(rel);
1982            self.config_cache
1983                .borrow_mut()
1984                .insert(rel.to_vec(), value.clone());
1985            value
1986        })
1987    }
1988}
1989
1990impl ProjectFacts for ViewBindingFacts<'_> {
1991    fn records_config_facts(&self) -> bool {
1992        true
1993    }
1994    fn records_answers(&self) -> bool {
1995        self.typed
1996    }
1997    fn config_fact(&self, rel: &[u8], name: &str) {
1998        self.record(rel);
1999        if !self.typed && matches!(name, "workspaces" | "packages") {
2000            // The members a workspace list names depend on which package
2001            // manifests exist under its globs, not only on this field. A
2002            // typed recorder keys each package name a reader looked up
2003            // instead ([`js_package_key`]).
2004            self.record(VIEW_CONFIG_MEMBERSHIP_DOMAIN.as_bytes());
2005        }
2006        self.config_event(rel, Some(name));
2007        // The resolver records a field each time it uses one, though it reads
2008        // the file's bytes only the first time it parses it, so the field is
2009        // recorded with its value here, for every file that uses it.
2010        self.answered(
2011            super::fact_answers::FactQuestion::ConfigField(rel.to_vec(), name.to_string()),
2012            || {
2013                super::fact_answers::config_field_answer(
2014                    rel,
2015                    self.config_value(rel).as_deref(),
2016                    name,
2017                )
2018            },
2019        );
2020    }
2021    fn memo_start(&self, path: &Path, kind: &str, name: &str) {
2022        self.memo_stack.borrow_mut().push((
2023            (path.into(), kind.into(), name.into()),
2024            ConsultationTrace::default(),
2025        ));
2026    }
2027    fn memo_finish(&self, path: &Path, kind: &str, name: &str) {
2028        let (key, trace) = self
2029            .memo_stack
2030            .borrow_mut()
2031            .pop()
2032            .expect("balanced resolver memo recording");
2033        debug_assert_eq!(key, (path.into(), kind.into(), name.into()));
2034        self.memo_traces.borrow_mut().insert(key, trace);
2035    }
2036    fn record_domain(&self, key: &str) {
2037        self.record(key.as_bytes());
2038    }
2039    fn pause_recording(&self) {
2040        self.paused.set(self.paused.get() + 1);
2041    }
2042    fn resume_recording(&self) {
2043        self.paused.set(self.paused.get().saturating_sub(1));
2044    }
2045    fn memo_replay(&self, path: &Path, kind: &str, name: &str) {
2046        let traces = self.memo_traces.borrow();
2047        let Some(trace) = traces.get(&(path.into(), kind.into(), name.into())) else {
2048            self.consultations.borrow_mut().unattributed = true;
2049            return;
2050        };
2051        self.consultations.borrow_mut().extend(&trace.config);
2052        self.probes
2053            .borrow_mut()
2054            .extend(trace.probes.iter().cloned());
2055        for (_, parent) in self.memo_stack.borrow_mut().iter_mut() {
2056            parent.config.extend(&trace.config);
2057            parent.probes.extend(trace.probes.iter().cloned());
2058        }
2059        if self.typed && self.paused.get() == 0 {
2060            for (_, parent) in self.memo_stack.borrow_mut().iter_mut() {
2061                parent
2062                    .answers
2063                    .extend(trace.answers.iter().map(|(q, a)| (q.clone(), a.clone())));
2064            }
2065            self.answers
2066                .borrow_mut()
2067                .extend(trace.answers.iter().map(|(q, a)| (q.clone(), a.clone())));
2068        }
2069    }
2070    fn workspace_package(&self, root: &Path, name: &str) -> Option<Option<std::path::PathBuf>> {
2071        self.workspace_packages
2072            .borrow()
2073            .get(&(root.into(), name.into()))
2074            .cloned()
2075    }
2076    fn remember_workspace_package(
2077        &self,
2078        root: &Path,
2079        name: &str,
2080        value: Option<std::path::PathBuf>,
2081    ) {
2082        self.workspace_packages
2083            .borrow_mut()
2084            .insert((root.into(), name.into()), value);
2085    }
2086    fn workspace_members(&self, root: &Path) -> Option<Arc<Vec<std::path::PathBuf>>> {
2087        self.workspace_members.borrow().get(root).cloned()
2088    }
2089    fn remember_workspace_members(&self, root: &Path, value: Arc<Vec<std::path::PathBuf>>) {
2090        self.workspace_members
2091            .borrow_mut()
2092            .insert(root.into(), value);
2093    }
2094    fn is_file(&self, rel: &[u8]) -> bool {
2095        let is_file = self.file_fact(rel);
2096        if is_file {
2097            self.record(rel);
2098        }
2099        self.answered(
2100            super::fact_answers::FactQuestion::IsFile(rel.to_vec()),
2101            || super::fact_answers::FactAnswer::Bool(is_file),
2102        );
2103        is_file
2104    }
2105    fn is_dir(&self, rel: &[u8]) -> bool {
2106        let is_dir = self.inner.is_dir(rel);
2107        self.answered(
2108            super::fact_answers::FactQuestion::IsDir(rel.to_vec()),
2109            || super::fact_answers::FactAnswer::Bool(is_dir),
2110        );
2111        is_dir
2112    }
2113    fn config_bytes(&self, rel: &[u8]) -> Option<Arc<[u8]>> {
2114        self.consultations.borrow_mut().unattributed = true;
2115        for (_, trace) in self.memo_stack.borrow_mut().iter_mut() {
2116            trace.config.unattributed = true;
2117        }
2118        let value = self.attributed_config_bytes(rel);
2119        // Read without naming fields: the whole file is the input.
2120        self.answered(
2121            super::fact_answers::FactQuestion::Config(rel.to_vec()),
2122            || super::fact_answers::config_answer(value.as_deref()),
2123        );
2124        value
2125    }
2126    fn attributed_config_bytes(&self, rel: &[u8]) -> Option<Arc<[u8]>> {
2127        self.config_event(rel, None);
2128        self.record(rel);
2129        // The fields the resolver reads from these bytes are recorded, with
2130        // their values, as it uses them (`config_fact`).
2131        self.config_value(rel)
2132    }
2133    fn symlink_target(&self, rel: &[u8]) -> Option<&[u8]> {
2134        let target = self.inner.symlink_target(rel);
2135        self.answered(
2136            super::fact_answers::FactQuestion::Link(rel.to_vec()),
2137            || super::fact_answers::FactAnswer::Path(target.map(<[u8]>::to_vec)),
2138        );
2139        target
2140    }
2141    fn canonical(&self, rel: &[u8]) -> Option<Vec<u8>> {
2142        // FactPaths canonicalizes before testing existence, so misses must be
2143        // recorded here as well as in is_file (not only after canonicalization).
2144        let cached = self.canonical_cache.borrow().get(rel).cloned();
2145        let canonical = cached.unwrap_or_else(|| {
2146            let value = self.inner.canonical(rel);
2147            self.canonical_cache
2148                .borrow_mut()
2149                .insert(rel.to_vec(), value.clone());
2150            value
2151        });
2152        // Existing directory probes are workspace-discovery implementation detail.
2153        // Config add/remove rechecks that discovery through its membership domain;
2154        // source-file probes and misses remain caller-specific dependencies.
2155        if canonical.as_ref().is_none_or(|path| self.file_fact(path)) {
2156            self.record(rel);
2157        }
2158        self.answered(
2159            super::fact_answers::FactQuestion::Canonical(rel.to_vec()),
2160            || super::fact_answers::FactAnswer::Path(canonical.clone()),
2161        );
2162        canonical
2163    }
2164    fn list_dir(&self, rel: &[u8]) -> Vec<super::facts::DirEntry> {
2165        let cached = self.directory_cache.borrow().get(rel).cloned();
2166        let value = cached.unwrap_or_else(|| {
2167            let value = self.inner.list_dir(rel);
2168            self.directory_cache
2169                .borrow_mut()
2170                .insert(rel.to_vec(), value.clone());
2171            value
2172        });
2173        self.answered(
2174            super::fact_answers::FactQuestion::ListDir(rel.to_vec()),
2175            || super::fact_answers::listing_answer(&value),
2176        );
2177        value
2178    }
2179}
2180
2181/// Binds one file's parse against its checkout's path facts. Returns the
2182/// file's resolver surface, and its binding: which paths each reference's
2183/// binding probed, and the paths and configuration fields binding consulted.
2184/// With `cache`, reference dependencies come from that earlier binding of the
2185/// same parse instead of being recorded again.
2186pub fn bind_file(
2187    rel: &str,
2188    blob: &ParseBlob,
2189    facts: &ViewBindingFacts<'_>,
2190    cache: Option<&ViewBindingDependencies>,
2191) -> Result<(super::DbFileIndex, ViewBindingDependencies), ManifestJoinError> {
2192    let root = Path::new("/");
2193    let paths = FactPaths { root, facts };
2194    facts.take();
2195    facts.take_config();
2196    facts.take_answers();
2197    let extract = blob.bind_with_dependencies(rel, &paths, cache.map(|cache| &cache.references))?;
2198    let file_index = super::DbFileIndex::from_extract(root, &extract, &paths);
2199    let mut binding = cache.cloned().unwrap_or_default();
2200    binding.surface = Some(ViewFileSurface::capture(&blob.language, &file_index));
2201    if cache.is_none() {
2202        binding.references = blob
2203            .refs
2204            .iter()
2205            .zip(&extract.raw_refs)
2206            .enumerate()
2207            .map(|(position, (_, bound))| {
2208                (
2209                    u32::try_from(position).expect("reference vector fits u32"),
2210                    bound.dependencies.clone(),
2211                )
2212            })
2213            .collect();
2214        binding.binding_probes = facts.take();
2215        binding.binding_facts = facts.take_config();
2216        binding.binding_answers = facts.take_answers();
2217        binding.dependencies = binding.references.values().flatten().cloned().collect();
2218        binding
2219            .dependencies
2220            .extend(binding.binding_probes.iter().cloned());
2221    }
2222    Ok((file_index, binding))
2223}
2224
2225/// Resolves every reference of one caller against `index`, adding one row per
2226/// reference to `rows`. Records in `binding` the surface queries resolution
2227/// asked with their answers, the paths it consulted beyond binding's, and the
2228/// configuration fields it read. Returns how many distinct bindings it
2229/// resolved (references sharing a binding are resolved once).
2230#[expect(
2231    clippy::too_many_arguments,
2232    reason = "one caller's resolution needs every one of these inputs"
2233)]
2234pub fn resolve_file(
2235    caller: &str,
2236    key: &BlobKey,
2237    blob: &ParseBlob,
2238    binding: &mut ViewBindingDependencies,
2239    index: &super::ProjectIndex<'_>,
2240    facts: &ViewBindingFacts<'_>,
2241    mut resolution_order: Option<&mut Vec<CallerRefKey>>,
2242    rows: &mut BTreeSet<DerivedRow>,
2243) -> Result<usize, ManifestJoinError> {
2244    let root = Path::new("/");
2245    let paths = FactPaths { root, facts };
2246    let basis: BTreeSet<String> = binding
2247        .references
2248        .values()
2249        .flatten()
2250        .chain(binding.binding_probes.iter())
2251        .cloned()
2252        .collect();
2253    facts.take_answers();
2254    let extract = blob.bind_with_dependencies(caller, &paths, Some(&binding.references))?;
2255    binding.resolution_answers = facts.take_answers();
2256    let mut caller_work = blob
2257        .refs
2258        .iter()
2259        .zip(extract.raw_refs)
2260        .zip(blob.reference_keys())
2261        .map(|((raw, bound), reference_key)| {
2262            (
2263                CallerRefKey {
2264                    caller_blob_key: key.clone(),
2265                    ref_ordinal: reference_key,
2266                    caller_path: caller.as_bytes().to_vec(),
2267                },
2268                (raw.kind, bound),
2269            )
2270        })
2271        .collect::<Vec<_>>();
2272    caller_work.sort_by(|a, b| (&a.0, a.1 .0).cmp(&(&b.0, b.1 .0)));
2273    // Scoped and self calls can already have declaration-proven bindings.
2274    // Let dispatch refine those bindings instead of skipping them in advance.
2275    let associated_ordinals = blob
2276        .refs
2277        .iter()
2278        .filter(|reference| {
2279            blob.language == "rust"
2280                && reference.full_ref.as_deref().is_some_and(|name| {
2281                    dispatch::associated_reference(name) || name.starts_with("self.")
2282                })
2283        })
2284        .map(|reference| reference.ordinal)
2285        .collect::<BTreeSet<_>>();
2286    let receiver_ordinals = blob
2287        .dispatch
2288        .sites
2289        .iter()
2290        .filter(|site| !associated_ordinals.contains(&site.ordinal))
2291        .map(|s| s.ordinal)
2292        .collect::<BTreeSet<_>>();
2293    let caller_data = &extract.data;
2294    let surface_index = ViewSurfaceIndex::for_caller(index, caller, caller_data);
2295    let mut resolutions = HashMap::<ViewResolutionBinding, (Option<String>, Option<String>)>::new();
2296    let mut caller_queries = BTreeMap::new();
2297    for (key, (kind, raw)) in caller_work {
2298        let memo_key = ViewResolutionBinding::new(&raw, caller_data);
2299        // Dependencies belonging to a call site are not part of the memoized
2300        // target. Preserve them even when another reference resolved its binding.
2301        binding.resolved_dependencies.extend(
2302            raw.dependencies
2303                .iter()
2304                .filter(|dependency| !basis.contains(*dependency))
2305                .cloned(),
2306        );
2307        let (target_file, target_symbol) = if receiver_ordinals.contains(&key.ref_ordinal) {
2308            (None, None)
2309        } else {
2310            match resolutions.entry(memo_key) {
2311                std::collections::hash_map::Entry::Occupied(entry) => entry.get().clone(),
2312                std::collections::hash_map::Entry::Vacant(entry) => {
2313                    facts.take();
2314                    facts.take_config();
2315                    facts.take_answers();
2316                    let resolved = super::resolve_ref(raw, &surface_index)
2317                        .map_err(|error| ManifestJoinError::Parse(error.to_string()))?;
2318                    // The memo table is local to each caller. Extending the
2319                    // binding's facts once keeps its configuration dependencies
2320                    // associated with that caller even on cache hits.
2321                    binding.resolution_facts.extend(&facts.take_config());
2322                    binding.resolution_answers.extend(facts.take_answers());
2323                    caller_queries.extend(surface_index.take());
2324                    binding.resolved_dependencies.extend(
2325                        resolved
2326                            .dependencies
2327                            .into_iter()
2328                            .chain(facts.take())
2329                            .filter(|dependency| !basis.contains(dependency)),
2330                    );
2331                    entry
2332                        .insert((resolved.target_file, resolved.target_symbol))
2333                        .clone()
2334                }
2335            }
2336        };
2337        if let Some(order) = resolution_order.as_deref_mut() {
2338            order.push(key.clone());
2339        }
2340        rows.insert(DerivedRow {
2341            caller_blob_key: key.caller_blob_key,
2342            ref_ordinal: key.ref_ordinal,
2343            caller_path: key.caller_path,
2344            kind,
2345            status: if target_file.is_some() {
2346                ResolutionStatus::Resolved
2347            } else {
2348                ResolutionStatus::Unresolved
2349            },
2350            target_path: target_file.map(String::into_bytes),
2351            target_symbol,
2352        });
2353    }
2354    binding.surface_queries = caller_queries.into_iter().collect();
2355    Ok(resolutions.len())
2356}
2357
2358/// Fills a binding's summary fields once binding and resolution are done:
2359/// every configuration field it consulted, whether any configuration read
2360/// was opaque, and every path its answers depend on.
2361pub fn finish_binding(binding: &mut ViewBindingDependencies) {
2362    binding.consulted_facts = binding
2363        .binding_facts
2364        .facts
2365        .union(&binding.resolution_facts.facts)
2366        .cloned()
2367        .collect();
2368    binding.unattributed =
2369        binding.binding_facts.unattributed() || binding.resolution_facts.unattributed();
2370    binding.dependencies = binding
2371        .references
2372        .values()
2373        .flatten()
2374        .cloned()
2375        .chain(binding.binding_probes.iter().cloned())
2376        .chain(binding.resolved_dependencies.iter().cloned())
2377        .chain(
2378            binding
2379                .surface_queries
2380                .iter()
2381                .flat_map(|(query, _)| query.dependencies()),
2382        )
2383        .collect();
2384}
2385
2386/// The project files the type names of one Rust, TypeScript or JavaScript
2387/// file resolve to, for method-call resolution, with the surface queries and
2388/// path probes they consulted.
2389pub fn dispatch_type_targets_for(
2390    file: &str,
2391    blob: &ParseBlob,
2392    index: &super::ProjectIndex<'_>,
2393    facts: &ViewBindingFacts<'_>,
2394) -> Result<DispatchTypeTargets, ManifestJoinError> {
2395    // The caller data is the file's own parse; binding consults path facts
2396    // only for reference dependencies, which are not wanted here.
2397    let data = blob.file_data(file)?;
2398    facts.take();
2399    facts.take_config();
2400    facts.take_answers();
2401    let recording = ViewSurfaceIndex::reading_inner(index, &data);
2402    let targets = resolve_dispatch_type_names(&recording, file, blob, &data);
2403    let probes = facts.take();
2404    facts.take_config();
2405    Ok(DispatchTypeTargets {
2406        targets,
2407        trace: DispatchTypeTargetTrace {
2408            queries: recording.take().into_iter().collect(),
2409            probes,
2410            answers: facts.take_answers(),
2411        },
2412    })
2413}
2414
2415/// Consumer-specific export surface: record the answers the resolver actually
2416/// used, rather than invalidating every caller when an unrelated export changes.
2417/// Querying these answers against a new index is cheaper than walking references
2418/// and is sound only while the caller's immutable parse blob remains unchanged.
2419#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
2420pub enum ViewSurfaceQuery {
2421    Language(String),
2422    Module(String, String),
2423    MacroUse(String),
2424    Parent(String),
2425    Reexports(String),
2426    Node(String, String),
2427    Callable(String, String),
2428    Alias(String, String),
2429    Export(String, String),
2430    Default(String),
2431    Contains(String),
2432    Crate(String),
2433    CrateRoot(String),
2434    Inline(String, Vec<String>, String),
2435    /// The `.go` files of the package a Go caller looks a symbol up in: its own
2436    /// directory, or the directory of an imported module path.
2437    GoPackage(String, Option<String>),
2438}
2439
2440fn surface_value(value: &impl Serialize) -> String {
2441    blake3::hash(&serde_json::to_vec(value).expect("resolver surface serializes"))
2442        .to_hex()
2443        .to_string()
2444}
2445
2446fn reexport_surface(value: &[super::ReexportIndex]) -> String {
2447    surface_value(
2448        &value
2449            .iter()
2450            .map(|entry| {
2451                (
2452                    &entry.target_file,
2453                    entry.named.iter().collect::<BTreeMap<_, _>>(),
2454                    entry.wildcard,
2455                )
2456            })
2457            .collect::<Vec<_>>(),
2458    )
2459}
2460
2461/// Recorded by today's views for every config file a resolution found, and
2462/// by every JavaScript workspace member list; set when any config file is
2463/// added or removed.
2464pub const VIEW_CONFIG_MEMBERSHIP_DOMAIN: &str = "\0view:config-membership";
2465/// The prefix of the data layer's JavaScript workspace package keys
2466/// ([`js_package_key`]). The data layer keeps every other config probe as a
2467/// path and a recorded answer, so it does not use
2468/// [`VIEW_CONFIG_MEMBERSHIP_DOMAIN`].
2469pub const VIEW_JS_WORKSPACES_DOMAIN: &str = "\0view:js-workspaces";
2470
2471/// The key a reader records for looking up the package `name` among the
2472/// members of the JavaScript workspace at `root` (checkout-relative, `/`
2473/// separators), found or not. Finding it walks the workspace's member folders
2474/// and reads each member's `package.json` name; recording those reads in
2475/// every file with a bare import cost a monorepo about 1,300 recorded reads
2476/// per file. The key replaces them: a `package.json` or `pnpm-workspace.yaml`
2477/// added, removed or edited, or a symlink changed, sets the key of each name
2478/// whose resolved member changed, so only the files that looked that name up
2479/// are bound again.
2480pub fn js_package_key(root: &str, name: &str) -> String {
2481    format!("{VIEW_JS_WORKSPACES_DOMAIN}\0{root}\0{name}")
2482}
2483/// The key of what Rust files at `segments` under `src_prefix` contain, for
2484/// inline module lookups that consult those files. A Rust file added,
2485/// removed or edited sets the key of its own module path.
2486pub fn rust_module_key(src_prefix: &str, segments: &[String]) -> String {
2487    format!("\0view:rust-module:{src_prefix}:{}", segments.join("::"))
2488}
2489
2490/// [`rust_module_key`] for the Rust file at `path`: the key its surface
2491/// changes set.
2492pub fn rust_module_key_for_file(path: &str) -> String {
2493    rust_module_key(
2494        &super::rust_src_prefix(path),
2495        &super::rust_module_segments_for_rel(path),
2496    )
2497}
2498
2499/// One module-name lookup in its declaring file, including an absent name.
2500pub fn rust_module_name_key(file: &str, name: &str) -> String {
2501    format!("\0view:rust-module-name:{file}\0{name}")
2502}
2503/// Recorded by every Go package file listing. A listing reads the directory,
2504/// not the files in it, so a file added to the package is no recorded
2505/// dependency of the callers that listed it; the owner rechecks this domain
2506/// whenever a `.go` file is added or removed.
2507pub const VIEW_GO_PACKAGE_DOMAIN: &str = "\0view:go-package-files";
2508/// The Go module map: every `go.mod` and the module path it declares. A
2509/// reader records this one key instead of the map's inputs, so its recorded
2510/// inputs are the same whichever reader built the map, and an edit that
2511/// changes the map (a `go.mod` added, removed or rewritten) re-checks every
2512/// reader through the `GoPackage` answers they recorded.
2513pub const VIEW_GO_MODULES_DOMAIN: &str = "\0view:go-modules";
2514/// The Rust workspace's crate names and source folders, read from every
2515/// `Cargo.toml`. Recorded like [`VIEW_GO_MODULES_DOMAIN`]: one key for the
2516/// map, set by any `Cargo.toml` added, removed or rewritten, with the
2517/// answers each reader used kept as `Crate` queries. Today's views set this
2518/// key; the data layer sets [`rust_crate_key`] for each crate name whose
2519/// entry changed instead.
2520pub const VIEW_RUST_CRATES_DOMAIN: &str = "\0view:rust-crates";
2521
2522/// The key a reader records for looking up the workspace crate `name`, found
2523/// or not. A `Cargo.toml` edit that adds, removes, renames or moves a crate
2524/// then reaches only the files that looked that name up, instead of every
2525/// Rust file: adding a crate nothing imports rebinds nothing, and a file
2526/// whose `use` named a crate that did not exist yet is rebound when it
2527/// appears.
2528pub fn rust_crate_key(name: &str) -> String {
2529    format!("{VIEW_RUST_CRATES_DOMAIN}\0{name}")
2530}
2531
2532impl ViewSurfaceQuery {
2533    test_support_visibility! {
2534    fn dependencies(&self) -> Vec<String> {
2535            match self {
2536                Self::Module(file, name) => {
2537                    vec![file.clone(), rust_module_name_key(file, name)]
2538                }
2539                // Both crate keys: today's views set the map's key, the data
2540                // layer the looked-up name's.
2541                Self::Crate(name) => vec![
2542                    VIEW_CONFIG_MEMBERSHIP_DOMAIN.into(),
2543                    VIEW_RUST_CRATES_DOMAIN.into(),
2544                    rust_crate_key(name),
2545                ],
2546                // The nearest `Cargo.toml` above the file decides its crate:
2547                // today's views set the config domain when any is added or
2548                // removed, the data layer the path of each one that was.
2549                Self::CrateRoot(file) => {
2550                    let mut dependencies = vec![file.clone(), VIEW_CONFIG_MEMBERSHIP_DOMAIN.into()];
2551                    let mut directory = std::path::Path::new(file).parent();
2552                    while let Some(current) = directory {
2553                        dependencies.push(if current.as_os_str().is_empty() {
2554                            "Cargo.toml".to_string()
2555                        } else {
2556                            format!("{}/Cargo.toml", current.display())
2557                        });
2558                        directory = current.parent();
2559                    }
2560                    dependencies
2561                }
2562                // A file's parent changes only when a declaration naming it does;
2563                // the incremental update then sets this file's key.
2564                Self::Parent(file) => vec![file.clone()],
2565                // An inline lookup checks the files whose module path is a
2566                // proper prefix of the looked-up path, in the caller's source
2567                // folder. A file appearing at, leaving or changing one of those
2568                // paths sets that path's key.
2569                Self::Inline(file, segments, _) => {
2570                    let prefix = super::rust_src_prefix(file);
2571                    let mut dependencies = vec![file.clone()];
2572                    dependencies.extend(
2573                        (0..segments.len()).map(|len| rust_module_key(&prefix, &segments[..len])),
2574                    );
2575                    dependencies
2576                }
2577                // Which directory an import path names comes from the module map,
2578                // so a `go.mod` edit alone can change the answer.
2579                Self::GoPackage(..) => {
2580                    vec![VIEW_GO_PACKAGE_DOMAIN.into(), VIEW_GO_MODULES_DOMAIN.into()]
2581                }
2582                Self::Language(file)
2583                | Self::MacroUse(file)
2584                | Self::Reexports(file)
2585                | Self::Node(file, _)
2586                | Self::Callable(file, _)
2587                | Self::Alias(file, _)
2588                | Self::Export(file, _)
2589                | Self::Default(file)
2590                | Self::Contains(file) => vec![file.clone()],
2591            }
2592        }
2593    }
2594
2595    test_support_visibility! {
2596    /// Whether one of [`Self::dependencies`] is in `changed`, without
2597        /// building the list for the queries whose dependencies are their file
2598        /// and fixed domain keys: a replay asks this of every recorded query of
2599        /// every file it replays, most of them naming one file.
2600        fn depends_on_any(&self, changed: &BTreeSet<String>) -> bool {
2601            match self {
2602                Self::Module(file, name) => {
2603                    changed.contains(file) || changed.contains(&rust_module_name_key(file, name))
2604                }
2605                Self::GoPackage(..) => {
2606                    changed.contains(VIEW_GO_PACKAGE_DOMAIN) || changed.contains(VIEW_GO_MODULES_DOMAIN)
2607                }
2608                Self::Language(file)
2609                | Self::MacroUse(file)
2610                | Self::Parent(file)
2611                | Self::Reexports(file)
2612                | Self::Node(file, _)
2613                | Self::Callable(file, _)
2614                | Self::Alias(file, _)
2615                | Self::Export(file, _)
2616                | Self::Default(file)
2617                | Self::Contains(file) => changed.contains(file),
2618                Self::Crate(..) | Self::CrateRoot(..) | Self::Inline(..) => self
2619                    .dependencies()
2620                    .iter()
2621                    .any(|dependency| changed.contains(dependency)),
2622            }
2623        }
2624    }
2625
2626    fn answer(&self, index: &impl super::ResolverIndex) -> String {
2627        match self {
2628            Self::Language(file) => {
2629                surface_value(&index.lang_for(file).map(|lang| format!("{lang:?}")))
2630            }
2631            Self::Module(file, module) => surface_value(&index.module_target(file, module)),
2632            Self::MacroUse(file) => surface_value(&index.macro_use_modules(file)),
2633            Self::Parent(file) => surface_value(&index.module_parent(file)),
2634            Self::Reexports(file) => reexport_surface(&index.reexports_for(file)),
2635            Self::Node(file, symbol) => surface_value(&index.node_for_symbol(file, symbol)),
2636            Self::Callable(file, node) => surface_value(&index.node_is_callable(file, node)),
2637            Self::Alias(file, symbol) => surface_value(&index.export_alias(file, symbol)),
2638            Self::Export(file, symbol) => surface_value(&index.has_export(file, symbol)),
2639            Self::Default(file) => surface_value(&index.default_export(file)),
2640            Self::Contains(file) => surface_value(&index.contains_file(file)),
2641            Self::Crate(name) => surface_value(&index.crate_src_prefix(name)),
2642            Self::CrateRoot(file) => surface_value(&index.rust_crate_root_file(file)),
2643            Self::Inline(file, segments, symbol) => {
2644                surface_value(&index.inline_scoped_target(file, segments, symbol))
2645            }
2646            Self::GoPackage(file, module) => {
2647                surface_value(&index.go_package_files(file, module.as_deref()))
2648            }
2649        }
2650    }
2651}
2652
2653/// Whether `query`'s answer in `index` is `expected`, asking `index` once
2654/// per memo: the memo keeps a copy of each query it answers, made only the
2655/// first time.
2656fn answer_is(
2657    query: &ViewSurfaceQuery,
2658    expected: &str,
2659    index: &impl super::ResolverIndex,
2660    answers: &mut BTreeMap<ViewSurfaceQuery, String>,
2661) -> bool {
2662    if let Some(answer) = answers.get(query) {
2663        return answer == expected;
2664    }
2665    let answer = query.answer(index);
2666    let same = answer == expected;
2667    answers.insert(query.clone(), answer);
2668    same
2669}
2670
2671/// A resolver index over one file's resolution that records each surface
2672/// query it answers. The callers gather what every reference of the file
2673/// recorded into one set for the whole file, so a question already answered
2674/// for this file is not asked, or recorded, again. A large file asks the
2675/// same crate-root and module questions for every reference.
2676struct ViewSurfaceIndex<'a, I> {
2677    inner: &'a I,
2678    queries: std::cell::RefCell<BTreeMap<ViewSurfaceQuery, String>>,
2679    caller: Option<(&'a str, &'a FileCallData)>,
2680    crate_roots: std::cell::RefCell<HashMap<String, Option<String>>>,
2681    caller_modules: std::cell::RefCell<HashMap<String, Vec<String>>>,
2682    /// The file data whose `use` answers this index keeps: the data of the
2683    /// file being resolved, borrowed for this index's whole life, so no
2684    /// other value can share its address.
2685    alias_owner: Option<&'a FileCallData>,
2686    caller_aliases: std::cell::OnceCell<std::rc::Rc<[super::RustModuleAliases]>>,
2687}
2688
2689impl<'a, I> ViewSurfaceIndex<'a, I> {
2690    /// An index for resolving `caller`'s references, which reads its own
2691    /// caller data from `caller` rather than from `inner`.
2692    fn for_caller(inner: &'a I, caller: &'a str, data: &'a FileCallData) -> Self {
2693        Self::new(inner, Some((caller, data)), Some(data))
2694    }
2695
2696    /// An index that reads every file's caller data from `inner`, keeping
2697    /// the `use` answers of `aliases_of` (the file being resolved).
2698    fn reading_inner(inner: &'a I, aliases_of: &'a FileCallData) -> Self {
2699        Self::new(inner, None, Some(aliases_of))
2700    }
2701
2702    fn new(
2703        inner: &'a I,
2704        caller: Option<(&'a str, &'a FileCallData)>,
2705        alias_owner: Option<&'a FileCallData>,
2706    ) -> Self {
2707        Self {
2708            inner,
2709            queries: Default::default(),
2710            caller,
2711            crate_roots: Default::default(),
2712            caller_modules: Default::default(),
2713            alias_owner,
2714            caller_aliases: Default::default(),
2715        }
2716    }
2717
2718    /// Whether this index keeps answers. Tests that compare cached and
2719    /// uncached module lookups turn it off.
2720    fn keeps_answers() -> bool {
2721        #[cfg(any(test, feature = "test-support"))]
2722        if super::rust_module_work::disabled() {
2723            return false;
2724        }
2725        true
2726    }
2727}
2728
2729impl<I> ViewSurfaceIndex<'_, I> {
2730    fn record(&self, query: ViewSurfaceQuery, value: &impl Serialize) {
2731        self.queries
2732            .borrow_mut()
2733            .insert(query, surface_value(value));
2734    }
2735    fn take(&self) -> BTreeMap<ViewSurfaceQuery, String> {
2736        std::mem::take(&mut *self.queries.borrow_mut())
2737    }
2738}
2739
2740impl<I: super::ResolverIndex> super::ResolverIndex for ViewSurfaceIndex<'_, I> {
2741    fn luau_config(&self, file: &str) -> Option<Arc<[u8]>> {
2742        // ProjectFacts records configuration bytes and missing paths directly;
2743        // these are checkout inputs, not parsed symbol data.
2744        self.inner.luau_config(file)
2745    }
2746    fn macro_use_modules(&self, file: &str) -> Vec<String> {
2747        let value = self.inner.macro_use_modules(file);
2748        self.record(ViewSurfaceQuery::MacroUse(file.into()), &value);
2749        value
2750    }
2751    fn go_package_files(&self, caller_file: &str, module: Option<&str>) -> Vec<String> {
2752        let value = self.inner.go_package_files(caller_file, module);
2753        self.record(
2754            ViewSurfaceQuery::GoPackage(caller_file.into(), module.map(str::to_string)),
2755            &value,
2756        );
2757        value
2758    }
2759    fn caller_data(&self, file: &str) -> Option<&FileCallData> {
2760        // resolve_ref reads only its own caller data; changed callers never reuse
2761        // surface answers, so the immutable blob itself guards this input.
2762        self.caller
2763            .filter(|(caller, _)| *caller == file)
2764            .map(|(_, data)| data)
2765            .or_else(|| self.inner.caller_data(file))
2766    }
2767    fn local_symbol(&self, file: &str, data: &FileCallData, query: &str) -> Option<String> {
2768        // Local symbols come from the caller blob, not a consulted file surface.
2769        self.inner.local_symbol(file, data, query)
2770    }
2771    fn lang_for(&self, file: &str) -> Option<LangId> {
2772        let value = self.inner.lang_for(file);
2773        self.record(
2774            ViewSurfaceQuery::Language(file.into()),
2775            &value.map(|lang| format!("{lang:?}")),
2776        );
2777        value
2778    }
2779    fn module_target(&self, file: &str, module: &str) -> Option<String> {
2780        let value = self.inner.module_target(file, module);
2781        self.record(ViewSurfaceQuery::Module(file.into(), module.into()), &value);
2782        value
2783    }
2784    fn module_parent(&self, file: &str) -> Option<(String, String)> {
2785        let value = self.inner.module_parent(file);
2786        self.record(ViewSurfaceQuery::Parent(file.into()), &value);
2787        value
2788    }
2789    fn reexports_for(&self, file: &str) -> Vec<super::ReexportIndex> {
2790        let value = self.inner.reexports_for(file);
2791        self.queries.borrow_mut().insert(
2792            ViewSurfaceQuery::Reexports(file.into()),
2793            reexport_surface(&value),
2794        );
2795        value
2796    }
2797    fn node_for_symbol(&self, file: &str, symbol: &str) -> Option<String> {
2798        let value = self.inner.node_for_symbol(file, symbol);
2799        self.record(ViewSurfaceQuery::Node(file.into(), symbol.into()), &value);
2800        value
2801    }
2802    fn node_is_callable(&self, file: &str, node: &str) -> bool {
2803        let value = self.inner.node_is_callable(file, node);
2804        self.record(ViewSurfaceQuery::Callable(file.into(), node.into()), &value);
2805        value
2806    }
2807    fn export_alias(&self, file: &str, symbol: &str) -> Option<String> {
2808        let value = self.inner.export_alias(file, symbol);
2809        self.record(ViewSurfaceQuery::Alias(file.into(), symbol.into()), &value);
2810        value
2811    }
2812    fn has_export(&self, file: &str, symbol: &str) -> bool {
2813        let value = self.inner.has_export(file, symbol);
2814        self.record(ViewSurfaceQuery::Export(file.into(), symbol.into()), &value);
2815        value
2816    }
2817    fn default_export(&self, file: &str) -> Option<String> {
2818        let value = self.inner.default_export(file);
2819        self.record(ViewSurfaceQuery::Default(file.into()), &value);
2820        value
2821    }
2822    fn contains_file(&self, file: &str) -> bool {
2823        let value = self.inner.contains_file(file);
2824        self.record(ViewSurfaceQuery::Contains(file.into()), &value);
2825        value
2826    }
2827    fn crate_src_prefix(&self, name: &str) -> Option<String> {
2828        let value = self.inner.crate_src_prefix(name);
2829        self.record(ViewSurfaceQuery::Crate(name.into()), &value);
2830        value
2831    }
2832    fn rust_crate_root_file(&self, file: &str) -> Option<String> {
2833        if let Some(value) = self.crate_roots.borrow().get(file) {
2834            return value.clone();
2835        }
2836        let value = self.inner.rust_crate_root_file(file);
2837        self.record(ViewSurfaceQuery::CrateRoot(file.into()), &value);
2838        if Self::keeps_answers() {
2839            self.crate_roots
2840                .borrow_mut()
2841                .insert(file.to_string(), value.clone());
2842        }
2843        value
2844    }
2845    fn rust_caller_module_segments(&self, caller_file: &str) -> Vec<String> {
2846        if let Some(segments) = self.caller_modules.borrow().get(caller_file) {
2847            return segments.clone();
2848        }
2849        // Computed through this index, so the queries it asks are recorded.
2850        let segments = super::rust_caller_module_segments_uncached(self, caller_file);
2851        if Self::keeps_answers() {
2852            self.caller_modules
2853                .borrow_mut()
2854                .insert(caller_file.to_string(), segments.clone());
2855        }
2856        segments
2857    }
2858    fn rust_module_aliases(&self, data: &FileCallData) -> std::rc::Rc<[super::RustModuleAliases]> {
2859        // Kept only for the data this index borrows for its whole life
2860        // (`alias_owner`), so no other value can share its address.
2861        match self.alias_owner {
2862            Some(owner) if std::ptr::eq(owner, data) && Self::keeps_answers() => {
2863                std::rc::Rc::clone(
2864                    self.caller_aliases
2865                        .get_or_init(|| super::rust_module_aliases_of(data)),
2866                )
2867            }
2868            _ => super::rust_module_aliases_of(data),
2869        }
2870    }
2871    fn inline_scoped_target(
2872        &self,
2873        file: &str,
2874        segments: &[String],
2875        symbol: &str,
2876    ) -> Option<(String, String)> {
2877        let value = self.inner.inline_scoped_target(file, segments, symbol);
2878        self.record(
2879            ViewSurfaceQuery::Inline(file.into(), segments.to_vec(), symbol.into()),
2880            &value,
2881        );
2882        value
2883    }
2884}
2885
2886aft_store::heap_bytes_none!(BlobRefKind, ResolutionStatus);
2887aft_store::heap_bytes_of_fields!(ParseBlob {
2888    entry_point_symbols,
2889    dispatch,
2890    extractor_version,
2891    language,
2892    ast_nodes,
2893    symbols,
2894    default_export_symbol,
2895    exported_symbols,
2896    callable_symbols,
2897    imports,
2898    python_bindings,
2899    refs,
2900});
2901aft_store::heap_bytes_of_fields!(AstPreorderNode {
2902    ordinal,
2903    kind,
2904    byte_start,
2905    byte_end,
2906});
2907aft_store::heap_bytes_of_fields!(BlobSymbol {
2908    is_test,
2909    ordinal,
2910    name,
2911    scoped_name,
2912    kind,
2913    exported,
2914    is_default_export,
2915    start_line,
2916    start_col,
2917    end_line,
2918    end_col,
2919    signature,
2920    program_start,
2921    entry_attribute,
2922});
2923aft_store::heap_bytes_of_fields!(BlobRef {
2924    ordinal,
2925    kind,
2926    caller_symbol,
2927    short_name,
2928    full_ref,
2929    module_path,
2930    line,
2931    byte_start,
2932    byte_end,
2933    path_override,
2934    local_name,
2935    requested_name,
2936    namespace_alias,
2937    wildcard,
2938    import_kind,
2939});
2940aft_store::heap_bytes_of_fields!(BlobImport {
2941    ordinal,
2942    module_path,
2943    names,
2944    default_import,
2945    namespace_import,
2946    byte_start,
2947    byte_end,
2948    raw_text,
2949    type_only,
2950    side_effect,
2951});
2952aft_store::heap_bytes_of_fields!(DerivedRow {
2953    caller_blob_key,
2954    ref_ordinal,
2955    caller_path,
2956    kind,
2957    status,
2958    target_path,
2959    target_symbol,
2960});
2961aft_store::heap_bytes_of_fields!(DispatchTypeTargets { targets, trace });
2962aft_store::heap_bytes_of_fields!(DispatchTypeTargetTrace {
2963    queries,
2964    probes,
2965    answers,
2966});
2967aft_store::heap_bytes_of_fields!(ViewBindingDependencies {
2968    references,
2969    dependencies,
2970    consulted_facts,
2971    unattributed,
2972    binding_facts,
2973    resolution_facts,
2974    binding_probes,
2975    resolved_dependencies,
2976    surface_queries,
2977    binding_answers,
2978    resolution_answers,
2979    surface,
2980});
2981aft_store::heap_bytes_of_fields!(ConfigConsultations {
2982    facts,
2983    reads,
2984    unattributed,
2985});
2986aft_store::heap_bytes_of_fields!(ViewFileSurface {
2987    language,
2988    exports,
2989    default_export,
2990    export_aliases,
2991    node_by_scoped,
2992    node_by_bare,
2993    node_kind_by_id,
2994    module_targets,
2995    declared_module_targets,
2996    macro_use_module_targets,
2997    reexports,
2998});
2999
3000impl aft_store::heap::HeapBytes for ViewSurfaceQuery {
3001    fn heap_bytes(&self, seen: &mut aft_store::heap::Seen) -> usize {
3002        match self {
3003            Self::Language(a)
3004            | Self::MacroUse(a)
3005            | Self::Parent(a)
3006            | Self::Reexports(a)
3007            | Self::Default(a)
3008            | Self::Contains(a)
3009            | Self::Crate(a)
3010            | Self::CrateRoot(a) => a.heap_bytes(seen),
3011            Self::Module(a, b)
3012            | Self::Node(a, b)
3013            | Self::Callable(a, b)
3014            | Self::Alias(a, b)
3015            | Self::Export(a, b) => a.heap_bytes(seen) + b.heap_bytes(seen),
3016            Self::Inline(a, names, b) => {
3017                a.heap_bytes(seen) + names.heap_bytes(seen) + b.heap_bytes(seen)
3018            }
3019            Self::GoPackage(a, b) => a.heap_bytes(seen) + b.heap_bytes(seen),
3020        }
3021    }
3022}