use tree_sitter::Node;
use crate::core::{Kind, Symbol};
use crate::lang::{Ctx, LanguagePlugin, extract_with, qualify};
const LANGUAGE: &str = "rust";
pub struct Rust;
impl LanguagePlugin for Rust {
fn language(&self) -> &'static str {
LANGUAGE
}
fn extensions(&self) -> &[&str] {
&["rs"]
}
fn extract(&self, file: &str, source: &str) -> Vec<Symbol> {
extract_with(
LANGUAGE,
tree_sitter_rust::LANGUAGE.into(),
file,
source,
|ctx, root, out| walk(ctx, root, None, out),
)
}
}
fn walk(ctx: &Ctx, node: Node, parent: Option<&str>, out: &mut Vec<Symbol>) {
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
match child.kind() {
"function_item" | "function_signature_item" => {
if let Some(name) = ctx.field_text(child, "name") {
let kind = if has_self(child) {
Kind::Method
} else {
Kind::Function
};
push(ctx, out, &name, kind, child, parent);
}
}
"struct_item" | "enum_item" | "union_item" => {
if let Some(name) = ctx.field_text(child, "name") {
let kind = match child.kind() {
"enum_item" => Kind::Enum,
_ => Kind::Struct,
};
push(ctx, out, &name, kind, child, parent);
}
}
"trait_item" => {
if let Some(name) = ctx.field_text(child, "name") {
push(ctx, out, &name, Kind::Trait, child, parent);
let qualified = qualify(parent, &name, "::");
walk(ctx, child, Some(&qualified), out);
}
}
"mod_item" => {
if child.child_by_field_name("body").is_some()
&& let Some(name) = ctx.field_text(child, "name")
{
push(ctx, out, &name, Kind::Module, child, parent);
let qualified = qualify(parent, &name, "::");
walk(ctx, child, Some(&qualified), out);
}
}
"impl_item" => {
let ty = ctx.field_text(child, "type").map(|t| base_type(&t));
let qualified = match &ty {
Some(t) => qualify(parent, t, "::"),
None => parent.map(str::to_string).unwrap_or_default(),
};
let p = if qualified.is_empty() {
None
} else {
Some(qualified.as_str())
};
walk(ctx, child, p, out);
}
_ => walk(ctx, child, parent, out),
}
}
}
fn push(ctx: &Ctx, out: &mut Vec<Symbol>, name: &str, kind: Kind, node: Node, p: Option<&str>) {
let mut s = ctx.symbol(name, kind, node, p);
s.visibility = Some(visibility(ctx, node));
out.push(s);
}
fn visibility(ctx: &Ctx, node: Node) -> &'static str {
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "visibility_modifier" {
let text = ctx.node_text(child).unwrap_or_default();
return if text.contains('(') {
"crate"
} else {
"public"
};
}
}
"private"
}
fn has_self(node: Node) -> bool {
node.child_by_field_name("parameters")
.is_some_and(|params| {
let mut cursor = params.walk();
params
.children(&mut cursor)
.any(|p| p.kind() == "self_parameter")
})
}
fn base_type(ty: &str) -> String {
let head = ty.split('<').next().unwrap_or(ty).trim();
head.rsplit("::").next().unwrap_or(head).trim().to_string()
}
#[cfg(test)]
mod tests {
use super::*;
fn extract(source: &str) -> Vec<Symbol> {
Rust.extract("test.rs", source)
}
fn find<'a>(syms: &'a [Symbol], name: &str) -> &'a Symbol {
syms.iter()
.find(|s| s.name == name)
.unwrap_or_else(|| panic!("no symbol named {name} in {syms:?}"))
}
#[test]
fn extracts_types_functions_and_impl_methods() {
let src = r#"
pub struct Widget {
size: u32,
}
pub enum Color {
Red,
Green,
}
pub trait Render {
fn render(&self) -> String;
}
impl Widget {
pub fn new() -> Self {
Widget { size: 0 }
}
}
pub fn build() -> Widget {
Widget::new()
}
"#;
let syms = extract(src);
let widget = find(&syms, "Widget");
assert_eq!(widget.kind, Kind::Struct);
assert_eq!(widget.parent, None);
assert_eq!(find(&syms, "Color").kind, Kind::Enum);
assert_eq!(find(&syms, "Render").kind, Kind::Trait);
let build = find(&syms, "build");
assert_eq!(build.kind, Kind::Function);
assert_eq!(build.parent, None);
let new = find(&syms, "new");
assert_eq!(new.kind, Kind::Function);
assert_eq!(new.parent.as_deref(), Some("Widget"));
let render = find(&syms, "render");
assert_eq!(render.kind, Kind::Method);
assert_eq!(render.parent.as_deref(), Some("Render"));
assert_eq!(widget.language, "rust");
}
#[test]
fn qualifies_through_modules_and_generic_impls() {
let src = r#"
mod outer {
pub struct Store<T> {
inner: T,
}
impl<T> Store<T> {
pub fn get(&self) -> &T {
&self.inner
}
}
}
"#;
let syms = extract(src);
assert_eq!(find(&syms, "outer").kind, Kind::Module);
assert_eq!(find(&syms, "Store").parent.as_deref(), Some("outer"));
assert_eq!(find(&syms, "get").parent.as_deref(), Some("outer::Store"));
}
#[test]
fn bare_module_declarations_are_not_indexed() {
let syms = extract("mod search;\nmod handler { pub fn run() {} }\n");
assert!(
!syms.iter().any(|s| s.name == "search"),
"bare `mod search;` should be skipped: {syms:?}"
);
assert_eq!(find(&syms, "handler").kind, Kind::Module);
assert_eq!(find(&syms, "run").kind, Kind::Function);
}
#[test]
fn empty_and_unparseable_yield_no_symbols() {
assert!(extract("").is_empty());
assert!(extract("// just a comment\n").is_empty());
}
#[test]
fn visibility_reflects_the_pub_modifier() {
let src = "pub fn open() {}\npub(crate) fn shared() {}\nfn helper() {}\n";
let syms = extract(src);
assert_eq!(find(&syms, "open").visibility, Some("public"));
assert_eq!(find(&syms, "shared").visibility, Some("crate"));
assert_eq!(find(&syms, "helper").visibility, Some("private"));
}
}