use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
#[path = "dispatch.rs"]
pub mod dispatch;
#[path = "join_record.rs"]
pub mod record;
#[cfg(any(test, feature = "test-support"))]
#[path = "extraction_work.rs"]
pub mod extraction_work;
#[cfg(any(test, feature = "test-support"))]
pub use extraction_work::CountingParser as Parser;
use serde::{Deserialize, Serialize};
#[cfg(not(any(test, feature = "test-support")))]
use tree_sitter::Parser;
test_support_visibility! {
#[path = "extraction_index.rs"]
mod extraction_index;
}
#[path = "single_walk.rs"]
pub mod single_walk;
#[path = "syntax_index.rs"]
pub mod syntax_index;
use super::facts::{BlobKey, FactPaths, NoProjectFacts, ProjectFacts};
use crate::callgraph::{self, FileCallData, SymbolMeta};
use crate::imports::{ImportBlock, ImportForm, ImportGroup, ImportKind, ImportStatement};
use crate::parser::LangId;
use crate::symbols::SymbolKind;
use std::collections::HashMap;
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
const TOP_LEVEL_SYMBOL: &str = "<top-level>";
pub const SUPERSEDED_PUBLISH: &str = "checkout view owner superseded; publication refused";
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ManifestJoinError {
GrammarParseTimeout {
path: String,
language: String,
timeout_ms: u64,
},
GrammarUnavailable(crate::grammar::GrammarUnavailable),
Cancelled,
UnsupportedLanguage(String),
Parse(String),
InvalidBlob(String),
}
impl fmt::Display for ManifestJoinError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::GrammarParseTimeout {
path, timeout_ms, ..
} => write!(
formatter,
"grammar parse exceeded {timeout_ms} ms for {path}"
),
Self::GrammarUnavailable(error) => formatter.write_str(&error.message),
Self::Cancelled => formatter.write_str(SUPERSEDED_PUBLISH),
Self::UnsupportedLanguage(language) => {
write!(formatter, "unsupported callgraph blob language {language}")
}
Self::Parse(reason) => write!(formatter, "callgraph blob parse failed: {reason}"),
Self::InvalidBlob(reason) => write!(formatter, "invalid callgraph blob: {reason}"),
}
}
}
impl std::error::Error for ManifestJoinError {}
pub fn extraction_error(error: crate::error::AftError) -> ManifestJoinError {
match error {
crate::error::AftError::GrammarParseTimeout {
path,
language,
timeout_ms,
} => ManifestJoinError::GrammarParseTimeout {
path,
language,
timeout_ms,
},
crate::error::AftError::GrammarUnavailable {
language,
state,
message,
cause,
retry_after_ms,
} => ManifestJoinError::GrammarUnavailable(crate::grammar::GrammarUnavailable {
language,
state,
message,
cause,
retry_after_ms,
}),
other => ManifestJoinError::Parse(other.to_string()),
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct AstPreorderNode {
pub ordinal: u32,
pub kind: Cow<'static, str>,
pub byte_start: usize,
pub byte_end: usize,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct BlobSymbol {
#[serde(default)]
pub is_test: Option<bool>,
pub ordinal: u32,
pub name: String,
pub scoped_name: String,
pub kind: String,
pub exported: bool,
pub is_default_export: bool,
pub start_line: u32,
pub start_col: u32,
pub end_line: u32,
pub end_col: u32,
pub signature: Option<String>,
#[serde(default)]
pub program_start: bool,
#[serde(default)]
pub entry_attribute: Option<String>,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum BlobRefKind {
Construction,
CallbackRef,
Call,
ValueRef,
Import,
Module,
Reexport,
ExportAlias,
MacroMention,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct BlobRef {
pub ordinal: u32,
pub kind: BlobRefKind,
pub caller_symbol: Option<String>,
pub short_name: Option<String>,
pub full_ref: Option<String>,
pub module_path: Option<String>,
pub line: u32,
pub byte_start: usize,
pub byte_end: usize,
pub path_override: Option<String>,
pub local_name: Option<String>,
pub requested_name: Option<String>,
pub namespace_alias: Option<String>,
pub wildcard: bool,
pub import_kind: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct BlobImport {
pub ordinal: u32,
pub module_path: String,
pub names: Vec<String>,
pub default_import: Option<String>,
pub namespace_import: Option<String>,
pub byte_start: usize,
pub byte_end: usize,
pub raw_text: String,
pub type_only: bool,
pub side_effect: bool,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ParseBlob {
pub entry_point_symbols: Vec<String>,
#[serde(default)]
pub dispatch: dispatch::DispatchFacts,
pub extractor_version: String,
pub language: String,
#[serde(skip_serializing, default)]
pub ast_nodes: Vec<AstPreorderNode>,
pub symbols: Vec<BlobSymbol>,
pub default_export_symbol: Option<String>,
pub exported_symbols: Vec<String>,
pub callable_symbols: Vec<String>,
pub imports: Vec<BlobImport>,
#[serde(default)]
pub python_bindings: Vec<callgraph::python::CallBinding>,
pub refs: Vec<BlobRef>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ConfigBlob {
pub extractor_version: String,
pub language: String,
pub source: Vec<u8>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum CallgraphBlob {
Parse(ParseBlob),
Config(ConfigBlob),
}
impl CallgraphBlob {
pub fn extract(
source: &str,
language: &str,
extractor_version: impl Into<String>,
) -> Result<Self, ManifestJoinError> {
single_walk::extract(source, language, extractor_version.into())
}
pub fn extract_tree_with_outline(
source: &str,
language: &str,
extractor_version: impl Into<String>,
tree: &tree_sitter::Tree,
) -> Result<(Self, Vec<crate::symbols::Symbol>), ManifestJoinError> {
let mut outline = Vec::new();
let blob = single_walk::extract_tree(
source,
language,
extractor_version.into(),
tree,
Some(&mut outline),
)?;
Ok((blob, outline))
}
pub fn extract_reference(
source: &str,
language: &str,
extractor_version: impl Into<String>,
) -> Result<Self, ManifestJoinError> {
let lang = language_id(language)
.ok_or_else(|| ManifestJoinError::UnsupportedLanguage(language.to_string()))?;
let extractor_version = extractor_version.into();
let tree = match crate::parser::cached_header_tree(source, lang) {
Some(tree) => tree,
None if crate::parser::markdown_too_deep_to_parse(lang, source) => {
return Err(ManifestJoinError::Parse(
crate::parser::MARKDOWN_TOO_DEEP.to_string(),
));
}
None => {
let mut parser = Parser::new();
crate::parser::initialize_parser(&mut parser, lang).map_err(extraction_error)?;
#[cfg(any(test, feature = "test-support"))]
parser.note_parse();
crate::parser::parse_with_parser(
&mut parser,
Path::new("<reference-content>"),
source,
lang,
None,
)
.map_err(extraction_error)?
}
};
let root = tree.root_node();
let ast_nodes = ast_preorder_nodes(root);
let line_index = super::LineIndex::new(source);
let mut data = callgraph::build_file_data_from_tree(
std::path::Path::new("__callgraph_blob__"),
source,
lang,
&tree,
&line_index,
)
.map_err(|error| ManifestJoinError::Parse(error.to_string()))?;
if lang == LangId::Rust {
super::extend_rust_imports_from_tree(source, root, &mut data);
}
let mut symbols = blob_symbols(&data);
let mut imports = blob_imports(&data);
let mut refs = blob_refs(&line_index, &data);
refs.extend(rust_module_refs(source, lang, root));
let paths = FactPaths {
root: Path::new("/"),
facts: &NoProjectFacts,
};
let file = Path::new("/__callgraph_blob__");
let mut structural = super::collect_reexport_refs_with_line_index(
paths.root,
file,
"__callgraph_blob__",
source,
lang,
&crate::callgraph::ModuleResolutionMemo::default(),
&paths,
&line_index,
Some(root),
)
.raw_refs;
structural.extend(
super::collect_source_less_export_alias_refs_with_line_index(
"__callgraph_blob__",
source,
&line_index,
)
.raw_refs,
);
if lang == LangId::Rust {
structural.extend(
super::collect_rust_pub_use_reexport_refs(
paths.root,
file,
"__callgraph_blob__",
&data.import_block.imports,
&line_index,
&paths,
)
.raw_refs,
);
}
refs.extend(structural.into_iter().map(structural_ref));
assign_ordinals(
&ast_nodes,
&line_index,
&mut symbols,
&mut imports,
&mut refs,
);
let mut exported_symbols = data.exported_symbols.clone();
exported_symbols.sort();
let mut callable_symbols = data.calls_by_symbol.keys().cloned().collect::<Vec<_>>();
callable_symbols.sort();
refs.sort_by(|left, right| {
(
left.ordinal,
left.kind,
left.byte_start,
left.byte_end,
left.full_ref.as_deref(),
left.caller_symbol.as_deref(),
)
.cmp(&(
right.ordinal,
right.kind,
right.byte_start,
right.byte_end,
right.full_ref.as_deref(),
right.caller_symbol.as_deref(),
))
});
refs.dedup_by(|left, right| {
left.ordinal == right.ordinal
&& left.kind == right.kind
&& left.byte_start == right.byte_start
&& left.byte_end == right.byte_end
&& left.full_ref == right.full_ref
&& left.caller_symbol == right.caller_symbol
});
let mut parse = ParseBlob {
entry_point_symbols: data
.symbol_metadata
.iter()
.filter(|(_, meta)| meta.entry_point_attribute.is_some())
.map(|(name, _)| name.clone())
.collect(),
dispatch: dispatch::DispatchFacts::default(),
extractor_version,
language: language.to_string(),
ast_nodes,
symbols,
default_export_symbol: data.default_export_symbol,
exported_symbols,
callable_symbols,
imports,
python_bindings: data.python_bindings,
refs,
};
parse.entry_point_symbols.sort();
parse.dispatch = dispatch::extract(source, lang, root, &mut parse)?;
Ok(Self::Parse(parse))
}
pub fn config(source: impl Into<Vec<u8>>, extractor_version: impl Into<String>) -> Self {
Self::Config(ConfigBlob {
extractor_version: extractor_version.into(),
language: "config".to_string(),
source: source.into(),
})
}
pub fn to_bytes(&self) -> Result<Vec<u8>, ManifestJoinError> {
serde_json::to_vec(self).map_err(|error| ManifestJoinError::InvalidBlob(error.to_string()))
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self, ManifestJoinError> {
serde_json::from_slice(bytes)
.map_err(|error| ManifestJoinError::InvalidBlob(error.to_string()))
}
pub fn parse(&self) -> Option<&ParseBlob> {
match self {
Self::Parse(blob) => Some(blob),
Self::Config(_) => None,
}
}
pub fn config_source(&self) -> Option<&ConfigBlob> {
match self {
Self::Parse(_) => None,
Self::Config(blob) => Some(blob),
}
}
}
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct CallerRefKey {
pub caller_blob_key: String,
pub ref_ordinal: u32,
pub caller_path: Vec<u8>,
}
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum ResolutionStatus {
Resolved,
Unresolved,
}
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct DerivedRow {
pub caller_blob_key: String,
pub ref_ordinal: u32,
pub caller_path: Vec<u8>,
pub kind: BlobRefKind,
pub status: ResolutionStatus,
pub target_path: Option<Vec<u8>>,
pub target_symbol: Option<String>,
}
impl DerivedRow {
pub fn ref_key(&self) -> CallerRefKey {
CallerRefKey {
caller_blob_key: self.caller_blob_key.clone(),
ref_ordinal: self.ref_ordinal,
caller_path: self.caller_path.clone(),
}
}
}
pub fn language_id(language: &str) -> Option<LangId> {
Some(match language {
"typescript" => LangId::TypeScript,
"tsx" => LangId::Tsx,
"javascript" => LangId::JavaScript,
"python" => LangId::Python,
"rust" => LangId::Rust,
"go" => LangId::Go,
"c" => LangId::C,
"cpp" => LangId::Cpp,
"cuda" => LangId::Cuda,
"metal" => LangId::Metal,
"zig" => LangId::Zig,
"csharp" => LangId::CSharp,
"bash" => LangId::Bash,
"html" => LangId::Html,
"markdown" => LangId::Markdown,
"solidity" => LangId::Solidity,
"scss" => LangId::Scss,
"vue" => LangId::Vue,
"json" => LangId::Json,
"scala" => LangId::Scala,
"java" => LangId::Java,
"ruby" => LangId::Ruby,
"kotlin" => LangId::Kotlin,
"swift" => LangId::Swift,
"php" => LangId::Php,
"lua" => LangId::Lua,
"perl" => LangId::Perl,
"yaml" => LangId::Yaml,
"pascal" => LangId::Pascal,
"r" => LangId::R,
"groovy" => LangId::Groovy,
"objc" => LangId::ObjC,
"toml" => LangId::Toml,
_ => return crate::grammar::extractor_language(language),
})
}
fn ast_preorder_nodes(root: tree_sitter::Node<'_>) -> Vec<AstPreorderNode> {
let mut nodes = Vec::new();
for node in extraction_index::preorder(root) {
let kind = Cow::Borrowed(node.kind());
#[cfg(any(test, feature = "test-support"))]
extraction_work::note(|work| {
work.kind_copies += usize::from(matches!(kind, Cow::Owned(_)))
});
nodes.push(AstPreorderNode {
ordinal: nodes.len() as u32,
kind,
byte_start: node.start_byte(),
byte_end: node.end_byte(),
});
}
nodes
}
test_support_visibility! {
fn blob_symbols(data: &FileCallData) -> Vec<BlobSymbol> {
data.symbol_metadata
.iter()
.map(|(scoped_name, meta)| blob_symbol(scoped_name, meta, &data.default_export_symbol))
.collect()
}
}
fn sort_blob_symbols(symbols: &mut [BlobSymbol]) {
symbols.sort_by(|left, right| {
(
left.ordinal,
left.start_line,
left.start_col,
left.scoped_name.as_str(),
)
.cmp(&(
right.ordinal,
right.start_line,
right.start_col,
right.scoped_name.as_str(),
))
});
}
fn blob_symbol(
scoped_name: &str,
meta: &SymbolMeta,
default_export: &Option<String>,
) -> BlobSymbol {
BlobSymbol {
is_test: meta.is_test,
ordinal: 0,
name: unqualified_symbol_name(scoped_name).to_string(),
scoped_name: scoped_name.to_string(),
kind: symbol_kind_name(&meta.kind).to_string(),
exported: meta.exported,
is_default_export: default_export.as_deref() == Some(scoped_name),
start_line: meta.range.start_line,
start_col: meta.range.start_col,
end_line: meta.range.end_line,
end_col: meta.range.end_col,
signature: meta.signature.clone(),
program_start: meta.program_start,
entry_attribute: meta.entry_point_attribute.clone(),
}
}
test_support_visibility! {
fn blob_imports(data: &FileCallData) -> Vec<BlobImport> {
data.import_block
.imports
.iter()
.map(|import| BlobImport {
ordinal: 0,
module_path: import.module_path.clone(),
names: import.names.clone(),
default_import: import.default_import.clone(),
namespace_import: import.namespace_import.clone(),
byte_start: import.byte_range.start,
byte_end: import.byte_range.end,
raw_text: import.raw_text.clone(),
type_only: import.kind == ImportKind::Type,
side_effect: import.kind == ImportKind::SideEffect,
})
.collect()
}
}
test_support_visibility! {
fn blob_refs(line_index: &super::LineIndex, data: &FileCallData) -> Vec<BlobRef> {
let mut refs = Vec::new();
for (caller_symbol, calls) in ordered_symbol_sites(&data.calls_by_symbol) {
for call in calls {
refs.push(call_ref(caller_symbol, call, BlobRefKind::Call));
}
}
for (caller_symbol, calls) in ordered_symbol_sites(&data.value_refs_by_symbol) {
for call in calls {
refs.push(call_ref(caller_symbol, call, BlobRefKind::ValueRef));
}
}
for (caller_symbol, calls) in ordered_symbol_sites(&data.macro_body_calls_by_macro) {
for call in calls {
refs.push(call_ref(caller_symbol, call, BlobRefKind::Call));
}
}
for (caller_symbol, mentions) in ordered_symbol_sites(&data.macro_mentions_by_symbol) {
for mention in mentions {
refs.push(call_ref(caller_symbol, mention, BlobRefKind::MacroMention));
}
}
for import in &data.import_block.imports {
refs.push(BlobRef {
ordinal: 0,
kind: BlobRefKind::Import,
caller_symbol: None,
short_name: None,
full_ref: Some(import.module_path.clone()),
module_path: Some(import.module_path.clone()),
line: line_index.byte_to_line(import.byte_range.start),
byte_start: import.byte_range.start,
byte_end: import.byte_range.end,
path_override: None,
local_name: None,
requested_name: None,
namespace_alias: import.namespace_import.clone(),
wildcard: super::import_is_wildcard(import),
import_kind: None,
});
}
refs
}
}
test_support_visibility! {
fn ordered_symbol_sites(
sites: &HashMap<String, Vec<callgraph::CallSite>>,
) -> Vec<(&str, &[callgraph::CallSite])> {
let mut ordered = sites
.iter()
.map(|(caller, calls)| (caller.as_str(), calls.as_slice()))
.collect::<Vec<_>>();
ordered.sort_unstable_by_key(|(caller, _)| *caller);
ordered
}
}
fn call_ref(caller_symbol: &str, call: &callgraph::CallSite, kind: BlobRefKind) -> BlobRef {
BlobRef {
ordinal: 0,
kind: match call.kind {
callgraph::CallSiteKind::Construction => BlobRefKind::Construction,
callgraph::CallSiteKind::CallbackReference => BlobRefKind::CallbackRef,
callgraph::CallSiteKind::Call => kind,
},
caller_symbol: Some(caller_symbol.to_string()),
short_name: Some(call.callee_name.clone()),
full_ref: Some(call.full_callee.clone()),
module_path: None,
line: call.line,
byte_start: call.byte_start,
byte_end: call.byte_end,
path_override: None,
local_name: None,
requested_name: None,
namespace_alias: None,
wildcard: false,
import_kind: None,
}
}
fn rust_module_refs(source: &str, lang: LangId, root: tree_sitter::Node<'_>) -> Vec<BlobRef> {
if lang != LangId::Rust {
return Vec::new();
}
let mut refs = Vec::new();
for node in extraction_index::preorder(root) {
if node.kind() == "mod_item"
&& node
.named_children(&mut node.walk())
.all(|child| child.kind() != "declaration_list")
{
if let Some(name) = node.child_by_field_name("name") {
let module_name = source[name.byte_range()].to_string();
refs.push(BlobRef {
ordinal: 0,
kind: BlobRefKind::Module,
caller_symbol: None,
short_name: Some(module_name.clone()),
full_ref: Some(if super::rust_module_has_macro_use(source, node) {
format!("#[macro_use] mod {module_name};")
} else {
module_name.clone()
}),
module_path: Some(module_name),
line: node.start_position().row as u32 + 1,
byte_start: node.start_byte(),
byte_end: node.end_byte(),
path_override: super::rust_module_path_override(source, node)
.map(str::to_string),
local_name: None,
requested_name: None,
namespace_alias: None,
wildcard: false,
import_kind: None,
});
}
}
}
refs
}
test_support_visibility! {
fn assign_ordinals(
ast_nodes: &[AstPreorderNode],
lines: &super::LineIndex,
symbols: &mut [BlobSymbol],
imports: &mut [BlobImport],
refs: &mut [BlobRef],
) {
let ranges = ast_nodes
.iter()
.map(|n| (n.byte_start, n.byte_end))
.collect::<Vec<_>>();
let queries = symbols
.iter()
.map(|symbol| {
let start = lines.inclusive_byte_offset(symbol.start_line, symbol.start_col);
let end = lines
.inclusive_byte_offset(symbol.end_line, symbol.end_col)
.max(start);
(start, end)
})
.chain(imports.iter().map(|i| (i.byte_start, i.byte_end)))
.chain(refs.iter().map(|r| (r.byte_start, r.byte_end)))
.collect::<Vec<_>>();
let ordinals =
extraction_index::range_minima(&ranges, &queries, extraction_index::LookupWork::Ordinal);
for (ordinal, target) in ordinals.into_iter().zip(
symbols
.iter_mut()
.map(|s| &mut s.ordinal)
.chain(imports.iter_mut().map(|i| &mut i.ordinal))
.chain(refs.iter_mut().map(|r| &mut r.ordinal)),
) {
*target = ordinal.map(|i| ast_nodes[i].ordinal).unwrap_or(0);
}
sort_blob_symbols(symbols);
imports.sort_by(|left, right| {
(left.ordinal, left.module_path.as_str()).cmp(&(right.ordinal, right.module_path.as_str()))
});
}
}
fn symbol_kind_name(kind: &SymbolKind) -> &'static str {
match kind {
SymbolKind::Function => "function",
SymbolKind::Kernel => "kernel",
SymbolKind::Class => "class",
SymbolKind::Method => "method",
SymbolKind::Struct => "struct",
SymbolKind::Interface => "interface",
SymbolKind::Enum => "enum",
SymbolKind::TypeAlias => "type_alias",
SymbolKind::Variable => "variable",
SymbolKind::Heading => "heading",
SymbolKind::FileSummary => "file_summary",
}
}
fn unqualified_symbol_name(scoped_name: &str) -> &str {
if scoped_name == TOP_LEVEL_SYMBOL {
return scoped_name;
}
scoped_name.rsplit("::").next().unwrap_or(scoped_name)
}
test_support_visibility! {
fn structural_ref(raw: super::RawRef) -> BlobRef {
BlobRef {
ordinal: 0,
kind: if raw.kind == "export_alias" {
BlobRefKind::ExportAlias
} else {
BlobRefKind::Reexport
},
caller_symbol: raw.caller_symbol,
short_name: raw.short_name,
full_ref: raw.full_ref,
module_path: raw.module_path,
line: raw.line,
byte_start: raw.byte_start,
byte_end: raw.byte_end,
path_override: None,
local_name: raw.local_name,
requested_name: raw.requested_name,
namespace_alias: raw.namespace_alias,
wildcard: raw.wildcard,
import_kind: raw.import_kind,
}
}
}
fn bound_name(name: &str, path: &str) -> String {
name.replace(
"<default:__callgraph_blob__>",
&format!(
"<default:{}>",
Path::new(path)
.file_name()
.unwrap_or_default()
.to_string_lossy()
),
)
}
impl ParseBlob {
pub fn iter_bound_dispatch_sites(&self) -> impl Iterator<Item = dispatch::SiteHint> + '_ {
let keys = (self.language == "python").then(|| {
self.refs
.iter()
.zip(self.reference_keys())
.filter(|(reference, _)| reference.kind == BlobRefKind::Call)
.map(|(reference, key)| {
((reference.ordinal, reference.caller_symbol.as_deref()), key)
})
.collect::<HashMap<_, _>>()
});
self.dispatch.sites.iter().cloned().map(move |mut site| {
if let Some(key) = keys
.as_ref()
.and_then(|keys| keys.get(&(site.ordinal, site.caller.as_deref())))
{
site.ordinal = *key;
}
site
})
}
pub fn bound_dispatch_sites(&self) -> Vec<dispatch::SiteHint> {
self.iter_bound_dispatch_sites().collect()
}
pub fn reference_keys(&self) -> Vec<u32> {
let mut groups: BTreeMap<u32, Vec<usize>> = BTreeMap::new();
for (position, reference) in self.refs.iter().enumerate() {
groups.entry(reference.ordinal).or_default().push(position);
}
let mut used = groups.keys().copied().collect::<BTreeSet<_>>();
let mut keys = self.refs.iter().map(|r| r.ordinal).collect::<Vec<_>>();
for (ordinal, positions) in groups {
if positions.len() < 2 {
continue;
}
let calls = positions
.iter()
.copied()
.filter(|p| self.refs[*p].kind == BlobRefKind::Call)
.collect::<Vec<_>>();
let primary = if calls.len() == 1 {
calls[0]
} else {
positions[0]
};
for position in positions {
if position == primary {
continue;
}
let reference = &self.refs[position];
let bytes = serde_json::to_vec(&(
"bound-reference-v2",
ordinal,
reference.kind,
reference.byte_start,
reference.byte_end,
&reference.caller_symbol,
&reference.full_ref,
&reference.module_path,
&reference.local_name,
&reference.requested_name,
))
.expect("source facts serialize");
let hash = blake3::hash(&bytes);
let mut key =
u32::from_le_bytes(hash.as_bytes()[..4].try_into().expect("four hash bytes"));
while !used.insert(key) {
key = key.wrapping_add(1);
}
keys[position] = key;
}
}
keys
}
pub(super) fn file_data(&self, path: &str) -> Result<FileCallData, ManifestJoinError> {
let lang = language_id(&self.language)
.ok_or_else(|| ManifestJoinError::UnsupportedLanguage(self.language.clone()))?;
let mut calls_by_symbol: HashMap<String, Vec<callgraph::CallSite>> = HashMap::new();
let mut value_refs_by_symbol: HashMap<String, Vec<callgraph::CallSite>> = HashMap::new();
let mut macro_body_calls_by_macro: HashMap<String, Vec<callgraph::CallSite>> =
HashMap::new();
let mut macro_mentions_by_symbol: HashMap<String, Vec<callgraph::CallSite>> =
HashMap::new();
for raw in &self.refs {
let map = match raw.kind {
BlobRefKind::Call
if raw
.caller_symbol
.as_deref()
.is_some_and(|s| s.ends_with('!')) =>
{
&mut macro_body_calls_by_macro
}
BlobRefKind::Call | BlobRefKind::Construction => &mut calls_by_symbol,
BlobRefKind::ValueRef | BlobRefKind::CallbackRef => &mut value_refs_by_symbol,
BlobRefKind::MacroMention => &mut macro_mentions_by_symbol,
_ => continue,
};
let Some(caller) = &raw.caller_symbol else {
continue;
};
map.entry(bound_name(caller, path))
.or_default()
.push(callgraph::CallSite {
kind: match raw.kind {
BlobRefKind::Construction => callgraph::CallSiteKind::Construction,
BlobRefKind::CallbackRef => callgraph::CallSiteKind::CallbackReference,
_ => callgraph::CallSiteKind::Call,
},
callee_name: raw.short_name.clone().unwrap_or_default(),
full_callee: raw.full_ref.clone().unwrap_or_default(),
line: raw.line,
byte_start: raw.byte_start,
byte_end: raw.byte_end,
});
}
for symbol in &self.callable_symbols {
calls_by_symbol.entry(bound_name(symbol, path)).or_default();
}
let mut symbol_metadata = HashMap::new();
for symbol in &self.symbols {
let kind = match symbol.kind.as_str() {
"function" => SymbolKind::Function,
"method" => SymbolKind::Method,
"class" => SymbolKind::Class,
"struct" => SymbolKind::Struct,
"interface" => SymbolKind::Interface,
"enum" => SymbolKind::Enum,
"type_alias" => SymbolKind::TypeAlias,
"heading" => SymbolKind::Heading,
"file_summary" => SymbolKind::FileSummary,
_ => SymbolKind::Variable,
};
symbol_metadata.insert(
bound_name(&symbol.scoped_name, path),
SymbolMeta {
is_test: symbol.is_test,
kind,
exported: symbol.exported,
signature: symbol.signature.clone(),
line: symbol.start_line + 1,
range: crate::symbols::Range {
start_line: symbol.start_line,
start_col: symbol.start_col,
end_line: symbol.end_line,
end_col: symbol.end_col,
},
entry_point_attribute: self
.entry_point_symbols
.contains(&symbol.scoped_name)
.then(|| "initializer_or_attribute".to_string()),
program_start: symbol.program_start,
},
);
}
let imports = self
.imports
.iter()
.map(|import| ImportStatement {
module_path: import.module_path.clone(),
names: import.names.clone(),
default_import: import.default_import.clone(),
namespace_import: import.namespace_import.clone(),
kind: if import.type_only {
ImportKind::Type
} else if import.side_effect {
ImportKind::SideEffect
} else {
ImportKind::Value
},
group: ImportGroup::Internal,
byte_range: import.byte_start..import.byte_end,
raw_text: import.raw_text.clone(),
form: if lang == LangId::Rust {
ImportForm::RustUse {
visibility: import.default_import.clone(),
named: import.names.clone(),
}
} else {
ImportForm::Es {
default_import: import.default_import.clone(),
namespace_import: import.namespace_import.clone(),
named: import.names.clone(),
type_only: import.type_only,
side_effect: import.side_effect,
attribute_clause: None,
attribute_type: None,
}
},
})
.collect::<Vec<_>>();
Ok(FileCallData {
calls_by_symbol,
value_refs_by_symbol,
macro_body_calls_by_macro,
macro_mentions_by_symbol,
symbol_metadata,
exported_symbols: self
.exported_symbols
.iter()
.map(|s| bound_name(s, path))
.collect(),
default_export_symbol: self
.default_export_symbol
.as_ref()
.map(|s| bound_name(s, path)),
import_block: ImportBlock {
imports,
byte_range: None,
},
python_bindings: self.python_bindings.clone(),
lang,
})
}
fn bind_with_dependencies(
&self,
path: &str,
facts: &FactPaths<'_>,
cached: Option<&BTreeMap<u32, BTreeSet<String>>>,
) -> Result<super::FileExtract, ManifestJoinError> {
let data = self.file_data(path)?;
let mut occurrences = HashMap::<String, usize>::new();
let nodes = self
.symbols
.iter()
.map(|symbol| {
let scoped_name = bound_name(&symbol.scoped_name, path);
let occurrence = occurrences.entry(scoped_name.clone()).or_default();
let id = format!("{path}:{occurrence}:{scoped_name}");
*occurrence += 1;
super::NodeRecord {
id,
name: bound_name(&symbol.name, path),
scoped_name,
kind: symbol.kind.clone(),
}
})
.collect::<Vec<_>>();
let abs = facts.root.join(path);
let mut raw_refs = Vec::new();
let mut module_dependencies = HashMap::new();
for (position, (raw, reference_key)) in
self.refs.iter().zip(self.reference_keys()).enumerate()
{
let position = u32::try_from(position).expect("reference vector fits u32");
let dependencies = if let Some(dependencies) =
cached.and_then(|cache| cache.get(&position))
{
dependencies.clone()
} else if raw.kind == BlobRefKind::Module {
super::rust_external_module_target(
&abs,
raw.path_override.as_deref(),
raw.module_path.as_deref().unwrap_or_default(),
facts,
)
.and_then(|p| facts.canonical(&p))
.map(|p| super::relative_path(facts.root, &p))
.into_iter()
.collect()
} else if let Some(module) = &raw.module_path {
module_dependencies
.entry(module.clone())
.or_insert_with(|| super::module_dependencies(facts.root, &abs, module, facts))
.clone()
} else {
BTreeSet::new()
};
let caller_symbol = raw
.caller_symbol
.as_ref()
.map(|name| bound_name(name, path));
raw_refs.push(super::RawRef {
ref_id: format!("{path}:{reference_key}:{:?}", raw.kind),
caller_symbol,
caller_file: path.to_string(),
kind: match raw.kind {
BlobRefKind::Call
if raw
.caller_symbol
.as_deref()
.is_some_and(|s| s.ends_with('!')) =>
{
super::MACRO_BODY_CALL_REF_KIND
}
BlobRefKind::Call => "call",
BlobRefKind::Construction => "construction",
BlobRefKind::CallbackRef => "callback_ref",
BlobRefKind::ValueRef => "value_ref",
BlobRefKind::Import => "import",
BlobRefKind::Module => "module",
BlobRefKind::Reexport => "reexport",
BlobRefKind::ExportAlias => "export_alias",
BlobRefKind::MacroMention => super::MACRO_MENTION_REF_KIND,
}
.to_string(),
short_name: raw.short_name.clone(),
full_ref: raw.full_ref.clone(),
module_path: raw.module_path.clone(),
import_kind: raw.import_kind.clone(),
local_name: raw.local_name.clone(),
requested_name: raw.requested_name.clone(),
namespace_alias: raw.namespace_alias.clone(),
wildcard: raw.wildcard,
line: raw.line,
byte_start: raw.byte_start,
byte_end: raw.byte_end,
dependencies,
});
}
Ok(super::FileExtract {
rel_path: path.to_string(),
lang: data.lang,
data,
nodes,
raw_refs,
})
}
}
pub(super) fn dispatch_type_names(parse: &ParseBlob) -> BTreeSet<String> {
let mut names = BTreeSet::new();
for ty in &parse.dispatch.types {
names.insert(ty.name.clone());
names.extend(ty.bases.iter().cloned());
}
for method in &parse.dispatch.methods {
names.insert(method.owner.clone());
names.extend(method.trait_name.iter().cloned());
}
for field in &parse.dispatch.fields {
let mut name = field.ty.as_str();
while let Some((_, outer, inner)) = dispatch::smart_pointer::parts(name) {
names.insert(outer.to_string());
name = inner;
}
names.insert(name.to_string());
}
names.extend(parse.dispatch.returns.iter().map(|r| r.ty.clone()));
for site in &parse.dispatch.sites {
if let Some(receiver) = &site.receiver {
if receiver.starts_with(dispatch::TEMPLATE_SELF_RECEIVER) {
continue;
}
let mut name = receiver.as_str();
while let Some(expression) = name.strip_prefix("@field:") {
name = expression
.rsplit_once('|')
.map(|(base, _)| base)
.unwrap_or(expression);
}
names.insert(name.strip_prefix("@return:").unwrap_or(name).to_string());
}
}
names
}
pub(super) fn resolve_dispatch_type_names<I: super::ResolverIndex>(
index: &I,
file: &str,
parse: &ParseBlob,
data: &FileCallData,
) -> BTreeMap<String, (String, String)> {
if parse.language != "rust" {
let mut targets = BTreeMap::new();
for name in dispatch_type_names(parse) {
if name.starts_with('@')
|| !parse.imports.iter().any(|import| {
!import.type_only
&& (import.default_import.as_deref() == Some(&name)
|| import
.names
.iter()
.any(|spec| crate::imports::specifier_local_name(spec) == name))
})
{
continue;
}
if let Some((_, target_file, symbol)) =
super::resolve_js_ts_target(index, file, &name, &name, data)
{
if super::ResolverIndex::node_for_symbol(index, &target_file, &symbol).is_some() {
targets.insert(name, (target_file, symbol));
}
}
}
if let Some(facts) = &parse.dispatch.static_facts {
let candidates = facts.import_receivers().collect::<BTreeSet<_>>();
for (name, module) in candidates {
let Some(target) = index.module_target(file, module) else {
continue;
};
let requested = parse
.imports
.iter()
.filter(|import| import.module_path == module && !import.type_only)
.find_map(|import| {
if import.default_import.as_deref() == Some(name) {
Some("default")
} else {
import
.names
.iter()
.find(|spec| crate::imports::specifier_local_name(spec) == name)
.map(|spec| crate::imports::specifier_imported_name(spec))
}
});
let bound = requested.and_then(|requested| {
super::resolve_exported_symbol(index, &target, requested, 0)
});
targets.insert(
format!("{}{name}", dispatch::STATIC_IMPORT_PREFIX),
bound.unwrap_or((target, String::new())),
);
}
}
return targets;
}
let mut names = dispatch_type_names(parse);
for import in &data.import_block.imports {
names.extend(callgraph::rust_import_local_names(import));
}
let references = parse
.refs
.iter()
.filter(|raw| matches!(raw.kind, BlobRefKind::Call | BlobRefKind::Construction))
.map(|raw| (raw.ordinal, raw))
.collect::<HashMap<_, _>>();
fn context_key<'a>(raw: &'a BlobRef, data: &FileCallData) -> (Option<(&'a str, bool)>, usize) {
(
raw.caller_symbol.as_deref().map(|caller| {
(
caller.rsplit_once("::").map_or("", |(scope, _)| scope),
data.symbol_metadata
.get(caller)
.is_some_and(|meta| meta.kind == SymbolKind::Method),
)
}),
data.import_block
.imports
.partition_point(|import| import.byte_range.start <= raw.byte_start),
)
}
let mut contexts = HashMap::<_, BTreeMap<_, &BlobRef>>::new();
for raw in references.values() {
if let Some(name) = raw.full_ref.as_ref().filter(|name| names.contains(*name)) {
contexts
.entry(name.as_str())
.or_default()
.insert(context_key(raw, data), raw);
}
}
for site in &parse.dispatch.sites {
let (Some(receiver), Some(reference)) = (&site.receiver, references.get(&site.ordinal))
else {
continue;
};
let mut name = receiver.as_str();
while let Some(expression) = name.strip_prefix("@field:") {
name = expression
.rsplit_once('|')
.map(|(base, _)| base)
.unwrap_or(expression);
}
name = name.strip_prefix("@return:").unwrap_or(name);
contexts
.entry(name)
.or_default()
.insert(context_key(reference, data), reference);
}
let mut targets = BTreeMap::new();
for name in names {
let short = name.rsplit("::").next().unwrap_or(&name);
let sites = contexts
.get(name.as_str())
.map(|refs| refs.values().copied().map(Some).collect::<Vec<_>>())
.unwrap_or_else(|| vec![None]);
let mut bindings = BTreeSet::new();
let mut incomplete = false;
for site in sites {
let raw = super::RawRef {
ref_id: String::new(),
caller_symbol: site.and_then(|raw| raw.caller_symbol.clone()),
caller_file: file.to_string(),
kind: "call".into(),
short_name: Some(short.into()),
full_ref: Some(name.clone()),
module_path: None,
import_kind: None,
local_name: None,
requested_name: None,
namespace_alias: None,
wildcard: false,
line: site.map_or(0, |raw| raw.line),
byte_start: site.map_or(0, |raw| raw.byte_start),
byte_end: site.map_or(0, |raw| raw.byte_end),
dependencies: BTreeSet::new(),
};
if let Some((_, target_file, symbol)) =
super::resolve_rust_target(index, file, &name, short, data, &raw)
{
if super::ResolverIndex::node_for_symbol(index, &target_file, &symbol).is_some() {
bindings.insert((target_file, symbol));
} else {
incomplete = true;
}
} else {
incomplete = true;
}
}
if !incomplete && bindings.len() == 1 {
targets.insert(name, bindings.into_iter().next().unwrap());
}
}
targets
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct DispatchTypeTargetTrace {
queries: Vec<(ViewSurfaceQuery, String)>,
probes: BTreeSet<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub answers: super::fact_answers::FactAnswers,
}
impl DispatchTypeTargetTrace {
pub fn dependencies(&self) -> BTreeSet<String> {
self.queries
.iter()
.flat_map(|(query, _)| query.dependencies())
.chain(self.probes.iter().cloned())
.collect()
}
pub fn probes(&self) -> &BTreeSet<String> {
&self.probes
}
pub fn probes_any(&self, paths: &BTreeSet<String>) -> bool {
!self.probes.is_disjoint(paths)
}
pub fn replays(
&self,
index: &impl super::ResolverIndex,
changed: &BTreeSet<String>,
answers: &mut BTreeMap<ViewSurfaceQuery, String>,
) -> bool {
self.queries.iter().all(|(query, expected)| {
!query.depends_on_any(changed) || answer_is(query, expected, index, answers)
})
}
pub fn all_answers_hold<'q>(
&'q self,
index: &impl super::ResolverIndex,
answers: &mut BTreeMap<&'q ViewSurfaceQuery, String>,
) -> bool {
self.queries.iter().all(|(query, expected)| {
*answers.entry(query).or_insert_with(|| query.answer(index)) == *expected
})
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct DispatchTypeTargets {
pub targets: BTreeMap<String, (String, String)>,
pub trace: DispatchTypeTargetTrace,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct ViewBindingDependencies {
pub references: BTreeMap<u32, BTreeSet<String>>,
pub dependencies: BTreeSet<String>,
#[serde(default)]
pub consulted_facts: BTreeSet<(String, String)>,
#[serde(default)]
pub unattributed: bool,
#[serde(default)]
binding_facts: ConfigConsultations,
#[serde(default)]
resolution_facts: ConfigConsultations,
binding_probes: BTreeSet<String>,
resolved_dependencies: BTreeSet<String>,
surface_queries: Vec<(ViewSurfaceQuery, String)>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub binding_answers: super::fact_answers::FactAnswers,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub resolution_answers: super::fact_answers::FactAnswers,
#[serde(skip)]
surface: Option<ViewFileSurface>,
}
impl ViewBindingDependencies {
pub fn without_surface(&self) -> Self {
Self {
surface: None,
..self.clone()
}
}
pub fn clear_surface(&mut self) {
self.surface = None;
}
pub fn same_surface(&self, other: &Self) -> bool {
self.surface == other.surface
}
pub fn changed_surface_keys(&self, other: &Self, file: &str) -> BTreeSet<String> {
if self.same_surface(other) {
return BTreeSet::new();
}
if let (Some(before), Some(after)) = (&self.surface, &other.surface) {
if before.language == "rust"
&& after.language == "rust"
&& before.without_declared_modules() == after.without_declared_modules()
{
let mut names = BTreeSet::new();
for (old, new) in [
(&before.module_targets, &after.module_targets),
(
&before.declared_module_targets,
&after.declared_module_targets,
),
] {
names.extend(
old.keys()
.chain(new.keys())
.filter(|name| old.get(*name) != new.get(*name))
.cloned(),
);
}
if !names.is_empty() {
return names
.iter()
.map(|name| rust_module_name_key(file, name))
.collect();
}
}
}
BTreeSet::from([file.to_string()])
}
pub fn surface_replays(
&self,
index: &impl super::ResolverIndex,
changed: &BTreeSet<String>,
answers: &mut BTreeMap<ViewSurfaceQuery, String>,
) -> bool {
self.surface_queries.iter().all(|(query, expected)| {
!query.depends_on_any(changed) || answer_is(query, expected, index, answers)
})
}
pub fn reuse_resolution(&mut self, old: &Self) {
self.resolved_dependencies = old.resolved_dependencies.clone();
self.surface_queries = old.surface_queries.clone();
self.resolution_facts = old.resolution_facts.clone();
self.resolution_answers = old.resolution_answers.clone();
finish_binding(self);
}
pub fn binding_keys(&self) -> BTreeSet<String> {
self.references
.values()
.flatten()
.cloned()
.chain(self.binding_probes.iter().cloned())
.collect()
}
pub fn answers(
&self,
) -> impl Iterator<
Item = (
&super::fact_answers::FactQuestion,
&super::fact_answers::FactAnswer,
),
> {
self.binding_answers
.iter()
.chain(self.resolution_answers.iter())
}
pub fn all_surface_answers_hold<'q>(
&'q self,
index: &impl super::ResolverIndex,
answers: &mut BTreeMap<&'q ViewSurfaceQuery, String>,
) -> bool {
self.surface_queries.iter().all(|(query, expected)| {
*answers.entry(query).or_insert_with(|| query.answer(index)) == *expected
})
}
}
#[derive(Hash, PartialEq, Eq)]
struct ViewResolutionBinding {
kind: String,
full_ref: Option<String>,
short_name: Option<String>,
visible_rust_imports: usize,
python_binding: Option<Option<(String, String)>>,
}
impl ViewResolutionBinding {
fn new(raw: &super::RawRef, caller: &FileCallData) -> Self {
Self {
kind: raw.kind.clone(),
full_ref: raw.full_ref.clone(),
short_name: raw.short_name.clone(),
python_binding: if caller.lang == LangId::Python {
caller
.python_bindings
.binary_search_by_key(&(raw.byte_start, raw.byte_end), |binding| {
(binding.byte_start, binding.byte_end)
})
.ok()
.map(|position| caller.python_bindings[position].target.clone())
} else {
None
},
visible_rust_imports: if caller.lang == LangId::Rust {
caller
.import_block
.imports
.partition_point(|import| import.byte_range.start <= raw.byte_start)
} else {
0
},
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
struct ViewFileSurface {
language: String,
exports: BTreeSet<String>,
default_export: Option<String>,
export_aliases: BTreeMap<String, String>,
node_by_scoped: BTreeMap<String, String>,
node_by_bare: BTreeMap<String, String>,
node_kind_by_id: BTreeMap<String, String>,
module_targets: BTreeMap<String, Option<String>>,
declared_module_targets: BTreeMap<String, Option<String>>,
macro_use_module_targets: BTreeSet<String>,
reexports: Vec<(Option<String>, BTreeMap<String, String>, bool)>,
}
impl ViewFileSurface {
fn without_declared_modules(&self) -> Self {
let mut rest = self.clone();
rest.module_targets
.retain(|name, _| !self.declared_module_targets.contains_key(name));
rest.declared_module_targets.clear();
rest
}
fn capture(language: &str, index: &super::DbFileIndex) -> Self {
Self {
language: language.into(),
exports: index.exports.iter().cloned().collect(),
default_export: index.default_export.clone(),
export_aliases: index.export_aliases.clone().into_iter().collect(),
node_by_scoped: index.node_by_scoped.clone().into_iter().collect(),
node_by_bare: index.node_by_bare.clone().into_iter().collect(),
node_kind_by_id: index.node_kind_by_id.clone().into_iter().collect(),
module_targets: index.module_targets.clone().into_iter().collect(),
declared_module_targets: index.declared_module_targets.clone().into_iter().collect(),
macro_use_module_targets: index.macro_use_module_targets.clone(),
reexports: index
.reexports
.iter()
.map(|r| {
(
r.target_file.clone(),
r.named.clone().into_iter().collect(),
r.wildcard,
)
})
.collect(),
}
}
}
pub fn view_resolution_config(path: &[u8]) -> bool {
matches!(
path.rsplit(|byte| *byte == b'/').next(),
Some(
b"package.json" | b"tsconfig.json" | b"pnpm-workspace.yaml" | b"Cargo.toml" | b"go.mod"
)
)
}
test_support_visibility! {
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
struct ConfigConsultations {
facts: BTreeSet<(String, String)>,
reads: BTreeSet<String>,
unattributed: bool,
}
}
impl ConfigConsultations {
fn extend(&mut self, other: &Self) {
self.facts.extend(other.facts.iter().cloned());
self.reads.extend(other.reads.iter().cloned());
self.unattributed |= other.unattributed;
}
test_support_visibility! {
fn unattributed(&self) -> bool {
self.unattributed
|| self
.reads
.iter()
.any(|path| !self.facts.iter().any(|(input, _)| input == path))
}
}
}
#[derive(Clone, Default)]
struct ConsultationTrace {
config: ConfigConsultations,
probes: BTreeSet<String>,
answers: super::fact_answers::FactAnswers,
}
type ConsultationMemoKey = (std::path::PathBuf, String, String);
pub struct ViewBindingFacts<'a> {
inner: Rc<dyn ProjectFacts + 'a>,
probes: std::cell::RefCell<BTreeSet<String>>,
#[cfg(any(test, feature = "test-support"))]
pub consultations: std::cell::RefCell<ConfigConsultations>,
#[cfg(not(any(test, feature = "test-support")))]
consultations: std::cell::RefCell<ConfigConsultations>,
memo_stack: std::cell::RefCell<Vec<(ConsultationMemoKey, ConsultationTrace)>>,
memo_traces: std::cell::RefCell<BTreeMap<ConsultationMemoKey, ConsultationTrace>>,
workspace_packages:
std::cell::RefCell<BTreeMap<(std::path::PathBuf, String), Option<std::path::PathBuf>>>,
workspace_members:
std::cell::RefCell<BTreeMap<std::path::PathBuf, Arc<Vec<std::path::PathBuf>>>>,
canonical_cache: std::cell::RefCell<HashMap<Vec<u8>, Option<Vec<u8>>>>,
file_cache: std::cell::RefCell<HashMap<Vec<u8>, bool>>,
config_cache: std::cell::RefCell<HashMap<Vec<u8>, Option<Arc<[u8]>>>>,
directory_cache: std::cell::RefCell<HashMap<Vec<u8>, Vec<super::facts::DirEntry>>>,
paused: std::cell::Cell<u32>,
typed: bool,
answers: std::cell::RefCell<super::fact_answers::FactAnswers>,
answer_cache: std::cell::RefCell<
HashMap<super::fact_answers::FactQuestion, super::fact_answers::FactAnswer>,
>,
}
impl<'a> ViewBindingFacts<'a> {
pub fn new(inner: Rc<dyn ProjectFacts + 'a>) -> Self {
Self {
inner,
probes: Default::default(),
consultations: Default::default(),
memo_stack: Default::default(),
memo_traces: Default::default(),
workspace_packages: Default::default(),
workspace_members: Default::default(),
canonical_cache: Default::default(),
file_cache: Default::default(),
config_cache: Default::default(),
directory_cache: Default::default(),
paused: Default::default(),
typed: false,
answers: Default::default(),
answer_cache: Default::default(),
}
}
pub fn typed(inner: Rc<dyn ProjectFacts + 'a>) -> Self {
Self {
typed: true,
..Self::new(inner)
}
}
pub fn take_answers(&self) -> super::fact_answers::FactAnswers {
std::mem::take(&mut *self.answers.borrow_mut())
}
fn answered(
&self,
question: super::fact_answers::FactQuestion,
answer: impl FnOnce() -> super::fact_answers::FactAnswer,
) {
if !self.typed || self.paused.get() > 0 {
return;
}
let cached = self.answer_cache.borrow().get(&question).cloned();
let answer = cached.unwrap_or_else(|| {
let answer = answer();
self.answer_cache
.borrow_mut()
.insert(question.clone(), answer.clone());
answer
});
for (_, trace) in self.memo_stack.borrow_mut().iter_mut() {
trace.answers.insert(question.clone(), answer.clone());
}
self.answers.borrow_mut().insert(question, answer);
}
fn file_fact(&self, rel: &[u8]) -> bool {
if let Some(value) = self.file_cache.borrow().get(rel) {
return *value;
}
let value = self.inner.is_file(rel);
self.file_cache.borrow_mut().insert(rel.to_vec(), value);
value
}
fn record(&self, path: &[u8]) {
if self.paused.get() > 0 {
return;
}
if !self.typed && view_resolution_config(path) {
self.record(VIEW_CONFIG_MEMBERSHIP_DOMAIN.as_bytes());
return;
}
if let Ok(path) = std::str::from_utf8(path) {
let mut parts = Vec::new();
for part in path.split('/') {
match part {
"" | "." => {}
".." => {
parts.pop();
}
_ => parts.push(part),
}
}
let path = parts.join("/");
self.probes.borrow_mut().insert(path.clone());
for (_, trace) in self.memo_stack.borrow_mut().iter_mut() {
trace.probes.insert(path.clone());
}
}
}
test_support_visibility! {
fn take_config(&self) -> ConfigConsultations {
let mut result = std::mem::take(&mut *self.consultations.borrow_mut());
result.unattributed = result.unattributed();
result.reads.clear();
result
}
}
fn config_event(&self, path: &[u8], name: Option<&str>) {
if self.paused.get() > 0 {
return;
}
let Ok(path) = std::str::from_utf8(path) else {
self.consultations.borrow_mut().unattributed = true;
return;
};
let mut event = ConfigConsultations::default();
if let Some(name) = name {
event.facts.insert((path.into(), name.into()));
} else {
event.reads.insert(path.into());
}
self.consultations.borrow_mut().extend(&event);
for (_, trace) in self.memo_stack.borrow_mut().iter_mut() {
trace.config.extend(&event);
}
}
fn take(&self) -> BTreeSet<String> {
std::mem::take(&mut *self.probes.borrow_mut())
}
fn config_value(&self, rel: &[u8]) -> Option<Arc<[u8]>> {
let cached = self.config_cache.borrow().get(rel).cloned();
cached.unwrap_or_else(|| {
let value = self.inner.config_bytes(rel);
self.config_cache
.borrow_mut()
.insert(rel.to_vec(), value.clone());
value
})
}
}
impl ProjectFacts for ViewBindingFacts<'_> {
fn records_config_facts(&self) -> bool {
true
}
fn records_answers(&self) -> bool {
self.typed
}
fn config_fact(&self, rel: &[u8], name: &str) {
self.record(rel);
if !self.typed && matches!(name, "workspaces" | "packages") {
self.record(VIEW_CONFIG_MEMBERSHIP_DOMAIN.as_bytes());
}
self.config_event(rel, Some(name));
self.answered(
super::fact_answers::FactQuestion::ConfigField(rel.to_vec(), name.to_string()),
|| {
super::fact_answers::config_field_answer(
rel,
self.config_value(rel).as_deref(),
name,
)
},
);
}
fn memo_start(&self, path: &Path, kind: &str, name: &str) {
self.memo_stack.borrow_mut().push((
(path.into(), kind.into(), name.into()),
ConsultationTrace::default(),
));
}
fn memo_finish(&self, path: &Path, kind: &str, name: &str) {
let (key, trace) = self
.memo_stack
.borrow_mut()
.pop()
.expect("balanced resolver memo recording");
debug_assert_eq!(key, (path.into(), kind.into(), name.into()));
self.memo_traces.borrow_mut().insert(key, trace);
}
fn record_domain(&self, key: &str) {
self.record(key.as_bytes());
}
fn pause_recording(&self) {
self.paused.set(self.paused.get() + 1);
}
fn resume_recording(&self) {
self.paused.set(self.paused.get().saturating_sub(1));
}
fn memo_replay(&self, path: &Path, kind: &str, name: &str) {
let traces = self.memo_traces.borrow();
let Some(trace) = traces.get(&(path.into(), kind.into(), name.into())) else {
self.consultations.borrow_mut().unattributed = true;
return;
};
self.consultations.borrow_mut().extend(&trace.config);
self.probes
.borrow_mut()
.extend(trace.probes.iter().cloned());
for (_, parent) in self.memo_stack.borrow_mut().iter_mut() {
parent.config.extend(&trace.config);
parent.probes.extend(trace.probes.iter().cloned());
}
if self.typed && self.paused.get() == 0 {
for (_, parent) in self.memo_stack.borrow_mut().iter_mut() {
parent
.answers
.extend(trace.answers.iter().map(|(q, a)| (q.clone(), a.clone())));
}
self.answers
.borrow_mut()
.extend(trace.answers.iter().map(|(q, a)| (q.clone(), a.clone())));
}
}
fn workspace_package(&self, root: &Path, name: &str) -> Option<Option<std::path::PathBuf>> {
self.workspace_packages
.borrow()
.get(&(root.into(), name.into()))
.cloned()
}
fn remember_workspace_package(
&self,
root: &Path,
name: &str,
value: Option<std::path::PathBuf>,
) {
self.workspace_packages
.borrow_mut()
.insert((root.into(), name.into()), value);
}
fn workspace_members(&self, root: &Path) -> Option<Arc<Vec<std::path::PathBuf>>> {
self.workspace_members.borrow().get(root).cloned()
}
fn remember_workspace_members(&self, root: &Path, value: Arc<Vec<std::path::PathBuf>>) {
self.workspace_members
.borrow_mut()
.insert(root.into(), value);
}
fn is_file(&self, rel: &[u8]) -> bool {
let is_file = self.file_fact(rel);
if is_file {
self.record(rel);
}
self.answered(
super::fact_answers::FactQuestion::IsFile(rel.to_vec()),
|| super::fact_answers::FactAnswer::Bool(is_file),
);
is_file
}
fn is_dir(&self, rel: &[u8]) -> bool {
let is_dir = self.inner.is_dir(rel);
self.answered(
super::fact_answers::FactQuestion::IsDir(rel.to_vec()),
|| super::fact_answers::FactAnswer::Bool(is_dir),
);
is_dir
}
fn config_bytes(&self, rel: &[u8]) -> Option<Arc<[u8]>> {
self.consultations.borrow_mut().unattributed = true;
for (_, trace) in self.memo_stack.borrow_mut().iter_mut() {
trace.config.unattributed = true;
}
let value = self.attributed_config_bytes(rel);
self.answered(
super::fact_answers::FactQuestion::Config(rel.to_vec()),
|| super::fact_answers::config_answer(value.as_deref()),
);
value
}
fn attributed_config_bytes(&self, rel: &[u8]) -> Option<Arc<[u8]>> {
self.config_event(rel, None);
self.record(rel);
self.config_value(rel)
}
fn symlink_target(&self, rel: &[u8]) -> Option<&[u8]> {
let target = self.inner.symlink_target(rel);
self.answered(
super::fact_answers::FactQuestion::Link(rel.to_vec()),
|| super::fact_answers::FactAnswer::Path(target.map(<[u8]>::to_vec)),
);
target
}
fn canonical(&self, rel: &[u8]) -> Option<Vec<u8>> {
let cached = self.canonical_cache.borrow().get(rel).cloned();
let canonical = cached.unwrap_or_else(|| {
let value = self.inner.canonical(rel);
self.canonical_cache
.borrow_mut()
.insert(rel.to_vec(), value.clone());
value
});
if canonical.as_ref().is_none_or(|path| self.file_fact(path)) {
self.record(rel);
}
self.answered(
super::fact_answers::FactQuestion::Canonical(rel.to_vec()),
|| super::fact_answers::FactAnswer::Path(canonical.clone()),
);
canonical
}
fn list_dir(&self, rel: &[u8]) -> Vec<super::facts::DirEntry> {
let cached = self.directory_cache.borrow().get(rel).cloned();
let value = cached.unwrap_or_else(|| {
let value = self.inner.list_dir(rel);
self.directory_cache
.borrow_mut()
.insert(rel.to_vec(), value.clone());
value
});
self.answered(
super::fact_answers::FactQuestion::ListDir(rel.to_vec()),
|| super::fact_answers::listing_answer(&value),
);
value
}
}
pub fn bind_file(
rel: &str,
blob: &ParseBlob,
facts: &ViewBindingFacts<'_>,
cache: Option<&ViewBindingDependencies>,
) -> Result<(super::DbFileIndex, ViewBindingDependencies), ManifestJoinError> {
let root = Path::new("/");
let paths = FactPaths { root, facts };
facts.take();
facts.take_config();
facts.take_answers();
let extract = blob.bind_with_dependencies(rel, &paths, cache.map(|cache| &cache.references))?;
let file_index = super::DbFileIndex::from_extract(root, &extract, &paths);
let mut binding = cache.cloned().unwrap_or_default();
binding.surface = Some(ViewFileSurface::capture(&blob.language, &file_index));
if cache.is_none() {
binding.references = blob
.refs
.iter()
.zip(&extract.raw_refs)
.enumerate()
.map(|(position, (_, bound))| {
(
u32::try_from(position).expect("reference vector fits u32"),
bound.dependencies.clone(),
)
})
.collect();
binding.binding_probes = facts.take();
binding.binding_facts = facts.take_config();
binding.binding_answers = facts.take_answers();
binding.dependencies = binding.references.values().flatten().cloned().collect();
binding
.dependencies
.extend(binding.binding_probes.iter().cloned());
}
Ok((file_index, binding))
}
#[expect(
clippy::too_many_arguments,
reason = "one caller's resolution needs every one of these inputs"
)]
pub fn resolve_file(
caller: &str,
key: &BlobKey,
blob: &ParseBlob,
binding: &mut ViewBindingDependencies,
index: &super::ProjectIndex<'_>,
facts: &ViewBindingFacts<'_>,
mut resolution_order: Option<&mut Vec<CallerRefKey>>,
rows: &mut BTreeSet<DerivedRow>,
) -> Result<usize, ManifestJoinError> {
let root = Path::new("/");
let paths = FactPaths { root, facts };
let basis: BTreeSet<String> = binding
.references
.values()
.flatten()
.chain(binding.binding_probes.iter())
.cloned()
.collect();
facts.take_answers();
let extract = blob.bind_with_dependencies(caller, &paths, Some(&binding.references))?;
binding.resolution_answers = facts.take_answers();
let mut caller_work = blob
.refs
.iter()
.zip(extract.raw_refs)
.zip(blob.reference_keys())
.map(|((raw, bound), reference_key)| {
(
CallerRefKey {
caller_blob_key: key.clone(),
ref_ordinal: reference_key,
caller_path: caller.as_bytes().to_vec(),
},
(raw.kind, bound),
)
})
.collect::<Vec<_>>();
caller_work.sort_by(|a, b| (&a.0, a.1 .0).cmp(&(&b.0, b.1 .0)));
let associated_ordinals = blob
.refs
.iter()
.filter(|reference| {
blob.language == "rust"
&& reference.full_ref.as_deref().is_some_and(|name| {
dispatch::associated_reference(name) || name.starts_with("self.")
})
})
.map(|reference| reference.ordinal)
.collect::<BTreeSet<_>>();
let receiver_ordinals = blob
.dispatch
.sites
.iter()
.filter(|site| !associated_ordinals.contains(&site.ordinal))
.map(|s| s.ordinal)
.collect::<BTreeSet<_>>();
let caller_data = &extract.data;
let surface_index = ViewSurfaceIndex::for_caller(index, caller, caller_data);
let mut resolutions = HashMap::<ViewResolutionBinding, (Option<String>, Option<String>)>::new();
let mut caller_queries = BTreeMap::new();
for (key, (kind, raw)) in caller_work {
let memo_key = ViewResolutionBinding::new(&raw, caller_data);
binding.resolved_dependencies.extend(
raw.dependencies
.iter()
.filter(|dependency| !basis.contains(*dependency))
.cloned(),
);
let (target_file, target_symbol) = if receiver_ordinals.contains(&key.ref_ordinal) {
(None, None)
} else {
match resolutions.entry(memo_key) {
std::collections::hash_map::Entry::Occupied(entry) => entry.get().clone(),
std::collections::hash_map::Entry::Vacant(entry) => {
facts.take();
facts.take_config();
facts.take_answers();
let resolved = super::resolve_ref(raw, &surface_index)
.map_err(|error| ManifestJoinError::Parse(error.to_string()))?;
binding.resolution_facts.extend(&facts.take_config());
binding.resolution_answers.extend(facts.take_answers());
caller_queries.extend(surface_index.take());
binding.resolved_dependencies.extend(
resolved
.dependencies
.into_iter()
.chain(facts.take())
.filter(|dependency| !basis.contains(dependency)),
);
entry
.insert((resolved.target_file, resolved.target_symbol))
.clone()
}
}
};
if let Some(order) = resolution_order.as_deref_mut() {
order.push(key.clone());
}
rows.insert(DerivedRow {
caller_blob_key: key.caller_blob_key,
ref_ordinal: key.ref_ordinal,
caller_path: key.caller_path,
kind,
status: if target_file.is_some() {
ResolutionStatus::Resolved
} else {
ResolutionStatus::Unresolved
},
target_path: target_file.map(String::into_bytes),
target_symbol,
});
}
binding.surface_queries = caller_queries.into_iter().collect();
Ok(resolutions.len())
}
pub fn finish_binding(binding: &mut ViewBindingDependencies) {
binding.consulted_facts = binding
.binding_facts
.facts
.union(&binding.resolution_facts.facts)
.cloned()
.collect();
binding.unattributed =
binding.binding_facts.unattributed() || binding.resolution_facts.unattributed();
binding.dependencies = binding
.references
.values()
.flatten()
.cloned()
.chain(binding.binding_probes.iter().cloned())
.chain(binding.resolved_dependencies.iter().cloned())
.chain(
binding
.surface_queries
.iter()
.flat_map(|(query, _)| query.dependencies()),
)
.collect();
}
pub fn dispatch_type_targets_for(
file: &str,
blob: &ParseBlob,
index: &super::ProjectIndex<'_>,
facts: &ViewBindingFacts<'_>,
) -> Result<DispatchTypeTargets, ManifestJoinError> {
let data = blob.file_data(file)?;
facts.take();
facts.take_config();
facts.take_answers();
let recording = ViewSurfaceIndex::reading_inner(index, &data);
let targets = resolve_dispatch_type_names(&recording, file, blob, &data);
let probes = facts.take();
facts.take_config();
Ok(DispatchTypeTargets {
targets,
trace: DispatchTypeTargetTrace {
queries: recording.take().into_iter().collect(),
probes,
answers: facts.take_answers(),
},
})
}
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub enum ViewSurfaceQuery {
Language(String),
Module(String, String),
MacroUse(String),
Parent(String),
Reexports(String),
Node(String, String),
Callable(String, String),
Alias(String, String),
Export(String, String),
Default(String),
Contains(String),
Crate(String),
CrateRoot(String),
Inline(String, Vec<String>, String),
GoPackage(String, Option<String>),
}
fn surface_value(value: &impl Serialize) -> String {
blake3::hash(&serde_json::to_vec(value).expect("resolver surface serializes"))
.to_hex()
.to_string()
}
fn reexport_surface(value: &[super::ReexportIndex]) -> String {
surface_value(
&value
.iter()
.map(|entry| {
(
&entry.target_file,
entry.named.iter().collect::<BTreeMap<_, _>>(),
entry.wildcard,
)
})
.collect::<Vec<_>>(),
)
}
pub const VIEW_CONFIG_MEMBERSHIP_DOMAIN: &str = "\0view:config-membership";
pub const VIEW_JS_WORKSPACES_DOMAIN: &str = "\0view:js-workspaces";
pub fn js_package_key(root: &str, name: &str) -> String {
format!("{VIEW_JS_WORKSPACES_DOMAIN}\0{root}\0{name}")
}
pub fn rust_module_key(src_prefix: &str, segments: &[String]) -> String {
format!("\0view:rust-module:{src_prefix}:{}", segments.join("::"))
}
pub fn rust_module_key_for_file(path: &str) -> String {
rust_module_key(
&super::rust_src_prefix(path),
&super::rust_module_segments_for_rel(path),
)
}
pub fn rust_module_name_key(file: &str, name: &str) -> String {
format!("\0view:rust-module-name:{file}\0{name}")
}
pub const VIEW_GO_PACKAGE_DOMAIN: &str = "\0view:go-package-files";
pub const VIEW_GO_MODULES_DOMAIN: &str = "\0view:go-modules";
pub const VIEW_RUST_CRATES_DOMAIN: &str = "\0view:rust-crates";
pub fn rust_crate_key(name: &str) -> String {
format!("{VIEW_RUST_CRATES_DOMAIN}\0{name}")
}
impl ViewSurfaceQuery {
test_support_visibility! {
fn dependencies(&self) -> Vec<String> {
match self {
Self::Module(file, name) => {
vec![file.clone(), rust_module_name_key(file, name)]
}
Self::Crate(name) => vec![
VIEW_CONFIG_MEMBERSHIP_DOMAIN.into(),
VIEW_RUST_CRATES_DOMAIN.into(),
rust_crate_key(name),
],
Self::CrateRoot(file) => {
let mut dependencies = vec![file.clone(), VIEW_CONFIG_MEMBERSHIP_DOMAIN.into()];
let mut directory = std::path::Path::new(file).parent();
while let Some(current) = directory {
dependencies.push(if current.as_os_str().is_empty() {
"Cargo.toml".to_string()
} else {
format!("{}/Cargo.toml", current.display())
});
directory = current.parent();
}
dependencies
}
Self::Parent(file) => vec![file.clone()],
Self::Inline(file, segments, _) => {
let prefix = super::rust_src_prefix(file);
let mut dependencies = vec![file.clone()];
dependencies.extend(
(0..segments.len()).map(|len| rust_module_key(&prefix, &segments[..len])),
);
dependencies
}
Self::GoPackage(..) => {
vec![VIEW_GO_PACKAGE_DOMAIN.into(), VIEW_GO_MODULES_DOMAIN.into()]
}
Self::Language(file)
| Self::MacroUse(file)
| Self::Reexports(file)
| Self::Node(file, _)
| Self::Callable(file, _)
| Self::Alias(file, _)
| Self::Export(file, _)
| Self::Default(file)
| Self::Contains(file) => vec![file.clone()],
}
}
}
test_support_visibility! {
fn depends_on_any(&self, changed: &BTreeSet<String>) -> bool {
match self {
Self::Module(file, name) => {
changed.contains(file) || changed.contains(&rust_module_name_key(file, name))
}
Self::GoPackage(..) => {
changed.contains(VIEW_GO_PACKAGE_DOMAIN) || changed.contains(VIEW_GO_MODULES_DOMAIN)
}
Self::Language(file)
| Self::MacroUse(file)
| Self::Parent(file)
| Self::Reexports(file)
| Self::Node(file, _)
| Self::Callable(file, _)
| Self::Alias(file, _)
| Self::Export(file, _)
| Self::Default(file)
| Self::Contains(file) => changed.contains(file),
Self::Crate(..) | Self::CrateRoot(..) | Self::Inline(..) => self
.dependencies()
.iter()
.any(|dependency| changed.contains(dependency)),
}
}
}
fn answer(&self, index: &impl super::ResolverIndex) -> String {
match self {
Self::Language(file) => {
surface_value(&index.lang_for(file).map(|lang| format!("{lang:?}")))
}
Self::Module(file, module) => surface_value(&index.module_target(file, module)),
Self::MacroUse(file) => surface_value(&index.macro_use_modules(file)),
Self::Parent(file) => surface_value(&index.module_parent(file)),
Self::Reexports(file) => reexport_surface(&index.reexports_for(file)),
Self::Node(file, symbol) => surface_value(&index.node_for_symbol(file, symbol)),
Self::Callable(file, node) => surface_value(&index.node_is_callable(file, node)),
Self::Alias(file, symbol) => surface_value(&index.export_alias(file, symbol)),
Self::Export(file, symbol) => surface_value(&index.has_export(file, symbol)),
Self::Default(file) => surface_value(&index.default_export(file)),
Self::Contains(file) => surface_value(&index.contains_file(file)),
Self::Crate(name) => surface_value(&index.crate_src_prefix(name)),
Self::CrateRoot(file) => surface_value(&index.rust_crate_root_file(file)),
Self::Inline(file, segments, symbol) => {
surface_value(&index.inline_scoped_target(file, segments, symbol))
}
Self::GoPackage(file, module) => {
surface_value(&index.go_package_files(file, module.as_deref()))
}
}
}
}
fn answer_is(
query: &ViewSurfaceQuery,
expected: &str,
index: &impl super::ResolverIndex,
answers: &mut BTreeMap<ViewSurfaceQuery, String>,
) -> bool {
if let Some(answer) = answers.get(query) {
return answer == expected;
}
let answer = query.answer(index);
let same = answer == expected;
answers.insert(query.clone(), answer);
same
}
struct ViewSurfaceIndex<'a, I> {
inner: &'a I,
queries: std::cell::RefCell<BTreeMap<ViewSurfaceQuery, String>>,
caller: Option<(&'a str, &'a FileCallData)>,
crate_roots: std::cell::RefCell<HashMap<String, Option<String>>>,
caller_modules: std::cell::RefCell<HashMap<String, Vec<String>>>,
alias_owner: Option<&'a FileCallData>,
caller_aliases: std::cell::OnceCell<std::rc::Rc<[super::RustModuleAliases]>>,
}
impl<'a, I> ViewSurfaceIndex<'a, I> {
fn for_caller(inner: &'a I, caller: &'a str, data: &'a FileCallData) -> Self {
Self::new(inner, Some((caller, data)), Some(data))
}
fn reading_inner(inner: &'a I, aliases_of: &'a FileCallData) -> Self {
Self::new(inner, None, Some(aliases_of))
}
fn new(
inner: &'a I,
caller: Option<(&'a str, &'a FileCallData)>,
alias_owner: Option<&'a FileCallData>,
) -> Self {
Self {
inner,
queries: Default::default(),
caller,
crate_roots: Default::default(),
caller_modules: Default::default(),
alias_owner,
caller_aliases: Default::default(),
}
}
fn keeps_answers() -> bool {
#[cfg(any(test, feature = "test-support"))]
if super::rust_module_work::disabled() {
return false;
}
true
}
}
impl<I> ViewSurfaceIndex<'_, I> {
fn record(&self, query: ViewSurfaceQuery, value: &impl Serialize) {
self.queries
.borrow_mut()
.insert(query, surface_value(value));
}
fn take(&self) -> BTreeMap<ViewSurfaceQuery, String> {
std::mem::take(&mut *self.queries.borrow_mut())
}
}
impl<I: super::ResolverIndex> super::ResolverIndex for ViewSurfaceIndex<'_, I> {
fn luau_config(&self, file: &str) -> Option<Arc<[u8]>> {
self.inner.luau_config(file)
}
fn macro_use_modules(&self, file: &str) -> Vec<String> {
let value = self.inner.macro_use_modules(file);
self.record(ViewSurfaceQuery::MacroUse(file.into()), &value);
value
}
fn go_package_files(&self, caller_file: &str, module: Option<&str>) -> Vec<String> {
let value = self.inner.go_package_files(caller_file, module);
self.record(
ViewSurfaceQuery::GoPackage(caller_file.into(), module.map(str::to_string)),
&value,
);
value
}
fn caller_data(&self, file: &str) -> Option<&FileCallData> {
self.caller
.filter(|(caller, _)| *caller == file)
.map(|(_, data)| data)
.or_else(|| self.inner.caller_data(file))
}
fn local_symbol(&self, file: &str, data: &FileCallData, query: &str) -> Option<String> {
self.inner.local_symbol(file, data, query)
}
fn lang_for(&self, file: &str) -> Option<LangId> {
let value = self.inner.lang_for(file);
self.record(
ViewSurfaceQuery::Language(file.into()),
&value.map(|lang| format!("{lang:?}")),
);
value
}
fn module_target(&self, file: &str, module: &str) -> Option<String> {
let value = self.inner.module_target(file, module);
self.record(ViewSurfaceQuery::Module(file.into(), module.into()), &value);
value
}
fn module_parent(&self, file: &str) -> Option<(String, String)> {
let value = self.inner.module_parent(file);
self.record(ViewSurfaceQuery::Parent(file.into()), &value);
value
}
fn reexports_for(&self, file: &str) -> Vec<super::ReexportIndex> {
let value = self.inner.reexports_for(file);
self.queries.borrow_mut().insert(
ViewSurfaceQuery::Reexports(file.into()),
reexport_surface(&value),
);
value
}
fn node_for_symbol(&self, file: &str, symbol: &str) -> Option<String> {
let value = self.inner.node_for_symbol(file, symbol);
self.record(ViewSurfaceQuery::Node(file.into(), symbol.into()), &value);
value
}
fn node_is_callable(&self, file: &str, node: &str) -> bool {
let value = self.inner.node_is_callable(file, node);
self.record(ViewSurfaceQuery::Callable(file.into(), node.into()), &value);
value
}
fn export_alias(&self, file: &str, symbol: &str) -> Option<String> {
let value = self.inner.export_alias(file, symbol);
self.record(ViewSurfaceQuery::Alias(file.into(), symbol.into()), &value);
value
}
fn has_export(&self, file: &str, symbol: &str) -> bool {
let value = self.inner.has_export(file, symbol);
self.record(ViewSurfaceQuery::Export(file.into(), symbol.into()), &value);
value
}
fn default_export(&self, file: &str) -> Option<String> {
let value = self.inner.default_export(file);
self.record(ViewSurfaceQuery::Default(file.into()), &value);
value
}
fn contains_file(&self, file: &str) -> bool {
let value = self.inner.contains_file(file);
self.record(ViewSurfaceQuery::Contains(file.into()), &value);
value
}
fn crate_src_prefix(&self, name: &str) -> Option<String> {
let value = self.inner.crate_src_prefix(name);
self.record(ViewSurfaceQuery::Crate(name.into()), &value);
value
}
fn rust_crate_root_file(&self, file: &str) -> Option<String> {
if let Some(value) = self.crate_roots.borrow().get(file) {
return value.clone();
}
let value = self.inner.rust_crate_root_file(file);
self.record(ViewSurfaceQuery::CrateRoot(file.into()), &value);
if Self::keeps_answers() {
self.crate_roots
.borrow_mut()
.insert(file.to_string(), value.clone());
}
value
}
fn rust_caller_module_segments(&self, caller_file: &str) -> Vec<String> {
if let Some(segments) = self.caller_modules.borrow().get(caller_file) {
return segments.clone();
}
let segments = super::rust_caller_module_segments_uncached(self, caller_file);
if Self::keeps_answers() {
self.caller_modules
.borrow_mut()
.insert(caller_file.to_string(), segments.clone());
}
segments
}
fn rust_module_aliases(&self, data: &FileCallData) -> std::rc::Rc<[super::RustModuleAliases]> {
match self.alias_owner {
Some(owner) if std::ptr::eq(owner, data) && Self::keeps_answers() => {
std::rc::Rc::clone(
self.caller_aliases
.get_or_init(|| super::rust_module_aliases_of(data)),
)
}
_ => super::rust_module_aliases_of(data),
}
}
fn inline_scoped_target(
&self,
file: &str,
segments: &[String],
symbol: &str,
) -> Option<(String, String)> {
let value = self.inner.inline_scoped_target(file, segments, symbol);
self.record(
ViewSurfaceQuery::Inline(file.into(), segments.to_vec(), symbol.into()),
&value,
);
value
}
}
aft_store::heap_bytes_none!(BlobRefKind, ResolutionStatus);
aft_store::heap_bytes_of_fields!(ParseBlob {
entry_point_symbols,
dispatch,
extractor_version,
language,
ast_nodes,
symbols,
default_export_symbol,
exported_symbols,
callable_symbols,
imports,
python_bindings,
refs,
});
aft_store::heap_bytes_of_fields!(AstPreorderNode {
ordinal,
kind,
byte_start,
byte_end,
});
aft_store::heap_bytes_of_fields!(BlobSymbol {
is_test,
ordinal,
name,
scoped_name,
kind,
exported,
is_default_export,
start_line,
start_col,
end_line,
end_col,
signature,
program_start,
entry_attribute,
});
aft_store::heap_bytes_of_fields!(BlobRef {
ordinal,
kind,
caller_symbol,
short_name,
full_ref,
module_path,
line,
byte_start,
byte_end,
path_override,
local_name,
requested_name,
namespace_alias,
wildcard,
import_kind,
});
aft_store::heap_bytes_of_fields!(BlobImport {
ordinal,
module_path,
names,
default_import,
namespace_import,
byte_start,
byte_end,
raw_text,
type_only,
side_effect,
});
aft_store::heap_bytes_of_fields!(DerivedRow {
caller_blob_key,
ref_ordinal,
caller_path,
kind,
status,
target_path,
target_symbol,
});
aft_store::heap_bytes_of_fields!(DispatchTypeTargets { targets, trace });
aft_store::heap_bytes_of_fields!(DispatchTypeTargetTrace {
queries,
probes,
answers,
});
aft_store::heap_bytes_of_fields!(ViewBindingDependencies {
references,
dependencies,
consulted_facts,
unattributed,
binding_facts,
resolution_facts,
binding_probes,
resolved_dependencies,
surface_queries,
binding_answers,
resolution_answers,
surface,
});
aft_store::heap_bytes_of_fields!(ConfigConsultations {
facts,
reads,
unattributed,
});
aft_store::heap_bytes_of_fields!(ViewFileSurface {
language,
exports,
default_export,
export_aliases,
node_by_scoped,
node_by_bare,
node_kind_by_id,
module_targets,
declared_module_targets,
macro_use_module_targets,
reexports,
});
impl aft_store::heap::HeapBytes for ViewSurfaceQuery {
fn heap_bytes(&self, seen: &mut aft_store::heap::Seen) -> usize {
match self {
Self::Language(a)
| Self::MacroUse(a)
| Self::Parent(a)
| Self::Reexports(a)
| Self::Default(a)
| Self::Contains(a)
| Self::Crate(a)
| Self::CrateRoot(a) => a.heap_bytes(seen),
Self::Module(a, b)
| Self::Node(a, b)
| Self::Callable(a, b)
| Self::Alias(a, b)
| Self::Export(a, b) => a.heap_bytes(seen) + b.heap_bytes(seen),
Self::Inline(a, names, b) => {
a.heap_bytes(seen) + names.heap_bytes(seen) + b.heap_bytes(seen)
}
Self::GoPackage(a, b) => a.heap_bytes(seen) + b.heap_bytes(seen),
}
}
}