Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
2b6a00d
fix: scope codegraph batch complexity targets to file paths
carlos-alm Jul 5, 2026
b28051a
fix: exclude parameters and interface/type members from dead-role cla…
carlos-alm Jul 5, 2026
17fbcba
fix: credit import-type usages as exports consumers
carlos-alm Jul 5, 2026
26918bb
fix: prevent fn-impact/query crash when -f/--file is passed
carlos-alm Jul 5, 2026
be6432c
fix: correct exported-symbol detection for literal and object-literal…
carlos-alm Jul 5, 2026
4ead840
fix: exclude primitive type keywords from ast --kind string matching
carlos-alm Jul 5, 2026
f6326bf
fix: resolve call edges through renamed import specifiers
carlos-alm Jul 5, 2026
590f560
fix: couple file_hashes updates with edge regeneration in incremental…
carlos-alm Jul 5, 2026
d3ea4a4
fix: compare signature-change diffs using new-file line ranges
carlos-alm Jul 5, 2026
c306812
feat: add environment doctor check for stale native binary and missin…
carlos-alm Jul 5, 2026
8bb5893
fix: eliminate non-deterministic ordering in community detection
carlos-alm Jul 6, 2026
46037b1
fix: sync update-graph.sh hook extension allowlist with EXTENSIONS
carlos-alm Jul 6, 2026
6a84cf9
fix: recompute directory structure metrics for affected directories o…
carlos-alm Jul 6, 2026
8d936d1
refactor: register hardcoded execFileSync/execSync maxBuffer values i…
carlos-alm Jul 6, 2026
11c84be
fix: gate blast-radius check on newly introduced risk, not pre-existi…
carlos-alm Jul 6, 2026
963301a
fix: gate identifier-argument dynamic call edges on callback-acceptin…
carlos-alm Jul 6, 2026
3e8035d
fix: gate Array.from's callback arg by position, not just callee name
carlos-alm Jul 6, 2026
879635e
fix: scope reexportedSymbols to actually-named re-export specifiers
carlos-alm Jul 6, 2026
0fe9fc3
fix: stop CFG block/edge count from overriding AST-derived cyclomatic…
carlos-alm Jul 6, 2026
ccf3c19
fix: backfill edges.technique for incrementally-inserted calls edges
carlos-alm Jul 6, 2026
d5b1162
fix: wrap remote embedding JSON parse failure in EngineError
carlos-alm Jul 6, 2026
8971017
refactor: extract shared platform-default-path helper in config.ts
carlos-alm Jul 6, 2026
056c5e4
refactor: decompose loadConfig and related high-effort functions in c…
carlos-alm Jul 6, 2026
0738171
refactor: decompose findDbPath and openRepo in db/connection.ts (docs…
carlos-alm Jul 6, 2026
6f2423c
refactor: dedupe busy/locked error detection into isBusyOrLockedError
carlos-alm Jul 6, 2026
4c02378
fix: log statSync failures in findDbPath instead of silently swallowi…
carlos-alm Jul 6, 2026
0698e16
test: add direct unit coverage for closeDbPair/closeDbPairDeferred/cl…
carlos-alm Jul 6, 2026
4ac3b99
fix: correct blast-radius/fn-impact computation for line-shifted decl…
carlos-alm Jul 6, 2026
6767f09
feat: wire points-to solver max-iterations cap through DEFAULTS.analy…
carlos-alm Jul 6, 2026
5f6f30a
refactor: route console.log calls in domain/search through logger
carlos-alm Jul 6, 2026
b479318
refactor: reduce cyclomatic complexity of computeDeltaModularityDirected
carlos-alm Jul 6, 2026
c39ac40
refactor: unify impact-level rendering format between audit and fn-im…
carlos-alm Jul 6, 2026
067674f
refactor: dedupe computeSavings via pct helper and persist partial to…
carlos-alm Jul 6, 2026
f6807b4
fix: add main.rs driver to rust dynamic tracer fixture
carlos-alm Jul 6, 2026
1c07a54
fix: scope diff file-header detection to between-hunk positions
carlos-alm Jul 6, 2026
bf82aa2
fix: update titan-grind's dead-symbol script for current roles --json…
carlos-alm Jul 6, 2026
cd02d27
fix: thread configured busyTimeoutMs through remaining read-only quer…
carlos-alm Jul 6, 2026
980b5dc
fix: resolve computed string-literal keys in object-literal extractio…
carlos-alm Jul 6, 2026
4a873a3
fix: add same-class bare-call fallback to incremental rebuild path (d…
carlos-alm Jul 6, 2026
8f3348a
fix: unify Object.defineProperty accessor fallback kind-filtering bet…
carlos-alm Jul 6, 2026
acf804c
refactor: share chunked statement-cache primitive between builder and…
carlos-alm Jul 6, 2026
986c851
refactor: cache prepared statements in applyEdgeTechniquesAfterNative…
carlos-alm Jul 6, 2026
71e9174
fix: replace fixed-depth directory-proximity check with symmetric dis…
carlos-alm Jul 6, 2026
d2935cc
refactor: remove unreachable Partition delta-computation interface me…
carlos-alm Jul 6, 2026
6515186
fix: emit reference edges for function identifiers used as object-lit…
carlos-alm Jul 6, 2026
30c491a
refactor: unify call-ref and tests rendering format between audit and…
carlos-alm Jul 6, 2026
9db911b
fix: classify destructured bindings as constant, not function (docs c…
carlos-alm Jul 6, 2026
70559fc
refactor: adopt timeMedian in remaining benchmark timing loops
carlos-alm Jul 6, 2026
822e0eb
refactor: decompose runPerfBenchmarks in token-benchmark.ts
carlos-alm Jul 6, 2026
fcdfe7d
fix: attribute liveness to Lua functions assigned to global/builtin i…
carlos-alm Jul 6, 2026
ee6362c
refactor: extract shared sedi() helper for tracer scripts
carlos-alm Jul 6, 2026
d4e6212
fix: restore reflection dynamicKind for .call/.apply/.bind (docs chec…
carlos-alm Jul 6, 2026
aec5d2b
fix: restrict entry-role classification to function/method-kind symbo…
carlos-alm Jul 6, 2026
d250f8d
fix: credit destructured dynamic import() bindings as exports consumers
carlos-alm Jul 6, 2026
75978e2
fix: recognize Lua function nodes in complexity metrics computation (…
carlos-alm Jul 6, 2026
de8fb24
fix: resolve merge conflicts with main
carlos-alm Jul 8, 2026
cbb79e3
test: add native colon-syntax method declaration test (#1924)
carlos-alm Jul 8, 2026
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
169 changes: 169 additions & 0 deletions crates/codegraph-core/src/ast_analysis/complexity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,44 @@ pub static BASH_RULES: LangRules = LangRules {
switch_like_nodes: &["case_statement"],
};

// Lua's `if_statement` is flat, not nested: `elseif`/`else` are separate node
// kinds (`elseif_statement`, `else_statement`) attached to the *same*
// `if_statement` via repeated `alternative:` fields — confirmed by parsing
// `if a then .. elseif b then .. else .. end` with tree-sitter-lua and
// inspecting the S-expression. Structurally identical to Python's
// elif_clause/else_clause (Pattern B), not JS's nested else_clause>if_statement
// (Pattern A) or Go's alternative-holds-nested-if (Pattern C) — so
// else_via_alternative: false, and neither elseif_statement nor else_statement
// is in nesting_nodes (they're siblings of the primary if, not separately
// nested branches). Mirrors `complexityLua` in `src/ast-analysis/rules/b3.ts`.
//
// binary_expression is Lua's single generic binary-op node (arithmetic,
// comparison, concat, AND logical `and`/`or`) — same shared-type pattern as
// Ruby's `binary` node; handle_logical_op only fires when `node.child(1)` (the
// operator token) is in logical_operators, so comparisons/arithmetic sharing
// the same node kind are correctly ignored.
pub static LUA_RULES: LangRules = LangRules {
branch_nodes: &[
"if_statement",
"elseif_statement",
"else_statement",
"for_statement",
"while_statement",
"repeat_statement",
],
case_nodes: &[],
logical_operators: &["and", "or"],
logical_node_types: &["binary_expression"],
optional_chain_type: None,
nesting_nodes: &["if_statement", "for_statement", "while_statement", "repeat_statement"],
function_nodes: &["function_declaration"],
if_node_type: Some("if_statement"),
else_node_type: Some("else_statement"),
elif_node_type: Some("elseif_statement"),
else_via_alternative: false,
switch_like_nodes: &[],
};
Comment on lines +446 to +466

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Anonymous function expressions not tracked in native engine

function_nodes only contains "function_declaration", which covers function f() end, local function f() end, and colon/dot-style named declarations. However, the common Lua pattern local f = function() end (a function_definition value node assigned to a variable) uses a different node kind and will not be picked up by find_first_function. The TS side has an equivalent gap via functionNodes: new Set(['function_declaration']). Both engines agree, so this is consistent, but Lua's table-as-module idiom (M.foo = function(...) end) means a fair portion of real Lua codebases will produce zero functions rows for this PR's complexity path.

The PR description tracks the related hasFuncBody() dotted-name issue in #1922, but this anonymous-expression gap is orthogonal. A follow-up task (or a note in the TODO adjacent to LUA_RULES) to also handle "function_definition" would prevent silent metric gaps for files that use this pattern exclusively.

Fix in Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed real and distinct from #1922 (that's the WASM-only file-level gate; this is a genuine node-kind gap in both engines). Out of scope for this PR — it already deferred two comparable gaps (#1922, #1923) to keep focus on 'Lua has zero complexity config at all.' Filed #2036 to track it.


/// Look up complexity rules by language ID (matches `COMPLEXITY_RULES` keys in JS).
pub fn lang_rules(lang_id: &str) -> Option<&'static LangRules> {
match lang_id {
Expand All @@ -444,6 +482,7 @@ pub fn lang_rules(lang_id: &str) -> Option<&'static LangRules> {
"swift" => Some(&SWIFT_RULES),
"scala" => Some(&SCALA_RULES),
"bash" => Some(&BASH_RULES),
"lua" => Some(&LUA_RULES),
_ => None,
}
}
Expand Down Expand Up @@ -1022,6 +1061,34 @@ pub static BASH_HALSTEAD: HalsteadRules = HalsteadRules {
skip_types: &[],
};

// Member/method access (`dot_index_expression` `.`, `method_index_expression`
// `:`) and invocation (`function_call`) are wrapper nodes without a dedicated
// "call happened" token, so they're counted as compound operators — mirrors
// Python's ["call", "subscript", "attribute"]. The '.'/':' separator tokens
// are ALSO in operator_leaf_types (matching Python counting both "attribute"
// and "."), so member access contributes two distinct operator kinds,
// consistent with the other languages above. Mirrors `halsteadLua` in
// `src/ast-analysis/rules/b3.ts`.
pub static LUA_HALSTEAD: HalsteadRules = HalsteadRules {
operator_leaf_types: &[
"+", "-", "*", "/", "//", "%", "^", "#", "..",
"==", "~=", "<=", ">=", "<", ">", "=",
"and", "or", "not",
"&", "|", "~", "<<", ">>",
".", ",", ":", "::", ";",
"if", "then", "else", "elseif", "end",
"for", "while", "do", "repeat", "until",
"function", "local", "return", "break", "goto", "in",
],
operand_leaf_types: &[
"identifier", "number", "string_content", "true", "false", "nil", "...",
],
compound_operators: &[
"function_call", "bracket_index_expression", "dot_index_expression", "method_index_expression",
],
skip_types: &[],
};

/// Look up Halstead rules by language ID.
pub fn halstead_rules(lang_id: &str) -> Option<&'static HalsteadRules> {
match lang_id {
Expand All @@ -1039,6 +1106,7 @@ pub fn halstead_rules(lang_id: &str) -> Option<&'static HalsteadRules> {
"swift" => Some(&SWIFT_HALSTEAD),
"scala" => Some(&SCALA_HALSTEAD),
"bash" => Some(&BASH_HALSTEAD),
"lua" => Some(&LUA_HALSTEAD),
_ => None,
}
}
Expand All @@ -1056,6 +1124,7 @@ pub fn comment_prefixes(lang_id: &str) -> &'static [&'static str] {
"swift" => &["//", "/*"],
"scala" => &["//", "/*"],
"bash" => &["#"],
"lua" => &["--"],
_ => &["//", "/*", "*", "*/"],
}
}
Expand Down Expand Up @@ -1604,4 +1673,104 @@ mod tests {
assert_eq!(m.cognitive, 1);
assert_eq!(m.cyclomatic, 2);
}

// ─── Lua tests (issue #1782) ────────────────────────────────────────────

fn compute_lua(code: &str) -> ComplexityMetrics {
let mut parser = Parser::new();
parser
.set_language(&tree_sitter_lua::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code.as_bytes(), None).unwrap();
let root = tree.root_node();
let func = find_first_function(&root, &LUA_RULES).expect("no function found");
compute_function_complexity(&func, &LUA_RULES)
}

#[test]
fn lua_empty_function() {
let m = compute_lua("local function f() end");
assert_eq!(m.cognitive, 0);
assert_eq!(m.cyclomatic, 1);
assert_eq!(m.max_nesting, 0);
}

#[test]
fn lua_single_if() {
let m = compute_lua("local function f(x)\n if x > 0 then\n return 1\n end\nend");
assert_eq!(m.cognitive, 1);
assert_eq!(m.cyclomatic, 2);
assert_eq!(m.max_nesting, 1);
}

#[test]
fn lua_if_elseif_else() {
// elseif_statement/else_statement are siblings of if_statement via
// repeated `alternative:` fields (Pattern B, like Python's elif/else).
let m = compute_lua(
"local function f(x)\n if x > 0 then\n return 1\n elseif x < 0 then\n return -1\n else\n return 0\n end\nend",
);
// if: +1 cog, +1 cyc; elseif: +1 cog, +1 cyc; else: +1 cog
assert_eq!(m.cognitive, 3);
assert_eq!(m.cyclomatic, 3);
assert_eq!(m.max_nesting, 1);
}

#[test]
fn lua_numeric_for_loop() {
let m = compute_lua("local function f()\n for i = 1, 10 do\n print(i)\n end\nend");
assert_eq!(m.cognitive, 1);
assert_eq!(m.cyclomatic, 2);
assert_eq!(m.max_nesting, 1);
}

#[test]
fn lua_while_loop() {
let m = compute_lua("local function f(n)\n while n > 0 do\n n = n - 1\n end\nend");
assert_eq!(m.cognitive, 1);
assert_eq!(m.cyclomatic, 2);
assert_eq!(m.max_nesting, 1);
}

#[test]
fn lua_repeat_until_loop() {
let m = compute_lua("local function f(n)\n repeat\n n = n - 1\n until n <= 0\nend");
assert_eq!(m.cognitive, 1);
assert_eq!(m.cyclomatic, 2);
assert_eq!(m.max_nesting, 1);
}

#[test]
fn lua_logical_operators() {
let m = compute_lua("local function f(a, b)\n if a and b then\n return 1\n end\nend");
// if: +1 cog, +1 cyc; and: +1 cog, +1 cyc
assert_eq!(m.cognitive, 2);
assert_eq!(m.cyclomatic, 3);
}

#[test]
fn lua_method_declaration() {
// Greptile follow-up to #1782: colon-syntax method declarations
// (`function Obj:method(x)`) have a `method_index_expression` name
// field but are still `function_declaration` nodes, so `function_nodes`
// already covers them — this pins that native/TS parity explicitly.
// Mirrors the TS test 'method declaration (colon syntax) is
// recognized as a function'.
let m = compute_lua(
"local Obj = {}\nfunction Obj:method(x)\n if x > 0 then\n return x\n end\nend",
);
assert_eq!(m.cognitive, 1);
assert_eq!(m.cyclomatic, 2);
assert_eq!(m.max_nesting, 1);
}

#[test]
fn lua_nested_if() {
let m = compute_lua(
"local function f(x, y)\n if x > 0 then\n if y > 0 then\n return 1\n end\n end\nend",
);
assert_eq!(m.cognitive, 3);
assert_eq!(m.cyclomatic, 3);
assert_eq!(m.max_nesting, 2);
}
}
Comment on lines 1673 to 1776

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 No native test for colon/dot-syntax method declarations

The TS test suite includes 'method declaration (colon syntax) is recognized as a function' (using function Obj:method(x)), but the Rust test module has no equivalent. function_nodes: &["function_declaration"] should cover this form (the name field is a method_index_expression), but a missing native test means a future grammar change that breaks method recognition in the native engine would go undetected until the TS discrepancy surfaced. Adding even a minimal lua_method_declaration test mirroring the TS case would close the coverage gap.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Fix in Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — added lua_method_declaration, mirroring the TS test exactly, in cbb79e39.

1 change: 1 addition & 0 deletions src/ast-analysis/metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ const COMMENT_PREFIXES = new Map<string, string[]>([
['python', ['#']],
['ruby', ['#']],
['php', ['//', '#', '/*', '*', '*/']],
['lua', ['--']],
]);

/**
Expand Down
114 changes: 113 additions & 1 deletion src/ast-analysis/rules/b3.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { DataflowRulesConfig } from '../../types.js';
import type { ComplexityRules, DataflowRulesConfig, HalsteadRules } from '../../types.js';
import { makeDataflowRules } from '../shared.js';

// ─── Lua ──────────────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -30,6 +30,118 @@ export const dataflowLua: DataflowRulesConfig = makeDataflowRules({
memberPropertyField: 'field',
});

// Lua's `if_statement` is flat, not nested: `elseif`/`else` are separate node
// types (`elseif_statement`, `else_statement`) attached to the *same*
// `if_statement` via repeated `alternative:` fields — confirmed by parsing
// `if a then .. elseif b then .. else .. end` and inspecting the S-expression:
// `(if_statement condition: (...) consequence: (...) alternative: (elseif_statement ...) alternative: (else_statement ...))`.
// This is structurally identical to Python's elif_clause/else_clause pattern
// (Pattern B), not JS's nested else_clause>if_statement (Pattern A) or Go's
// alternative-field-holds-nested-if (Pattern C) — so elseViaAlternative: false
// and neither elseif_statement nor else_statement is in nestingNodes (matching
// how Python's elif_clause/else_clause are siblings of the primary if, not
// separately-nested branches).
//
// binary_expression is Lua's single generic binary-op node (arithmetic,
// comparison, concat, AND logical `and`/`or`) — same shared-type pattern as
// Ruby's `binary` node. classifyLogicalOp/handleLogicalOperator only acts when
// `node.child(1)` (the operator token) is in logicalOperators, so comparisons
// and arithmetic on the same node type are correctly ignored.
export const complexityLua: ComplexityRules = {
branchNodes: new Set([
'if_statement',
'elseif_statement',
'else_statement',
'for_statement',
'while_statement',
'repeat_statement',
]),
caseNodes: new Set([]),
logicalOperators: new Set(['and', 'or']),
logicalNodeType: 'binary_expression',
optionalChainType: null,
nestingNodes: new Set(['if_statement', 'for_statement', 'while_statement', 'repeat_statement']),
functionNodes: new Set(['function_declaration']),
ifNodeType: 'if_statement',
elseNodeType: 'else_statement',
elifNodeType: 'elseif_statement',
elseViaAlternative: false,
switchLikeNodes: new Set([]),
};

// Member/method access (`dot_index_expression` `.`, `method_index_expression`
// `:`) and invocation (`function_call`) are wrapper nodes without a dedicated
// "call happened" token, so they're counted as compound operators — mirrors
// Python's ['call', 'subscript', 'attribute']. The '.'/':' separator tokens are
// ALSO in operatorLeafTypes (matching Python counting both 'attribute' and
// '.'), so member access contributes two distinct operator kinds, consistent
// with the existing per-language precedent.
export const halsteadLua: HalsteadRules = {
operatorLeafTypes: new Set([
'+',
'-',
'*',
'/',
'//',
'%',
'^',
'#',
'..',
'==',
'~=',
'<=',
'>=',
'<',
'>',
'=',
'and',
'or',
'not',
'&',
'|',
'~',
'<<',
'>>',
'.',
',',
':',
'::',
';',
'if',
'then',
'else',
'elseif',
'end',
'for',
'while',
'do',
'repeat',
'until',
'function',
'local',
'return',
'break',
'goto',
'in',
]),
operandLeafTypes: new Set([
'identifier',
'number',
'string_content',
'true',
'false',
'nil',
'...',
]),
compoundOperators: new Set([
'function_call',
'bracket_index_expression',
'dot_index_expression',
'method_index_expression',
]),
skipTypes: new Set([]),
};

// ─── R ────────────────────────────────────────────────────────────────────────
//
// R functions are defined as: `name <- function_definition` (binary_operator with `<-`).
Expand Down
2 changes: 2 additions & 0 deletions src/ast-analysis/rules/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export const COMPLEXITY_RULES: Map<string, ComplexityRules> = new Map([
['csharp', csharp.complexity],
['ruby', ruby.complexity],
['php', php.complexity],
['lua', b3.complexityLua],
]);

// ─── Halstead Rules ───────────────────────────────────────────────────────
Expand All @@ -46,6 +47,7 @@ export const HALSTEAD_RULES: Map<string, HalsteadRules> = new Map([
['csharp', csharp.halstead],
['ruby', ruby.halstead],
['php', php.halstead],
['lua', b3.halsteadLua],
]);

// ─── CFG Rules ────────────────────────────────────────────────────────────
Expand Down
Loading
Loading