use std::borrow::Cow;
use std::collections::HashMap;
use std::path::Path;
use super::syntax_index::SyntaxIndex;
use super::{
assign_ordinals, blob_imports, blob_refs, blob_symbols, dispatch, language_id, structural_ref,
AstPreorderNode, BlobRef, BlobRefKind, CallgraphBlob, ManifestJoinError, ParseBlob, Parser,
};
use crate::callgraph;
use crate::callgraph_store::facts::{FactPaths, NoProjectFacts};
use crate::parser::LangId;
test_support_visibility! {
pub(super) fn extract(
source: &str,
language: &str,
extractor_version: String,
) -> Result<CallgraphBlob, ManifestJoinError> {
let lang = language_id(language)
.ok_or_else(|| ManifestJoinError::UnsupportedLanguage(language.to_string()))?;
let tree = parse_source(source, lang)?;
extract_tree(source, language, extractor_version, &tree, None)
}
}
pub(super) fn extract_tree(
source: &str,
language: &str,
extractor_version: String,
tree: &tree_sitter::Tree,
outline: Option<&mut Vec<crate::symbols::Symbol>>,
) -> Result<CallgraphBlob, ManifestJoinError> {
let lang = language_id(language)
.ok_or_else(|| ManifestJoinError::UnsupportedLanguage(language.to_string()))?;
let root = tree.root_node();
let index = SyntaxIndex::new(root);
let ast_nodes = ast_preorder_nodes(&index);
let line_index = crate::callgraph_store::LineIndex::new(source);
let mut data = callgraph::build_file_data_from_index(
Path::new("__callgraph_blob__"),
source,
lang,
tree,
&line_index,
&index,
outline,
)
.map_err(|error| ManifestJoinError::Parse(error.to_string()))?;
if lang == LangId::Rust {
crate::callgraph_store::extend_rust_imports_from_uses(
source,
index
.preorder_kinds()
.filter(|(_, kind)| *kind == "use_declaration")
.map(|(node, _)| node),
&mut data,
);
}
let mut symbols = blob_symbols(&data);
let mut imports = blob_imports(&data);
let mut refs = blob_refs(&line_index, &data);
if lang == LangId::Luau {
refs.extend(
crate::luau::exports(source, root)
.into_iter()
.map(|(name, export)| BlobRef {
ordinal: 0,
kind: BlobRefKind::ExportAlias,
caller_symbol: None,
short_name: None,
full_ref: Some(name.clone()),
module_path: None,
line: 1,
byte_start: 0,
byte_end: source.len(),
path_override: None,
local_name: Some(name),
requested_name: Some(export.symbol),
namespace_alias: None,
wildcard: false,
import_kind: Some("export_alias".to_string()),
}),
);
}
if lang == LangId::Rust {
refs.extend(rust_module_refs(source, &index));
}
let paths = FactPaths {
root: Path::new("/"),
facts: &NoProjectFacts,
};
let file = Path::new("/__callgraph_blob__");
let mut structural = crate::callgraph_store::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(
crate::callgraph_store::collect_source_less_export_alias_refs_with_line_index(
"__callgraph_blob__",
source,
&line_index,
)
.raw_refs,
);
if lang == LangId::Rust {
structural.extend(
crate::callgraph_store::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_with(source, lang, root, &mut parse, &index)?;
Ok(CallgraphBlob::Parse(parse))
}
fn ast_preorder_nodes(index: &SyntaxIndex<'_>) -> Vec<AstPreorderNode> {
index
.preorder_kinds()
.enumerate()
.map(|(ordinal, (node, kind))| AstPreorderNode {
ordinal: ordinal as u32,
kind: Cow::Borrowed(kind),
byte_start: node.start_byte(),
byte_end: node.end_byte(),
})
.collect()
}
fn rust_module_refs(source: &str, index: &SyntaxIndex<'_>) -> Vec<BlobRef> {
let mut refs = Vec::new();
for (node, kind) in index.preorder_kinds() {
if kind != "mod_item"
|| node
.named_children(&mut node.walk())
.any(|child| child.kind() == "declaration_list")
{
continue;
}
let Some(name) = node.child_by_field_name("name") else {
continue;
};
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 crate::callgraph_store::rust_module_has_macro_use_with(source, node, index) {
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: crate::callgraph_store::rust_module_path_override_with(
source, node, index,
)
.map(str::to_string),
local_name: None,
requested_name: None,
namespace_alias: None,
wildcard: false,
import_kind: None,
});
}
refs
}
pub fn parse_source(source: &str, lang: LangId) -> Result<tree_sitter::Tree, ManifestJoinError> {
refuse_unsafe_markdown(source, lang)?;
if let Some(tree) = crate::parser::cached_header_tree(source, lang) {
return Ok(tree);
}
with_parser(lang, |parser| {
crate::parser::parse_with_parser(
parser,
std::path::Path::new("<index-content>"),
source,
lang,
None,
)
.map_err(super::extraction_error)
})
}
fn refuse_unsafe_markdown(source: &str, lang: LangId) -> Result<(), ManifestJoinError> {
if crate::parser::markdown_too_deep_to_parse(lang, source) {
return Err(ManifestJoinError::Parse(
crate::parser::MARKDOWN_TOO_DEEP.to_string(),
));
}
Ok(())
}
pub fn reparse_source(
previous_source: &str,
previous: &tree_sitter::Tree,
source: &str,
lang: LangId,
) -> Result<tree_sitter::Tree, ManifestJoinError> {
refuse_unsafe_markdown(source, lang)?;
let Some(edit) = text_edit(previous_source.as_bytes(), source.as_bytes()) else {
return Ok(previous.clone());
};
let mut tree = previous.clone();
tree.edit(&edit);
with_parser(lang, |parser| {
crate::parser::parse_with_parser(
parser,
std::path::Path::new("<index-content>"),
source,
lang,
Some(&tree),
)
.map_err(super::extraction_error)
})
}
test_support_visibility! {
fn text_edit(old: &[u8], new: &[u8]) -> Option<tree_sitter::InputEdit> {
if old == new {
return None;
}
let prefix = old.iter().zip(new).take_while(|(a, b)| a == b).count();
let longest_suffix = old.len().min(new.len()) - prefix;
let suffix = old
.iter()
.rev()
.zip(new.iter().rev())
.take(longest_suffix)
.take_while(|(a, b)| a == b)
.count();
let point = |text: &[u8], byte: usize| {
let before = &text[..byte];
let row = before.iter().filter(|&&b| b == b'\n').count();
let line_start = before
.iter()
.rposition(|&b| b == b'\n')
.map_or(0, |i| i + 1);
tree_sitter::Point::new(row, byte - line_start)
};
Some(tree_sitter::InputEdit {
start_byte: prefix,
old_end_byte: old.len() - suffix,
new_end_byte: new.len() - suffix,
start_position: point(old, prefix),
old_end_position: point(old, old.len() - suffix),
new_end_position: point(new, new.len() - suffix),
})
}
}
thread_local! {
static EXTRACTION_PARSERS: std::cell::RefCell<HashMap<LangId, Parser>> =
std::cell::RefCell::new(HashMap::new());
}
#[cfg(all(
any(test, feature = "test-support"),
feature = "test-hooks",
feature = "wasm-grammars"
))]
pub fn install_luau_parser_for_test(parser: Parser) {
EXTRACTION_PARSERS.with(|parsers| {
parsers.borrow_mut().insert(LangId::Luau, parser);
});
}
#[cfg(all(
any(test, feature = "test-support"),
feature = "test-hooks",
feature = "wasm-grammars"
))]
pub fn retains_luau_parser_for_test() -> bool {
EXTRACTION_PARSERS.with(|parsers| parsers.borrow().contains_key(&LangId::Luau))
}
fn with_parser(
lang: LangId,
parse: impl FnOnce(&mut Parser) -> Result<tree_sitter::Tree, ManifestJoinError>,
) -> Result<tree_sitter::Tree, ManifestJoinError> {
EXTRACTION_PARSERS.with(|parsers| {
let mut parsers = parsers.borrow_mut();
let mut parser = match parsers.remove(&lang) {
Some(parser) => parser,
None => {
let mut parser = Parser::new();
crate::parser::initialize_parser(&mut parser, lang)
.map_err(super::extraction_error)?;
parser
}
};
#[cfg(any(test, feature = "test-support"))]
parser.note_parse();
let result = parse(&mut parser);
if result.is_ok() {
parsers.insert(lang, parser);
}
result
})
}