Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ jobs:
# The release build compiles the model in; keep that code path building.
- name: Check the bundled-model build
run: CORA_BUNDLED_MODEL_DIR="$PWD/tests/fixtures/tiny-model" cargo check --features tree-sitter,bundled-model
# The build without Tree-sitter (regex extraction only) is documented, and it
# had stopped compiling without anyone noticing (#793).
- name: Lint the build without Tree-sitter
run: cargo clippy --all-targets --no-default-features -- -D warnings
- name: Test the build without Tree-sitter
run: cargo test --no-default-features

fmt:
name: Format
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- **The build without Tree-sitter compiles again, and CI keeps it that way (#793).** `cargo build --no-default-features` (regex extraction only, documented in the README) failed because the edge types lived in the Tree-sitter module; they are shared now. Running its tests showed that the regex extractor skipped `pub(crate)`, `pub(super)` and `pub(in ..)` items and read `const fn name` as a constant called `fn`; both are fixed. CI lints and tests this configuration in the `Check` job.

- **`cora dead-code`, `callers` and `impact` see functions passed as values and functions named in serde attributes (#802).** The Rust extractor recorded a call only for a `call_expression` and inside macros, so `.map(helper)`, `.and_then(Type::make)` and `#[serde(default = "default_true")]` made the function look unused. On this repository `cora dead-code` went from 43 findings, none of them dead code, to the 5 that are (the unwired bundling engine of #792), and `callers` now lists the function that passes another one as a value. A variable that merely has the name of a function (a parameter, a `let`, a pattern binding) is not recorded. The first `cora index` after the upgrade re-extracts every file once (#803).

- **`cora index` re-extracts every file once after an extractor change (#803).** A file was skipped when its `mtime:size` matched, so an upgrade that improved an extractor (the Ruby nesting of #791, for example) never reached the files that had not changed, until someone ran `cora index --rebuild`. The fingerprint now carries an extractor version, so the first `cora index` after such an upgrade re-extracts all files once; later runs skip unchanged files as before.
Expand Down
60 changes: 1 addition & 59 deletions src/index/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// ! Provides proper AST-based symbol and edge extraction using tree-sitter.
// ! Only compiled when the `tree-sitter` feature is enabled.

use crate::index::extract::CallSite;
use crate::index::edge::{AstEdge, EdgeKind};
use crate::index::extract::ExtractedDef;
use crate::index::symbols::SymbolKind;
use regex::Regex;
Expand Down Expand Up @@ -46,64 +46,6 @@ impl From<AstNode> for ExtractedDef {
}
}

/// Edge type in the knowledge graph.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EdgeKind {
Calls,
Imports,
Implements,
Inherits,
Route,
}

impl EdgeKind {
pub fn as_str(&self) -> &'static str {
match self {
Self::Calls => "CALLS",
Self::Imports => "IMPORTS",
Self::Implements => "IMPLEMENTS",
Self::Inherits => "INHERITS",
Self::Route => "ROUTE",
}
}
}

/// An edge in the code graph.
#[derive(Debug, Clone)]
pub struct AstEdge {
pub source: String,
pub kind: EdgeKind,
pub target: String,
pub file: String,
pub line: u32,
/// For call edges: the type or module the callee was reached through
/// (`WebSearchTool` in `WebSearchTool::from_env()`, the enclosing impl type
/// for `self.m()` and `Self::m()`). `None` when it is not statically
/// obvious, which makes the edge ambiguous (#714).
pub qualifier: Option<String>,
/// For call edges: the impl type of the calling method, when it is one.
pub caller_type: Option<String>,
}

impl From<&AstEdge> for CallSite {
fn from(e: &AstEdge) -> Self {
Self {
caller: e.source.clone(),
callee: e.target.clone(),
file: e.file.clone(),
line: e.line,
qualifier: e.qualifier.clone(),
caller_type: e.caller_type.clone(),
}
}
}

impl From<AstEdge> for CallSite {
fn from(e: AstEdge) -> Self {
CallSite::from(&e)
}
}

// ─── Public API ─────────────────────────────────────────────────────────

/// Get the tree-sitter Language for a file extension.
Expand Down
68 changes: 68 additions & 0 deletions src/index/edge.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
//! Edge types of the code graph, shared by the Tree-sitter extractor and the regex
//! route detector (the regex path also builds in a no-Tree-sitter build, #793).

use crate::index::extract::CallSite;

/// Edge type in the knowledge graph.
///
/// Without the `tree-sitter` feature only the regex route detector builds edges, so
/// every kind but `Route` is made by the Tree-sitter extractor alone.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(not(feature = "tree-sitter"), allow(dead_code))]
pub enum EdgeKind {
Calls,
Imports,
Implements,
Inherits,
Route,
}

#[cfg_attr(not(feature = "tree-sitter"), allow(dead_code))]
impl EdgeKind {
pub fn as_str(&self) -> &'static str {
match self {
Self::Calls => "CALLS",
Self::Imports => "IMPORTS",
Self::Implements => "IMPLEMENTS",
Self::Inherits => "INHERITS",
Self::Route => "ROUTE",
}
}
}

/// An edge in the code graph.
#[derive(Debug, Clone)]
#[cfg_attr(not(feature = "tree-sitter"), allow(dead_code))] // `kind` is read by the Tree-sitter path
pub struct AstEdge {
pub source: String,
pub kind: EdgeKind,
pub target: String,
pub file: String,
pub line: u32,
/// For call edges: the type or module the callee was reached through
/// (`WebSearchTool` in `WebSearchTool::from_env()`, the enclosing impl type
/// for `self.m()` and `Self::m()`). `None` when it is not statically
/// obvious, which makes the edge ambiguous (#714).
pub qualifier: Option<String>,
/// For call edges: the impl type of the calling method, when it is one.
pub caller_type: Option<String>,
}

impl From<&AstEdge> for CallSite {
fn from(e: &AstEdge) -> Self {
Self {
caller: e.source.clone(),
callee: e.target.clone(),
file: e.file.clone(),
line: e.line,
qualifier: e.qualifier.clone(),
caller_type: e.caller_type.clone(),
}
}
}

impl From<AstEdge> for CallSite {
fn from(e: AstEdge) -> Self {
CallSite::from(&e)
}
}
89 changes: 63 additions & 26 deletions src/index/extract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,28 @@ use super::symbols::{IndexedSymbol, SymbolKind};

// ─── Rust ───

static RE_RUST_FN: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^\s*(?:pub\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+(\w+)").unwrap());
static RE_RUST_FN: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:const\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+(\w+)")
.unwrap()
});

static RE_RUST_STRUCT: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^\s*(?:pub\s+)?struct\s+(\w+)").unwrap());
LazyLock::new(|| Regex::new(r"^\s*(?:pub(?:\([^)]*\))?\s+)?struct\s+(\w+)").unwrap());

static RE_RUST_ENUM: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^\s*(?:pub\s+)?enum\s+(\w+)").unwrap());
LazyLock::new(|| Regex::new(r"^\s*(?:pub(?:\([^)]*\))?\s+)?enum\s+(\w+)").unwrap());

static RE_RUST_TRAIT: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^\s*(?:pub\s+)?trait\s+(\w+)").unwrap());
LazyLock::new(|| Regex::new(r"^\s*(?:pub(?:\([^)]*\))?\s+)?trait\s+(\w+)").unwrap());

static RE_RUST_TYPE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^\s*(?:pub\s+)?type\s+(\w+)").unwrap());
LazyLock::new(|| Regex::new(r"^\s*(?:pub(?:\([^)]*\))?\s+)?type\s+(\w+)").unwrap());

static RE_RUST_CONST: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^\s*(?:pub\s+)?(?:const|static)\s+(\w+)").unwrap());
LazyLock::new(|| Regex::new(r"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:const|static)\s+(\w+)").unwrap());

static RE_RUST_MOD: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^\s*(?:pub\s+)?mod\s+(\w+)").unwrap());
LazyLock::new(|| Regex::new(r"^\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+(\w+)").unwrap());

// RE_RUST_IMPL removed — not needed for symbol definitions

Expand Down Expand Up @@ -277,7 +279,11 @@ fn extract_rust(line: &str, line_no: u32, file: &str, raw: &str, out: &mut Vec<E
if let Some(cap) = RE_RUST_TYPE.captures(line) {
out.push(def(cap, SymbolKind::TypeAlias, line_no, file, raw));
}
if let Some(cap) = RE_RUST_CONST.captures(line) {
// `const fn name` is a function, not a constant called `fn`.
if let Some(cap) = RE_RUST_CONST
.captures(line)
.filter(|c| !matches!(&c[1], "fn" | "unsafe" | "async" | "extern"))
{
out.push(def(cap, SymbolKind::Constant, line_no, file, raw));
}
if let Some(cap) = RE_RUST_MOD.captures(line) {
Expand Down Expand Up @@ -588,8 +594,8 @@ pub fn detect_routes(
content: &str,
language: &str,
file_path: &str,
) -> Vec<crate::index::ast::AstEdge> {
use crate::index::ast::{AstEdge, EdgeKind};
) -> Vec<crate::index::edge::AstEdge> {
use crate::index::edge::{AstEdge, EdgeKind};
use regex::Regex;

let mut edges = Vec::new();
Expand Down Expand Up @@ -832,19 +838,7 @@ pub struct ExtractedAll {
}

/// A knowledge-graph edge (calls, imports, implements, inherits, etc.).
#[cfg(feature = "tree-sitter")]
pub type KgEdge = crate::index::ast::AstEdge;

/// A knowledge-graph edge stub when tree-sitter is disabled (never used).
#[cfg(not(feature = "tree-sitter"))]
#[derive(Debug, Clone, Default)]
pub struct KgEdge {
pub source: String,
pub kind: String,
pub target: String,
pub file: String,
pub line: u32,
}
pub type KgEdge = crate::index::edge::AstEdge;

/// Extract everything from a file in a single pass.
/// When tree-sitter is available, this parses the source only once and returns
Expand All @@ -858,13 +852,13 @@ pub fn extract_all(content: &str, language: &str, file_path: &str) -> ExtractedA
let (nodes, edges) = ast::extract(content, language, file_path);
let calls: Vec<CallSite> = edges
.iter()
.filter(|e| e.kind == ast::EdgeKind::Calls)
.filter(|e| e.kind == crate::index::edge::EdgeKind::Calls)
.cloned()
.map(Into::into)
.collect();
let kg_edges: Vec<_> = edges
.into_iter()
.filter(|e| e.kind != ast::EdgeKind::Calls)
.filter(|e| e.kind != crate::index::edge::EdgeKind::Calls)
.collect();
let symbols = nodes.into_iter().map(Into::into).collect();
return ExtractedAll {
Expand Down Expand Up @@ -979,6 +973,49 @@ fn def(cap: regex::Captures, kind: SymbolKind, line: u32, file: &str, raw: &str)

#[cfg(test)]
mod tests {

/// #793: the regex path skipped `pub(crate)`, `pub(super)` and `const fn`, so a
/// build without Tree-sitter never indexed most Rust items.
#[test]
fn rust_regex_handles_restricted_visibility_and_const_fn() {
let mut out = Vec::new();
for (n, line) in [
"pub(crate) fn crate_only() {}",
"pub(super) fn parent_only() {}",
"pub(in crate::a) fn scoped() {}",
"pub const fn const_item() {}",
"const fn private_const() {}",
"pub(crate) struct Inner;",
"pub(crate) enum Mode { A }",
"pub(crate) trait Shape {}",
"pub(crate) type Alias = u8;",
"pub(crate) const LIMIT: u8 = 1;",
"pub(crate) mod util;",
"pub fn plain() {}",
]
.iter()
.enumerate()
{
extract_rust(line, (n + 1) as u32, "x.rs", line, &mut out);
}
let names: Vec<&str> = out.iter().map(|d| d.name.as_str()).collect();
for want in [
"crate_only",
"parent_only",
"scoped",
"const_item",
"private_const",
"Inner",
"Mode",
"Shape",
"Alias",
"LIMIT",
"util",
"plain",
] {
assert!(names.contains(&want), "{want} missing from {names:?}");
}
}
use super::*;

#[test]
Expand Down
10 changes: 9 additions & 1 deletion src/index/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub mod arch;
mod ast;
pub mod brain;
mod dead_filters;
mod edge;
mod extract;
pub mod graph;
pub mod queries;
Expand Down Expand Up @@ -1174,14 +1175,21 @@ pub struct AuthService {

index_project(&conn, root, false).unwrap();
let pid = ensure_project(&conn, root).unwrap();
// Seed an edge row directly so the check holds without tree-sitter.
// Seed the rows directly, so the check does not depend on which extractor the
// build has (Tree-sitter or regex records calls differently).
for f in ["keep.rs", "gone.rs"] {
conn.execute(
"INSERT INTO edges (source, kind, target, file, line, project_id)
VALUES ('a', 'CALLS', 'b', ?1, 1, ?2)",
rusqlite::params![f, pid],
)
.unwrap();
conn.execute(
"INSERT INTO call_graph (caller, callee, file, line, project_id)
VALUES ('a', 'b', ?1, 1, ?2)",
rusqlite::params![f, pid],
)
.unwrap();
}
assert!(count_for_file(&conn, "symbols", pid, "gone.rs") > 0);
assert!(count_for_file(&conn, "call_graph", pid, "gone.rs") > 0);
Expand Down
Loading