From 35464b531d5573c1c7830bf9e4b6ae1868f81de7 Mon Sep 17 00:00:00 2001 From: "Anaz S. Aji" <12648688+ajianaz@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:11:10 +0000 Subject: [PATCH] fix(build): compile and test the build without Tree-sitter, and check it in CI Closes #793. --- .github/workflows/ci.yml | 6 +++ CHANGELOG.md | 2 + src/index/ast.rs | 60 +-------------------------- src/index/edge.rs | 68 ++++++++++++++++++++++++++++++ src/index/extract.rs | 89 ++++++++++++++++++++++++++++------------ src/index/mod.rs | 10 ++++- 6 files changed, 149 insertions(+), 86 deletions(-) create mode 100644 src/index/edge.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e14f346..edde6ac 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md index f8a9dcf..2f2b9b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/src/index/ast.rs b/src/index/ast.rs index 10a5cb4..38792c8 100644 --- a/src/index/ast.rs +++ b/src/index/ast.rs @@ -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; @@ -46,64 +46,6 @@ impl From 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, - /// For call edges: the impl type of the calling method, when it is one. - pub caller_type: Option, -} - -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 for CallSite { - fn from(e: AstEdge) -> Self { - CallSite::from(&e) - } -} - // ─── Public API ───────────────────────────────────────────────────────── /// Get the tree-sitter Language for a file extension. diff --git a/src/index/edge.rs b/src/index/edge.rs new file mode 100644 index 0000000..d39d98f --- /dev/null +++ b/src/index/edge.rs @@ -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, + /// For call edges: the impl type of the calling method, when it is one. + pub caller_type: Option, +} + +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 for CallSite { + fn from(e: AstEdge) -> Self { + CallSite::from(&e) + } +} diff --git a/src/index/extract.rs b/src/index/extract.rs index 78f0b1e..16ed464 100644 --- a/src/index/extract.rs +++ b/src/index/extract.rs @@ -10,26 +10,28 @@ use super::symbols::{IndexedSymbol, SymbolKind}; // ─── Rust ─── -static RE_RUST_FN: LazyLock = - LazyLock::new(|| Regex::new(r"^\s*(?:pub\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+(\w+)").unwrap()); +static RE_RUST_FN: LazyLock = LazyLock::new(|| { + Regex::new(r"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:const\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+(\w+)") + .unwrap() +}); static RE_RUST_STRUCT: LazyLock = - 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 = - 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 = - 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 = - 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 = - 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 = - 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 @@ -277,7 +279,11 @@ fn extract_rust(line: &str, line_no: u32, file: &str, raw: &str, out: &mut Vec Vec { - use crate::index::ast::{AstEdge, EdgeKind}; +) -> Vec { + use crate::index::edge::{AstEdge, EdgeKind}; use regex::Regex; let mut edges = Vec::new(); @@ -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 @@ -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 = 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 { @@ -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] diff --git a/src/index/mod.rs b/src/index/mod.rs index d06a2b1..ee4e269 100644 --- a/src/index/mod.rs +++ b/src/index/mod.rs @@ -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; @@ -1174,7 +1175,8 @@ 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) @@ -1182,6 +1184,12 @@ pub struct AuthService { 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);