aKode 0.8.0: grafo del codice locale (tree-sitter + git) e strumento code_graph, memorie ancorate ai simboli con stato stale, client MCP akode-mcp-client
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
6
akode-rs/code-graph/BUILD.bazel
Normal file
6
akode-rs/code-graph/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "code-graph",
|
||||
crate_name = "akode_code_graph",
|
||||
)
|
||||
36
akode-rs/code-graph/Cargo.toml
Normal file
36
akode-rs/code-graph/Cargo.toml
Normal file
@@ -0,0 +1,36 @@
|
||||
[package]
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
name = "akode-code-graph"
|
||||
version.workspace = true
|
||||
|
||||
[lib]
|
||||
name = "akode_code_graph"
|
||||
path = "src/lib.rs"
|
||||
doctest = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
rusqlite = { version = "0.39", features = ["bundled"] }
|
||||
sha1 = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tree-sitter = { workspace = true }
|
||||
tree-sitter-bash = { workspace = true }
|
||||
tree-sitter-go = "0.25"
|
||||
tree-sitter-javascript = "0.25"
|
||||
tree-sitter-json = "0.24"
|
||||
tree-sitter-python = "0.25"
|
||||
tree-sitter-rust = "0.24"
|
||||
tree-sitter-swift = "0.7"
|
||||
tree-sitter-toml-ng = "0.7"
|
||||
tree-sitter-typescript = "0.23"
|
||||
tree-sitter-yaml = "0.7"
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
364
akode-rs/code-graph/src/anchor.rs
Normal file
364
akode-rs/code-graph/src/anchor.rs
Normal file
@@ -0,0 +1,364 @@
|
||||
//! Anchors that tie a memory to the code it talks about.
|
||||
//!
|
||||
//! An anchor is `path` + qualified symbol name + kind + the hash of the symbol's text (see
|
||||
//! [`crate::parse::body_hash`]). Only these identifiers and the hash leave the machine: never
|
||||
//! the source. Anchors are computed and checked by parsing the cited files directly from disk,
|
||||
//! so they work even before the repository index exists and always see the working tree.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::index::MAX_FILE_BYTES;
|
||||
use crate::lang::Lang;
|
||||
use crate::parse::Parsed;
|
||||
use crate::parse::parse;
|
||||
|
||||
/// At most this many anchors per memory.
|
||||
pub const MAX_ANCHORS: usize = 6;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Anchor {
|
||||
pub path: String,
|
||||
pub symbol: String,
|
||||
pub kind: String,
|
||||
pub line: u32,
|
||||
pub hash: String,
|
||||
}
|
||||
|
||||
/// Result of checking one anchor against the working tree.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum AnchorCheck {
|
||||
/// Same text; the symbol may have moved inside the file.
|
||||
Fresh { line: u32 },
|
||||
/// The symbol is still there but its text changed.
|
||||
Changed { line: u32 },
|
||||
/// No symbol with that name in the file (renamed, moved or deleted), or no file.
|
||||
Missing,
|
||||
}
|
||||
|
||||
impl AnchorCheck {
|
||||
pub fn is_fresh(&self) -> bool {
|
||||
matches!(self, AnchorCheck::Fresh { .. })
|
||||
}
|
||||
}
|
||||
|
||||
/// A citation as stored by the memory server.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize)]
|
||||
pub struct Citation {
|
||||
pub path: String,
|
||||
#[serde(default)]
|
||||
pub lines: Option<String>,
|
||||
#[serde(default)]
|
||||
pub quote: Option<String>,
|
||||
}
|
||||
|
||||
/// Parses files of one checkout on demand and keeps them for the batch.
|
||||
pub struct Verifier {
|
||||
root: PathBuf,
|
||||
files: HashMap<String, Option<(Lang, Parsed, String)>>,
|
||||
}
|
||||
|
||||
impl Verifier {
|
||||
pub fn new(root: &Path) -> Self {
|
||||
Self {
|
||||
root: root.to_path_buf(),
|
||||
files: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn file(&mut self, path: &str) -> Option<&(Lang, Parsed, String)> {
|
||||
let root = self.root.clone();
|
||||
self.files
|
||||
.entry(path.to_string())
|
||||
.or_insert_with(|| {
|
||||
if path.contains("..") || Path::new(path).is_absolute() {
|
||||
return None;
|
||||
}
|
||||
let lang = Lang::from_path(path)?;
|
||||
let absolute = root.join(path);
|
||||
let meta = std::fs::metadata(&absolute).ok()?;
|
||||
if !meta.is_file() || meta.len() > MAX_FILE_BYTES {
|
||||
return None;
|
||||
}
|
||||
let source = std::fs::read_to_string(&absolute).ok()?;
|
||||
let parsed = parse(lang, &source);
|
||||
Some((lang, parsed, source))
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// Checks one anchor against the current file.
|
||||
pub fn check(&mut self, anchor: &Anchor) -> AnchorCheck {
|
||||
let Some((lang, parsed, _)) = self.file(&anchor.path) else {
|
||||
return AnchorCheck::Missing;
|
||||
};
|
||||
let lang = *lang;
|
||||
let candidates: Vec<_> = parsed
|
||||
.symbols
|
||||
.iter()
|
||||
.filter(|symbol| symbol.qualified_name(lang) == anchor.symbol && symbol.kind == anchor.kind)
|
||||
.collect();
|
||||
if let Some(same) = candidates.iter().find(|symbol| symbol.hash == anchor.hash) {
|
||||
return AnchorCheck::Fresh { line: same.line };
|
||||
}
|
||||
match candidates
|
||||
.iter()
|
||||
.min_by_key(|symbol| symbol.line.abs_diff(anchor.line))
|
||||
{
|
||||
Some(nearest) => AnchorCheck::Changed { line: nearest.line },
|
||||
None => AnchorCheck::Missing,
|
||||
}
|
||||
}
|
||||
|
||||
/// Anchors for one citation: the innermost definitions that contain the cited lines (or the
|
||||
/// line where the quote is found).
|
||||
pub fn anchors_for_citation(&mut self, citation: &Citation) -> Vec<Anchor> {
|
||||
let path = citation.path.trim().trim_start_matches("./").to_string();
|
||||
let range = citation.lines.as_deref().and_then(parse_lines);
|
||||
let Some((lang, parsed, source)) = self.file(&path) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let range = range.or_else(|| {
|
||||
let quote = citation.quote.as_deref()?.trim();
|
||||
find_quote_line(source, quote).map(|line| (line, line))
|
||||
});
|
||||
let Some((from, to)) = range else {
|
||||
return Vec::new();
|
||||
};
|
||||
let lang = *lang;
|
||||
// Innermost symbols overlapping the range, skipping containers that hold another match.
|
||||
let overlapping: Vec<usize> = parsed
|
||||
.symbols
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, symbol)| symbol.line <= to && symbol.end_line >= from)
|
||||
.map(|(index, _)| index)
|
||||
.collect();
|
||||
let innermost: Vec<usize> = overlapping
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|index| {
|
||||
!overlapping.iter().any(|other| {
|
||||
*other != *index && parsed.symbols[*other].parent == Some(*index)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
innermost
|
||||
.into_iter()
|
||||
.take(3)
|
||||
.map(|index| {
|
||||
let symbol = &parsed.symbols[index];
|
||||
Anchor {
|
||||
path: path.clone(),
|
||||
symbol: symbol.qualified_name(lang),
|
||||
kind: symbol.kind.to_string(),
|
||||
line: symbol.line,
|
||||
hash: symbol.hash.clone(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Anchors for identifiers named in the memory text (`` `name` `` or `name()`), looked up in
|
||||
/// the given files only.
|
||||
pub fn anchors_for_names(&mut self, paths: &[String], names: &[String]) -> Vec<Anchor> {
|
||||
let mut out = Vec::new();
|
||||
for path in paths {
|
||||
let Some((lang, parsed, _)) = self.file(path) else {
|
||||
continue;
|
||||
};
|
||||
let lang = *lang;
|
||||
for name in names {
|
||||
let matches: Vec<_> = parsed
|
||||
.symbols
|
||||
.iter()
|
||||
.filter(|symbol| {
|
||||
!matches!(symbol.kind, "key" | "section")
|
||||
&& (symbol.name == *name || symbol.qualified_name(lang) == *name)
|
||||
})
|
||||
.collect();
|
||||
// Ambiguous names in the same file are skipped: the anchor must be unambiguous.
|
||||
if let [symbol] = matches.as_slice() {
|
||||
out.push(Anchor {
|
||||
path: path.clone(),
|
||||
symbol: symbol.qualified_name(lang),
|
||||
kind: symbol.kind.to_string(),
|
||||
line: symbol.line,
|
||||
hash: symbol.hash.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// All anchors of a memory: its citations, then identifiers of its text found in cited files.
|
||||
pub fn anchors_for_memory(root: &Path, citations: &[Citation], text: &str) -> Vec<Anchor> {
|
||||
let mut verifier = Verifier::new(root);
|
||||
let mut anchors: Vec<Anchor> = Vec::new();
|
||||
for citation in citations {
|
||||
anchors.extend(verifier.anchors_for_citation(citation));
|
||||
}
|
||||
let paths: Vec<String> = citations
|
||||
.iter()
|
||||
.map(|citation| citation.path.trim().trim_start_matches("./").to_string())
|
||||
.collect();
|
||||
anchors.extend(verifier.anchors_for_names(&paths, &identifiers_in_text(text)));
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
anchors.retain(|anchor| seen.insert((anchor.path.clone(), anchor.symbol.clone(), anchor.kind.clone())));
|
||||
anchors.truncate(MAX_ANCHORS);
|
||||
anchors
|
||||
}
|
||||
|
||||
/// `12` or `12-30` (1-based, inclusive).
|
||||
pub fn parse_lines(raw: &str) -> Option<(u32, u32)> {
|
||||
let raw = raw.trim();
|
||||
let (from, to) = match raw.split_once('-') {
|
||||
Some((from, to)) => (from.trim().parse().ok()?, to.trim().parse().ok()?),
|
||||
None => {
|
||||
let line = raw.parse().ok()?;
|
||||
(line, line)
|
||||
}
|
||||
};
|
||||
(from >= 1 && to >= from).then_some((from, to))
|
||||
}
|
||||
|
||||
/// 1-based line where `quote` starts, comparing with whitespace collapsed.
|
||||
fn find_quote_line(source: &str, quote: &str) -> Option<u32> {
|
||||
let wanted: String = quote.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
if wanted.len() < 4 {
|
||||
return None;
|
||||
}
|
||||
let first_word = wanted.split(' ').next()?;
|
||||
for (index, line) in source.lines().enumerate() {
|
||||
if !line.contains(first_word) {
|
||||
continue;
|
||||
}
|
||||
let window: String = source
|
||||
.lines()
|
||||
.skip(index)
|
||||
.take(8)
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
.split_whitespace()
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
if window.contains(&wanted) {
|
||||
return u32::try_from(index + 1).ok();
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Identifiers in backticks or followed by `()`: `` `parse_porcelain_z` ``, `Index::new()`.
|
||||
pub fn identifiers_in_text(text: &str) -> Vec<String> {
|
||||
let is_ident = |candidate: &str| {
|
||||
let candidate = candidate.trim_end_matches("()");
|
||||
candidate.len() >= 3
|
||||
&& candidate.len() <= 120
|
||||
&& candidate.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_')
|
||||
&& candidate
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == ':' || c == '.')
|
||||
&& !candidate.contains("..")
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for (index, part) in text.split('`').enumerate() {
|
||||
if index % 2 == 1 && is_ident(part.trim()) {
|
||||
out.push(part.trim().trim_end_matches("()").to_string());
|
||||
}
|
||||
}
|
||||
for word in text.split(|c: char| c.is_whitespace() || c == ',' || c == ';' || c == '`') {
|
||||
if let Some(stripped) = word.strip_suffix("()")
|
||||
&& is_ident(stripped)
|
||||
{
|
||||
out.push(stripped.to_string());
|
||||
}
|
||||
}
|
||||
// `Type::name` also matches by its last segment inside the file.
|
||||
let mut expanded = Vec::new();
|
||||
for name in out {
|
||||
if let Some((_, last)) = name.rsplit_once("::") {
|
||||
expanded.push(last.to_string());
|
||||
}
|
||||
expanded.push(name);
|
||||
}
|
||||
expanded.sort();
|
||||
expanded.dedup();
|
||||
expanded
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn write(dir: &Path, path: &str, content: &str) {
|
||||
let full = dir.join(path);
|
||||
std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
|
||||
std::fs::write(full, content).expect("write");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anchors_follow_changes_of_the_cited_symbol() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let root = dir.path();
|
||||
write(
|
||||
root,
|
||||
"src/lib.rs",
|
||||
"pub struct Index;\nimpl Index {\n pub fn open() -> u32 {\n 1\n }\n}\nfn helper() {}\n",
|
||||
);
|
||||
let anchors = anchors_for_memory(
|
||||
root,
|
||||
&[Citation {
|
||||
path: "src/lib.rs".to_string(),
|
||||
lines: Some("4".to_string()),
|
||||
quote: None,
|
||||
}],
|
||||
"`helper` is called by `Index::open`.",
|
||||
);
|
||||
let names: Vec<(&str, &str)> = anchors.iter().map(|a| (a.symbol.as_str(), a.kind.as_str())).collect();
|
||||
assert_eq!(names, vec![("Index::open", "method"), ("helper", "function")]);
|
||||
|
||||
// Whitespace only: still fresh. Moved down by one line: fresh with the new line.
|
||||
write(
|
||||
root,
|
||||
"src/lib.rs",
|
||||
"\npub struct Index;\nimpl Index {\n pub fn open() -> u32 { 1 }\n}\nfn helper() {}\n",
|
||||
);
|
||||
let mut verifier = Verifier::new(root);
|
||||
assert_eq!(verifier.check(&anchors[0]), AnchorCheck::Fresh { line: 4 });
|
||||
|
||||
// Body changed: stale. Function removed: missing.
|
||||
write(root, "src/lib.rs", "pub struct Index;\nimpl Index {\n pub fn open() -> u32 { 2 }\n}\n");
|
||||
let mut verifier = Verifier::new(root);
|
||||
assert_eq!(verifier.check(&anchors[0]), AnchorCheck::Changed { line: 3 });
|
||||
assert_eq!(verifier.check(&anchors[1]), AnchorCheck::Missing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quote_and_identifiers() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
write(dir.path(), "a.py", "def first():\n return 1\n\ndef second():\n value = compute(\n 2)\n return value\n");
|
||||
let mut verifier = Verifier::new(dir.path());
|
||||
let anchors = verifier.anchors_for_citation(&Citation {
|
||||
path: "a.py".to_string(),
|
||||
lines: None,
|
||||
quote: Some("value = compute( 2)".to_string()),
|
||||
});
|
||||
assert_eq!(anchors.len(), 1);
|
||||
assert_eq!(anchors[0].symbol, "second");
|
||||
assert_eq!(
|
||||
identifiers_in_text("Use `Index::new` and call reload() then `a b`."),
|
||||
vec!["Index::new".to_string(), "new".to_string(), "reload".to_string()]
|
||||
);
|
||||
assert_eq!(parse_lines("10-12"), Some((10, 12)));
|
||||
assert_eq!(parse_lines("x"), None);
|
||||
assert!(verifier.anchors_for_citation(&Citation { path: "../etc/passwd".to_string(), lines: Some("1".to_string()), quote: None }).is_empty());
|
||||
}
|
||||
}
|
||||
131
akode-rs/code-graph/src/git.rs
Normal file
131
akode-rs/code-graph/src/git.rs
Normal file
@@ -0,0 +1,131 @@
|
||||
//! The few git commands the indexer needs (always with `-C <root>`, never writing).
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::process::Stdio;
|
||||
|
||||
use sha1::Digest;
|
||||
use sha1::Sha1;
|
||||
|
||||
fn git(root: &Path, args: &[&str]) -> Option<Vec<u8>> {
|
||||
let output = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(root)
|
||||
.args(["-c", "core.quotepath=false"])
|
||||
.args(args)
|
||||
.env("GIT_LITERAL_PATHSPECS", "1")
|
||||
.env("GIT_OPTIONAL_LOCKS", "0")
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.output()
|
||||
.ok()?;
|
||||
output.status.success().then_some(output.stdout)
|
||||
}
|
||||
|
||||
fn split_z(raw: &[u8]) -> impl Iterator<Item = String> + '_ {
|
||||
raw.split(|byte| *byte == 0)
|
||||
.filter(|entry| !entry.is_empty())
|
||||
.map(|entry| String::from_utf8_lossy(entry).into_owned())
|
||||
}
|
||||
|
||||
/// Top level of the work tree that contains `dir`.
|
||||
pub fn toplevel(dir: &Path) -> Option<PathBuf> {
|
||||
let raw = git(dir, &["rev-parse", "--show-toplevel"])?;
|
||||
let path = String::from_utf8_lossy(&raw).trim().to_string();
|
||||
(!path.is_empty()).then(|| PathBuf::from(path))
|
||||
}
|
||||
|
||||
/// Current commit, `None` before the first commit.
|
||||
pub fn head(root: &Path) -> Option<String> {
|
||||
let raw = git(root, &["rev-parse", "--verify", "-q", "HEAD"])?;
|
||||
let head = String::from_utf8_lossy(&raw).trim().to_string();
|
||||
(!head.is_empty()).then_some(head)
|
||||
}
|
||||
|
||||
/// Tracked files with the blob id in the index (stage 0).
|
||||
pub fn tracked(root: &Path) -> Option<HashMap<String, String>> {
|
||||
let raw = git(root, &["ls-files", "-s", "-z"])?;
|
||||
Some(
|
||||
split_z(&raw)
|
||||
.filter_map(|entry| {
|
||||
let (meta, path) = entry.split_once('\t')?;
|
||||
let mut fields = meta.split(' ');
|
||||
let mode = fields.next()?;
|
||||
let oid = fields.next()?;
|
||||
let stage = fields.next()?;
|
||||
// Submodules (160000) and symlinks (120000) are not files to parse.
|
||||
(stage == "0" && mode.starts_with("100")).then(|| (path.to_string(), oid.to_string()))
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Tracked files, restricted to the given paths.
|
||||
pub fn tracked_subset(root: &Path, paths: &[String]) -> HashMap<String, String> {
|
||||
let mut out = HashMap::new();
|
||||
for chunk in paths.chunks(500) {
|
||||
let mut args = vec!["ls-files", "-s", "-z", "--"];
|
||||
args.extend(chunk.iter().map(String::as_str));
|
||||
if let Some(raw) = git(root, &args) {
|
||||
for entry in split_z(&raw) {
|
||||
if let Some((meta, path)) = entry.split_once('\t') {
|
||||
let mut fields = meta.split(' ');
|
||||
if let (Some(mode), Some(oid), Some("0")) =
|
||||
(fields.next(), fields.next(), fields.next())
|
||||
&& mode.starts_with("100")
|
||||
{
|
||||
out.insert(path.to_string(), oid.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Paths that differ from the index or are untracked (not ignored).
|
||||
pub fn dirty(root: &Path) -> Option<BTreeSet<String>> {
|
||||
let raw = git(
|
||||
root,
|
||||
&["status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames"],
|
||||
)?;
|
||||
Some(
|
||||
split_z(&raw)
|
||||
.filter(|entry| entry.len() > 3)
|
||||
.map(|entry| entry[3..].to_string())
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Paths changed between two commits; `None` when `from` is unknown (gc, other clone).
|
||||
pub fn changed_between(root: &Path, from: &str, to: &str) -> Option<Vec<String>> {
|
||||
let raw = git(root, &["diff", "--name-only", "-z", "--no-renames", from, to])?;
|
||||
Some(split_z(&raw).collect())
|
||||
}
|
||||
|
||||
/// Git blob id of some content (same id `ls-files -s` reports for a clean file).
|
||||
pub fn blob_id(content: &[u8]) -> String {
|
||||
let mut hasher = Sha1::new();
|
||||
hasher.update(format!("blob {}\0", content.len()).as_bytes());
|
||||
hasher.update(content);
|
||||
hasher
|
||||
.finalize()
|
||||
.iter()
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::blob_id;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn blob_id_matches_git() {
|
||||
// `printf 'hello\n' | git hash-object --stdin`
|
||||
assert_eq!(blob_id(b"hello\n"), "ce013625030ba8dba906f756967f9e9ca394464a");
|
||||
}
|
||||
}
|
||||
471
akode-rs/code-graph/src/index.rs
Normal file
471
akode-rs/code-graph/src/index.rs
Normal file
@@ -0,0 +1,471 @@
|
||||
//! SQLite index of one repository, kept up to date from git.
|
||||
//!
|
||||
//! The database lives outside the repository (`<akode home>/code-graph/<name>-<hash>.sqlite`), so
|
||||
//! git never sees it. Every file is keyed by its git blob id: clean files take the id from
|
||||
//! `git ls-files -s` without being read, modified and untracked files are hashed the same way, so
|
||||
//! a file that becomes clean again after a commit is not parsed twice.
|
||||
//!
|
||||
//! An update looks only at what can have changed: the files of `git diff` between the last
|
||||
//! indexed commit and HEAD, the files of `git status`, and the files that were dirty at the last
|
||||
//! update. Without a usable last commit (first run, history rewritten) it compares every tracked
|
||||
//! file, which still parses only the files whose blob id changed.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Instant;
|
||||
|
||||
use rusqlite::Connection;
|
||||
use rusqlite::OptionalExtension;
|
||||
use rusqlite::params;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
|
||||
use crate::git;
|
||||
use crate::lang::Lang;
|
||||
use crate::parse::Parsed;
|
||||
use crate::parse::parse;
|
||||
|
||||
/// Files larger than this are not parsed (generated code, data).
|
||||
pub const MAX_FILE_BYTES: u64 = 1024 * 1024;
|
||||
const SCHEMA_VERSION: &str = "4";
|
||||
/// At most this many parser threads.
|
||||
const MAX_THREADS: usize = 8;
|
||||
|
||||
pub type Result<T> = std::result::Result<T, String>;
|
||||
|
||||
fn db_err(error: rusqlite::Error) -> String {
|
||||
format!("code graph database: {error}")
|
||||
}
|
||||
|
||||
/// What an update did.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct UpdateReport {
|
||||
/// `full`, `diff` (HEAD moved) or `status` (same HEAD).
|
||||
pub mode: &'static str,
|
||||
/// Paths compared with the index.
|
||||
pub checked: usize,
|
||||
pub parsed: usize,
|
||||
pub removed: usize,
|
||||
pub files: usize,
|
||||
pub symbols: usize,
|
||||
pub references: usize,
|
||||
pub millis: u128,
|
||||
}
|
||||
|
||||
pub struct CodeIndex {
|
||||
conn: Connection,
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
struct Job {
|
||||
path: String,
|
||||
lang: Lang,
|
||||
oid: String,
|
||||
content: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
struct Done {
|
||||
path: String,
|
||||
lang: Lang,
|
||||
oid: String,
|
||||
lines: usize,
|
||||
parsed: Parsed,
|
||||
}
|
||||
|
||||
impl CodeIndex {
|
||||
/// Where the index of `root` lives under the aKode home.
|
||||
pub fn default_path(akode_home: &Path, root: &Path) -> PathBuf {
|
||||
let digest = Sha256::digest(root.to_string_lossy().as_bytes());
|
||||
let short: String = digest.iter().take(6).map(|byte| format!("{byte:02x}")).collect();
|
||||
let name: String = root
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| "repo".to_string())
|
||||
.chars()
|
||||
.map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
|
||||
.take(40)
|
||||
.collect();
|
||||
akode_home.join("code-graph").join(format!("{name}-{short}.sqlite"))
|
||||
}
|
||||
|
||||
/// Opens the index of the repository that contains `dir`.
|
||||
pub fn open_for_dir(akode_home: &Path, dir: &Path) -> Result<Self> {
|
||||
let root = git::toplevel(dir).ok_or_else(|| {
|
||||
format!("{} is not inside a git repository", dir.display())
|
||||
})?;
|
||||
let path = Self::default_path(akode_home, &root);
|
||||
Self::open(&path, &root)
|
||||
}
|
||||
|
||||
pub fn open(db_path: &Path, root: &Path) -> Result<Self> {
|
||||
if let Some(parent) = db_path.parent() {
|
||||
std::fs::create_dir_all(parent)
|
||||
.map_err(|error| format!("cannot create {}: {error}", parent.display()))?;
|
||||
}
|
||||
let conn = Connection::open(db_path).map_err(db_err)?;
|
||||
conn.busy_timeout(std::time::Duration::from_secs(10)).map_err(db_err)?;
|
||||
conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;")
|
||||
.map_err(db_err)?;
|
||||
let index = Self {
|
||||
conn,
|
||||
root: root.to_path_buf(),
|
||||
};
|
||||
index.ensure_schema()?;
|
||||
Ok(index)
|
||||
}
|
||||
|
||||
pub fn root(&self) -> &Path {
|
||||
&self.root
|
||||
}
|
||||
|
||||
pub(crate) fn conn(&self) -> &Connection {
|
||||
&self.conn
|
||||
}
|
||||
|
||||
fn ensure_schema(&self) -> Result<()> {
|
||||
self.conn
|
||||
.execute_batch("CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT NOT NULL);")
|
||||
.map_err(db_err)?;
|
||||
let version = self.meta("schema")?;
|
||||
if version.as_deref() != Some(SCHEMA_VERSION) {
|
||||
self.conn
|
||||
.execute_batch(
|
||||
"DROP TABLE IF EXISTS refs; DROP TABLE IF EXISTS symbols; DROP TABLE IF EXISTS files;
|
||||
DELETE FROM meta;
|
||||
CREATE TABLE files(id INTEGER PRIMARY KEY, path TEXT NOT NULL UNIQUE,
|
||||
lang TEXT NOT NULL, oid TEXT NOT NULL, lines INTEGER NOT NULL);
|
||||
CREATE TABLE symbols(id INTEGER PRIMARY KEY, file_id INTEGER NOT NULL,
|
||||
name TEXT NOT NULL, kind TEXT NOT NULL, container TEXT,
|
||||
line INTEGER NOT NULL, end_line INTEGER NOT NULL,
|
||||
signature TEXT NOT NULL, hash TEXT NOT NULL, parent_id INTEGER);
|
||||
CREATE INDEX symbols_name ON symbols(name);
|
||||
CREATE INDEX symbols_name_nocase ON symbols(name COLLATE NOCASE);
|
||||
CREATE INDEX symbols_file ON symbols(file_id, line);
|
||||
CREATE TABLE refs(file_id INTEGER NOT NULL, symbol_id INTEGER,
|
||||
name TEXT NOT NULL, kind TEXT NOT NULL, line INTEGER NOT NULL, target TEXT);
|
||||
CREATE INDEX refs_name ON refs(name);
|
||||
CREATE INDEX refs_symbol ON refs(symbol_id);
|
||||
CREATE INDEX refs_file ON refs(file_id);",
|
||||
)
|
||||
.map_err(db_err)?;
|
||||
self.set_meta("schema", SCHEMA_VERSION)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn meta(&self, key: &str) -> Result<Option<String>> {
|
||||
self.conn
|
||||
.query_row("SELECT value FROM meta WHERE key = ?1", [key], |row| row.get(0))
|
||||
.optional()
|
||||
.map_err(db_err)
|
||||
}
|
||||
|
||||
fn set_meta(&self, key: &str, value: &str) -> Result<()> {
|
||||
self.conn
|
||||
.execute(
|
||||
"INSERT INTO meta(key, value) VALUES(?1, ?2)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
||||
params![key, value],
|
||||
)
|
||||
.map(|_| ())
|
||||
.map_err(db_err)
|
||||
}
|
||||
|
||||
/// Brings the index up to date with HEAD and the working tree.
|
||||
pub fn update(&mut self) -> Result<UpdateReport> {
|
||||
let started = Instant::now();
|
||||
let root = self.root.clone();
|
||||
let head = git::head(&root);
|
||||
let dirty = git::dirty(&root).ok_or("git status failed")?;
|
||||
let stored_head = self.meta("head")?;
|
||||
let stored_dirty: BTreeSet<String> = self
|
||||
.meta("dirty")?
|
||||
.and_then(|raw| serde_json::from_str(&raw).ok())
|
||||
.unwrap_or_default();
|
||||
let stored: HashMap<String, (i64, String)> = {
|
||||
let mut statement = self
|
||||
.conn
|
||||
.prepare("SELECT path, id, oid FROM files")
|
||||
.map_err(db_err)?;
|
||||
statement
|
||||
.query_map([], |row| Ok((row.get::<_, String>(0)?, (row.get(1)?, row.get(2)?))))
|
||||
.map_err(db_err)?
|
||||
.collect::<std::result::Result<_, _>>()
|
||||
.map_err(db_err)?
|
||||
};
|
||||
|
||||
let incremental = match (&stored_head, &head) {
|
||||
(Some(stored_head), Some(head)) if !stored.is_empty() => {
|
||||
if stored_head == head {
|
||||
Some(("status", Vec::new()))
|
||||
} else {
|
||||
git::changed_between(&root, stored_head, head).map(|changed| ("diff", changed))
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let (mode, candidates, tracked) = match incremental {
|
||||
Some((mode, changed)) => {
|
||||
let mut candidates: BTreeSet<String> = changed.into_iter().collect();
|
||||
candidates.extend(dirty.iter().cloned());
|
||||
candidates.extend(stored_dirty.iter().cloned());
|
||||
let clean: Vec<String> = candidates
|
||||
.iter()
|
||||
.filter(|path| !dirty.contains(*path))
|
||||
.cloned()
|
||||
.collect();
|
||||
(mode, candidates, git::tracked_subset(&root, &clean))
|
||||
}
|
||||
None => {
|
||||
let tracked = git::tracked(&root).ok_or("git ls-files failed")?;
|
||||
let mut candidates: BTreeSet<String> = tracked.keys().cloned().collect();
|
||||
candidates.extend(dirty.iter().cloned());
|
||||
candidates.extend(stored.keys().cloned());
|
||||
("full", candidates, tracked)
|
||||
}
|
||||
};
|
||||
|
||||
let mut jobs = Vec::new();
|
||||
let mut removed = Vec::new();
|
||||
for path in &candidates {
|
||||
let lang = Lang::from_path(path);
|
||||
let absolute = root.join(path);
|
||||
let size = std::fs::metadata(&absolute).ok().filter(|meta| meta.is_file()).map(|meta| meta.len());
|
||||
let (Some(lang), Some(size)) = (lang, size) else {
|
||||
if let Some((id, _)) = stored.get(path) {
|
||||
removed.push(*id);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
if size > MAX_FILE_BYTES {
|
||||
if let Some((id, _)) = stored.get(path) {
|
||||
removed.push(*id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (oid, content) = match tracked.get(path).filter(|_| !dirty.contains(path)) {
|
||||
Some(oid) => (oid.clone(), None),
|
||||
None => match std::fs::read(&absolute) {
|
||||
Ok(content) => (git::blob_id(&content), Some(content)),
|
||||
Err(_) => continue,
|
||||
},
|
||||
};
|
||||
if stored.get(path).is_some_and(|(_, stored_oid)| *stored_oid == oid) {
|
||||
continue;
|
||||
}
|
||||
jobs.push(Job {
|
||||
path: path.clone(),
|
||||
lang,
|
||||
oid,
|
||||
content,
|
||||
});
|
||||
}
|
||||
|
||||
let done = parse_all(&root, jobs);
|
||||
let parsed = done.len();
|
||||
self.write(&stored, &removed, done)?;
|
||||
if let Some(head) = &head {
|
||||
self.set_meta("head", head)?;
|
||||
}
|
||||
let dirty_supported: Vec<&String> = dirty
|
||||
.iter()
|
||||
.filter(|path| Lang::from_path(path).is_some())
|
||||
.collect();
|
||||
self.set_meta(
|
||||
"dirty",
|
||||
&serde_json::to_string(&dirty_supported).unwrap_or_else(|_| "[]".to_string()),
|
||||
)?;
|
||||
let (files, symbols, references) = self.counts()?;
|
||||
Ok(UpdateReport {
|
||||
mode,
|
||||
checked: candidates.len(),
|
||||
parsed,
|
||||
removed: removed.len(),
|
||||
files,
|
||||
symbols,
|
||||
references,
|
||||
millis: started.elapsed().as_millis(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn counts(&self) -> Result<(usize, usize, usize)> {
|
||||
let count = |table: &str| -> Result<usize> {
|
||||
self.conn
|
||||
.query_row(&format!("SELECT count(*) FROM {table}"), [], |row| row.get::<_, i64>(0))
|
||||
.map(|n| usize::try_from(n).unwrap_or(0))
|
||||
.map_err(db_err)
|
||||
};
|
||||
Ok((count("files")?, count("symbols")?, count("refs")?))
|
||||
}
|
||||
|
||||
fn write(
|
||||
&mut self,
|
||||
stored: &HashMap<String, (i64, String)>,
|
||||
removed: &[i64],
|
||||
done: Vec<Done>,
|
||||
) -> Result<()> {
|
||||
let tx = self.conn.transaction().map_err(db_err)?;
|
||||
{
|
||||
let mut delete_refs = tx.prepare("DELETE FROM refs WHERE file_id = ?1").map_err(db_err)?;
|
||||
let mut delete_symbols =
|
||||
tx.prepare("DELETE FROM symbols WHERE file_id = ?1").map_err(db_err)?;
|
||||
let mut delete_file = tx.prepare("DELETE FROM files WHERE id = ?1").map_err(db_err)?;
|
||||
for id in removed {
|
||||
delete_refs.execute([id]).map_err(db_err)?;
|
||||
delete_symbols.execute([id]).map_err(db_err)?;
|
||||
delete_file.execute([id]).map_err(db_err)?;
|
||||
}
|
||||
let mut insert_file = tx
|
||||
.prepare("INSERT INTO files(path, lang, oid, lines) VALUES(?1, ?2, ?3, ?4)")
|
||||
.map_err(db_err)?;
|
||||
let mut update_file = tx
|
||||
.prepare("UPDATE files SET lang = ?2, oid = ?3, lines = ?4 WHERE id = ?1")
|
||||
.map_err(db_err)?;
|
||||
let mut insert_symbol = tx
|
||||
.prepare(
|
||||
"INSERT INTO symbols(file_id, name, kind, container, line, end_line, signature, hash, parent_id)
|
||||
VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
|
||||
)
|
||||
.map_err(db_err)?;
|
||||
let mut insert_ref = tx
|
||||
.prepare(
|
||||
"INSERT INTO refs(file_id, symbol_id, name, kind, line, target) VALUES(?1, ?2, ?3, ?4, ?5, ?6)",
|
||||
)
|
||||
.map_err(db_err)?;
|
||||
for file in done {
|
||||
let lines = i64::try_from(file.lines).unwrap_or(i64::MAX);
|
||||
let file_id = match stored.get(&file.path) {
|
||||
Some((id, _)) => {
|
||||
delete_refs.execute([id]).map_err(db_err)?;
|
||||
delete_symbols.execute([id]).map_err(db_err)?;
|
||||
update_file
|
||||
.execute(params![id, file.lang.name(), file.oid, lines])
|
||||
.map_err(db_err)?;
|
||||
*id
|
||||
}
|
||||
None => {
|
||||
insert_file
|
||||
.execute(params![file.path, file.lang.name(), file.oid, lines])
|
||||
.map_err(db_err)?;
|
||||
tx.last_insert_rowid()
|
||||
}
|
||||
};
|
||||
let mut ids: Vec<i64> = Vec::with_capacity(file.parsed.symbols.len());
|
||||
for symbol in &file.parsed.symbols {
|
||||
let parent = symbol.parent.and_then(|index| ids.get(index).copied());
|
||||
insert_symbol
|
||||
.execute(params![
|
||||
file_id,
|
||||
symbol.name,
|
||||
symbol.kind,
|
||||
symbol.container,
|
||||
symbol.line,
|
||||
symbol.end_line,
|
||||
symbol.signature,
|
||||
symbol.hash,
|
||||
parent
|
||||
])
|
||||
.map_err(db_err)?;
|
||||
ids.push(tx.last_insert_rowid());
|
||||
}
|
||||
for reference in &file.parsed.references {
|
||||
let symbol = reference.symbol.and_then(|index| ids.get(index).copied());
|
||||
insert_ref
|
||||
.execute(params![
|
||||
file_id,
|
||||
symbol,
|
||||
reference.name,
|
||||
reference.kind,
|
||||
reference.line,
|
||||
reference.target
|
||||
])
|
||||
.map_err(db_err)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
tx.set_meta_indexed()?;
|
||||
tx.commit().map_err(db_err)
|
||||
}
|
||||
}
|
||||
|
||||
trait IndexedAt {
|
||||
fn set_meta_indexed(&self) -> Result<()>;
|
||||
}
|
||||
|
||||
impl IndexedAt for rusqlite::Transaction<'_> {
|
||||
fn set_meta_indexed(&self) -> Result<()> {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|duration| duration.as_secs())
|
||||
.unwrap_or(0);
|
||||
self.execute(
|
||||
"INSERT INTO meta(key, value) VALUES('indexed_at', ?1)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
||||
[now.to_string()],
|
||||
)
|
||||
.map(|_| ())
|
||||
.map_err(db_err)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads and parses the files on a few threads.
|
||||
fn parse_all(root: &Path, jobs: Vec<Job>) -> Vec<Done> {
|
||||
if jobs.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let threads = std::thread::available_parallelism()
|
||||
.map(usize::from)
|
||||
.unwrap_or(2)
|
||||
.clamp(1, MAX_THREADS)
|
||||
.min(jobs.len());
|
||||
let next = AtomicUsize::new(0);
|
||||
let results = Mutex::new(Vec::with_capacity(jobs.len()));
|
||||
let jobs: Vec<Mutex<Option<Job>>> = jobs.into_iter().map(|job| Mutex::new(Some(job))).collect();
|
||||
std::thread::scope(|scope| {
|
||||
for _ in 0..threads {
|
||||
scope.spawn(|| {
|
||||
let mut local = Vec::new();
|
||||
loop {
|
||||
let index = next.fetch_add(1, Ordering::Relaxed);
|
||||
let Some(slot) = jobs.get(index) else {
|
||||
break;
|
||||
};
|
||||
let Some(job) = slot.lock().ok().and_then(|mut slot| slot.take()) else {
|
||||
continue;
|
||||
};
|
||||
let content = match job.content {
|
||||
Some(content) => content,
|
||||
None => match std::fs::read(root.join(&job.path)) {
|
||||
Ok(content) => content,
|
||||
Err(_) => continue,
|
||||
},
|
||||
};
|
||||
let Ok(source) = String::from_utf8(content) else {
|
||||
continue;
|
||||
};
|
||||
let parsed = parse(job.lang, &source);
|
||||
local.push(Done {
|
||||
path: job.path,
|
||||
lang: job.lang,
|
||||
oid: job.oid,
|
||||
lines: source.lines().count(),
|
||||
parsed,
|
||||
});
|
||||
}
|
||||
if let Ok(mut results) = results.lock() {
|
||||
results.extend(local);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
results.into_inner().unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "index_tests.rs"]
|
||||
mod tests;
|
||||
75
akode-rs/code-graph/src/index_tests.rs
Normal file
75
akode-rs/code-graph/src/index_tests.rs
Normal file
@@ -0,0 +1,75 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
use super::CodeIndex;
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) {
|
||||
let status = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(dir)
|
||||
.args(["-c", "user.name=t", "-c", "user.email=t@example.com", "-c", "commit.gpgSign=false"])
|
||||
.args(args)
|
||||
.output()
|
||||
.expect("git");
|
||||
assert!(status.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&status.stderr));
|
||||
}
|
||||
|
||||
fn write(dir: &Path, path: &str, content: &str) {
|
||||
let full = dir.join(path);
|
||||
std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
|
||||
std::fs::write(full, content).expect("write");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incremental_updates_from_git() {
|
||||
let repo = tempfile::tempdir().expect("repo");
|
||||
let home = tempfile::tempdir().expect("home");
|
||||
let root = repo.path().canonicalize().expect("canonical");
|
||||
git(&root, &["init", "-q"]);
|
||||
write(&root, "src/lib.rs", "pub fn alpha() { beta(); }\npub fn beta() {}\n");
|
||||
write(&root, "src/other.rs", "use crate::alpha;\nfn gamma() { alpha(); }\n");
|
||||
write(&root, "README.md", "# not indexed\n");
|
||||
git(&root, &["add", "."]);
|
||||
git(&root, &["commit", "-q", "-m", "one"]);
|
||||
|
||||
let mut index = CodeIndex::open_for_dir(home.path(), &root.join("src")).expect("open");
|
||||
let report = index.update().expect("first");
|
||||
assert_eq!((report.mode, report.parsed, report.files, report.symbols), ("full", 2, 2, 3));
|
||||
|
||||
let report = index.update().expect("no change");
|
||||
assert_eq!((report.mode, report.parsed, report.checked), ("status", 0, 0));
|
||||
|
||||
// Working tree change, then untracked file.
|
||||
write(&root, "src/lib.rs", "pub fn alpha() { beta(); delta(); }\npub fn beta() {}\nfn delta() {}\n");
|
||||
write(&root, "src/new.rs", "fn epsilon() { delta(); }\n");
|
||||
let report = index.update().expect("dirty");
|
||||
assert_eq!((report.mode, report.parsed, report.files, report.symbols), ("status", 2, 3, 5));
|
||||
|
||||
// Commit: the dirty files become clean with the same blob ids, nothing to parse.
|
||||
git(&root, &["add", "."]);
|
||||
git(&root, &["commit", "-q", "-m", "two"]);
|
||||
let report = index.update().expect("commit");
|
||||
assert_eq!((report.mode, report.parsed), ("diff", 0));
|
||||
|
||||
// A file deleted in a commit disappears from the index.
|
||||
git(&root, &["rm", "-q", "src/new.rs"]);
|
||||
git(&root, &["commit", "-q", "-m", "three"]);
|
||||
let report = index.update().expect("delete");
|
||||
assert_eq!((report.mode, report.removed, report.files), ("diff", 1, 2));
|
||||
|
||||
let callers = index.callers("delta", 500).expect("callers");
|
||||
assert!(callers.contains("src/lib.rs:1 in function alpha"), "{callers}");
|
||||
assert!(!callers.contains("new.rs"), "{callers}");
|
||||
let callees = index.callees("alpha", 500).expect("callees");
|
||||
assert!(callees.contains("- beta (line 1) → function src/lib.rs:2"), "{callees}");
|
||||
let related = index.related("src/other.rs", "", 500).expect("related");
|
||||
assert!(related.contains("- src/lib.rs (2: alpha)"), "{related}");
|
||||
let map = index.module_map("src", "", 500).expect("map");
|
||||
assert!(map.contains("src/lib.rs (rust, 3 lines): function alpha, function beta, function delta"), "{map}");
|
||||
let definition = index.definition("beta", 5, 500).expect("definition");
|
||||
assert!(definition.contains("function beta — src/lib.rs:2"), "{definition}");
|
||||
let search = index.search("alp", None, None, 10, 500).expect("search");
|
||||
assert!(search.contains("function alpha — src/lib.rs:1"), "{search}");
|
||||
assert!(index.repo_summary(200).expect("summary").starts_with("Code map: 2 indexed files (rust 2)"));
|
||||
}
|
||||
142
akode-rs/code-graph/src/lang.rs
Normal file
142
akode-rs/code-graph/src/lang.rs
Normal file
@@ -0,0 +1,142 @@
|
||||
//! Supported languages, detected from the file name.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// A language the indexer can parse.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Lang {
|
||||
Rust,
|
||||
TypeScript,
|
||||
Tsx,
|
||||
JavaScript,
|
||||
Python,
|
||||
Go,
|
||||
Swift,
|
||||
Bash,
|
||||
Toml,
|
||||
Json,
|
||||
Yaml,
|
||||
}
|
||||
|
||||
/// Lock files and other generated manifests: large, never useful as symbols.
|
||||
const SKIPPED_FILE_NAMES: &[&str] = &[
|
||||
"Cargo.lock",
|
||||
"package-lock.json",
|
||||
"pnpm-lock.yaml",
|
||||
"yarn.lock",
|
||||
"composer.lock",
|
||||
"Gemfile.lock",
|
||||
"poetry.lock",
|
||||
"go.sum",
|
||||
"MODULE.bazel.lock",
|
||||
"flake.lock",
|
||||
];
|
||||
|
||||
impl Lang {
|
||||
/// Detects the language from the path; `None` for unsupported or skipped files.
|
||||
pub fn from_path(path: &str) -> Option<Lang> {
|
||||
let file_name = Path::new(path).file_name()?.to_str()?;
|
||||
if SKIPPED_FILE_NAMES.contains(&file_name)
|
||||
|| file_name.ends_with(".min.js")
|
||||
|| file_name.ends_with(".d.ts") && file_name.len() > 200
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let extension = Path::new(path).extension().and_then(|ext| ext.to_str());
|
||||
match extension {
|
||||
Some("rs") => Some(Lang::Rust),
|
||||
Some("ts" | "mts" | "cts") => Some(Lang::TypeScript),
|
||||
Some("tsx") => Some(Lang::Tsx),
|
||||
Some("js" | "mjs" | "cjs" | "jsx") => Some(Lang::JavaScript),
|
||||
Some("py" | "pyi") => Some(Lang::Python),
|
||||
Some("go") => Some(Lang::Go),
|
||||
Some("swift") => Some(Lang::Swift),
|
||||
Some("sh" | "bash" | "zsh") => Some(Lang::Bash),
|
||||
Some("toml") => Some(Lang::Toml),
|
||||
Some("json") => Some(Lang::Json),
|
||||
Some("yaml" | "yml") => Some(Lang::Yaml),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Short stable name stored in the index.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Lang::Rust => "rust",
|
||||
Lang::TypeScript => "typescript",
|
||||
Lang::Tsx => "tsx",
|
||||
Lang::JavaScript => "javascript",
|
||||
Lang::Python => "python",
|
||||
Lang::Go => "go",
|
||||
Lang::Swift => "swift",
|
||||
Lang::Bash => "bash",
|
||||
Lang::Toml => "toml",
|
||||
Lang::Json => "json",
|
||||
Lang::Yaml => "yaml",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_name(name: &str) -> Option<Lang> {
|
||||
[
|
||||
Lang::Rust,
|
||||
Lang::TypeScript,
|
||||
Lang::Tsx,
|
||||
Lang::JavaScript,
|
||||
Lang::Python,
|
||||
Lang::Go,
|
||||
Lang::Swift,
|
||||
Lang::Bash,
|
||||
Lang::Toml,
|
||||
Lang::Json,
|
||||
Lang::Yaml,
|
||||
]
|
||||
.into_iter()
|
||||
.find(|lang| lang.name() == name)
|
||||
}
|
||||
|
||||
/// Configuration files: only their structure (sections and keys) is indexed.
|
||||
pub fn structure_only(self) -> bool {
|
||||
matches!(self, Lang::Toml | Lang::Json | Lang::Yaml)
|
||||
}
|
||||
|
||||
/// Separator between a container and a member in qualified names.
|
||||
pub fn separator(self) -> &'static str {
|
||||
match self {
|
||||
Lang::Rust => "::",
|
||||
_ => ".",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn grammar(self) -> tree_sitter::Language {
|
||||
match self {
|
||||
Lang::Rust => tree_sitter_rust::LANGUAGE.into(),
|
||||
Lang::TypeScript => tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
|
||||
Lang::Tsx => tree_sitter_typescript::LANGUAGE_TSX.into(),
|
||||
Lang::JavaScript => tree_sitter_javascript::LANGUAGE.into(),
|
||||
Lang::Python => tree_sitter_python::LANGUAGE.into(),
|
||||
Lang::Go => tree_sitter_go::LANGUAGE.into(),
|
||||
Lang::Swift => tree_sitter_swift::LANGUAGE.into(),
|
||||
Lang::Bash => tree_sitter_bash::LANGUAGE.into(),
|
||||
Lang::Toml => tree_sitter_toml_ng::LANGUAGE.into(),
|
||||
Lang::Json => tree_sitter_json::LANGUAGE.into(),
|
||||
Lang::Yaml => tree_sitter_yaml::LANGUAGE.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Lang;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn detects_languages_and_skips_lock_files() {
|
||||
assert_eq!(Lang::from_path("src/main.rs"), Some(Lang::Rust));
|
||||
assert_eq!(Lang::from_path("web/App.tsx"), Some(Lang::Tsx));
|
||||
assert_eq!(Lang::from_path("Cargo.lock"), None);
|
||||
assert_eq!(Lang::from_path("frontend/package-lock.json"), None);
|
||||
assert_eq!(Lang::from_path("README.md"), None);
|
||||
assert_eq!(Lang::from_path(".github/ci.yml"), Some(Lang::Yaml));
|
||||
assert_eq!(Lang::from_name("swift"), Some(Lang::Swift));
|
||||
}
|
||||
}
|
||||
17
akode-rs/code-graph/src/lib.rs
Normal file
17
akode-rs/code-graph/src/lib.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
//! Code graph of a repository for aKode: definitions and references extracted with tree-sitter
|
||||
//! (no model involved), stored in a SQLite index per repository outside the checkout and kept
|
||||
//! up to date from git. Also computes the anchors that tie project memories to symbols.
|
||||
|
||||
pub mod anchor;
|
||||
pub mod git;
|
||||
pub mod index;
|
||||
pub mod lang;
|
||||
pub mod parse;
|
||||
pub mod query;
|
||||
|
||||
pub use anchor::Anchor;
|
||||
pub use anchor::AnchorCheck;
|
||||
pub use anchor::Citation;
|
||||
pub use anchor::Verifier;
|
||||
pub use index::CodeIndex;
|
||||
pub use index::UpdateReport;
|
||||
942
akode-rs/code-graph/src/parse.rs
Normal file
942
akode-rs/code-graph/src/parse.rs
Normal file
@@ -0,0 +1,942 @@
|
||||
//! Extraction of symbols (definitions) and references from one file with tree-sitter.
|
||||
//!
|
||||
//! The walk is iterative (deep expression trees cannot overflow the stack) and generic: each
|
||||
//! language only says which nodes define symbols, which nodes are containers (Rust `impl`,
|
||||
//! Swift `extension`), and which nodes are references (calls, imports, type names).
|
||||
//!
|
||||
//! Precision, as declared to the model: definitions are exact (the grammar says where they
|
||||
//! are); references are by name only. A call `x.parse()` is recorded as a reference to the
|
||||
//! name `parse`, so callers of a method shared by several types include all of them.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
use tree_sitter::Node;
|
||||
use tree_sitter::Parser;
|
||||
|
||||
use crate::lang::Lang;
|
||||
|
||||
/// Maximum characters kept for a signature.
|
||||
const MAX_SIGNATURE_CHARS: usize = 200;
|
||||
/// Maximum characters kept for an import target.
|
||||
const MAX_TARGET_CHARS: usize = 200;
|
||||
/// Depth of keys indexed in configuration files (1 = top-level keys and table headers).
|
||||
const MAX_KEY_DEPTH: usize = 2;
|
||||
|
||||
/// Rust macros from the standard library and common crates: never definitions of the repo.
|
||||
const IGNORED_RUST_MACROS: &[&str] = &[
|
||||
"assert",
|
||||
"assert_eq",
|
||||
"assert_ne",
|
||||
"assert_matches",
|
||||
"debug_assert",
|
||||
"debug_assert_eq",
|
||||
"debug_assert_ne",
|
||||
"format",
|
||||
"format_args",
|
||||
"print",
|
||||
"println",
|
||||
"eprint",
|
||||
"eprintln",
|
||||
"write",
|
||||
"writeln",
|
||||
"vec",
|
||||
"panic",
|
||||
"todo",
|
||||
"unimplemented",
|
||||
"unreachable",
|
||||
"matches",
|
||||
"debug",
|
||||
"info",
|
||||
"warn",
|
||||
"error",
|
||||
"trace",
|
||||
"json",
|
||||
"concat",
|
||||
"env",
|
||||
"include_str",
|
||||
"include_bytes",
|
||||
"stringify",
|
||||
"cfg",
|
||||
"anyhow",
|
||||
"bail",
|
||||
"ensure",
|
||||
];
|
||||
|
||||
/// One definition.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Symbol {
|
||||
pub name: String,
|
||||
/// function, method, struct, enum, trait, interface, protocol, class, type, module, const,
|
||||
/// macro, section, key.
|
||||
pub kind: &'static str,
|
||||
/// Enclosing type or module (`impl Foo` → `Foo`), if any.
|
||||
pub container: Option<String>,
|
||||
/// 1-based first line.
|
||||
pub line: u32,
|
||||
/// 1-based last line.
|
||||
pub end_line: u32,
|
||||
/// Declaration up to the body, whitespace collapsed.
|
||||
pub signature: String,
|
||||
/// 16 hex chars of SHA-256 over the whole definition with whitespace collapsed.
|
||||
pub hash: String,
|
||||
/// Index of the enclosing symbol in the same file.
|
||||
pub parent: Option<usize>,
|
||||
}
|
||||
|
||||
impl Symbol {
|
||||
/// `Container::name` (Rust) or `Container.name`, or just the name.
|
||||
pub fn qualified_name(&self, lang: Lang) -> String {
|
||||
match &self.container {
|
||||
Some(container) => format!("{container}{}{}", lang.separator(), self.name),
|
||||
None => self.name.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One reference by name.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Reference {
|
||||
pub name: String,
|
||||
/// call, macro, import, type.
|
||||
pub kind: &'static str,
|
||||
pub line: u32,
|
||||
/// Index of the innermost enclosing symbol.
|
||||
pub symbol: Option<usize>,
|
||||
/// Module path for imports; type qualifier of Rust path calls (`Index::new` → `Index`).
|
||||
pub target: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Parsed {
|
||||
pub symbols: Vec<Symbol>,
|
||||
pub references: Vec<Reference>,
|
||||
}
|
||||
|
||||
/// Hash of a definition: SHA-256 over the text with every whitespace run collapsed, so that
|
||||
/// re-indenting or re-wrapping does not make a memory stale.
|
||||
pub fn body_hash(text: &str) -> String {
|
||||
let mut hasher = Sha256::new();
|
||||
let mut first = true;
|
||||
for word in text.split_whitespace() {
|
||||
if !first {
|
||||
hasher.update(b" ");
|
||||
}
|
||||
first = false;
|
||||
hasher.update(word.as_bytes());
|
||||
}
|
||||
let digest = hasher.finalize();
|
||||
digest
|
||||
.iter()
|
||||
.take(8)
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Ctx {
|
||||
/// Innermost enclosing symbol.
|
||||
symbol: Option<usize>,
|
||||
/// Name of the enclosing container for qualified names.
|
||||
container: Option<Arc<str>>,
|
||||
/// Kind of the enclosing container (impl, trait, class...).
|
||||
container_kind: Option<&'static str>,
|
||||
/// Number of enclosing keys/sections in configuration files.
|
||||
key_depth: usize,
|
||||
}
|
||||
|
||||
/// What a node is for the index.
|
||||
enum Role {
|
||||
Definition {
|
||||
name: String,
|
||||
kind: &'static str,
|
||||
/// Children get this container (types, modules, sections).
|
||||
opens_container: bool,
|
||||
},
|
||||
/// Only a container for its children (Rust `impl`, Swift `extension`).
|
||||
Container { name: String, kind: &'static str },
|
||||
/// Not indexed and not descended into.
|
||||
Skip,
|
||||
Other,
|
||||
}
|
||||
|
||||
/// Parses one file. Returns an empty result when the grammar cannot be loaded.
|
||||
pub fn parse(lang: Lang, source: &str) -> Parsed {
|
||||
let mut parser = Parser::new();
|
||||
if parser.set_language(&lang.grammar()).is_err() {
|
||||
return Parsed::default();
|
||||
}
|
||||
let Some(tree) = parser.parse(source, None) else {
|
||||
return Parsed::default();
|
||||
};
|
||||
let mut out = Parsed::default();
|
||||
let root_ctx = Ctx {
|
||||
symbol: None,
|
||||
container: None,
|
||||
container_kind: None,
|
||||
key_depth: 0,
|
||||
};
|
||||
let mut stack: Vec<(Node<'_>, Ctx)> = vec![(tree.root_node(), root_ctx)];
|
||||
while let Some((node, ctx)) = stack.pop() {
|
||||
let mut child_ctx = ctx.clone();
|
||||
match role(lang, node, source, &ctx) {
|
||||
Role::Skip => continue,
|
||||
Role::Definition {
|
||||
name,
|
||||
kind,
|
||||
opens_container,
|
||||
} => {
|
||||
let kind = refine_kind(kind, &ctx);
|
||||
let index = out.symbols.len();
|
||||
out.symbols.push(Symbol {
|
||||
name: name.clone(),
|
||||
kind,
|
||||
container: ctx.container.as_deref().map(str::to_string),
|
||||
line: line_of(node.start_position().row),
|
||||
end_line: line_of(node.end_position().row),
|
||||
signature: signature(lang, node, source),
|
||||
hash: body_hash(text(node, source)),
|
||||
parent: ctx.symbol,
|
||||
});
|
||||
child_ctx.symbol = Some(index);
|
||||
if lang.structure_only() {
|
||||
child_ctx.key_depth += 1;
|
||||
child_ctx.container = Some(Arc::from(
|
||||
match &ctx.container {
|
||||
Some(parent) => format!("{parent}.{name}"),
|
||||
None => name,
|
||||
}
|
||||
.as_str(),
|
||||
));
|
||||
child_ctx.container_kind = Some(kind);
|
||||
} else if opens_container {
|
||||
child_ctx.container = Some(Arc::from(name.as_str()));
|
||||
child_ctx.container_kind = Some(kind);
|
||||
}
|
||||
}
|
||||
Role::Container { name, kind } => {
|
||||
child_ctx.container = Some(Arc::from(name.as_str()));
|
||||
child_ctx.container_kind = Some(kind);
|
||||
}
|
||||
Role::Other => {}
|
||||
}
|
||||
if !lang.structure_only() {
|
||||
references(lang, node, source, &ctx, &mut out.references);
|
||||
}
|
||||
let mut cursor = node.walk();
|
||||
let children: Vec<Node<'_>> = node.children(&mut cursor).collect();
|
||||
for child in children.into_iter().rev() {
|
||||
if child.is_named() {
|
||||
stack.push((child, child_ctx.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Children were pushed in reverse, so symbols are already in source order within a parent;
|
||||
// sorting by line keeps the whole list ordered for module maps.
|
||||
out.references.sort_by_key(|reference| reference.line);
|
||||
if lang == Lang::Go {
|
||||
split_go_receivers(&mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn line_of(row: usize) -> u32 {
|
||||
u32::try_from(row + 1).unwrap_or(u32::MAX)
|
||||
}
|
||||
|
||||
fn text<'a>(node: Node<'_>, source: &'a str) -> &'a str {
|
||||
source.get(node.byte_range()).unwrap_or("")
|
||||
}
|
||||
|
||||
fn field_text(node: Node<'_>, field: &str, source: &str) -> Option<String> {
|
||||
node.child_by_field_name(field)
|
||||
.map(|child| text(child, source).trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
/// A function inside a type or trait is a method.
|
||||
fn refine_kind(kind: &'static str, ctx: &Ctx) -> &'static str {
|
||||
if kind == "function"
|
||||
&& matches!(
|
||||
ctx.container_kind,
|
||||
Some("impl" | "trait" | "class" | "struct" | "enum" | "interface" | "protocol" | "extension")
|
||||
)
|
||||
{
|
||||
"method"
|
||||
} else {
|
||||
kind
|
||||
}
|
||||
}
|
||||
|
||||
/// `foo::Bar<T>` → `Bar`; `&mut Baz` → `Baz`.
|
||||
fn type_base_name(raw: &str) -> String {
|
||||
let without_generics = raw.split('<').next().unwrap_or(raw);
|
||||
let last = without_generics
|
||||
.rsplit("::")
|
||||
.next()
|
||||
.unwrap_or(without_generics);
|
||||
last.trim_start_matches(['&', '*'])
|
||||
.trim_start_matches("mut ")
|
||||
.trim_start_matches("dyn ")
|
||||
.trim()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn unquote(raw: &str) -> String {
|
||||
raw.trim()
|
||||
.trim_matches(|c| c == '"' || c == '\'' || c == '`')
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn signature(lang: Lang, node: Node<'_>, source: &str) -> String {
|
||||
let start = node.start_byte();
|
||||
let end = ["body", "value"]
|
||||
.iter()
|
||||
.filter(|field| !(lang.structure_only() && **field == "value"))
|
||||
.find_map(|field| node.child_by_field_name(field))
|
||||
.map(|body| body.start_byte())
|
||||
.filter(|end| *end > start)
|
||||
.unwrap_or_else(|| {
|
||||
let full = text(node, source);
|
||||
start + full.find('\n').unwrap_or(full.len())
|
||||
});
|
||||
let raw = source.get(start..end).unwrap_or("");
|
||||
let collapsed = raw.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
let collapsed = collapsed.trim_end_matches(['{', ':', '=']).trim_end().to_string();
|
||||
if collapsed.chars().count() > MAX_SIGNATURE_CHARS {
|
||||
let cut: String = collapsed.chars().take(MAX_SIGNATURE_CHARS).collect();
|
||||
format!("{cut}…")
|
||||
} else {
|
||||
collapsed
|
||||
}
|
||||
}
|
||||
|
||||
fn def(name: Option<String>, kind: &'static str, opens_container: bool) -> Role {
|
||||
match name {
|
||||
Some(name) => Role::Definition {
|
||||
name,
|
||||
kind,
|
||||
opens_container,
|
||||
},
|
||||
None => Role::Other,
|
||||
}
|
||||
}
|
||||
|
||||
fn role(lang: Lang, node: Node<'_>, source: &str, ctx: &Ctx) -> Role {
|
||||
let name = || field_text(node, "name", source);
|
||||
match lang {
|
||||
Lang::Rust => match node.kind() {
|
||||
"function_item" => def(name(), "function", false),
|
||||
"function_signature_item" => def(name(), "function", false),
|
||||
"struct_item" | "union_item" => def(name(), "struct", true),
|
||||
"enum_item" => def(name(), "enum", true),
|
||||
"trait_item" => def(name(), "trait", true),
|
||||
"type_item" => def(name(), "type", false),
|
||||
"mod_item" => def(name(), "module", true),
|
||||
"const_item" | "static_item" => def(name(), "const", false),
|
||||
"macro_definition" => def(name(), "macro", false),
|
||||
"impl_item" => match field_text(node, "type", source) {
|
||||
Some(raw) => Role::Container {
|
||||
name: type_base_name(&raw),
|
||||
kind: "impl",
|
||||
},
|
||||
None => Role::Other,
|
||||
},
|
||||
_ => Role::Other,
|
||||
},
|
||||
Lang::TypeScript | Lang::Tsx | Lang::JavaScript => match node.kind() {
|
||||
"function_declaration" | "generator_function_declaration" => {
|
||||
def(name(), "function", false)
|
||||
}
|
||||
"class_declaration" | "abstract_class_declaration" => def(name(), "class", true),
|
||||
"class" => match name() {
|
||||
Some(name) => def(Some(name), "class", true),
|
||||
None => Role::Other,
|
||||
},
|
||||
"interface_declaration" => def(name(), "interface", true),
|
||||
"type_alias_declaration" => def(name(), "type", false),
|
||||
"enum_declaration" => def(name(), "enum", true),
|
||||
"internal_module" | "module" => def(name().map(|n| unquote(&n)), "module", true),
|
||||
"method_definition" | "method_signature" | "abstract_method_signature" => {
|
||||
def(name(), "method", false)
|
||||
}
|
||||
"variable_declarator" => {
|
||||
let is_function = node.child_by_field_name("value").is_some_and(|value| {
|
||||
matches!(
|
||||
value.kind(),
|
||||
"arrow_function" | "function_expression" | "function" | "generator_function"
|
||||
)
|
||||
});
|
||||
let named = node
|
||||
.child_by_field_name("name")
|
||||
.is_some_and(|name| name.kind() == "identifier");
|
||||
if is_function && named {
|
||||
def(name(), "function", false)
|
||||
} else if named && ctx.symbol.is_none() && is_constant_name(&name().unwrap_or_default()) {
|
||||
def(name(), "const", false)
|
||||
} else {
|
||||
Role::Other
|
||||
}
|
||||
}
|
||||
"public_field_definition" | "field_definition" => {
|
||||
let is_function = node.child_by_field_name("value").is_some_and(|value| {
|
||||
matches!(value.kind(), "arrow_function" | "function_expression")
|
||||
});
|
||||
let field_name = name().or_else(|| field_text(node, "property", source));
|
||||
if is_function {
|
||||
def(field_name, "method", false)
|
||||
} else {
|
||||
Role::Other
|
||||
}
|
||||
}
|
||||
_ => Role::Other,
|
||||
},
|
||||
Lang::Python => match node.kind() {
|
||||
"function_definition" => def(name(), "function", false),
|
||||
"class_definition" => def(name(), "class", true),
|
||||
"assignment" if ctx.symbol.is_none() => {
|
||||
let left = node.child_by_field_name("left");
|
||||
match left {
|
||||
Some(left) if left.kind() == "identifier" => {
|
||||
let value = text(left, source).to_string();
|
||||
if is_constant_name(&value) {
|
||||
def(Some(value), "const", false)
|
||||
} else {
|
||||
Role::Other
|
||||
}
|
||||
}
|
||||
_ => Role::Other,
|
||||
}
|
||||
}
|
||||
_ => Role::Other,
|
||||
},
|
||||
Lang::Go => match node.kind() {
|
||||
"function_declaration" => def(name(), "function", false),
|
||||
"method_declaration" => {
|
||||
let receiver = node
|
||||
.child_by_field_name("receiver")
|
||||
.and_then(|receiver| first_descendant_of_kind(receiver, "type_identifier"))
|
||||
.map(|node| text(node, source).to_string());
|
||||
match (name(), receiver) {
|
||||
(Some(name), Some(receiver)) => Role::Definition {
|
||||
name: format!("{receiver}\u{0}{name}"),
|
||||
kind: "method",
|
||||
opens_container: false,
|
||||
},
|
||||
(name, None) => def(name, "method", false),
|
||||
(None, Some(_)) => Role::Other,
|
||||
}
|
||||
}
|
||||
"type_spec" | "type_alias" => {
|
||||
let kind = match node.child_by_field_name("type").map(|t| t.kind()) {
|
||||
Some("struct_type") => "struct",
|
||||
Some("interface_type") => "interface",
|
||||
_ => "type",
|
||||
};
|
||||
def(name(), kind, true)
|
||||
}
|
||||
"const_spec" | "var_spec" if ctx.symbol.is_none() => {
|
||||
def(name(), "const", false)
|
||||
}
|
||||
_ => Role::Other,
|
||||
},
|
||||
Lang::Swift => match node.kind() {
|
||||
"function_declaration" | "protocol_function_declaration" => {
|
||||
def(name(), "function", false)
|
||||
}
|
||||
"init_declaration" => def(Some("init".to_string()), "function", false),
|
||||
"protocol_declaration" => def(name(), "protocol", true),
|
||||
"typealias_declaration" => def(name(), "type", false),
|
||||
"class_declaration" => {
|
||||
let keyword = {
|
||||
let mut cursor = node.walk();
|
||||
node.children(&mut cursor)
|
||||
.find(|child| !child.is_named())
|
||||
.map(|child| child.kind())
|
||||
.unwrap_or("class")
|
||||
};
|
||||
let Some(raw) = name() else {
|
||||
return Role::Other;
|
||||
};
|
||||
let base = type_base_name(&raw);
|
||||
match keyword {
|
||||
"extension" => Role::Container {
|
||||
name: base,
|
||||
kind: "extension",
|
||||
},
|
||||
"struct" => def(Some(base), "struct", true),
|
||||
"enum" => def(Some(base), "enum", true),
|
||||
_ => def(Some(base), "class", true),
|
||||
}
|
||||
}
|
||||
_ => Role::Other,
|
||||
},
|
||||
Lang::Bash => match node.kind() {
|
||||
"function_definition" => def(name(), "function", false),
|
||||
_ => Role::Other,
|
||||
},
|
||||
Lang::Toml => match node.kind() {
|
||||
"table" | "table_array_element" => {
|
||||
let header = {
|
||||
let mut cursor = node.walk();
|
||||
node.named_children(&mut cursor)
|
||||
.find(|child| matches!(child.kind(), "bare_key" | "dotted_key" | "quoted_key"))
|
||||
.map(|child| unquote(text(child, source)))
|
||||
};
|
||||
// Tables are flat in TOML: a header resets the container.
|
||||
match header {
|
||||
Some(header) => Role::Definition {
|
||||
name: header,
|
||||
kind: "section",
|
||||
opens_container: true,
|
||||
},
|
||||
None => Role::Other,
|
||||
}
|
||||
}
|
||||
"pair" if ctx.key_depth < MAX_KEY_DEPTH => {
|
||||
let key = {
|
||||
let mut cursor = node.walk();
|
||||
node.named_children(&mut cursor)
|
||||
.next()
|
||||
.map(|child| unquote(text(child, source)))
|
||||
};
|
||||
match key {
|
||||
Some(key) => Role::Definition {
|
||||
name: key,
|
||||
kind: "key",
|
||||
opens_container: false,
|
||||
},
|
||||
None => Role::Skip,
|
||||
}
|
||||
}
|
||||
"pair" => Role::Skip,
|
||||
_ => Role::Other,
|
||||
},
|
||||
Lang::Json => match node.kind() {
|
||||
"pair" if ctx.key_depth < MAX_KEY_DEPTH => {
|
||||
def(field_text(node, "key", source).map(|key| unquote(&key)), "key", true)
|
||||
}
|
||||
"pair" => Role::Skip,
|
||||
_ => Role::Other,
|
||||
},
|
||||
Lang::Yaml => match node.kind() {
|
||||
"block_mapping_pair" | "flow_pair" if ctx.key_depth < MAX_KEY_DEPTH => {
|
||||
def(field_text(node, "key", source).map(|key| unquote(&key)), "key", true)
|
||||
}
|
||||
"block_mapping_pair" | "flow_pair" => Role::Skip,
|
||||
_ => Role::Other,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn is_constant_name(name: &str) -> bool {
|
||||
name.len() > 1
|
||||
&& name.chars().any(|c| c.is_ascii_uppercase())
|
||||
&& name
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
|
||||
}
|
||||
|
||||
fn first_descendant_of_kind<'tree>(node: Node<'tree>, kind: &str) -> Option<Node<'tree>> {
|
||||
let mut stack = vec![node];
|
||||
while let Some(current) = stack.pop() {
|
||||
if current.kind() == kind {
|
||||
return Some(current);
|
||||
}
|
||||
let mut cursor = current.walk();
|
||||
let children: Vec<Node<'tree>> = current.named_children(&mut cursor).collect();
|
||||
stack.extend(children.into_iter().rev());
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Last identifier of a callee expression (`a::b::c` → `c`, `x.y()` → `y`).
|
||||
fn callee_name(lang: Lang, node: Node<'_>, source: &str) -> Option<String> {
|
||||
let name = match (lang, node.kind()) {
|
||||
(_, "identifier" | "simple_identifier" | "field_identifier" | "property_identifier") => {
|
||||
Some(text(node, source).to_string())
|
||||
}
|
||||
(Lang::Rust, "field_expression") => field_text(node, "field", source),
|
||||
(Lang::Rust, "scoped_identifier") => field_text(node, "name", source),
|
||||
(Lang::Rust, "generic_function") => node
|
||||
.child_by_field_name("function")
|
||||
.and_then(|inner| callee_name(lang, inner, source)),
|
||||
(Lang::TypeScript | Lang::Tsx | Lang::JavaScript, "member_expression") => {
|
||||
field_text(node, "property", source)
|
||||
}
|
||||
(Lang::Python, "attribute") => field_text(node, "attribute", source),
|
||||
(Lang::Go, "selector_expression") => field_text(node, "field", source),
|
||||
(Lang::Swift, "navigation_expression") => node
|
||||
.child_by_field_name("suffix")
|
||||
.and_then(|suffix| suffix.child_by_field_name("suffix"))
|
||||
.map(|suffix| text(suffix, source).to_string()),
|
||||
_ => None,
|
||||
}?;
|
||||
let name = name.trim().trim_start_matches("r#").to_string();
|
||||
(!name.is_empty() && name.len() <= 120).then_some(name)
|
||||
}
|
||||
|
||||
fn push_ref(
|
||||
out: &mut Vec<Reference>,
|
||||
name: String,
|
||||
kind: &'static str,
|
||||
node: Node<'_>,
|
||||
symbol: Option<usize>,
|
||||
target: Option<String>,
|
||||
) {
|
||||
let target = target.map(|target| {
|
||||
let collapsed = target.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
collapsed.chars().take(MAX_TARGET_CHARS).collect()
|
||||
});
|
||||
out.push(Reference {
|
||||
name,
|
||||
kind,
|
||||
line: line_of(node.start_position().row),
|
||||
symbol,
|
||||
target,
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether a type identifier is the name of the definition it belongs to.
|
||||
fn is_definition_name(node: Node<'_>) -> bool {
|
||||
let Some(parent) = node.parent() else {
|
||||
return false;
|
||||
};
|
||||
const DEFINITIONS: &[&str] = &[
|
||||
"struct_item",
|
||||
"enum_item",
|
||||
"union_item",
|
||||
"trait_item",
|
||||
"type_item",
|
||||
"class_declaration",
|
||||
"abstract_class_declaration",
|
||||
"interface_declaration",
|
||||
"type_alias_declaration",
|
||||
"enum_declaration",
|
||||
"type_spec",
|
||||
"type_alias",
|
||||
"protocol_declaration",
|
||||
"typealias_declaration",
|
||||
];
|
||||
let is_name = DEFINITIONS.contains(&parent.kind())
|
||||
&& parent
|
||||
.child_by_field_name("name")
|
||||
.is_some_and(|name| name.id() == node.id());
|
||||
is_name
|
||||
|| parent.kind() == "user_type"
|
||||
&& parent
|
||||
.parent()
|
||||
.is_some_and(|grand| grand.kind() == "class_declaration"
|
||||
&& grand.child_by_field_name("name").is_some_and(|name| name.id() == parent.id()))
|
||||
}
|
||||
|
||||
/// Type qualifier of a Rust path call (`Index::new()` → `Index`, `Self::x()` → the container).
|
||||
fn rust_qualifier(callee: Node<'_>, source: &str, ctx: &Ctx) -> Option<String> {
|
||||
let callee = if callee.kind() == "generic_function" {
|
||||
callee.child_by_field_name("function")?
|
||||
} else {
|
||||
callee
|
||||
};
|
||||
if callee.kind() != "scoped_identifier" {
|
||||
return None;
|
||||
}
|
||||
let path = callee.child_by_field_name("path")?;
|
||||
let base = type_base_name(text(path, source));
|
||||
if base == "Self" {
|
||||
return ctx.container.as_deref().map(str::to_string);
|
||||
}
|
||||
base.starts_with(|c: char| c.is_ascii_uppercase()).then_some(base)
|
||||
}
|
||||
|
||||
fn references(lang: Lang, node: Node<'_>, source: &str, ctx: &Ctx, out: &mut Vec<Reference>) {
|
||||
let symbol = ctx.symbol;
|
||||
match (lang, node.kind()) {
|
||||
(Lang::Rust, "call_expression") => {
|
||||
let Some(callee) = node.child_by_field_name("function") else {
|
||||
return;
|
||||
};
|
||||
if let Some(name) = callee_name(lang, callee, source) {
|
||||
let qualifier = rust_qualifier(callee, source, ctx);
|
||||
push_ref(out, name, "call", node, symbol, qualifier);
|
||||
}
|
||||
}
|
||||
// Macro arguments are token trees, not expressions: `name(` and `Type::name(` inside
|
||||
// `assert!(...)`, `format!(...)` or `tokio::select! { ... }` are calls too.
|
||||
(Lang::Rust, "token_tree") => {
|
||||
let mut cursor = node.walk();
|
||||
let tokens: Vec<Node<'_>> = node.children(&mut cursor).collect();
|
||||
for (index, token) in tokens.iter().enumerate() {
|
||||
if token.kind() != "identifier" {
|
||||
continue;
|
||||
}
|
||||
let Some(next) = tokens.get(index + 1) else {
|
||||
continue;
|
||||
};
|
||||
let name = text(*token, source).to_string();
|
||||
if next.kind() == "token_tree" && text(*next, source).starts_with('(') {
|
||||
let qualifier = (index >= 2
|
||||
&& text(tokens[index - 1], source) == "::"
|
||||
&& tokens[index - 2].kind() == "identifier")
|
||||
.then(|| text(tokens[index - 2], source).to_string())
|
||||
.map(|q| if q == "Self" { ctx.container.as_deref().unwrap_or("Self").to_string() } else { q })
|
||||
.filter(|q| q.starts_with(|c: char| c.is_ascii_uppercase()));
|
||||
push_ref(out, name, "call", *token, symbol, qualifier);
|
||||
} else if text(*next, source) == "!"
|
||||
&& tokens.get(index + 2).is_some_and(|tree| tree.kind() == "token_tree")
|
||||
&& !IGNORED_RUST_MACROS.contains(&name.as_str())
|
||||
{
|
||||
push_ref(out, name, "macro", *token, symbol, None);
|
||||
} else if (text(*next, source) == "::"
|
||||
|| next.kind() == "token_tree" && text(*next, source).starts_with('{'))
|
||||
&& name.starts_with(|c: char| c.is_ascii_uppercase())
|
||||
&& name != "Self"
|
||||
{
|
||||
push_ref(out, name, "type", *token, symbol, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
// `ProjectRow::json` used as a value names the type too.
|
||||
(Lang::Rust, "scoped_identifier" | "scoped_type_identifier") => {
|
||||
if let Some(path) = node.child_by_field_name("path")
|
||||
&& path.kind() == "identifier"
|
||||
{
|
||||
let name = text(path, source).to_string();
|
||||
if name.starts_with(|c: char| c.is_ascii_uppercase()) && name != "Self" {
|
||||
push_ref(out, name, "type", path, symbol, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
(Lang::Rust, "macro_invocation") => {
|
||||
if let Some(name) = node
|
||||
.child_by_field_name("macro")
|
||||
.and_then(|callee| callee_name(lang, callee, source))
|
||||
&& !IGNORED_RUST_MACROS.contains(&name.as_str())
|
||||
{
|
||||
push_ref(out, name, "macro", node, symbol, None);
|
||||
}
|
||||
}
|
||||
(Lang::Rust, "use_declaration") => {
|
||||
if let Some(argument) = node.child_by_field_name("argument") {
|
||||
let target = text(argument, source).to_string();
|
||||
for name in rust_use_leaves(argument, source) {
|
||||
push_ref(out, name, "import", node, symbol, Some(target.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
(Lang::Rust | Lang::TypeScript | Lang::Tsx | Lang::Go | Lang::Swift, "type_identifier") => {
|
||||
if !is_definition_name(node) {
|
||||
let name = text(node, source).to_string();
|
||||
if name.len() > 1 {
|
||||
push_ref(out, name, "type", node, symbol, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
(Lang::TypeScript | Lang::Tsx | Lang::JavaScript, "call_expression") => {
|
||||
if let Some(name) = node
|
||||
.child_by_field_name("function")
|
||||
.and_then(|callee| callee_name(lang, callee, source))
|
||||
{
|
||||
push_ref(out, name, "call", node, symbol, None);
|
||||
}
|
||||
}
|
||||
(Lang::TypeScript | Lang::Tsx | Lang::JavaScript, "new_expression") => {
|
||||
if let Some(name) = node
|
||||
.child_by_field_name("constructor")
|
||||
.and_then(|callee| callee_name(lang, callee, source))
|
||||
{
|
||||
push_ref(out, name, "call", node, symbol, None);
|
||||
}
|
||||
}
|
||||
(Lang::Tsx | Lang::JavaScript, "jsx_opening_element" | "jsx_self_closing_element") => {
|
||||
if let Some(name) = node
|
||||
.child_by_field_name("name")
|
||||
.and_then(|callee| callee_name(lang, callee, source))
|
||||
&& name.starts_with(|c: char| c.is_ascii_uppercase())
|
||||
{
|
||||
push_ref(out, name, "call", node, symbol, None);
|
||||
}
|
||||
}
|
||||
(Lang::TypeScript | Lang::Tsx | Lang::JavaScript, "import_statement" | "export_statement") => {
|
||||
let Some(source_node) = node.child_by_field_name("source") else {
|
||||
return;
|
||||
};
|
||||
let target = unquote(text(source_node, source));
|
||||
let mut names = Vec::new();
|
||||
let mut stack = vec![node];
|
||||
while let Some(current) = stack.pop() {
|
||||
match current.kind() {
|
||||
"import_specifier" | "export_specifier" => {
|
||||
if let Some(name) = field_text(current, "name", source) {
|
||||
names.push(name);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
"namespace_import" | "import_clause" => {
|
||||
let mut cursor = current.walk();
|
||||
for child in current.named_children(&mut cursor) {
|
||||
if child.kind() == "identifier" {
|
||||
names.push(text(child, source).to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let mut cursor = current.walk();
|
||||
let children: Vec<Node<'_>> = current.named_children(&mut cursor).collect();
|
||||
stack.extend(children);
|
||||
}
|
||||
if names.is_empty() {
|
||||
names.push(module_leaf(&target));
|
||||
}
|
||||
for name in names {
|
||||
push_ref(out, name, "import", node, symbol, Some(target.clone()));
|
||||
}
|
||||
}
|
||||
(Lang::Python, "call") => {
|
||||
if let Some(name) = node
|
||||
.child_by_field_name("function")
|
||||
.and_then(|callee| callee_name(lang, callee, source))
|
||||
{
|
||||
push_ref(out, name, "call", node, symbol, None);
|
||||
}
|
||||
}
|
||||
(Lang::Python, "import_statement") => {
|
||||
let mut cursor = node.walk();
|
||||
for child in node.children_by_field_name("name", &mut cursor) {
|
||||
let dotted = match child.kind() {
|
||||
"aliased_import" => field_text(child, "name", source).unwrap_or_default(),
|
||||
_ => text(child, source).to_string(),
|
||||
};
|
||||
if !dotted.is_empty() {
|
||||
push_ref(out, module_leaf(&dotted), "import", node, symbol, Some(dotted));
|
||||
}
|
||||
}
|
||||
}
|
||||
(Lang::Python, "import_from_statement") => {
|
||||
let module = field_text(node, "module_name", source).unwrap_or_default();
|
||||
let mut cursor = node.walk();
|
||||
for child in node.children_by_field_name("name", &mut cursor) {
|
||||
let name = match child.kind() {
|
||||
"aliased_import" => field_text(child, "name", source).unwrap_or_default(),
|
||||
_ => text(child, source).to_string(),
|
||||
};
|
||||
if !name.is_empty() {
|
||||
push_ref(out, module_leaf(&name), "import", node, symbol, Some(module.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
(Lang::Go, "call_expression") => {
|
||||
if let Some(name) = node
|
||||
.child_by_field_name("function")
|
||||
.and_then(|callee| callee_name(lang, callee, source))
|
||||
{
|
||||
push_ref(out, name, "call", node, symbol, None);
|
||||
}
|
||||
}
|
||||
(Lang::Go, "import_spec") => {
|
||||
if let Some(path) = field_text(node, "path", source) {
|
||||
let path = unquote(&path);
|
||||
let name = field_text(node, "name", source).unwrap_or_else(|| module_leaf(&path));
|
||||
push_ref(out, name, "import", node, symbol, Some(path));
|
||||
}
|
||||
}
|
||||
(Lang::Swift, "call_expression") => {
|
||||
let mut cursor = node.walk();
|
||||
let callee = node.named_children(&mut cursor).next();
|
||||
if let Some(name) = callee.and_then(|callee| callee_name(lang, callee, source)) {
|
||||
push_ref(out, name, "call", node, symbol, None);
|
||||
}
|
||||
}
|
||||
(Lang::Swift, "import_declaration") => {
|
||||
let module = text(node, source)
|
||||
.trim_start_matches("import")
|
||||
.trim()
|
||||
.to_string();
|
||||
if !module.is_empty() {
|
||||
push_ref(out, module_leaf(&module), "import", node, symbol, Some(module));
|
||||
}
|
||||
}
|
||||
(Lang::Bash, "command") => {
|
||||
let Some(name) = field_text(node, "name", source) else {
|
||||
return;
|
||||
};
|
||||
if name == "source" || name == "." {
|
||||
let mut cursor = node.walk();
|
||||
let target = node
|
||||
.children_by_field_name("argument", &mut cursor)
|
||||
.next()
|
||||
.map(|argument| unquote(text(argument, source)));
|
||||
if let Some(target) = target {
|
||||
push_ref(out, module_leaf(&target), "import", node, symbol, Some(target));
|
||||
}
|
||||
} else if !name.contains(['$', '/', '"', '\'']) {
|
||||
push_ref(out, name, "call", node, symbol, None);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Last segment of a module path (`a/b/c.ts` → `c`, `a.b.c` → `c`).
|
||||
fn module_leaf(path: &str) -> String {
|
||||
let trimmed = path.trim_end_matches('/');
|
||||
if trimmed.contains('/') {
|
||||
let file = trimmed.rsplit('/').next().unwrap_or(trimmed);
|
||||
let stem = file.split('.').next().unwrap_or(file);
|
||||
return if stem.is_empty() { file.to_string() } else { stem.to_string() };
|
||||
}
|
||||
trimmed
|
||||
.rsplit(['.', ':'])
|
||||
.find(|segment| !segment.is_empty())
|
||||
.unwrap_or(trimmed)
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// Imported names of a Rust `use` tree: `a::b::{C, d::E as F}` → C, E.
|
||||
fn rust_use_leaves(node: Node<'_>, source: &str) -> Vec<String> {
|
||||
let mut leaves = Vec::new();
|
||||
let mut stack = vec![node];
|
||||
while let Some(current) = stack.pop() {
|
||||
match current.kind() {
|
||||
"identifier" | "type_identifier" => leaves.push(text(current, source).to_string()),
|
||||
"scoped_identifier" => {
|
||||
if let Some(name) = current.child_by_field_name("name") {
|
||||
stack.push(name);
|
||||
}
|
||||
}
|
||||
"use_as_clause" => {
|
||||
if let Some(path) = current.child_by_field_name("path") {
|
||||
stack.push(path);
|
||||
}
|
||||
}
|
||||
"scoped_use_list" => {
|
||||
if let Some(list) = current.child_by_field_name("list") {
|
||||
stack.push(list);
|
||||
}
|
||||
}
|
||||
"use_list" => {
|
||||
let mut cursor = current.walk();
|
||||
let children: Vec<Node<'_>> = current.named_children(&mut cursor).collect();
|
||||
stack.extend(children.into_iter().rev());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
leaves.retain(|leaf| !matches!(leaf.as_str(), "self" | "super" | "crate" | "*"));
|
||||
leaves
|
||||
}
|
||||
|
||||
/// Go methods are stored as `Receiver\0name` by [`role`]; split them into container and name.
|
||||
fn split_go_receivers(parsed: &mut Parsed) {
|
||||
for symbol in &mut parsed.symbols {
|
||||
if let Some((receiver, name)) = symbol.name.split_once('\u{0}') {
|
||||
symbol.container = Some(receiver.to_string());
|
||||
symbol.name = name.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "parse_tests.rs"]
|
||||
mod tests;
|
||||
235
akode-rs/code-graph/src/parse_tests.rs
Normal file
235
akode-rs/code-graph/src/parse_tests.rs
Normal file
@@ -0,0 +1,235 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn defs(lang: Lang, source: &str) -> Vec<(String, &'static str, u32)> {
|
||||
parse(lang, source)
|
||||
.symbols
|
||||
.iter()
|
||||
.map(|symbol| (symbol.qualified_name(lang), symbol.kind, symbol.line))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn refs(lang: Lang, source: &str) -> Vec<(String, &'static str, u32)> {
|
||||
parse(lang, source)
|
||||
.references
|
||||
.iter()
|
||||
.filter(|reference| reference.kind != "type")
|
||||
.map(|reference| (reference.name.clone(), reference.kind, reference.line))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rust_definitions_methods_and_calls() {
|
||||
let source = r#"use crate::store::{Store, open as open_store};
|
||||
pub struct Index { n: u32 }
|
||||
impl<T> Index {
|
||||
pub fn new() -> Self { helper(); Self::build(); Self { n: 0 } }
|
||||
fn build() {}
|
||||
}
|
||||
trait Walk { fn walk(&self); }
|
||||
fn helper() { let x = Index::new(); x.n.max(1); my_macro!(); println!("x"); }
|
||||
mod inner { pub const LIMIT: u32 = 3; }
|
||||
"#;
|
||||
assert_eq!(
|
||||
defs(Lang::Rust, source),
|
||||
vec![
|
||||
("Index".to_string(), "struct", 2),
|
||||
("Index::new".to_string(), "method", 4),
|
||||
("Index::build".to_string(), "method", 5),
|
||||
("Walk".to_string(), "trait", 7),
|
||||
("Walk::walk".to_string(), "method", 7),
|
||||
("helper".to_string(), "function", 8),
|
||||
("inner".to_string(), "module", 9),
|
||||
("inner::LIMIT".to_string(), "const", 9),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
refs(Lang::Rust, source),
|
||||
vec![
|
||||
("Store".to_string(), "import", 1),
|
||||
("open".to_string(), "import", 1),
|
||||
("helper".to_string(), "call", 4),
|
||||
("build".to_string(), "call", 4),
|
||||
("new".to_string(), "call", 8),
|
||||
("max".to_string(), "call", 8),
|
||||
("my_macro".to_string(), "macro", 8),
|
||||
]
|
||||
);
|
||||
let parsed = parse(Lang::Rust, source);
|
||||
let helper_call = parsed
|
||||
.references
|
||||
.iter()
|
||||
.find(|reference| reference.name == "helper")
|
||||
.expect("call to helper");
|
||||
assert_eq!(
|
||||
parsed.symbols[helper_call.symbol.expect("enclosing symbol")].name,
|
||||
"new"
|
||||
);
|
||||
assert_eq!(parsed.symbols[1].signature, "pub fn new() -> Self");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rust_calls_inside_macro_arguments() {
|
||||
let source = "fn t() {\n assert!(grade(1));\n tokio::select! { _ = tick() => { Self::stop(); } }\n let v = Row::json;\n let r = Rec { a: 1 };\n let e = Ev::Line { line };\n}\n";
|
||||
let found: Vec<(String, &str, u32)> = parse(Lang::Rust, source)
|
||||
.references
|
||||
.iter()
|
||||
.map(|r| (r.name.clone(), r.kind, r.line))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
found,
|
||||
vec![
|
||||
("grade".to_string(), "call", 2),
|
||||
("select".to_string(), "macro", 3),
|
||||
("tick".to_string(), "call", 3),
|
||||
("stop".to_string(), "call", 3),
|
||||
("Row".to_string(), "type", 4),
|
||||
("Rec".to_string(), "type", 5),
|
||||
("Ev".to_string(), "type", 6),
|
||||
("Line".to_string(), "type", 6),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hash_ignores_whitespace_only_changes() {
|
||||
let a = parse(Lang::Rust, "fn f() {\n 1 + 1\n}\n");
|
||||
let b = parse(Lang::Rust, "fn f() { 1 + 1 }");
|
||||
let c = parse(Lang::Rust, "fn f() { 1 + 2 }");
|
||||
assert_eq!(a.symbols[0].hash, b.symbols[0].hash);
|
||||
assert!(a.symbols[0].hash != c.symbols[0].hash);
|
||||
assert_eq!(a.symbols[0].hash.len(), 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typescript_and_tsx() {
|
||||
let source = r#"import { useState } from "react";
|
||||
import api from "./api";
|
||||
export class Store { load() { return fetchAll(); } }
|
||||
export const helper = (x: number) => x + 1;
|
||||
const LIMIT = 5;
|
||||
interface Props { a: string }
|
||||
export function App(props: Props) { const s = new Store(); return <Panel value={helper(1)} />; }
|
||||
"#;
|
||||
assert_eq!(
|
||||
defs(Lang::Tsx, source),
|
||||
vec![
|
||||
("Store".to_string(), "class", 3),
|
||||
("Store.load".to_string(), "method", 3),
|
||||
("helper".to_string(), "function", 4),
|
||||
("LIMIT".to_string(), "const", 5),
|
||||
("Props".to_string(), "interface", 6),
|
||||
("App".to_string(), "function", 7),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
refs(Lang::Tsx, source),
|
||||
vec![
|
||||
("useState".to_string(), "import", 1),
|
||||
("api".to_string(), "import", 2),
|
||||
("fetchAll".to_string(), "call", 3),
|
||||
("Store".to_string(), "call", 7),
|
||||
("Panel".to_string(), "call", 7),
|
||||
("helper".to_string(), "call", 7),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_go_swift_bash() {
|
||||
let python = "import os.path\nfrom a.b import c as d\nMAX = 3\nclass A:\n def m(self):\n return helper(self.x)\n\ndef helper(x):\n return os.path.join(x)\n";
|
||||
assert_eq!(
|
||||
defs(Lang::Python, python),
|
||||
vec![
|
||||
("MAX".to_string(), "const", 3),
|
||||
("A".to_string(), "class", 4),
|
||||
("A.m".to_string(), "method", 5),
|
||||
("helper".to_string(), "function", 8),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
refs(Lang::Python, python),
|
||||
vec![
|
||||
("path".to_string(), "import", 1),
|
||||
("c".to_string(), "import", 2),
|
||||
("helper".to_string(), "call", 6),
|
||||
("join".to_string(), "call", 9),
|
||||
]
|
||||
);
|
||||
|
||||
let go = "package main\nimport \"fmt\"\ntype Server struct{}\nfunc (s *Server) Run() { fmt.Println(start()) }\nfunc start() int { return 1 }\n";
|
||||
assert_eq!(
|
||||
defs(Lang::Go, go),
|
||||
vec![
|
||||
("Server".to_string(), "struct", 3),
|
||||
("Server.Run".to_string(), "method", 4),
|
||||
("start".to_string(), "function", 5),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
refs(Lang::Go, go),
|
||||
vec![
|
||||
("fmt".to_string(), "import", 2),
|
||||
("Println".to_string(), "call", 4),
|
||||
("start".to_string(), "call", 4),
|
||||
]
|
||||
);
|
||||
|
||||
let swift = "import Foundation\nstruct Person {\n init(name: String) {}\n func greet() -> String { helper(\"x\") }\n}\nextension Person { func bye() {} }\nfunc helper(_ s: String) -> String { s }\n";
|
||||
assert_eq!(
|
||||
defs(Lang::Swift, swift),
|
||||
vec![
|
||||
("Person".to_string(), "struct", 2),
|
||||
("Person.init".to_string(), "method", 3),
|
||||
("Person.greet".to_string(), "method", 4),
|
||||
("Person.bye".to_string(), "method", 6),
|
||||
("helper".to_string(), "function", 7),
|
||||
]
|
||||
);
|
||||
|
||||
let bash = "source ./lib.sh\nbuild() {\n cargo build\n}\nbuild\n";
|
||||
assert_eq!(defs(Lang::Bash, bash), vec![("build".to_string(), "function", 2)]);
|
||||
assert_eq!(
|
||||
refs(Lang::Bash, bash),
|
||||
vec![
|
||||
("lib".to_string(), "import", 1),
|
||||
("cargo".to_string(), "call", 3),
|
||||
("build".to_string(), "call", 5),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configuration_files_keep_only_structure() {
|
||||
let toml = "[package]\nname = \"x\"\n[dependencies]\nserde = { version = \"1\", features = [\"derive\"] }\n";
|
||||
assert_eq!(
|
||||
defs(Lang::Toml, toml),
|
||||
vec![
|
||||
("package".to_string(), "section", 1),
|
||||
("package.name".to_string(), "key", 2),
|
||||
("dependencies".to_string(), "section", 3),
|
||||
("dependencies.serde".to_string(), "key", 4),
|
||||
]
|
||||
);
|
||||
let json = "{\"scripts\": {\"build\": \"tsc\", \"deep\": {\"x\": 1}}, \"name\": \"a\"}";
|
||||
assert_eq!(
|
||||
defs(Lang::Json, json),
|
||||
vec![
|
||||
("scripts".to_string(), "key", 1),
|
||||
("scripts.build".to_string(), "key", 1),
|
||||
("scripts.deep".to_string(), "key", 1),
|
||||
("name".to_string(), "key", 1),
|
||||
]
|
||||
);
|
||||
let yaml = "jobs:\n build:\n steps:\n - run: make\nname: ci\n";
|
||||
assert_eq!(
|
||||
defs(Lang::Yaml, yaml),
|
||||
vec![
|
||||
("jobs".to_string(), "key", 1),
|
||||
("jobs.build".to_string(), "key", 2),
|
||||
("name".to_string(), "key", 5),
|
||||
]
|
||||
);
|
||||
assert!(parse(Lang::Yaml, yaml).references.is_empty());
|
||||
}
|
||||
743
akode-rs/code-graph/src/query.rs
Normal file
743
akode-rs/code-graph/src/query.rs
Normal file
@@ -0,0 +1,743 @@
|
||||
//! Read-only questions to the index, answered as compact text with `path:line` and a budget.
|
||||
//!
|
||||
//! References are matched by name (see [`crate::parse`]): answers about callers say how many
|
||||
//! definitions share the name, so the model knows when a list may contain homonyms.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use rusqlite::params;
|
||||
|
||||
use crate::index::CodeIndex;
|
||||
use crate::index::Result;
|
||||
use crate::lang::Lang;
|
||||
|
||||
/// Kinds that are configuration structure, not code.
|
||||
const CONFIG_KINDS: &[&str] = &["section", "key"];
|
||||
/// Kinds that are types (their "callers" are the places that use the type).
|
||||
const TYPE_KINDS: &[&str] = &[
|
||||
"struct", "enum", "trait", "interface", "protocol", "class", "type",
|
||||
];
|
||||
/// A name defined in more places than this is too generic to link files (`new`, `fmt`).
|
||||
const MAX_DEFINITIONS_FOR_LINKS: i64 = 3;
|
||||
|
||||
/// A symbol row with its file.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct SymbolRow {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub kind: String,
|
||||
pub container: Option<String>,
|
||||
pub line: u32,
|
||||
pub end_line: u32,
|
||||
pub signature: String,
|
||||
pub hash: String,
|
||||
pub path: String,
|
||||
pub lang: String,
|
||||
}
|
||||
|
||||
impl SymbolRow {
|
||||
pub fn qualified(&self) -> String {
|
||||
let separator = Lang::from_name(&self.lang).map_or(".", Lang::separator);
|
||||
match &self.container {
|
||||
Some(container) => format!("{container}{separator}{}", self.name),
|
||||
None => self.name.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn location(&self) -> String {
|
||||
if self.end_line > self.line {
|
||||
format!("{}:{}-{}", self.path, self.line, self.end_line)
|
||||
} else {
|
||||
format!("{}:{}", self.path, self.line)
|
||||
}
|
||||
}
|
||||
|
||||
fn is_test_path(&self) -> bool {
|
||||
is_test_path(&self.path)
|
||||
}
|
||||
}
|
||||
|
||||
fn is_test_path(path: &str) -> bool {
|
||||
path.contains("/tests/")
|
||||
|| path.starts_with("tests/")
|
||||
|| path.contains("_test")
|
||||
|| path.contains("_tests.")
|
||||
|| path.contains(".test.")
|
||||
|| path.contains(".spec.")
|
||||
}
|
||||
|
||||
const SYMBOL_COLUMNS: &str = "s.id, s.name, s.kind, s.container, s.line, s.end_line, s.signature, s.hash, f.path, f.lang";
|
||||
|
||||
fn symbol_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<SymbolRow> {
|
||||
Ok(SymbolRow {
|
||||
id: row.get(0)?,
|
||||
name: row.get(1)?,
|
||||
kind: row.get(2)?,
|
||||
container: row.get(3)?,
|
||||
line: row.get(4)?,
|
||||
end_line: row.get(5)?,
|
||||
signature: row.get(6)?,
|
||||
hash: row.get(7)?,
|
||||
path: row.get(8)?,
|
||||
lang: row.get(9)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn db_err(error: rusqlite::Error) -> String {
|
||||
format!("code graph database: {error}")
|
||||
}
|
||||
|
||||
/// Text output bounded by a character budget.
|
||||
struct Out {
|
||||
text: String,
|
||||
max_chars: usize,
|
||||
omitted: usize,
|
||||
}
|
||||
|
||||
impl Out {
|
||||
fn new(max_tokens: usize) -> Self {
|
||||
Self {
|
||||
text: String::new(),
|
||||
max_chars: max_tokens.max(100) * 4,
|
||||
omitted: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn line(&mut self, line: impl AsRef<str>) {
|
||||
let line = line.as_ref();
|
||||
if self.omitted > 0 || self.text.len() + line.len() + 1 > self.max_chars {
|
||||
self.omitted += 1;
|
||||
return;
|
||||
}
|
||||
self.text.push_str(line);
|
||||
self.text.push('\n');
|
||||
}
|
||||
|
||||
fn finish(mut self, hint: &str) -> String {
|
||||
if self.omitted > 0 {
|
||||
self.text
|
||||
.push_str(&format!("… {} more line(s) omitted (budget); {hint}\n", self.omitted));
|
||||
}
|
||||
self.text.trim_end().to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// `path#name`, `Type::name`, `Type.name` or `name`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct SymbolSpec {
|
||||
path: Option<String>,
|
||||
container: Option<String>,
|
||||
name: String,
|
||||
}
|
||||
|
||||
fn parse_spec(raw: &str) -> SymbolSpec {
|
||||
let raw = raw.trim().trim_end_matches("()").trim_matches('`');
|
||||
let (path, rest) = match raw.split_once('#') {
|
||||
Some((path, rest)) => (Some(path.trim().to_string()), rest.trim()),
|
||||
None => (None, raw),
|
||||
};
|
||||
let split = rest
|
||||
.rsplit_once("::")
|
||||
.or_else(|| rest.rsplit_once('.'))
|
||||
.filter(|(container, name)| !container.is_empty() && !name.is_empty());
|
||||
match split {
|
||||
Some((container, name)) => SymbolSpec {
|
||||
path,
|
||||
container: Some(container.rsplit("::").next().unwrap_or(container).to_string()),
|
||||
name: name.to_string(),
|
||||
},
|
||||
None => SymbolSpec {
|
||||
path,
|
||||
container: None,
|
||||
name: rest.to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeIndex {
|
||||
/// Converts a path given by the model (absolute, or relative to `cwd`/root) to an index path.
|
||||
pub fn normalize_path(&self, raw: &str, cwd_prefix: &str) -> String {
|
||||
let raw = raw.trim().trim_start_matches("./");
|
||||
let root = self.root().to_string_lossy().to_string();
|
||||
if let Some(stripped) = raw.strip_prefix(&format!("{root}/")) {
|
||||
return stripped.to_string();
|
||||
}
|
||||
if !cwd_prefix.is_empty() {
|
||||
let joined = format!("{cwd_prefix}/{raw}");
|
||||
if self.path_exists(&joined) {
|
||||
return joined;
|
||||
}
|
||||
}
|
||||
raw.trim_end_matches('/').to_string()
|
||||
}
|
||||
|
||||
fn path_exists(&self, path: &str) -> bool {
|
||||
let like = format!("{}%", like_escape(path));
|
||||
self.conn()
|
||||
.query_row(
|
||||
"SELECT 1 FROM files WHERE path = ?1 OR path LIKE ?2 ESCAPE '\\' LIMIT 1",
|
||||
params![path, like],
|
||||
|_| Ok(()),
|
||||
)
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
fn symbols_where(&self, clause: &str, binds: &[&dyn rusqlite::ToSql]) -> Result<Vec<SymbolRow>> {
|
||||
let sql = format!(
|
||||
"SELECT {SYMBOL_COLUMNS} FROM symbols s JOIN files f ON f.id = s.file_id WHERE {clause} LIMIT 400"
|
||||
);
|
||||
let mut statement = self.conn().prepare(&sql).map_err(db_err)?;
|
||||
let rows = statement
|
||||
.query_map(binds, symbol_row)
|
||||
.map_err(db_err)?
|
||||
.collect::<std::result::Result<Vec<_>, _>>()
|
||||
.map_err(db_err)?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// Definitions matching a symbol spec, best first.
|
||||
pub fn resolve(&self, raw: &str) -> Result<Vec<SymbolRow>> {
|
||||
let spec = parse_spec(raw);
|
||||
let mut rows = self.symbols_where("s.name = ?1", &[&spec.name])?;
|
||||
if rows.is_empty() {
|
||||
rows = self.symbols_where("s.name = ?1 COLLATE NOCASE", &[&spec.name])?;
|
||||
}
|
||||
if rows.is_empty() && spec.container.is_some() {
|
||||
// `a.b` can also be a single config key name.
|
||||
let whole = raw.trim().to_string();
|
||||
rows = self.symbols_where("s.name = ?1", &[&whole])?;
|
||||
}
|
||||
if let Some(container) = &spec.container {
|
||||
let filtered: Vec<SymbolRow> = rows
|
||||
.iter()
|
||||
.filter(|row| {
|
||||
row.container.as_deref().is_some_and(|c| c.eq_ignore_ascii_case(container))
|
||||
|| row.path.contains(container.as_str())
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
if !filtered.is_empty() {
|
||||
rows = filtered;
|
||||
}
|
||||
}
|
||||
if let Some(path) = &spec.path {
|
||||
rows.retain(|row| row.path == *path || row.path.starts_with(path.as_str()) || row.path.ends_with(path.as_str()));
|
||||
}
|
||||
rows.sort_by_key(|row| {
|
||||
(
|
||||
CONFIG_KINDS.contains(&row.kind.as_str()),
|
||||
row.is_test_path(),
|
||||
row.path.len(),
|
||||
row.line,
|
||||
)
|
||||
});
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// Symbols whose name matches `query` (exact, then prefix, then substring).
|
||||
pub fn search(&self, query: &str, kind: Option<&str>, path: Option<&str>, limit: usize, max_tokens: usize) -> Result<String> {
|
||||
let spec = parse_spec(query);
|
||||
let needle = spec.name.clone();
|
||||
let like_any = format!("%{}%", like_escape(&needle));
|
||||
let mut rows = self.symbols_where(
|
||||
"s.name LIKE ?1 ESCAPE '\\' ORDER BY length(s.name)",
|
||||
&[&like_any],
|
||||
)?;
|
||||
if let Some(kind) = kind {
|
||||
rows.retain(|row| row.kind == kind);
|
||||
}
|
||||
if let Some(path) = path {
|
||||
rows.retain(|row| row.path.starts_with(path));
|
||||
}
|
||||
if let Some(container) = &spec.container {
|
||||
rows.retain(|row| row.container.as_deref().is_some_and(|c| c.eq_ignore_ascii_case(container)));
|
||||
}
|
||||
let lower = needle.to_lowercase();
|
||||
rows.sort_by_key(|row| {
|
||||
let name = row.name.to_lowercase();
|
||||
let rank = if row.name == needle {
|
||||
0
|
||||
} else if name == lower {
|
||||
1
|
||||
} else if name.starts_with(&lower) {
|
||||
2
|
||||
} else {
|
||||
3
|
||||
};
|
||||
(rank, CONFIG_KINDS.contains(&row.kind.as_str()), row.is_test_path(), row.name.len(), row.path.clone(), row.line)
|
||||
});
|
||||
let total = rows.len();
|
||||
let mut out = Out::new(max_tokens);
|
||||
if total == 0 {
|
||||
return Ok(format!("No symbol matches \"{query}\". Try a shorter part of the name, or action=module_map on a directory."));
|
||||
}
|
||||
out.line(format!("{total}{} symbol(s) matching \"{query}\":", if total >= 400 { "+" } else { "" }));
|
||||
for row in rows.iter().take(limit.max(1)) {
|
||||
out.line(format!("- {} {} — {} · {}", row.kind, row.qualified(), row.location(), row.signature));
|
||||
}
|
||||
if total > limit {
|
||||
out.line(format!("({} more; narrow with kind or path)", total - limit));
|
||||
}
|
||||
Ok(out.finish("narrow with kind or path"))
|
||||
}
|
||||
|
||||
/// Where a symbol is defined, with the first lines of the definition.
|
||||
pub fn definition(&self, raw: &str, snippet_lines: usize, max_tokens: usize) -> Result<String> {
|
||||
let rows = self.resolve(raw)?;
|
||||
if rows.is_empty() {
|
||||
return Ok(format!("No definition of \"{raw}\" in the index. Try action=search with part of the name."));
|
||||
}
|
||||
let mut out = Out::new(max_tokens);
|
||||
if rows.len() > 1 {
|
||||
out.line(format!("{} definitions of \"{raw}\" (best first):", rows.len()));
|
||||
}
|
||||
for (position, row) in rows.iter().enumerate() {
|
||||
out.line(format!("- {} {} — {}", row.kind, row.qualified(), row.location()));
|
||||
if position < 2 && snippet_lines > 0 {
|
||||
let snippet = self.read_lines(&row.path, row.line, row.end_line.min(row.line + snippet_lines as u32 - 1));
|
||||
for (offset, text) in snippet.iter().enumerate() {
|
||||
out.line(format!(" {:>5} {}", row.line as usize + offset, text));
|
||||
}
|
||||
if row.end_line as usize >= row.line as usize + snippet_lines {
|
||||
out.line(format!(" … ({} lines in total; read the file for the rest)", row.end_line - row.line + 1));
|
||||
}
|
||||
} else if position >= 2 {
|
||||
out.line(format!(" {}", row.signature));
|
||||
}
|
||||
}
|
||||
Ok(out.finish("qualify the name (Type::name or path#name)"))
|
||||
}
|
||||
|
||||
fn read_lines(&self, path: &str, from: u32, to: u32) -> Vec<String> {
|
||||
let Ok(content) = std::fs::read_to_string(self.root().join(path)) else {
|
||||
return Vec::new();
|
||||
};
|
||||
content
|
||||
.lines()
|
||||
.skip(from.saturating_sub(1) as usize)
|
||||
.take((to.saturating_sub(from) + 1) as usize)
|
||||
.map(|line| {
|
||||
let line = line.trim_end();
|
||||
if line.chars().count() > 160 {
|
||||
format!("{}…", line.chars().take(160).collect::<String>())
|
||||
} else {
|
||||
line.to_string()
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Places that call (or, for types, use) a symbol, grouped by the enclosing definition.
|
||||
pub fn callers(&self, raw: &str, max_tokens: usize) -> Result<String> {
|
||||
let targets = self.resolve(raw)?;
|
||||
let spec = parse_spec(raw);
|
||||
let name = targets.first().map(|row| row.name.clone()).unwrap_or(spec.name.clone());
|
||||
let is_type = !targets.is_empty() && targets.iter().all(|row| TYPE_KINDS.contains(&row.kind.as_str()));
|
||||
let kinds: &[&str] = if is_type { &["type", "call", "import"] } else { &["call", "macro"] };
|
||||
let mut statement = self
|
||||
.conn()
|
||||
.prepare(
|
||||
"SELECT f.path, r.line, r.kind, r.target, s.name, s.container, s.kind, f.lang
|
||||
FROM refs r JOIN files f ON f.id = r.file_id LEFT JOIN symbols s ON s.id = r.symbol_id
|
||||
WHERE r.name = ?1 ORDER BY f.path, r.line LIMIT 2000",
|
||||
)
|
||||
.map_err(db_err)?;
|
||||
let refs = statement
|
||||
.query_map([&name], |row| {
|
||||
Ok((
|
||||
row.get::<_, String>(0)?,
|
||||
row.get::<_, u32>(1)?,
|
||||
row.get::<_, String>(2)?,
|
||||
row.get::<_, Option<String>>(3)?,
|
||||
row.get::<_, Option<String>>(4)?,
|
||||
row.get::<_, Option<String>>(5)?,
|
||||
row.get::<_, Option<String>>(6)?,
|
||||
row.get::<_, String>(7)?,
|
||||
))
|
||||
})
|
||||
.map_err(db_err)?
|
||||
.collect::<std::result::Result<Vec<_>, _>>()
|
||||
.map_err(db_err)?;
|
||||
// Qualified Rust calls name their type: drop the ones that point to another type.
|
||||
let wanted_containers: HashSet<String> = if spec.container.is_some() || targets.len() == 1 {
|
||||
targets.iter().filter_map(|row| row.container.clone()).collect()
|
||||
} else {
|
||||
HashSet::new()
|
||||
};
|
||||
let mut excluded = 0;
|
||||
let mut groups: BTreeMap<(String, String), Vec<u32>> = BTreeMap::new();
|
||||
for (path, line, kind, target, caller, caller_container, caller_kind, lang) in refs {
|
||||
if !kinds.contains(&kind.as_str()) {
|
||||
continue;
|
||||
}
|
||||
if kind == "call"
|
||||
&& !wanted_containers.is_empty()
|
||||
&& let Some(qualifier) = &target
|
||||
&& !wanted_containers.contains(qualifier)
|
||||
{
|
||||
excluded += 1;
|
||||
continue;
|
||||
}
|
||||
// The definition itself is not a caller.
|
||||
if targets.iter().any(|t| t.path == path && t.line == line) {
|
||||
continue;
|
||||
}
|
||||
let separator = Lang::from_name(&lang).map_or(".", Lang::separator);
|
||||
let within = match (caller, caller_kind) {
|
||||
(Some(caller), Some(caller_kind)) => {
|
||||
let qualified = match caller_container {
|
||||
Some(container) => format!("{container}{separator}{caller}"),
|
||||
None => caller,
|
||||
};
|
||||
format!("{caller_kind} {qualified}")
|
||||
}
|
||||
_ => "top level".to_string(),
|
||||
};
|
||||
let label = if kind == "import" { format!("{within} (import)") } else { within };
|
||||
groups.entry((path, label)).or_default().push(line);
|
||||
}
|
||||
let mut out = Out::new(max_tokens);
|
||||
let definitions = match targets.len() {
|
||||
0 => format!("\"{name}\" is not defined in this repository (library or generated code)"),
|
||||
1 => format!("defined at {} ({})", targets[0].location(), targets[0].kind),
|
||||
n => format!(
|
||||
"{n} definitions share the name \"{name}\" ({}); callers are matched by name and may include homonyms",
|
||||
targets.iter().take(3).map(SymbolRow::location).collect::<Vec<_>>().join(", ")
|
||||
),
|
||||
};
|
||||
let total: usize = groups.values().map(Vec::len).sum();
|
||||
out.line(format!(
|
||||
"{} of \"{raw}\": {total} reference(s) in {} place(s); {definitions}.",
|
||||
if is_type { "Uses" } else { "Callers" },
|
||||
groups.len()
|
||||
));
|
||||
if excluded > 0 {
|
||||
out.line(format!("({excluded} call(s) qualified with another type were left out.)"));
|
||||
}
|
||||
let mut sorted: Vec<_> = groups.into_iter().collect();
|
||||
sorted.sort_by_key(|((path, _), _)| (is_test_path(path), path.clone()));
|
||||
for ((path, within), lines) in sorted {
|
||||
let lines = lines.iter().map(u32::to_string).collect::<Vec<_>>().join(",");
|
||||
out.line(format!("- {path}:{lines} in {within}"));
|
||||
}
|
||||
Ok(out.finish("ask about a qualified name (Type::name) or a path#name"))
|
||||
}
|
||||
|
||||
/// Calls made by a symbol, each resolved to its definition when the name is known.
|
||||
pub fn callees(&self, raw: &str, max_tokens: usize) -> Result<String> {
|
||||
let targets = self.resolve(raw)?;
|
||||
let Some(target) = targets.first() else {
|
||||
return Ok(format!("No definition of \"{raw}\" in the index. Try action=search."));
|
||||
};
|
||||
let mut out = Out::new(max_tokens);
|
||||
if targets.len() > 1 {
|
||||
out.line(format!(
|
||||
"\"{raw}\" has {} definitions; showing {} ({}). Qualify the name for another one.",
|
||||
targets.len(),
|
||||
target.qualified(),
|
||||
target.location()
|
||||
));
|
||||
}
|
||||
let mut statement = self
|
||||
.conn()
|
||||
.prepare(
|
||||
"SELECT r.name, min(r.line), r.target FROM refs r
|
||||
WHERE r.symbol_id = ?1 AND r.kind IN ('call', 'macro') GROUP BY r.name, r.target ORDER BY min(r.line)",
|
||||
)
|
||||
.map_err(db_err)?;
|
||||
let calls = statement
|
||||
.query_map([target.id], |row| {
|
||||
Ok((row.get::<_, String>(0)?, row.get::<_, u32>(1)?, row.get::<_, Option<String>>(2)?))
|
||||
})
|
||||
.map_err(db_err)?
|
||||
.collect::<std::result::Result<Vec<_>, _>>()
|
||||
.map_err(db_err)?;
|
||||
out.line(format!(
|
||||
"{} {} ({}) calls {} name(s):",
|
||||
target.kind,
|
||||
target.qualified(),
|
||||
target.location(),
|
||||
calls.len()
|
||||
));
|
||||
let mut external = Vec::new();
|
||||
let mut common = Vec::new();
|
||||
for (name, line, qualifier) in calls {
|
||||
let mut defs = self.symbols_where(
|
||||
"s.name = ?1 AND s.kind NOT IN ('key', 'section')",
|
||||
&[&name],
|
||||
)?;
|
||||
if let Some(qualifier) = &qualifier {
|
||||
// `Type::name` with a type of the repository, or a library type.
|
||||
defs.retain(|row| row.container.as_deref() == Some(qualifier.as_str()));
|
||||
}
|
||||
defs.sort_by_key(|row| (row.path != target.path, row.is_test_path(), row.path.len()));
|
||||
let shown = match qualifier {
|
||||
Some(qualifier) => format!("{qualifier}::{name}"),
|
||||
None => name.clone(),
|
||||
};
|
||||
let same_file = defs.iter().filter(|row| row.path == target.path).count();
|
||||
match defs.len() {
|
||||
0 => external.push(shown),
|
||||
1 => out.line(format!("- {shown} (line {line}) → {} {}", defs[0].kind, defs[0].location())),
|
||||
_ if same_file == 1 => out.line(format!(
|
||||
"- {shown} (line {line}) → {} {} (same file; {} other definition(s))",
|
||||
defs[0].kind,
|
||||
defs[0].location(),
|
||||
defs.len() - 1
|
||||
)),
|
||||
n if n > 5 => common.push(format!("{shown} ({n})")),
|
||||
n => out.line(format!(
|
||||
"- {shown} (line {line}) → {n} candidates: {}",
|
||||
defs.iter().take(3).map(SymbolRow::location).collect::<Vec<_>>().join(", ")
|
||||
)),
|
||||
}
|
||||
}
|
||||
if !common.is_empty() {
|
||||
out.line(format!("- common names with many definitions (ask callers/definition with Type::name): {}", common.join(", ")));
|
||||
}
|
||||
if !external.is_empty() {
|
||||
out.line(format!("- not defined in the repository: {}", external.join(", ")));
|
||||
}
|
||||
Ok(out.finish("ask callees of a smaller function"))
|
||||
}
|
||||
|
||||
fn file_id(&self, path: &str) -> Option<i64> {
|
||||
self.conn()
|
||||
.query_row("SELECT id FROM files WHERE path = ?1", [path], |row| row.get(0))
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Files linked to a file (or to the file of a symbol) by references in both directions.
|
||||
pub fn related(&self, raw: &str, cwd_prefix: &str, max_tokens: usize) -> Result<String> {
|
||||
let normalized = self.normalize_path(raw, cwd_prefix);
|
||||
let path = if self.file_id(&normalized).is_some() {
|
||||
normalized
|
||||
} else {
|
||||
match self.resolve(raw)?.first() {
|
||||
Some(row) => row.path.clone(),
|
||||
None => return Ok(format!("\"{raw}\" is neither an indexed file nor a known symbol.")),
|
||||
}
|
||||
};
|
||||
let Some(file_id) = self.file_id(&path) else {
|
||||
return Ok(format!("{path} is not indexed."));
|
||||
};
|
||||
let package = self.package_root(&path);
|
||||
let package_like = format!("{}%", like_escape(&package));
|
||||
let query = |sql: &str| -> Result<Vec<(String, String, i64)>> {
|
||||
let mut statement = self.conn().prepare(sql).map_err(db_err)?;
|
||||
statement
|
||||
.query_map(params![file_id, MAX_DEFINITIONS_FOR_LINKS, package_like], |row| {
|
||||
Ok((row.get(0)?, row.get(1)?, row.get(2)?))
|
||||
})
|
||||
.map_err(db_err)?
|
||||
.collect::<std::result::Result<Vec<_>, _>>()
|
||||
.map_err(db_err)
|
||||
};
|
||||
// Files whose definitions this file uses.
|
||||
let outgoing = query(
|
||||
"SELECT f.path, r.name, count(*) FROM refs r
|
||||
JOIN symbols s ON s.name = r.name AND s.file_id != r.file_id AND s.kind NOT IN ('key', 'section')
|
||||
JOIN files f ON f.id = s.file_id
|
||||
WHERE r.file_id = ?1 AND r.kind IN ('call', 'macro', 'type', 'import')
|
||||
AND (SELECT count(*) FROM symbols d WHERE d.name = r.name) <= ?2
|
||||
AND (f.path LIKE ?3 ESCAPE '\\' OR EXISTS (SELECT 1 FROM refs i WHERE i.file_id = r.file_id AND i.name = r.name AND i.kind = 'import'))
|
||||
GROUP BY f.path, r.name",
|
||||
)?;
|
||||
// Files that use definitions of this file.
|
||||
let incoming = query(
|
||||
"SELECT f.path, r.name, count(*) FROM symbols s
|
||||
JOIN refs r ON r.name = s.name AND r.file_id != s.file_id AND r.kind IN ('call', 'macro', 'type', 'import')
|
||||
JOIN files f ON f.id = r.file_id
|
||||
WHERE s.file_id = ?1 AND s.kind NOT IN ('key', 'section')
|
||||
AND (SELECT count(*) FROM symbols d WHERE d.name = s.name) <= ?2
|
||||
AND (f.path LIKE ?3 ESCAPE '\\' OR EXISTS (SELECT 1 FROM refs i WHERE i.file_id = r.file_id AND i.name = s.name AND i.kind = 'import'))
|
||||
GROUP BY f.path, s.name",
|
||||
)?;
|
||||
let summarize = |rows: Vec<(String, String, i64)>| -> Vec<(String, i64, Vec<String>)> {
|
||||
let mut by_file: HashMap<String, (i64, Vec<String>)> = HashMap::new();
|
||||
for (path, name, count) in rows {
|
||||
let entry = by_file.entry(path).or_default();
|
||||
entry.0 += count;
|
||||
entry.1.push(name);
|
||||
}
|
||||
let mut list: Vec<(String, i64, Vec<String>)> =
|
||||
by_file.into_iter().map(|(path, (count, names))| (path, count, names)).collect();
|
||||
list.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
|
||||
list
|
||||
};
|
||||
let mut out = Out::new(max_tokens);
|
||||
out.line(format!(
|
||||
"Files related to {path} (references to names defined in at most {MAX_DEFINITIONS_FOR_LINKS} places, inside {} or imported):",
|
||||
if package.is_empty() { "the repository".to_string() } else { package.clone() }
|
||||
));
|
||||
for (title, list) in [("Uses definitions from", summarize(outgoing)), ("Used by", summarize(incoming))] {
|
||||
out.line(format!("{title} ({} file(s)):", list.len()));
|
||||
for (file, count, mut names) in list.into_iter().take(12) {
|
||||
names.sort();
|
||||
names.dedup();
|
||||
let more = names.len().saturating_sub(5);
|
||||
let names = names.into_iter().take(5).collect::<Vec<_>>().join(", ");
|
||||
let more = if more > 0 { format!(", +{more}") } else { String::new() };
|
||||
out.line(format!("- {file} ({count}: {names}{more})"));
|
||||
}
|
||||
}
|
||||
Ok(out.finish("ask about a single file"))
|
||||
}
|
||||
|
||||
/// Folder of the nearest package manifest above a file (`Cargo.toml`, `package.json`...),
|
||||
/// with a trailing slash; empty at the repository root.
|
||||
fn package_root(&self, path: &str) -> String {
|
||||
const MANIFESTS: &[&str] = &["Cargo.toml", "package.json", "go.mod", "pyproject.toml", "setup.py", "Package.swift"];
|
||||
let mut dir = std::path::Path::new(path).parent();
|
||||
while let Some(current) = dir {
|
||||
let prefix = current.to_string_lossy().to_string();
|
||||
if prefix.is_empty() {
|
||||
break;
|
||||
}
|
||||
if MANIFESTS.iter().any(|manifest| self.file_id(&format!("{prefix}/{manifest}")).is_some()) {
|
||||
return format!("{prefix}/");
|
||||
}
|
||||
dir = current.parent();
|
||||
}
|
||||
String::new()
|
||||
}
|
||||
|
||||
/// Outline of a file, or of the files under a directory.
|
||||
pub fn module_map(&self, raw: &str, cwd_prefix: &str, max_tokens: usize) -> Result<String> {
|
||||
let path = self.normalize_path(raw, cwd_prefix);
|
||||
let mut out = Out::new(max_tokens);
|
||||
if let Some(file_id) = self.file_id(&path) {
|
||||
let rows = self.symbols_where("s.file_id = ?1 ORDER BY s.line", &[&file_id])?;
|
||||
let depth_of = |row: &SymbolRow| -> usize {
|
||||
rows.iter()
|
||||
.filter(|outer| outer.id != row.id && outer.line <= row.line && outer.end_line >= row.end_line && (outer.line, outer.end_line) != (row.line, row.end_line))
|
||||
.count()
|
||||
};
|
||||
out.line(format!("{path}: {} symbol(s)", rows.len()));
|
||||
for row in &rows {
|
||||
let indent = " ".repeat(depth_of(row).min(4));
|
||||
out.line(format!("{indent}{} {} {} · {}", row.line, row.kind, row.name, row.signature));
|
||||
}
|
||||
return Ok(out.finish("ask module_map of a smaller file or use definition"));
|
||||
}
|
||||
let prefix = if path.is_empty() || path == "." { String::new() } else { format!("{}/", path.trim_end_matches('/')) };
|
||||
let like = format!("{}%", like_escape(&prefix));
|
||||
let mut statement = self
|
||||
.conn()
|
||||
.prepare("SELECT id, path, lang, lines FROM files WHERE path LIKE ?1 ESCAPE '\\' ORDER BY path LIMIT 5000")
|
||||
.map_err(db_err)?;
|
||||
let files = statement
|
||||
.query_map([&like], |row| Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?, row.get::<_, String>(2)?, row.get::<_, i64>(3)?)))
|
||||
.map_err(db_err)?
|
||||
.collect::<std::result::Result<Vec<_>, _>>()
|
||||
.map_err(db_err)?;
|
||||
if files.is_empty() {
|
||||
return Ok(format!("No indexed file under \"{raw}\"."));
|
||||
}
|
||||
// Many files: group by the next path segment.
|
||||
if files.len() > 40 {
|
||||
let mut groups: BTreeMap<String, (usize, i64)> = BTreeMap::new();
|
||||
for (_, file, _, lines) in &files {
|
||||
let rest = &file[prefix.len()..];
|
||||
let key = match rest.split_once('/') {
|
||||
Some((dir, _)) => format!("{prefix}{dir}/"),
|
||||
None => file.clone(),
|
||||
};
|
||||
let entry = groups.entry(key).or_default();
|
||||
entry.0 += 1;
|
||||
entry.1 += lines;
|
||||
}
|
||||
out.line(format!("{}: {} indexed file(s); by folder:", if prefix.is_empty() { "repository" } else { &prefix }, files.len()));
|
||||
for (key, (count, lines)) in groups {
|
||||
out.line(format!("- {key} ({count} file(s), {lines} lines)"));
|
||||
}
|
||||
return Ok(out.finish("ask module_map of a sub-folder"));
|
||||
}
|
||||
out.line(format!("{}: {} file(s)", if prefix.is_empty() { "repository" } else { &prefix }, files.len()));
|
||||
let mut top = self
|
||||
.conn()
|
||||
.prepare("SELECT kind, name FROM symbols WHERE file_id = ?1 AND parent_id IS NULL ORDER BY line LIMIT 40")
|
||||
.map_err(db_err)?;
|
||||
for (file_id, file, lang, lines) in files {
|
||||
let names = top
|
||||
.query_map([file_id], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)))
|
||||
.map_err(db_err)?
|
||||
.collect::<std::result::Result<Vec<_>, _>>()
|
||||
.map_err(db_err)?;
|
||||
let shown: Vec<String> = names.iter().take(8).map(|(kind, name)| format!("{kind} {name}")).collect();
|
||||
let more = names.len().saturating_sub(8);
|
||||
let more = if more > 0 { format!(", +{more}") } else { String::new() };
|
||||
out.line(format!("- {file} ({lang}, {lines} lines): {}{more}", shown.join(", ")));
|
||||
}
|
||||
Ok(out.finish("ask module_map of a single file"))
|
||||
}
|
||||
|
||||
/// Short, deterministic map of the repository for the initial context.
|
||||
pub fn repo_summary(&self, max_tokens: usize) -> Result<String> {
|
||||
let mut statement = self
|
||||
.conn()
|
||||
.prepare("SELECT path, lang FROM files ORDER BY path")
|
||||
.map_err(db_err)?;
|
||||
let files = statement
|
||||
.query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)))
|
||||
.map_err(db_err)?
|
||||
.collect::<std::result::Result<Vec<_>, _>>()
|
||||
.map_err(db_err)?;
|
||||
let mut langs: BTreeMap<String, usize> = BTreeMap::new();
|
||||
let mut dirs: BTreeMap<String, (usize, BTreeMap<String, usize>)> = BTreeMap::new();
|
||||
for (path, lang) in &files {
|
||||
*langs.entry(lang.clone()).or_default() += 1;
|
||||
let segments: Vec<&str> = path.split('/').collect();
|
||||
let key = match segments.len() {
|
||||
0 | 1 => ".".to_string(),
|
||||
2 => format!("{}/", segments[0]),
|
||||
_ => format!("{}/{}/", segments[0], segments[1]),
|
||||
};
|
||||
let entry = dirs.entry(key).or_default();
|
||||
entry.0 += 1;
|
||||
*entry.1.entry(lang.clone()).or_default() += 1;
|
||||
}
|
||||
let mut out = Out::new(max_tokens);
|
||||
let mut lang_list: Vec<_> = langs.into_iter().collect();
|
||||
lang_list.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
|
||||
out.line(format!(
|
||||
"Code map: {} indexed files ({}). Folders with at least 3 files:",
|
||||
files.len(),
|
||||
lang_list.iter().map(|(lang, count)| format!("{lang} {count}")).collect::<Vec<_>>().join(", ")
|
||||
));
|
||||
for (dir, (count, langs)) in dirs.into_iter().filter(|(_, (count, _))| *count >= 3) {
|
||||
let main = langs.into_iter().max_by_key(|(_, n)| *n).map(|(lang, _)| lang).unwrap_or_default();
|
||||
out.line(format!("- {dir} {count} ({main})"));
|
||||
}
|
||||
Ok(out.finish("use code_graph module_map for details"))
|
||||
}
|
||||
}
|
||||
|
||||
fn like_escape(raw: &str) -> String {
|
||||
raw.replace('\\', "\\\\").replace('%', "\\%").replace('_', "\\_")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::parse_spec;
|
||||
use super::SymbolSpec;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn symbol_specs() {
|
||||
assert_eq!(
|
||||
parse_spec("akode_core::Index::new()"),
|
||||
SymbolSpec { path: None, container: Some("Index".to_string()), name: "new".to_string() }
|
||||
);
|
||||
assert_eq!(
|
||||
parse_spec("src/lib.rs#helper"),
|
||||
SymbolSpec { path: Some("src/lib.rs".to_string()), container: None, name: "helper".to_string() }
|
||||
);
|
||||
assert_eq!(
|
||||
parse_spec("Store.load"),
|
||||
SymbolSpec { path: None, container: Some("Store".to_string()), name: "load".to_string() }
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user