use std::collections::{BTreeSet, HashSet};
use rustc_hash::{FxHashMap, FxHashSet};
use crate::callgraph_store::join::syntax_index::{Direct, Nav};
use crate::parser::LangId;
const MAX_AST_WALK_DEPTH: u32 = 1_500;
const MAX_RUST_MACRO_CALL_DEPTH: u32 = 32;
thread_local! {
static RUST_FRAGMENT_PARSER: std::cell::RefCell<Option<tree_sitter::Parser>> = const { std::cell::RefCell::new(None) };
#[cfg(any(test, feature = "test-support"))]
pub static RUST_FRAGMENT_TREES: std::cell::RefCell<Option<FxHashMap<String, tree_sitter::Tree>>> = const { std::cell::RefCell::new(None) };
#[cfg(not(any(test, feature = "test-support")))]
static RUST_FRAGMENT_TREES: std::cell::RefCell<Option<FxHashMap<String, tree_sitter::Tree>>> = const { std::cell::RefCell::new(None) };
}
#[cfg(any(test, feature = "test-support"))]
thread_local! {
pub static RUST_FRAGMENT_PARSER_INITIALIZATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
pub static RUST_FRAGMENT_PARSES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
pub struct RustMacroFragmentCache {
owner: bool,
_thread: std::marker::PhantomData<*mut ()>,
}
pub fn cache_rust_macro_fragments() -> RustMacroFragmentCache {
let owner = RUST_FRAGMENT_TREES.with(|trees| {
let mut trees = trees.borrow_mut();
if trees.is_some() {
false
} else {
*trees = Some(FxHashMap::default());
true
}
});
RustMacroFragmentCache {
owner,
_thread: std::marker::PhantomData,
}
}
impl Drop for RustMacroFragmentCache {
fn drop(&mut self) {
if self.owner {
RUST_FRAGMENT_TREES.with(|trees| *trees.borrow_mut() = None);
}
}
}
pub fn call_node_kinds(lang: LangId) -> &'static [&'static str] {
match lang {
LangId::TypeScript | LangId::JavaScript => &["call_expression", "new_expression"],
LangId::Tsx => &[
"call_expression",
"new_expression",
"jsx_opening_element",
"jsx_self_closing_element",
],
LangId::Go => &["call_expression"],
LangId::Python => &["call"],
LangId::Rust => &["call_expression", "macro_invocation"],
LangId::Solidity | LangId::Scala => &["call_expression"],
LangId::Java => &["method_invocation"],
LangId::Ruby => &["call"],
LangId::Kotlin | LangId::Swift => &["call_expression"],
LangId::Php => &[
"function_call_expression",
"member_call_expression",
"nullsafe_member_call_expression",
"scoped_call_expression",
],
LangId::Perl => &["function_call_expression", "method_call_expression"],
LangId::Lua | LangId::Luau => &["function_call"],
LangId::C | LangId::Cpp | LangId::Cuda | LangId::Metal | LangId::Zig => {
&["call_expression"]
}
LangId::CSharp => &["invocation_expression"],
LangId::Bash
| LangId::Scss
| LangId::Vue
| LangId::Html
| LangId::Markdown
| LangId::Json
| LangId::Yaml
| LangId::Pascal
| LangId::R
| LangId::Groovy
| LangId::ObjC
| LangId::Toml => &[],
}
}
test_support_visibility! {
fn walk_for_calls(
node: tree_sitter::Node,
source: &str,
byte_start: usize,
byte_end: usize,
call_kinds: &[&str],
results: &mut Vec<(String, u32)>,
) {
walk_for_calls_at_depth(node, source, byte_start, byte_end, call_kinds, results, 0);
}
}
fn walk_for_calls_at_depth(
node: tree_sitter::Node,
source: &str,
byte_start: usize,
byte_end: usize,
call_kinds: &[&str],
results: &mut Vec<(String, u32)>,
depth: u32,
) {
let node_start = node.start_byte();
let node_end = node.end_byte();
if node_end <= byte_start || node_start >= byte_end {
return;
}
if call_kinds.contains(&node.kind()) && node_start >= byte_start && node_end <= byte_end {
if let Some(name) = extract_callee_name(&node, source) {
results.push((name, node.start_position().row as u32 + 1));
}
}
if depth >= MAX_AST_WALK_DEPTH {
return;
}
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
walk_for_calls_at_depth(
cursor.node(),
source,
byte_start,
byte_end,
call_kinds,
results,
depth + 1,
);
if !cursor.goto_next_sibling() {
break;
}
}
}
}
pub fn extract_callee_name(node: &tree_sitter::Node, source: &str) -> Option<String> {
let kind = node.kind();
if kind == "macro_invocation" {
let first_child = node.child(0)?;
let text = &source[first_child.byte_range()];
return Some(format!("{}!", text));
}
let func_node = callee_node(node)?;
let func_kind = func_node.kind();
match func_kind {
"identifier" => Some(source[func_node.byte_range()].to_string()),
"member_expression"
| "field_expression"
| "attribute"
| "member_access_expression"
| "qualified_identifier"
| "generic_function"
| "generic_name"
| "template_function"
| "template_method" => {
extract_last_segment(&func_node, source)
}
"subscript_expression" => extract_computed_member_name(&func_node, source)
.or_else(|| extract_last_segment(&func_node, source)),
_ => {
let text = &source[func_node.byte_range()];
let name = if text.contains('.') {
text.rsplit('.').next().map(|s| s.trim().to_string())
} else {
Some(text.trim().to_string())
};
name.filter(|name| is_name_like_callee(name))
}
}
}
fn is_name_like_callee(text: &str) -> bool {
!text.is_empty()
&& text.chars().all(|ch| {
ch.is_alphanumeric() || matches!(ch, '_' | '$' | ':' | '\\' | '@' | '?' | '!')
})
}
pub fn extract_full_callee(node: &tree_sitter::Node, source: &str) -> Option<String> {
let kind = node.kind();
if kind == "macro_invocation" {
let first_child = node.child(0)?;
let text = &source[first_child.byte_range()];
return Some(format!("{}!", text));
}
let func_node = callee_node(node)?;
let func_node = strip_generic_callee_wrapper(func_node);
Some(source[func_node.byte_range()].trim().to_string())
}
fn callee_node<'a>(node: &tree_sitter::Node<'a>) -> Option<tree_sitter::Node<'a>> {
match node.kind() {
"new_expression" => node
.child_by_field_name("constructor")
.or_else(|| node.named_child(0)),
"jsx_opening_element" | "jsx_self_closing_element" => node
.child_by_field_name("name")
.or_else(|| node.named_child(0)),
"method_call_expression" => node
.child_by_field_name("method")
.or_else(|| node.child_by_field_name("function")),
_ => node
.child_by_field_name("function")
.or_else(|| node.child(0)),
}
}
fn strip_generic_callee_wrapper<'a>(node: tree_sitter::Node<'a>) -> tree_sitter::Node<'a> {
if node.kind() == "generic_function" {
node.child_by_field_name("function")
.or_else(|| node.named_child(0))
.unwrap_or(node)
} else {
node
}
}
pub fn extract_computed_member_name(node: &tree_sitter::Node, source: &str) -> Option<String> {
let index = node.child_by_field_name("index")?;
let text = source[index.byte_range()].trim();
computed_member_literal(text)
}
test_support_visibility! {
fn computed_member_literal(text: &str) -> Option<String> {
if text.len() >= 2
&& ((text.starts_with('"') && text.ends_with('"'))
|| (text.starts_with('\'') && text.ends_with('\'')))
{
return Some(text[1..text.len().saturating_sub(1)].to_string());
}
None
}
}
fn extract_last_segment(node: &tree_sitter::Node, source: &str) -> Option<String> {
let mut node = *node;
'descend: loop {
node = strip_generic_callee_wrapper(node);
if let Some(name) = node.child_by_field_name("name") {
node = name;
continue;
}
let child_count = node.child_count();
for i in (0..child_count).rev() {
if let Some(child) = node.child(i as u32) {
match child.kind() {
"property_identifier" | "field_identifier" | "identifier" => {
return Some(source[child.byte_range()].to_string());
}
"generic_function" | "generic_name" | "template_function"
| "template_method" => {
node = child;
continue 'descend;
}
_ => {}
}
}
}
let text = &source[node.byte_range()];
return text.rsplit('.').next().map(|s| s.trim().to_string());
}
}
fn extract_type_references_in_range(
source: &str,
root: tree_sitter::Node,
byte_start: usize,
byte_end: usize,
lang: LangId,
) -> BTreeSet<String> {
let mut results = BTreeSet::new();
collect_type_references(root, source, byte_start, byte_end, lang, &mut results);
results
}
pub fn extract_type_references(
source: &str,
root: tree_sitter::Node,
lang: LangId,
) -> BTreeSet<String> {
extract_type_references_in_range(source, root, 0, source.len(), lang)
}
test_support_visibility! {
fn collect_type_references(
node: tree_sitter::Node,
source: &str,
byte_start: usize,
byte_end: usize,
lang: LangId,
results: &mut BTreeSet<String>,
) {
collect_type_references_at_depth(node, source, byte_start, byte_end, lang, results, 0);
}
}
fn collect_type_references_at_depth(
node: tree_sitter::Node,
source: &str,
byte_start: usize,
byte_end: usize,
lang: LangId,
results: &mut BTreeSet<String>,
depth: u32,
) {
let node_start = node.start_byte();
let node_end = node.end_byte();
if node_end <= byte_start || node_start >= byte_end {
return;
}
if depth >= MAX_AST_WALK_DEPTH {
return;
}
if node_start >= byte_start && node_end <= byte_end {
collect_type_reference_fields(&node, source, lang, results);
if is_type_context_node(lang, node.kind()) {
collect_type_reference_identifiers(node, source, lang, results);
return;
}
}
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
collect_type_references_at_depth(
cursor.node(),
source,
byte_start,
byte_end,
lang,
results,
depth + 1,
);
if !cursor.goto_next_sibling() {
break;
}
}
}
}
fn collect_type_reference_fields(
node: &tree_sitter::Node,
source: &str,
lang: LangId,
results: &mut BTreeSet<String>,
) {
for field in ["type", "return_type", "result", "trait"] {
if let Some(child) = node.child_by_field_name(field) {
collect_type_reference_identifiers(child, source, lang, results);
}
}
if matches!(lang, LangId::TypeScript | LangId::Tsx) && node.kind() == "type_alias_declaration" {
if let Some(value) = node.child_by_field_name("value") {
collect_type_reference_identifiers(value, source, lang, results);
}
}
if lang == LangId::Rust && node.kind() == "struct_expression" {
if let Some(name) = node.child_by_field_name("name") {
collect_type_reference_identifiers(name, source, lang, results);
}
}
}
fn is_type_context_node(lang: LangId, kind: &str) -> bool {
match lang {
LangId::TypeScript | LangId::Tsx => matches!(
kind,
"type_annotation"
| "type_arguments"
| "extends_clause"
| "implements_clause"
| "satisfies_expression"
),
LangId::JavaScript => false,
LangId::Python => kind == "type",
LangId::Rust => matches!(
kind,
"parameter"
| "field_declaration"
| "generic_type"
| "type_arguments"
| "reference_type"
| "array_type"
| "tuple_type"
| "bounded_type"
),
LangId::Go => matches!(
kind,
"field_declaration"
| "parameter_declaration"
| "generic_type"
| "type_arguments"
| "type_elem"
| "pointer_type"
| "array_type"
| "slice_type"
| "map_type"
| "qualified_type"
| "channel_type"
| "function_type"
),
_ => false,
}
}
fn collect_type_reference_identifiers(
node: tree_sitter::Node,
source: &str,
lang: LangId,
results: &mut BTreeSet<String>,
) {
collect_type_reference_identifiers_at_depth(node, source, lang, results, 0);
}
fn collect_type_reference_identifiers_at_depth(
node: tree_sitter::Node,
source: &str,
lang: LangId,
results: &mut BTreeSet<String>,
depth: u32,
) {
if is_type_reference_identifier(lang, node.kind()) {
let name = source[node.byte_range()].trim();
if let Some(name) = clean_type_reference_name(name) {
results.insert(name);
}
}
if depth >= MAX_AST_WALK_DEPTH {
return;
}
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
collect_type_reference_identifiers_at_depth(
cursor.node(),
source,
lang,
results,
depth + 1,
);
if !cursor.goto_next_sibling() {
break;
}
}
}
}
fn is_type_reference_identifier(lang: LangId, kind: &str) -> bool {
match lang {
LangId::TypeScript | LangId::Tsx => matches!(kind, "type_identifier" | "identifier"),
LangId::Python => kind == "identifier",
LangId::Rust | LangId::Go => kind == "type_identifier",
_ => false,
}
}
fn clean_type_reference_name(name: &str) -> Option<String> {
let name = name
.rsplit(['.', ':'])
.find(|segment| !segment.is_empty())
.unwrap_or(name)
.trim()
.trim_start_matches('?');
if name.is_empty()
|| !name
.chars()
.next()
.is_some_and(|c| c == '_' || c.is_alphabetic())
{
return None;
}
Some(name.to_string())
}
pub fn extract_go_value_references(source: &str, root: tree_sitter::Node) -> Vec<CallTuple> {
let mut results = Vec::new();
let mut pending = vec![(root, root.parent())];
while let Some((node, parent)) = pending.pop() {
let is_callee = parent.is_some_and(|p| {
p.kind() == "call_expression" && p.child_by_field_name("function") == Some(node)
});
let is_value = node.kind() == "selector_expression"
|| (node.kind() == "identifier"
&& parent.is_some_and(|p| {
matches!(
p.kind(),
"argument_list"
| "expression_list"
| "return_statement"
| "binary_expression"
| "unary_expression"
| "parenthesized_expression"
| "keyed_element"
| "literal_element"
)
}));
if is_value && !is_callee {
let full = source[node.byte_range()].to_string();
let short = full.rsplit('.').next().unwrap_or(&full).to_string();
results.push((
full,
short,
node.start_position().row as u32 + 1,
node.start_byte(),
node.end_byte(),
));
}
if node.kind() == "selector_expression" {
let mut selector = node;
let mut operand = node.child_by_field_name("operand");
while let Some(base) = operand {
if base.kind() == "selector_expression" {
selector = base;
operand = base.child_by_field_name("operand");
} else {
if !matches!(base.kind(), "identifier" | "package_identifier") {
pending.push((base, Some(selector)));
}
break;
}
}
} else {
let start = pending.len();
pending.extend(
node.named_children(&mut node.walk())
.map(|child| (child, Some(node))),
);
pending[start..].reverse();
}
}
results
}
pub fn extract_js_callback_references(
source: &str,
root: tree_sitter::Node<'_>,
) -> Vec<(String, String, u32, usize, usize)> {
extract_js_callback_references_with(source, root, Direct)
}
pub fn extract_js_callback_references_with<'tree>(
source: &str,
root: tree_sitter::Node<'tree>,
nav: impl Nav<'tree>,
) -> Vec<(String, String, u32, usize, usize)> {
let mut results = Vec::new();
let mut scopes = FxHashMap::default();
nav.walk_named(root, |node, kind| {
if kind == "arguments" {
for argument in node.named_children(&mut node.walk()) {
if matches!(nav.kind(argument), "identifier" | "member_expression") {
let full = source[argument.byte_range()].trim();
let root_name = full.split('.').next().unwrap_or(full);
if !js_callback_is_shadowed(source, argument, root_name, nav, &mut scopes) {
results.push((
full.to_string(),
full.rsplit('.').next().unwrap_or(full).to_string(),
argument.start_position().row as u32 + 1,
argument.start_byte(),
argument.end_byte(),
));
}
}
}
}
true
});
results.sort_by_key(|site| site.3);
results
}
struct JsScopeBindings<'source> {
parameters: FxHashSet<&'source str>,
declarations: FxHashMap<&'source str, bool>,
}
fn js_scope_bindings<'tree, 'source>(
source: &'source str,
scope: tree_sitter::Node<'tree>,
nav: impl Nav<'tree>,
) -> JsScopeBindings<'source> {
let mut bindings = JsScopeBindings {
parameters: FxHashSet::default(),
declarations: FxHashMap::default(),
};
if let Some(parameters) = scope.child_by_field_name("parameters") {
nav.walk_named(parameters, |node, kind| {
if kind == "identifier" {
bindings.parameters.insert(&source[node.byte_range()]);
}
true
});
}
if matches!(nav.kind(scope), "statement_block" | "program") {
for declaration in scope.named_children(&mut scope.walk()) {
if !matches!(
declaration.kind(),
"lexical_declaration" | "variable_declaration"
) {
continue;
}
for binding in declaration.named_children(&mut declaration.walk()) {
if let Some(name) = binding.child_by_field_name("name") {
let shadows = !binding.child_by_field_name("value").is_some_and(|value| {
matches!(value.kind(), "arrow_function" | "function_expression")
});
bindings
.declarations
.entry(&source[name.byte_range()])
.or_insert(shadows);
}
}
}
}
bindings
}
fn js_callback_is_shadowed<'tree, 'source>(
source: &'source str,
argument: tree_sitter::Node<'tree>,
name: &str,
nav: impl Nav<'tree>,
scopes: &mut FxHashMap<usize, JsScopeBindings<'source>>,
) -> bool {
let mut ancestor = nav.parent(argument);
while let Some(scope) = ancestor {
let bindings = scopes
.entry(scope.id())
.or_insert_with(|| js_scope_bindings(source, scope, nav));
if bindings.parameters.contains(name) {
return true;
}
if let Some(&shadows) = bindings.declarations.get(name) {
return shadows;
}
ancestor = nav.parent(scope);
}
false
}
pub fn extract_rust_value_references(
source: &str,
root: tree_sitter::Node,
) -> Vec<(String, String, u32, usize, usize)> {
extract_rust_value_references_with(source, root, Direct)
}
pub fn extract_rust_value_references_with<'tree>(
source: &str,
root: tree_sitter::Node<'tree>,
nav: impl Nav<'tree>,
) -> Vec<(String, String, u32, usize, usize)> {
#[cfg(any(test, feature = "test-support"))]
if LEGACY_VALUE_REFERENCES.with(|legacy| legacy.get()) {
let mut results = Vec::new();
collect_rust_value_references(root, source, &mut results, 0);
return results;
}
let mut walk = RustValueWalk {
source,
nav,
ancestors: Vec::new(),
blocks: FxHashMap::default(),
results: Vec::new(),
};
let mut parent = nav.parent(root);
while let Some(node) = parent {
walk.ancestors.push(node);
parent = nav.parent(node);
}
walk.ancestors.reverse();
for node in &walk.ancestors {
if nav.kind(*node) == "block" {
walk.blocks
.insert(node.id(), rust_block_bindings(*node, source));
}
}
walk.visit(root, 0);
walk.results
}
#[cfg(any(test, feature = "test-support"))]
thread_local! {
static LEGACY_VALUE_REFERENCES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
pub static VALUE_BINDING_WORK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
struct RustValueWalk<'tree, 'source, N> {
source: &'source str,
nav: N,
ancestors: Vec<tree_sitter::Node<'tree>>,
blocks: FxHashMap<usize, FxHashMap<&'source str, usize>>,
results: Vec<(String, String, u32, usize, usize)>,
}
fn rust_block_bindings<'source>(
block: tree_sitter::Node<'_>,
source: &'source str,
) -> FxHashMap<&'source str, usize> {
let mut bindings = FxHashMap::default();
let mut cursor = block.walk();
for child in block.children(&mut cursor) {
#[cfg(any(test, feature = "test-support"))]
VALUE_BINDING_WORK.with(|work| work.set(work.get() + 1));
if child.kind() != "let_declaration" {
continue;
}
if let Some(pattern) = child.child_by_field_name("pattern") {
let mut pending = vec![pattern];
while let Some(node) = pending.pop() {
#[cfg(any(test, feature = "test-support"))]
VALUE_BINDING_WORK.with(|work| work.set(work.get() + 1));
if node.kind() == "identifier" {
bindings
.entry(&source[node.byte_range()])
.or_insert(child.end_byte());
}
let mut pattern_cursor = node.walk();
pending.extend(node.children(&mut pattern_cursor));
}
}
}
bindings
}
impl<'tree, N: Nav<'tree>> RustValueWalk<'tree, '_, N> {
fn visit(&mut self, node: tree_sitter::Node<'tree>, depth: u32) {
let nav = self.nav;
let kind = nav.kind(node);
if kind == "block" {
self.blocks
.insert(node.id(), rust_block_bindings(node, self.source));
}
let nested = self.ancestors.last().is_some_and(|parent| {
matches!(
nav.kind(*parent),
"scoped_identifier" | "scoped_type_identifier" | "generic_function"
)
});
if matches!(kind, "identifier" | "scoped_identifier")
&& !nested
&& self.is_value_position(node)
{
let full = self.source[node.byte_range()].trim();
let short = full.rsplit("::").next().unwrap_or(full).trim();
if !full.is_empty()
&& !short.is_empty()
&& (kind != "identifier" || !self.is_shadowed(node))
{
self.results.push((
full.to_string(),
short.to_string(),
node.start_position().row as u32 + 1,
node.start_byte(),
node.end_byte(),
));
}
}
if depth < MAX_AST_WALK_DEPTH {
self.ancestors.push(node);
nav.for_each_child(node, |child| self.visit(child, depth + 1));
self.ancestors.pop();
}
if kind == "block" {
self.blocks.remove(&node.id());
}
}
fn is_value_position(&self, node: tree_sitter::Node<'_>) -> bool {
let mut current = node;
for parent in self.ancestors.iter().rev() {
let selected = |field: &str| {
parent
.child_by_field_name(field)
.is_some_and(|child| same_node(&child, ¤t))
};
let parent_kind = self.nav.kind(*parent);
if parent_kind == "call_expression" && selected("function") {
return false;
}
match parent_kind {
"block"
if parent.named_child(parent.named_child_count().saturating_sub(1) as u32)
== Some(current) =>
{
return true
}
"match_arm" if selected("value") => return true,
"arguments" | "array_expression" | "tuple_expression" => return true,
"let_declaration" if selected("value") => return true,
"assignment_expression" if selected("right") => return true,
"field_initializer" if selected("value") => return true,
"field_expression" if selected("value") => return true,
"index_expression" => return true,
"shorthand_field_initializer" | "return_expression" | "break_expression" => {
return true
}
"parenthesized_expression"
| "reference_expression"
| "unary_expression"
| "await_expression"
| "try_expression" => current = *parent,
_ => return false,
}
}
false
}
fn is_shadowed(&self, node: tree_sitter::Node<'_>) -> bool {
let name = &self.source[node.byte_range()];
let mut current = node;
for parent in self.ancestors.iter().rev() {
match self.nav.kind(*parent) {
"function_item" | "closure_expression" => {
if parent
.child_by_field_name("parameters")
.is_some_and(|parameters| {
rust_pattern_binds_name(parameters, self.source, name)
})
{
return true;
}
}
"match_arm" => {
if parent
.child_by_field_name("pattern")
.is_some_and(|pattern| rust_pattern_binds_name(pattern, self.source, name))
{
return true;
}
}
"for_expression" => {
if parent
.child_by_field_name("body")
.is_some_and(|body| node_contains(&body, &node))
&& parent
.child_by_field_name("pattern")
.is_some_and(|pattern| {
rust_pattern_binds_name(pattern, self.source, name)
})
{
return true;
}
}
"if_expression" | "while_expression" => {
if parent
.child_by_field_name("consequence")
.or_else(|| parent.child_by_field_name("body"))
.is_some_and(|body| node_contains(&body, &node))
&& parent
.child_by_field_name("condition")
.is_some_and(|condition| {
rust_let_condition_binds_name(condition, self.source, name)
})
{
return true;
}
}
"block" => {
#[cfg(any(test, feature = "test-support"))]
VALUE_BINDING_WORK.with(|work| work.set(work.get() + 1));
if self
.blocks
.get(&parent.id())
.and_then(|bindings| bindings.get(name))
.is_some_and(|end| *end <= current.start_byte())
{
return true;
}
}
_ => {}
}
current = *parent;
}
false
}
}
#[cfg(any(test, feature = "test-support"))]
pub fn legacy_rust_value_references(
source: &str,
root: tree_sitter::Node,
) -> Vec<(String, String, u32, usize, usize)> {
let mut results = Vec::new();
collect_rust_value_references(root, source, &mut results, 0);
results
}
#[cfg(any(test, feature = "test-support"))]
fn collect_rust_value_references(
node: tree_sitter::Node,
source: &str,
results: &mut Vec<(String, String, u32, usize, usize)>,
depth: u32,
) {
if matches!(node.kind(), "identifier" | "scoped_identifier")
&& !rust_path_is_nested(&node)
&& rust_path_is_value_position(&node)
{
let full = source[node.byte_range()].trim();
let short = full.rsplit("::").next().unwrap_or(full).trim();
if !full.is_empty()
&& !short.is_empty()
&& (node.kind() != "identifier" || !rust_bare_identifier_is_shadowed(&node, source))
{
results.push((
full.to_string(),
short.to_string(),
node.start_position().row as u32 + 1,
node.start_byte(),
node.end_byte(),
));
}
}
if depth >= MAX_AST_WALK_DEPTH {
return;
}
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
collect_rust_value_references(cursor.node(), source, results, depth + 1);
if !cursor.goto_next_sibling() {
break;
}
}
}
}
#[cfg(any(test, feature = "test-support"))]
fn rust_path_is_nested(node: &tree_sitter::Node<'_>) -> bool {
node.parent().is_some_and(|parent| {
matches!(
parent.kind(),
"scoped_identifier" | "scoped_type_identifier" | "generic_function"
)
})
}
#[cfg(any(test, feature = "test-support"))]
fn rust_path_is_value_position(node: &tree_sitter::Node<'_>) -> bool {
let mut current = *node;
while let Some(parent) = current.parent() {
if parent.kind() == "call_expression"
&& parent
.child_by_field_name("function")
.is_some_and(|function| same_node(&function, ¤t))
{
return false;
}
let is_selected_field = |field: &str| {
parent
.child_by_field_name(field)
.is_some_and(|child| same_node(&child, ¤t))
};
match parent.kind() {
"block"
if parent.named_child(parent.named_child_count().saturating_sub(1) as u32)
== Some(current) =>
{
return true
}
"match_arm" if is_selected_field("value") => return true,
"arguments" | "array_expression" | "tuple_expression" => return true,
"let_declaration" if is_selected_field("value") => return true,
"assignment_expression" if is_selected_field("right") => return true,
"field_initializer" if is_selected_field("value") => return true,
"field_expression" if is_selected_field("value") => return true,
"index_expression" => return true,
"shorthand_field_initializer" => return true,
"return_expression" | "break_expression" => return true,
"parenthesized_expression"
| "reference_expression"
| "unary_expression"
| "await_expression"
| "try_expression" => current = parent,
_ => return false,
}
}
false
}
#[cfg(any(test, feature = "test-support"))]
fn rust_bare_identifier_is_shadowed(node: &tree_sitter::Node<'_>, source: &str) -> bool {
rust_name_is_shadowed_at(*node, source, &source[node.byte_range()])
}
pub fn rust_name_is_shadowed_at(node: tree_sitter::Node<'_>, source: &str, name: &str) -> bool {
let mut current = node;
while let Some(parent) = current.parent() {
match parent.kind() {
"function_item" | "closure_expression" => {
if parent
.child_by_field_name("parameters")
.is_some_and(|parameters| rust_pattern_binds_name(parameters, source, name))
{
return true;
}
}
"match_arm" => {
if parent
.child_by_field_name("pattern")
.is_some_and(|pattern| rust_pattern_binds_name(pattern, source, name))
{
return true;
}
}
"for_expression" => {
if parent
.child_by_field_name("pattern")
.is_some_and(|pattern| rust_pattern_binds_name(pattern, source, name))
&& parent
.child_by_field_name("body")
.is_some_and(|body| node_contains(&body, &node))
{
return true;
}
}
"if_expression" | "while_expression" => {
let body = parent
.child_by_field_name("consequence")
.or_else(|| parent.child_by_field_name("body"));
if body.is_some_and(|body| node_contains(&body, &node))
&& parent
.child_by_field_name("condition")
.is_some_and(|condition| {
rust_let_condition_binds_name(condition, source, name)
})
{
return true;
}
}
"block" => {
let mut sibling = current.prev_named_sibling();
while let Some(previous) = sibling {
#[cfg(any(test, feature = "test-support"))]
VALUE_BINDING_WORK.with(|work| work.set(work.get() + 1));
if previous.kind() == "let_declaration"
&& previous
.child_by_field_name("pattern")
.is_some_and(|pattern| rust_pattern_binds_name(pattern, source, name))
{
return true;
}
sibling = previous.prev_named_sibling();
}
}
_ => {}
}
current = parent;
}
false
}
fn rust_let_condition_binds_name(
condition: tree_sitter::Node<'_>,
source: &str,
name: &str,
) -> bool {
let mut pending = vec![condition];
while let Some(node) = pending.pop() {
if node.kind() == "let_condition"
&& node
.child_by_field_name("pattern")
.or_else(|| node.named_child(0))
.is_some_and(|pattern| rust_pattern_binds_name(pattern, source, name))
{
return true;
}
pending.extend(node.children(&mut node.walk()));
}
false
}
fn rust_pattern_binds_name(node: tree_sitter::Node<'_>, source: &str, name: &str) -> bool {
let mut pending = vec![node];
while let Some(node) = pending.pop() {
if node.kind() == "identifier" && &source[node.byte_range()] == name {
return true;
}
pending.extend(node.children(&mut node.walk()));
}
false
}
fn same_node(left: &tree_sitter::Node<'_>, right: &tree_sitter::Node<'_>) -> bool {
left.id() == right.id()
}
fn node_contains(container: &tree_sitter::Node<'_>, node: &tree_sitter::Node<'_>) -> bool {
container.start_byte() <= node.start_byte() && node.end_byte() <= container.end_byte()
}
pub fn extract_calls_in_range(
source: &str,
root: tree_sitter::Node,
byte_start: usize,
byte_end: usize,
lang: LangId,
) -> Vec<(String, u32)> {
let mut results = Vec::new();
let call_kinds = call_node_kinds(lang);
walk_for_calls(
root,
source,
byte_start,
byte_end,
&call_kinds,
&mut results,
);
results
}
pub fn extract_calls_full(
source: &str,
root: tree_sitter::Node,
byte_start: usize,
byte_end: usize,
lang: LangId,
) -> Vec<(String, String, u32, usize, usize)> {
extract_calls_full_with(source, root, byte_start, byte_end, lang, Direct)
}
pub fn extract_calls_full_with<'tree>(
source: &str,
root: tree_sitter::Node<'tree>,
byte_start: usize,
byte_end: usize,
lang: LangId,
nav: impl Nav<'tree>,
) -> Vec<(String, String, u32, usize, usize)> {
if lang == LangId::Rust {
return extract_rust_calls_with_macro_facts_with(source, root, byte_start, byte_end, nav).0;
}
let mut results = Vec::new();
let call_kinds = call_node_kinds(lang);
if call_kinds.is_empty() {
return results;
}
collect_calls_full_with(
root,
source,
byte_start,
byte_end,
&call_kinds,
&mut results,
nav,
);
if lang == LangId::Luau {
for (full, short, _, _, _) in &mut results {
if let Some(name) = full.rsplit(['.', ':']).next() {
*short = name.to_string();
}
}
}
results
}
pub type CallTuple = (String, String, u32, usize, usize);
const MAX_UNPARSED_MACRO_MENTIONS_PER_FILE: usize = 512;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RustMacroBody {
pub name: String,
pub byte_start: usize,
pub byte_end: usize,
}
#[derive(Debug, Clone, Default)]
pub struct RustMacroFacts {
pub bodies: Vec<RustMacroBody>,
pub unparsed_mentions: Vec<CallTuple>,
mention_names: HashSet<String>,
}
impl RustMacroFacts {
fn push_mention(&mut self, mention: CallTuple) {
if self.unparsed_mentions.len() < MAX_UNPARSED_MACRO_MENTIONS_PER_FILE
&& self.mention_names.insert(mention.1.clone())
{
self.unparsed_mentions.push(mention);
}
}
}
pub fn extract_rust_calls_with_macro_facts(
source: &str,
root: tree_sitter::Node,
byte_start: usize,
byte_end: usize,
) -> (Vec<CallTuple>, RustMacroFacts) {
extract_rust_calls_with_macro_facts_with(source, root, byte_start, byte_end, Direct)
}
pub fn extract_rust_calls_with_macro_facts_with<'tree>(
source: &str,
root: tree_sitter::Node<'tree>,
byte_start: usize,
byte_end: usize,
nav: impl Nav<'tree>,
) -> (Vec<CallTuple>, RustMacroFacts) {
let mut results = Vec::new();
let call_kinds = call_node_kinds(LangId::Rust);
collect_calls_full_with(
root,
source,
byte_start,
byte_end,
&call_kinds,
&mut results,
nav,
);
let mut facts = RustMacroFacts::default();
collect_rust_macro_calls_with(
root,
source,
byte_start,
byte_end,
0,
&mut results,
&mut facts,
nav,
);
results.sort_by_key(|(_, _, _, start, end)| (*start, *end));
results.dedup();
facts
.unparsed_mentions
.sort_by_key(|(_, _, _, start, end)| (*start, *end));
(results, facts)
}
fn collect_rust_macro_calls(
node: tree_sitter::Node<'_>,
source: &str,
byte_start: usize,
byte_end: usize,
depth: u32,
results: &mut Vec<CallTuple>,
facts: &mut RustMacroFacts,
) {
collect_rust_macro_calls_with(
node, source, byte_start, byte_end, depth, results, facts, Direct,
);
}
#[allow(clippy::too_many_arguments)]
fn collect_rust_macro_calls_with<'tree>(
node: tree_sitter::Node<'tree>,
source: &str,
byte_start: usize,
byte_end: usize,
depth: u32,
results: &mut Vec<CallTuple>,
facts: &mut RustMacroFacts,
nav: impl Nav<'tree>,
) {
nav.walk(node, |node, _| {
visit_rust_macro_node(node, source, byte_start, byte_end, depth, results, facts)
});
}
fn visit_rust_macro_node(
node: tree_sitter::Node<'_>,
source: &str,
byte_start: usize,
byte_end: usize,
depth: u32,
results: &mut Vec<CallTuple>,
facts: &mut RustMacroFacts,
) -> bool {
if depth >= MAX_RUST_MACRO_CALL_DEPTH
|| node.end_byte() <= byte_start
|| node.start_byte() >= byte_end
{
return false;
}
match node.kind() {
"macro_invocation" => {
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
let child = cursor.node();
if child.kind() == "token_tree" {
collect_rust_token_tree_calls(child, source, depth, results, facts);
break;
}
if !cursor.goto_next_sibling() {
break;
}
}
}
return false;
}
"macro_definition" => {
let name = node
.child_by_field_name("name")
.and_then(|name| source.get(name.byte_range()))
.map(str::to_string);
let mut cursor = node.walk();
for rule in node.children(&mut cursor) {
if rule.kind() != "macro_rule" {
continue;
}
let Some(right) = rule.child_by_field_name("right") else {
continue;
};
if let Some(name) = &name {
let range = right.byte_range();
if range.end > range.start + 1 {
facts.bodies.push(RustMacroBody {
name: name.clone(),
byte_start: range.start + 1,
byte_end: range.end - 1,
});
}
}
collect_rust_token_tree_calls(right, source, depth, results, facts);
}
return false;
}
_ => {}
}
true
}
test_support_visibility! {
fn parse_rust_macro_fragment(fragment: &str) -> Option<tree_sitter::Tree> {
if let Some(tree) = RUST_FRAGMENT_TREES.with(|trees| {
trees
.borrow()
.as_ref()
.and_then(|trees| trees.get(fragment).cloned())
}) {
return Some(tree);
}
let tree = RUST_FRAGMENT_PARSER.with(|cached| {
let mut cached = cached.borrow_mut();
if cached.is_none() {
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&crate::parser::grammar_for(LangId::Rust).ok()?)
.ok()?;
#[cfg(any(test, feature = "test-support"))]
RUST_FRAGMENT_PARSER_INITIALIZATIONS.with(|count| count.set(count.get() + 1));
*cached = Some(parser);
}
#[cfg(any(test, feature = "test-support"))]
RUST_FRAGMENT_PARSES.with(|count| count.set(count.get() + 1));
cached.as_mut()?.parse(fragment, None)
})?;
RUST_FRAGMENT_TREES.with(|trees| {
if let Some(trees) = trees.borrow_mut().as_mut() {
trees.insert(fragment.to_string(), tree.clone());
}
});
Some(tree)
}
}
fn collect_rust_token_tree_calls(
token_tree: tree_sitter::Node<'_>,
source: &str,
depth: u32,
results: &mut Vec<CallTuple>,
facts: &mut RustMacroFacts,
) {
let range = token_tree.byte_range();
if range.end <= range.start + 1 {
return;
}
let inner_start = range.start + 1;
let inner_end = range.end - 1;
let Some(fragment) = source.get(inner_start..inner_end) else {
return;
};
let Some(tree) = parse_rust_macro_fragment(fragment) else {
return;
};
let mut fragment_calls = Vec::new();
let mut fragment_facts = RustMacroFacts::default();
collect_calls_full(
tree.root_node(),
fragment,
0,
fragment.len(),
&call_node_kinds(LangId::Rust),
&mut fragment_calls,
);
collect_rust_macro_calls(
tree.root_node(),
fragment,
0,
fragment.len(),
depth + 1,
&mut fragment_calls,
&mut fragment_facts,
);
fragment_calls.retain_mut(|(full, _, _, _, _)| {
if full.contains("$crate::") {
*full = full.replace("$crate::", "crate::");
}
!full.contains('$')
});
if tree.root_node().has_error() {
collect_unparsed_mentions(
tree.root_node(),
fragment,
&fragment_calls,
&mut fragment_facts,
);
}
let token_start_row = token_tree.start_position().row as u32;
let remap = |(full, short, line, start, end): CallTuple| {
(
full,
short,
token_start_row + line,
inner_start + start,
inner_start + end,
)
};
results.extend(fragment_calls.into_iter().map(remap));
facts
.bodies
.extend(fragment_facts.bodies.into_iter().map(|body| RustMacroBody {
name: body.name,
byte_start: inner_start + body.byte_start,
byte_end: inner_start + body.byte_end,
}));
for mention in fragment_facts.unparsed_mentions {
facts.push_mention(remap(mention));
}
}
fn collect_unparsed_mentions(
root: tree_sitter::Node<'_>,
fragment: &str,
fragment_calls: &[CallTuple],
facts: &mut RustMacroFacts,
) {
let callee_names: BTreeSet<&str> = fragment_calls
.iter()
.map(|(_, short, _, _, _)| short.as_str())
.collect();
let mut pending = vec![(root, false)];
while let Some((node, in_error)) = pending.pop() {
if facts.unparsed_mentions.len() >= MAX_UNPARSED_MACRO_MENTIONS_PER_FILE {
return;
}
let in_error = in_error || node.is_error();
if in_error && node.kind() == "identifier" {
if let Some(name) = fragment.get(node.byte_range()) {
if !callee_names.contains(name) {
facts.push_mention((
name.to_string(),
name.to_string(),
node.start_position().row as u32 + 1,
node.start_byte(),
node.end_byte(),
));
}
}
continue;
}
if !in_error && !node.has_error() {
continue;
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
pending.push((child, in_error));
}
}
}
fn collect_calls_full(
node: tree_sitter::Node,
source: &str,
byte_start: usize,
byte_end: usize,
call_kinds: &[&str],
results: &mut Vec<(String, String, u32, usize, usize)>,
) {
collect_calls_full_with(
node, source, byte_start, byte_end, call_kinds, results, Direct,
);
}
fn collect_calls_full_with<'tree>(
node: tree_sitter::Node<'tree>,
source: &str,
byte_start: usize,
byte_end: usize,
call_kinds: &[&str],
results: &mut Vec<(String, String, u32, usize, usize)>,
nav: impl Nav<'tree>,
) {
nav.walk(node, |node, kind| {
let node_start = node.start_byte();
let node_end = node.end_byte();
let overlaps = node_end > byte_start && node_start < byte_end;
if overlaps
&& call_kinds.contains(&kind)
&& node_start >= byte_start
&& node_end <= byte_end
{
if let (Some(full), Some(short)) = (
extract_full_callee(&node, source),
extract_callee_name(&node, source),
) {
results.push((
full,
short,
node.start_position().row as u32 + 1,
node_start,
node_end,
));
}
}
overlaps
});
}