use super::calls::{collect_call_nodes, collect_rust_call_references};
use super::capture::handle_rust_capture;
use super::fqn::qualify_rust_fqns;
use super::impls::collect_rust_trait_implementations;
use super::macros::collect_rust_macro_references;
use super::types::{collect_rust_type_references, collect_type_nodes};
use super::utils::find_nearest_entity_by_line;
use crate::models::{EntityKind, ParsedEntity, ReferenceIntent};
use crate::pipeline::parser::utils::node_text;
use tree_sitter::Node;
fn type_ref_names(entity: &ParsedEntity) -> Vec<&str> {
entity
.reference_intents
.iter()
.filter_map(|ri| match ri {
ReferenceIntent::TypeReference { type_name, .. } => Some(type_name.as_str()),
_ => None,
})
.collect()
}
fn create_test_entity(name: &str, line: usize) -> ParsedEntity {
ParsedEntity::new(
name,
EntityKind::RustFunction,
name,
None,
None,
"rust",
"/test.rs",
line,
line + 10,
None,
"test-repo",
)
}
#[test]
fn test_handle_rust_capture_struct() {
let code = "struct MyStruct";
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let node = tree.root_node();
let result = handle_rust_capture("rust.struct.name", "MyStruct", node);
assert!(result.is_some());
let (name, kind, _line) = result.unwrap();
assert_eq!(name, "MyStruct");
assert_eq!(kind, EntityKind::RustStruct);
}
#[test]
fn test_handle_rust_capture_enum() {
let code = "enum Color";
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let node = tree.root_node();
let result = handle_rust_capture("rust.enum.name", "Color", node);
assert!(result.is_some());
let (name, kind, _line) = result.unwrap();
assert_eq!(name, "Color");
assert_eq!(kind, EntityKind::RustEnum);
}
#[test]
fn test_handle_rust_capture_trait() {
let code = "trait Iterator";
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let node = tree.root_node();
let result = handle_rust_capture("rust.trait.name", "Iterator", node);
assert!(result.is_some());
let (name, kind, _line) = result.unwrap();
assert_eq!(name, "Iterator");
assert_eq!(kind, EntityKind::RustTrait);
}
#[test]
fn test_handle_rust_capture_function() {
let code = "fn main";
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let node = tree.root_node();
let result = handle_rust_capture("rust.function.name", "main", node);
assert!(result.is_some());
let (name, kind, _line) = result.unwrap();
assert_eq!(name, "main");
assert_eq!(kind, EntityKind::RustFunction);
}
#[test]
fn test_handle_rust_capture_macro() {
let code = "macro_rules! vec";
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let node = tree.root_node();
let result = handle_rust_capture("rust.macro_def.name", "vec", node);
assert!(result.is_some());
let (name, kind, _line) = result.unwrap();
assert_eq!(name, "vec");
assert_eq!(kind, EntityKind::RustMacroDef);
}
#[test]
fn test_handle_rust_capture_type_alias() {
let code = "type Result";
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let node = tree.root_node();
let result = handle_rust_capture("rust.type_alias.name", "Result", node);
assert!(result.is_some());
let (name, kind, _line) = result.unwrap();
assert_eq!(name, "Result");
assert_eq!(kind, EntityKind::RustTypeAlias);
}
#[test]
fn test_handle_rust_capture_constant() {
let code = "const MAX_SIZE";
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let node = tree.root_node();
let result = handle_rust_capture("rust.constant.name", "MAX_SIZE", node);
assert!(result.is_some());
let (name, kind, _line) = result.unwrap();
assert_eq!(name, "MAX_SIZE");
assert_eq!(kind, EntityKind::RustConstant);
}
#[test]
fn test_handle_rust_capture_module() {
let code = "mod utils";
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let node = tree.root_node();
let result = handle_rust_capture("rust.module.name", "utils", node);
assert!(result.is_some());
let (name, kind, _line) = result.unwrap();
assert_eq!(name, "utils");
assert_eq!(kind, EntityKind::RustModule);
}
#[test]
fn test_find_nearest_entity_by_line_exact_match() {
let entities = vec![
create_test_entity("func1", 10),
create_test_entity("func2", 20),
create_test_entity("func3", 30),
];
let idx = find_nearest_entity_by_line(&entities, 20);
assert_eq!(idx, 1);
assert_eq!(entities[idx].start_line, 20);
}
#[test]
fn test_find_nearest_entity_by_line_between() {
let entities = vec![
create_test_entity("func1", 10),
create_test_entity("func2", 20),
create_test_entity("func3", 30),
];
let idx = find_nearest_entity_by_line(&entities, 25);
assert_eq!(idx, 1);
assert_eq!(entities[idx].start_line, 20);
}
#[test]
fn test_find_nearest_entity_by_line_before_first() {
let entities = vec![
create_test_entity("func1", 10),
create_test_entity("func2", 20),
];
let idx = find_nearest_entity_by_line(&entities, 5);
assert_eq!(idx, 0);
}
#[test]
fn test_find_nearest_entity_by_line_after_last() {
let entities = vec![
create_test_entity("func1", 10),
create_test_entity("func2", 20),
];
let idx = find_nearest_entity_by_line(&entities, 50);
assert_eq!(idx, 1);
assert_eq!(entities[idx].start_line, 20);
}
#[test]
fn test_find_nearest_entity_empty_list() {
let entities: Vec<ParsedEntity> = vec![];
let idx = find_nearest_entity_by_line(&entities, 10);
assert_eq!(idx, 0);
}
#[test]
fn test_collect_rust_macro_references_simple() {
let code = r#"
fn main() {
println!("Hello");
vec![1, 2, 3];
}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut entities = vec![create_test_entity("main", 2)];
let code_bytes = code.as_bytes();
collect_rust_macro_references(
tree.root_node(),
code_bytes,
&mut entities,
"/test.rs",
"test",
);
let intents_count = entities[0]
.reference_intents
.iter()
.filter(|ri| matches!(ri, ReferenceIntent::RustMacroCall { .. }))
.count();
assert!(intents_count > 0, "Should have found macro invocations");
}
#[test]
fn test_collect_rust_macro_references_multiple_entities() {
let code = r#"
fn func1() {
println!("one");
}
fn func2() {
vec![1];
println!("two");
}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut entities = vec![
create_test_entity("func1", 2),
create_test_entity("func2", 6),
];
let code_bytes = code.as_bytes();
collect_rust_macro_references(
tree.root_node(),
code_bytes,
&mut entities,
"/test.rs",
"test",
);
let func1_macros = entities[0]
.reference_intents
.iter()
.filter(|ri| matches!(ri, ReferenceIntent::RustMacroCall { .. }))
.count();
let func2_macros = entities[1]
.reference_intents
.iter()
.filter(|ri| matches!(ri, ReferenceIntent::RustMacroCall { .. }))
.count();
assert!(func1_macros > 0, "func1 should have macro intents");
assert!(func2_macros > 0, "func2 should have macro intents");
}
#[test]
fn test_handle_rust_capture_unknown_capture_name() {
let code = "unknown";
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let node = tree.root_node();
let result = handle_rust_capture("unknown.name", "something", node);
assert!(result.is_none());
}
#[test]
fn test_handle_rust_capture_generics_ignored() {
let code = "generics";
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let node = tree.root_node();
let result = handle_rust_capture("rust.generics", "some_generic", node);
assert!(result.is_none());
}
#[test]
fn test_collect_rust_trait_implementations() {
let code = r#"
trait Incrementable {
fn increment(&mut self);
}
struct Counter {
count: u32,
}
impl Incrementable for Counter {
fn increment(&mut self) {
self.count += 1;
}
}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut entities = vec![ParsedEntity::new(
"Counter",
EntityKind::RustStruct,
"Counter",
None,
None,
"rust",
"test.rs",
6,
8,
None,
"test_repo",
)];
collect_rust_trait_implementations(
tree.root_node(),
code.as_bytes(),
&mut entities,
"test.rs",
"test_repo",
);
assert_eq!(entities.len(), 1);
assert_eq!(entities[0].reference_intents.len(), 1);
if let ReferenceIntent::Implements { interface, line } = &entities[0].reference_intents[0] {
assert_eq!(interface, "Incrementable");
assert_eq!(*line, 10); } else {
panic!("Expected Implements reference intent");
}
}
#[test]
fn test_collect_rust_call_references() {
let code = r#"
fn helper_function(x: i32) -> i32 {
x + 1
}
fn main() {
let result = helper_function(5);
println!("{}", result);
}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut entities = vec![
ParsedEntity::new(
"helper_function",
EntityKind::RustFunction,
"helper_function",
None,
None,
"rust",
"test.rs",
2,
4,
None,
"test_repo",
),
ParsedEntity::new(
"main",
EntityKind::RustFunction,
"main",
None,
None,
"rust",
"test.rs",
6,
9,
None,
"test_repo",
),
];
collect_rust_call_references(
tree.root_node(),
code.as_bytes(),
&mut entities,
"test.rs",
"test_repo",
);
let main_entity = &entities[1];
assert!(
!main_entity.reference_intents.is_empty(),
"main() should have at least one reference intent"
);
let has_call = main_entity.reference_intents.iter().any(|intent| {
if let ReferenceIntent::Call { method, .. } = intent {
method == "helper_function"
} else {
false
}
});
assert!(
has_call,
"main() should have a Call reference to helper_function"
);
}
#[test]
fn test_rust_signature_capture() {
use crate::pipeline::parser::extractor::extract_entities;
use tree_sitter_rust;
let code = r#"
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn multiply(x: f64, y: f64) -> f64 {
x * y
}
"#;
let entities = extract_entities(
code,
tree_sitter_rust::LANGUAGE.into(),
include_str!("../../../../../queries/rust.scm"),
"rust",
"test.rs",
"test_repo",
)
.expect("Failed to extract entities");
assert!(
entities.len() >= 2,
"Should extract at least 2 functions, got {}",
entities.len()
);
let add_fn = entities
.iter()
.find(|e| e.name == "add")
.expect("add function not found");
eprintln!("add function signature: {:?}", add_fn.signature);
}
#[test]
fn test_pattern_matching_not_captured_as_type_ref() {
use crate::pipeline::parser::extractor::extract_entities;
let code = r#"
pub enum MyEnum {
Variant1,
Variant2,
}
impl std::fmt::Display for MyEnum {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
MyEnum::Variant1 => write!(f, "V1"),
MyEnum::Variant2 => write!(f, "V2"),
}
}
}
"#;
let entities = extract_entities(
code,
tree_sitter_rust::LANGUAGE.into(),
include_str!("../../../../../queries/rust.scm"),
"rust",
"test.rs",
"test_repo",
)
.expect("Failed to extract entities");
assert!(
entities.len() >= 2,
"Should extract at least MyEnum and fmt method, got {}",
entities.len()
);
let fmt_fn = entities
.iter()
.find(|e| e.name == "fmt")
.expect("fmt function not found");
let type_names = type_ref_names(fmt_fn);
assert!(
!type_names.contains(&"MyEnum"),
"fmt function should NOT capture MyEnum from pattern matching as a type reference"
);
}
#[test]
fn e2e_test_rust_type_references_and_use_statements() {
use crate::pipeline::parser::extractor::extract_entities;
let code = r#"
use crate::models::ImportedType;
pub struct MyStruct {
pub field_a: ImportedType,
}
impl MyStruct {
pub fn new() -> Self {
match self.field_a {
ImportedType::Variant1 => Self { field_a: ImportedType::default() },
ImportedType::Variant2 => Self { field_a: ImportedType::default() },
}
}
}
pub enum ImportedType {
Variant1,
Variant2,
}
impl Default for ImportedType {
fn default() -> Self {
ImportedType::Variant1
}
}
"#;
let entities = extract_entities(
code,
tree_sitter_rust::LANGUAGE.into(),
include_str!("../../../../../queries/rust.scm"),
"rust",
"test_e2e.rs",
"test_repo",
)
.expect("Failed to extract entities");
let my_struct = entities
.iter()
.find(|e| e.name == "MyStruct")
.expect("MyStruct not found");
let _imported_type = entities
.iter()
.find(|e| e.name == "ImportedType")
.expect("ImportedType not found");
let my_struct_types = type_ref_names(my_struct);
assert!(
my_struct_types.contains(&"ImportedType"),
"MyStruct SHOULD have REFERENCE to ImportedType from struct field type annotation"
);
let default_fn = entities
.iter()
.find(|e| e.name == "default" && e.start_line > 15)
.expect("default function not found");
let has_body_pattern_ref = default_fn.reference_intents.iter().any(|intent| {
matches!(intent, ReferenceIntent::TypeReference { type_name, line }
if type_name == "ImportedType" && *line > default_fn.start_line)
});
assert!(
!has_body_pattern_ref,
"default() should NOT capture ImportedType from value-context scoped_identifier in body"
);
}
#[test]
fn test_e2e_rust_struct_instantiation_and_method_calls() {
}
#[test]
fn test_token_tree_type_extraction() {
let code = r#"
fn test() {
let items = vec![
create_entity("E1", EntityKind::Class, 0.1),
create_entity("E2", Config::default(), 0.2),
];
println!("Type: {}", EntityKind::Method);
}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut type_refs = Vec::new();
collect_type_nodes(&tree.root_node(), code.as_bytes(), &mut type_refs, None);
let entity_kind_refs: Vec<_> = type_refs
.iter()
.filter(|(_, name)| name == "EntityKind")
.collect();
let config_refs: Vec<_> = type_refs
.iter()
.filter(|(_, name)| name == "Config")
.collect();
assert!(
!entity_kind_refs.is_empty(),
"Should capture EntityKind from vec![] macro"
);
assert!(
!config_refs.is_empty(),
"Should capture Config from vec![] macro"
);
}
#[test]
fn test_token_tree_various_macros() {
let code = r#"
fn test() {
println!("Debug: {:?}", EntityKind::Class);
assert_eq!(Config::default(), expected);
format!("Type is {}", MyType::variant);
vec![Item::new(), Item::default()];
}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut type_refs = Vec::new();
collect_type_nodes(&tree.root_node(), code.as_bytes(), &mut type_refs, None);
let mut type_names: Vec<String> = type_refs.iter().map(|(_, name)| name.clone()).collect();
type_names.sort();
type_names.dedup();
assert!(type_names.contains(&"EntityKind".to_string()));
assert!(type_names.contains(&"Config".to_string()));
assert!(type_names.contains(&"MyType".to_string()));
assert!(type_names.contains(&"Item".to_string()));
}
#[test]
fn test_token_tree_string_literal_filtering() {
let code = r#"
fn test() {
println!("This is a FakeType::variant in a string");
let x = vec![RealType::variant];
}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut type_refs = Vec::new();
collect_type_nodes(&tree.root_node(), code.as_bytes(), &mut type_refs, None);
let fake_type_refs: Vec<_> = type_refs
.iter()
.filter(|(_, name)| name == "FakeType")
.collect();
let real_type_refs: Vec<_> = type_refs
.iter()
.filter(|(_, name)| name == "RealType")
.collect();
assert!(
fake_type_refs.is_empty(),
"Should NOT capture FakeType from inside string literal"
);
assert!(
!real_type_refs.is_empty(),
"Should capture RealType from vec![] macro"
);
}
#[test]
fn test_token_tree_macro_rules() {
let code = r#"
macro_rules! create_handler {
($type:ty) => {
impl Handler for $type {
fn handle(&self) -> Result<()> {
MyType::process()
}
}
};
}
fn test() {
create_handler!(RequestHandler);
custom_macro!(Config::load(), EntityKind::Class);
}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut type_refs = Vec::new();
collect_type_nodes(&tree.root_node(), code.as_bytes(), &mut type_refs, None);
let type_names: Vec<String> = type_refs.iter().map(|(_, name)| name.clone()).collect();
assert!(
type_names.contains(&"MyType".to_string()),
"Should capture MyType from macro_rules! body"
);
assert!(
type_names.contains(&"Config".to_string()),
"Should capture Config from custom macro invocation"
);
assert!(
type_names.contains(&"EntityKind".to_string()),
"Should capture EntityKind from custom macro invocation"
);
}
#[test]
fn test_token_tree_nested_macros() {
let code = r#"
fn test() {
vec![
format!("Item: {}", Item::default()),
vec![Config::new(), Config::default()].into_iter().collect()
];
assert_eq!(
vec![MyType::variant1, MyType::variant2],
expected
);
}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut type_refs = Vec::new();
collect_type_nodes(&tree.root_node(), code.as_bytes(), &mut type_refs, None);
let mut type_names: Vec<String> = type_refs.iter().map(|(_, name)| name.clone()).collect();
type_names.sort();
type_names.dedup();
assert!(type_names.contains(&"Item".to_string()));
assert!(type_names.contains(&"Config".to_string()));
assert!(type_names.contains(&"MyType".to_string()));
}
#[test]
fn test_token_tree_edge_cases() {
let code = r#"
fn test() {
vec![
ValidType::variant,
invalid_type::variant,
Type123::variant,
_PrivateType::variant
];
}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut type_refs = Vec::new();
collect_type_nodes(&tree.root_node(), code.as_bytes(), &mut type_refs, None);
let type_names: Vec<String> = type_refs.iter().map(|(_, name)| name.clone()).collect();
assert!(type_names.contains(&"ValidType".to_string()));
assert!(type_names.contains(&"Type123".to_string()));
assert!(!type_names.contains(&"invalid_type".to_string()));
}
#[test]
fn test_token_tree_deeply_nested_optimization() {
let code = r#"
fn process() {
let result = vec![
vec![
vec![MyType::new(), MyType::default()],
vec![OtherType::create()],
],
vec![NestedType::validate()],
];
assert!(!result.is_empty());
}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut type_refs = Vec::new();
collect_type_nodes(&tree.root_node(), code.as_bytes(), &mut type_refs, None);
let type_names: Vec<String> = type_refs.iter().map(|(_, name)| name.clone()).collect();
assert!(
type_names.contains(&"MyType".to_string()),
"Should capture MyType from deeply nested vec! macros"
);
assert!(
type_names.contains(&"OtherType".to_string()),
"Should capture OtherType from nested vec! macro"
);
assert!(
type_names.contains(&"NestedType".to_string()),
"Should capture NestedType from deeply nested vec! macro"
);
let my_type_refs: Vec<_> = type_refs
.iter()
.filter(|(_, name)| *name == "MyType")
.collect();
assert_eq!(
my_type_refs.len(),
1,
"MyType should appear exactly once per unique (line, name) pair, found {} refs: {:?}",
my_type_refs.len(),
my_type_refs
);
}
#[test]
fn test_use_braces_captures_inner_names() {
let code = r#"
use crate::db::vector::{VectorDb, VectorSearchExt};
pub fn do_stuff() {}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut type_refs = Vec::new();
collect_type_nodes(&tree.root_node(), code.as_bytes(), &mut type_refs, None);
let type_names: Vec<&str> = type_refs.iter().map(|(_, n)| n.as_str()).collect();
assert!(
type_names.contains(&"VectorDb"),
"Should capture VectorDb from braced use, got: {:?}",
type_names
);
assert!(
type_names.contains(&"VectorSearchExt"),
"Should capture VectorSearchExt from braced use, got: {:?}",
type_names
);
}
#[test]
fn test_use_nested_braces() {
let code = r#"
use foo::{Bar, baz::{Qux, Quux}};
pub fn do_stuff() {}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut type_refs = Vec::new();
collect_type_nodes(&tree.root_node(), code.as_bytes(), &mut type_refs, None);
let type_names: Vec<&str> = type_refs.iter().map(|(_, n)| n.as_str()).collect();
assert!(
type_names.contains(&"Bar"),
"Should capture Bar, got: {:?}",
type_names
);
assert!(
type_names.contains(&"Qux"),
"Should capture Qux, got: {:?}",
type_names
);
assert!(
type_names.contains(&"Quux"),
"Should capture Quux, got: {:?}",
type_names
);
assert!(
!type_names.contains(&"foo"),
"Should NOT capture foo, got: {:?}",
type_names
);
assert!(
!type_names.contains(&"baz"),
"Should NOT capture baz, got: {:?}",
type_names
);
}
#[test]
fn test_use_as_clause_keeps_original_only() {
let code = r#"
use foo::Bar as Baz;
pub fn do_stuff() {}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut type_refs = Vec::new();
collect_type_nodes(&tree.root_node(), code.as_bytes(), &mut type_refs, None);
let type_names: Vec<&str> = type_refs.iter().map(|(_, n)| n.as_str()).collect();
assert!(
type_names.contains(&"Bar"),
"Should capture Bar (original), got: {:?}",
type_names
);
assert!(
!type_names.contains(&"Baz"),
"Should NOT capture Baz (alias), got: {:?}",
type_names
);
}
#[test]
fn test_use_glob_ignored() {
let code = r#"
use foo::*;
pub fn do_stuff() {}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut type_refs = Vec::new();
collect_type_nodes(&tree.root_node(), code.as_bytes(), &mut type_refs, None);
let type_names: Vec<&str> = type_refs.iter().map(|(_, n)| n.as_str()).collect();
assert!(
!type_names.contains(&"foo"),
"Should NOT capture foo from glob import, got: {:?}",
type_names
);
}
#[test]
fn test_use_simple_still_works() {
let code = r#"
use crate::pipeline::embed::Embedder;
pub fn do_stuff() {}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut type_refs = Vec::new();
collect_type_nodes(&tree.root_node(), code.as_bytes(), &mut type_refs, None);
let type_names: Vec<&str> = type_refs.iter().map(|(_, n)| n.as_str()).collect();
assert!(
type_names.contains(&"Embedder"),
"Should capture Embedder from simple use, got: {:?}",
type_names
);
}
fn find_call_with_name<'a>(
calls: &'a [(usize, String, Option<String>)],
method: &str,
) -> Option<&'a (usize, String, Option<String>)> {
calls.iter().find(|(_, m, _)| m == method)
}
#[test]
fn test_extract_scoped_call_returns_receiver() {
let code = "fn main() { let _ = KnotMcpHandler::new(); }";
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut calls: Vec<(usize, String, Option<String>)> = Vec::new();
collect_call_nodes(&tree.root_node(), code.as_bytes(), &mut calls);
let entry = find_call_with_name(&calls, "new")
.expect("expected a call to `new` from KnotMcpHandler::new");
assert_eq!(entry.2.as_deref(), Some("KnotMcpHandler"));
}
#[test]
fn test_extract_scoped_call_multi_segment_uppercase() {
let code = "fn main() { let _ = crate::mcp_handler::KnotMcpHandler::new(); }";
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut calls: Vec<(usize, String, Option<String>)> = Vec::new();
collect_call_nodes(&tree.root_node(), code.as_bytes(), &mut calls);
let entry = find_call_with_name(&calls, "new")
.expect("expected a call to `new` from crate::mcp_handler::KnotMcpHandler::new");
assert_eq!(entry.2.as_deref(), Some("KnotMcpHandler"));
}
#[test]
fn test_extract_scoped_call_lowercase_module_drops_receiver() {
let code = "fn main() { std::env::set_var(\"FOO\", \"1\"); }";
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut calls: Vec<(usize, String, Option<String>)> = Vec::new();
collect_call_nodes(&tree.root_node(), code.as_bytes(), &mut calls);
let entry = find_call_with_name(&calls, "set_var")
.expect("expected a call to `set_var` from std::env::set_var");
assert!(
entry.2.is_none(),
"lowercase module should not produce a receiver, got {:?}",
entry.2
);
}
#[test]
fn test_extract_scoped_call_self_translated_to_enclosing_class() {
let code = r#"
struct Foo;
impl Foo {
pub fn foo_outer() -> Self {
let _ = Self::new();
Foo
}
}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut entities = vec![ParsedEntity::new(
"foo_outer",
EntityKind::RustMethod,
"Foo::foo_outer",
None,
None,
"rust",
"/test.rs",
5,
8,
Some("Foo".to_string()),
"test_repo",
)];
collect_rust_call_references(
tree.root_node(),
code.as_bytes(),
&mut entities,
"/test.rs",
"test_repo",
);
let call = entities[0]
.reference_intents
.iter()
.find_map(|ri| {
if let ReferenceIntent::Call {
method, receiver, ..
} = ri
{
Some((method.clone(), receiver.clone()))
} else {
None
}
})
.expect("expected a Call reference intent attached to foo_outer");
assert_eq!(call.0, "new");
assert_eq!(
call.1.as_deref(),
Some("Foo"),
"Self::new should translate `Self` to the enclosing class"
);
}
#[test]
fn test_rust_method_fqn_includes_impl_target_inherent() {
let code = r#"
struct Foo;
impl Foo {
pub fn new() -> Self { Foo }
}
"#;
let entities = crate::pipeline::parser::extractor::extract_entities(
code,
tree_sitter_rust::LANGUAGE.into(),
include_str!("../../../../../queries/rust.scm"),
"rust",
"/test.rs",
"test_repo",
)
.expect("Failed to extract entities");
let new_method = entities
.iter()
.find(|e| e.name == "new")
.expect("new method not found");
assert_eq!(new_method.kind, EntityKind::RustMethod);
assert_eq!(new_method.fqn, "Foo::new");
assert_eq!(new_method.enclosing_class.as_deref(), Some("Foo"));
}
#[test]
fn test_rust_method_fqn_includes_impl_target_trait_for() {
let code = r#"
trait Bar { fn new() -> Self; }
struct Foo;
impl Bar for Foo {
fn new() -> Self { Foo }
}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let _tree = parser.parse(code, None).unwrap();
let entities = crate::pipeline::parser::extractor::extract_entities(
code,
tree_sitter_rust::LANGUAGE.into(),
include_str!("../../../../../queries/rust.scm"),
"rust",
"/test.rs",
"test_repo",
)
.expect("Failed to extract entities");
let new_method = entities
.iter()
.find(|e| e.name == "new")
.expect("new method not found");
assert_eq!(new_method.kind, EntityKind::RustMethod);
assert_eq!(
new_method.fqn, "Foo::new",
"FQN should use self-type (Foo), not the trait (Bar)"
);
assert_eq!(new_method.enclosing_class.as_deref(), Some("Foo"));
}
#[test]
fn test_rust_method_fqn_with_generics() {
let code = r#"
struct Foo<T>(T);
impl<T> Foo<T> {
pub fn new() -> Self { unimplemented!() }
}
"#;
let entities = crate::pipeline::parser::extractor::extract_entities(
code,
tree_sitter_rust::LANGUAGE.into(),
include_str!("../../../../../queries/rust.scm"),
"rust",
"/test.rs",
"test_repo",
)
.expect("Failed to extract entities");
let new_method = entities
.iter()
.find(|e| e.name == "new")
.expect("new method not found");
assert_eq!(new_method.fqn, "Foo::new");
}
#[test]
fn test_self_in_return_type_resolves_to_enclosing_class() {
let code = r#"
struct Foo;
impl Foo {
pub fn new() -> Self {
Foo
}
}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut entities = vec![ParsedEntity::new(
"new",
EntityKind::RustMethod,
"Foo::new",
None,
None,
"rust",
"/test.rs",
5,
7,
Some("Foo".to_string()),
"test_repo",
)];
collect_rust_type_references(
tree.root_node(),
code.as_bytes(),
&mut entities,
"/test.rs",
"test_repo",
);
let type_names = type_ref_names(&entities[0]);
assert!(
type_names.contains(&"Foo"),
"Self in return type should resolve to enclosing class Foo, got: {:?}",
type_names
);
assert!(
!type_names.contains(&"Self"),
"Self should not appear as a raw type reference, got: {:?}",
type_names
);
}
#[test]
fn test_self_in_struct_expression_resolves_to_enclosing_class() {
let code = r#"
struct Foo {
value: i32,
}
impl Foo {
pub fn build() -> Foo {
Self { value: 0 }
}
}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut entities = vec![ParsedEntity::new(
"build",
EntityKind::RustMethod,
"Foo::build",
None,
None,
"rust",
"/test.rs",
7,
9,
Some("Foo".to_string()),
"test_repo",
)];
collect_rust_type_references(
tree.root_node(),
code.as_bytes(),
&mut entities,
"/test.rs",
"test_repo",
);
let type_names = type_ref_names(&entities[0]);
assert!(
type_names.contains(&"Foo"),
"Self {{ ... }} struct literal should resolve to enclosing class Foo, got: {:?}",
type_names
);
assert!(
!type_names.contains(&"Self"),
"Self should not appear as a raw type reference, got: {:?}",
type_names
);
}
#[test]
fn test_self_outside_impl_emits_as_self() {
let code = r#"
fn standalone() -> Self {
Self
}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let mut entities = vec![ParsedEntity::new(
"standalone",
EntityKind::RustFunction,
"standalone",
None,
None,
"rust",
"/test.rs",
2,
4,
None,
"test_repo",
)];
collect_rust_type_references(
tree.root_node(),
code.as_bytes(),
&mut entities,
"/test.rs",
"test_repo",
);
let type_names = type_ref_names(&entities[0]);
assert!(
type_names.contains(&"Self"),
"Self without enclosing class should remain as raw \"Self\", got: {:?}",
type_names
);
}
fn make_rust_entity(
name: &str,
kind: EntityKind,
fqn: &str,
file: &str,
enclosing: Option<&str>,
) -> ParsedEntity {
ParsedEntity::new(
name,
kind,
fqn,
None,
None,
"rust",
file,
10,
20,
enclosing.map(|s| s.to_string()),
"test_repo",
)
}
fn write_min_cargo_toml(dir: &std::path::Path, name: &str) {
std::fs::create_dir_all(dir).unwrap();
let content = format!(
"[package]\nname = \"{}\"\nversion = \"0.1.0\"\nedition = \"2024\"\n",
name
);
std::fs::write(dir.join("Cargo.toml"), content).unwrap();
}
#[test]
fn diagnose_macro_token_tree_contents() {
let code = r#"
fn body() {
is_supported("direct");
assert!(is_supported("inside_assert"));
assert_eq!(is_supported("a"), true);
let _ = vec![is_supported("inside_vec")];
}
"#;
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code, None).unwrap();
let bytes = code.as_bytes();
fn walk(node: Node<'_>, bytes: &[u8], depth: usize) {
let prefix = " ".repeat(depth);
let text = node_text(node, bytes);
let preview: String = text.chars().take(60).collect();
eprintln!(
"{}{} [{}..{}] {:?}",
prefix,
node.kind(),
node.start_position().row + 1,
node.end_position().row + 1,
preview
);
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
walk(child, bytes, depth + 1);
}
}
eprintln!("\n=== AST dump for macro-vs-direct call comparison ===");
walk(tree.root_node(), bytes, 0);
eprintln!("=== END AST dump ===\n");
fn count_calls(node: Node<'_>) -> usize {
let mut n = if node.kind() == "call_expression" {
1
} else {
0
};
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
n += count_calls(child);
}
n
}
let n = count_calls(tree.root_node());
eprintln!("Total `call_expression` nodes found in tree: {}", n);
let mut calls: Vec<(usize, String, Option<String>)> = Vec::new();
collect_call_nodes(&tree.root_node(), bytes, &mut calls);
eprintln!(
"Calls reported by collect_call_nodes: {} → {:?}",
calls.len(),
calls
);
}
#[test]
fn diagnose_cfg_test_mod_extraction() {
let code = r#"
pub fn is_supported(ext: &str) -> bool {
matches!(ext, "rs" | "ts")
}
pub fn production_caller(ext: &str) -> bool {
is_supported(ext)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_supported_rs() {
assert!(is_supported("rs"));
}
#[test]
fn test_is_supported_rejects_txt() {
assert!(!is_supported("txt"));
}
}
"#;
let query_src = include_str!("../../../../../queries/rust.scm");
let entities = crate::pipeline::parser::extractor::extract_entities(
code,
tree_sitter_rust::LANGUAGE.into(),
query_src,
"rust",
"/diag/lib.rs",
"diag",
)
.expect("extract_entities");
eprintln!("\n=== DIAGNOSTIC: extracted entities (pre-qualify) ===");
for e in &entities {
eprintln!(
" kind={:?} name={:<35} fqn={:<45} start_line={} reference_intents={}",
e.kind,
e.name,
e.fqn,
e.start_line,
e.reference_intents.len()
);
for ri in &e.reference_intents {
eprintln!(" - {:?}", ri);
}
}
eprintln!("=== END DIAGNOSTIC ===\n");
let has_is_supported = entities
.iter()
.any(|e| e.name == "is_supported" && e.kind == EntityKind::RustFunction);
let has_test_fn = entities
.iter()
.any(|e| e.name == "test_is_supported_rs" && e.kind == EntityKind::RustFunction);
let has_mod_tests = entities
.iter()
.any(|e| e.name == "tests" && e.kind == EntityKind::RustModule);
eprintln!(
"has is_supported function entity: {}",
has_is_supported
);
eprintln!("has test_is_supported_rs function entity: {}", has_test_fn);
eprintln!(
"has 'tests' RustModule entity: {}",
has_mod_tests
);
let test_entity = entities
.iter()
.find(|e| e.name == "test_is_supported_rs" && e.kind == EntityKind::RustFunction);
let call_attributed_to_test = test_entity
.map(|e| {
e.reference_intents.iter().any(
|ri| matches!(ri, ReferenceIntent::Call { method, .. } if method == "is_supported"),
)
})
.unwrap_or(false);
eprintln!(
"Call(is_supported) attributed to test_is_supported_rs: {}",
call_attributed_to_test
);
let collision_pre_qualify = entities
.iter()
.filter(|e| e.fqn == "test_is_supported_rs")
.count();
eprintln!(
"Number of entities with bare FQN 'test_is_supported_rs': {}",
collision_pre_qualify
);
assert!(has_is_supported, "parser must always emit production fns");
let _ = (
has_test_fn,
has_mod_tests,
call_attributed_to_test,
collision_pre_qualify,
);
}
#[test]
fn test_qualify_rust_fqns_struct_in_nested_module() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path();
write_min_cargo_toml(repo, "my_crate");
let file = repo.join("src/config.rs").to_string_lossy().into_owned();
let mut entities = vec![make_rust_entity(
"Config",
EntityKind::RustStruct,
"Config",
&file,
None,
)];
qualify_rust_fqns(&mut entities, &file, repo.to_str(), None);
assert_eq!(entities[0].fqn, "my_crate::config::Config");
}
#[test]
fn test_qualify_rust_fqns_method_uses_enclosing_class() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path();
write_min_cargo_toml(repo, "my_crate");
let file = repo.join("src/config.rs").to_string_lossy().into_owned();
let mut entities = vec![make_rust_entity(
"load",
EntityKind::RustMethod,
"Config::load",
&file,
Some("Config"),
)];
qualify_rust_fqns(&mut entities, &file, repo.to_str(), None);
assert_eq!(entities[0].fqn, "my_crate::config::Config::load");
}
#[test]
fn test_qualify_rust_fqns_function_in_crate_root() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path();
write_min_cargo_toml(repo, "my_crate");
let file = repo.join("src/lib.rs").to_string_lossy().into_owned();
let mut entities = vec![make_rust_entity(
"helper",
EntityKind::RustFunction,
"helper",
&file,
None,
)];
qualify_rust_fqns(&mut entities, &file, repo.to_str(), None);
assert_eq!(entities[0].fqn, "my_crate::helper");
}
#[test]
fn test_qualify_rust_fqns_no_repo_path_is_noop() {
let mut entities = vec![make_rust_entity(
"Config",
EntityKind::RustStruct,
"Config",
"/tmp/anywhere/src/config.rs",
None,
)];
qualify_rust_fqns(&mut entities, "/tmp/anywhere/src/config.rs", None, None);
assert_eq!(entities[0].fqn, "Config");
}
#[test]
fn test_qualify_rust_fqns_no_cargo_toml_uses_loose_prefix() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path();
std::fs::create_dir_all(repo.join("src")).unwrap();
let file = repo.join("src/config.rs").to_string_lossy().into_owned();
let mut entities = vec![make_rust_entity(
"Config",
EntityKind::RustStruct,
"Config",
&file,
None,
)];
qualify_rust_fqns(&mut entities, &file, repo.to_str(), None);
assert_eq!(
entities[0].fqn, "__loose::src::config::Config",
"files without Cargo.toml should get __loose:: prefix"
);
}
#[test]
fn test_qualify_rust_fqns_skips_non_rust_entities() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path();
write_min_cargo_toml(repo, "my_crate");
let file = repo.join("src/lib.rs").to_string_lossy().into_owned();
let mut entities = vec![ParsedEntity::new(
"Config",
EntityKind::Class,
"Config",
None,
None,
"java",
&file,
1,
5,
None,
"test_repo",
)];
qualify_rust_fqns(&mut entities, &file, repo.to_str(), None);
assert_eq!(
entities[0].fqn, "Config",
"non-Rust entities must be left untouched"
);
}
#[test]
fn test_qualify_rust_fqns_sets_enclosing_class_fqn_for_methods() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path();
write_min_cargo_toml(repo, "test_crate");
let src_dir = repo.join("src");
std::fs::create_dir_all(&src_dir).unwrap();
let file = src_dir.join("foo.rs").to_string_lossy().into_owned();
let mut entities = vec![
make_rust_entity("Foo", EntityKind::RustStruct, "Foo", &file, None),
make_rust_entity(
"bar",
EntityKind::RustMethod,
"Foo::bar",
&file,
Some("Foo"),
),
];
qualify_rust_fqns(&mut entities, &file, repo.to_str(), None);
assert!(
entities[0].enclosing_class_fqn.is_none(),
"structs should not have enclosing_class_fqn"
);
assert_eq!(
entities[1].enclosing_class_fqn,
Some("test_crate::foo::Foo".to_string()),
"method enclosing_class_fqn should be crate-qualified"
);
}
fn method_call_intents(body: &str) -> Vec<(String, Option<String>)> {
let code = format!("impl Foo {{\n fn caller(&self) {{\n {body}\n }}\n}}\n");
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_rust::LANGUAGE.into())
.unwrap();
let tree = parser.parse(&code, None).unwrap();
let end_line = code.lines().count();
let mut entities = vec![ParsedEntity::new(
"caller",
EntityKind::RustMethod,
"Foo::caller",
None,
None,
"rust",
"/test.rs",
2,
end_line,
Some("Foo".to_string()),
"test_repo",
)];
collect_rust_call_references(
tree.root_node(),
code.as_bytes(),
&mut entities,
"/test.rs",
"test_repo",
);
entities[0]
.reference_intents
.iter()
.filter_map(|ri| match ri {
ReferenceIntent::Call {
method, receiver, ..
} => Some((method.clone(), receiver.clone())),
_ => None,
})
.collect()
}
fn call(method: &str, receiver: &str) -> (String, Option<String>) {
(method.to_string(), Some(receiver.to_string()))
}
#[test]
fn test_self_method_call_emits_self_receiver() {
assert_eq!(
method_call_intents("self.compute_value(sku);"),
vec![call("compute_value", "self")]
);
}
#[test]
fn test_self_field_method_call_emits_dotted_receiver() {
assert_eq!(
method_call_intents("self.repo.save();"),
vec![call("save", "self.repo")]
);
}
#[test]
fn test_call_chain_receiver_emits_every_link() {
assert_eq!(
method_call_intents("a.b().c();"),
vec![call("c", "a.b()"), call("b", "a")]
);
}
#[test]
fn test_self_call_chain_receiver() {
assert_eq!(
method_call_intents("self.builder().finish();"),
vec![call("finish", "self.builder()"), call("builder", "self")]
);
}
#[test]
fn test_call_chain_receiver_drops_arguments() {
assert_eq!(
method_call_intents("items.iter().map(|x| {\n x + 1\n}).sum();"),
vec![
call("sum", "items.iter().map()"),
call("map", "items.iter()"),
call("iter", "items"),
]
);
}
#[test]
fn test_await_and_try_receivers_are_unwrapped() {
assert_eq!(
method_call_intents("self.fetch().await?.decode();"),
vec![call("decode", "self.fetch()"), call("fetch", "self")]
);
}
#[test]
fn test_scoped_call_receiver_in_chain() {
assert_eq!(
method_call_intents("Repo::open().save();"),
vec![call("save", "Repo::open()"), call("open", "Repo")]
);
}
#[test]
fn test_turbofish_method_call_is_captured() {
assert_eq!(
method_call_intents("let v = self.items.collect::<Vec<_>>();"),
vec![call("collect", "self.items")]
);
}
#[test]
fn test_turbofish_module_path_call_is_not_captured() {
assert_eq!(
method_call_intents("let v = serde_yaml::from_str::<Value>(src);"),
vec![]
);
}
#[test]
fn test_opaque_receiver_still_emits_call() {
let intents = method_call_intents("(*boxed).run();");
assert_eq!(intents.len(), 1);
assert_eq!(intents[0].0, "run");
assert_eq!(intents[0].1.as_deref(), Some("boxed"));
}