Skip to content
Merged
Show file tree
Hide file tree
Changes from 61 commits
Commits
Show all changes
64 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
af17b6d
fix: scope global call-resolution fallback to same-language candidate…
carlos-alm Jul 6, 2026
dd447bc
fix: credit instanceof ClassName checks as exports consumers
carlos-alm Jul 6, 2026
a79a8a1
fix: update automated-review workflow to use current claude-code-acti…
carlos-alm Jul 6, 2026
d84f6b5
refactor: widen outputResult signature, remove redundant casts at cal…
carlos-alm Jul 6, 2026
e7a2255
fix: port Leiden algorithm to native Rust for cross-engine community-…
carlos-alm Jul 7, 2026
b54972a
feat: detect exported-symbol loss from full file deletion in checkNoS…
carlos-alm Jul 7, 2026
3357ffb
fix: resolve merge conflicts with main (docs check acknowledged)
carlos-alm Jul 8, 2026
8419f34
fix: show Deleted files count unconditionally in check summary line
carlos-alm Jul 8, 2026
62e9ec2
test: cover noTests consumer-filter path in checkNoDeletedExportsInUse
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
39 changes: 29 additions & 10 deletions .claude/hooks/update-graph.sh
Original file line number Diff line number Diff line change
Expand Up @@ -24,23 +24,42 @@ if [ -z "$FILE_PATH" ]; then
exit 0
fi

# Only rebuild for source files codegraph tracks
# Skip docs, configs, test fixtures, and non-code files
case "$FILE_PATH" in
*.js|*.ts|*.tsx|*.jsx|*.py|*.go|*.rs|*.java|*.cs|*.php|*.rb|*.tf|*.hcl)
;;
*)
exit 0
;;
esac
PROJECT_DIR=$(git rev-parse --show-toplevel 2>/dev/null) || PROJECT_DIR="${CLAUDE_PROJECT_DIR:-.}"

# Only rebuild for source files codegraph tracks.
# Skip docs, configs, test fixtures, and non-code files.
#
# The real allowlist is EXTENSIONS (src/shared/constants.ts), derived from
# LANGUAGE_REGISTRY (src/domain/parser.ts) — the single source of truth for
# every language codegraph parses. `npm run build` snapshots it to
# dist/hook-extensions.txt (see scripts/gen-hook-extensions.mjs) so this
# hook can do a fast native bash/grep check on every Edit/Write instead of
# spawning a second Node process, or hand-copying the list, on every edit.
#
# The case statement below is only a fallback for before the first build
# (no dist/hook-extensions.txt yet). tests/unit/hook-extensions.test.ts
# fails if it ever drifts behind EXTENSIONS — keep it updated when
# LANGUAGE_REGISTRY gains a new extension.
EXT=".${FILE_PATH##*.}"
GENERATED_EXT_LIST="$PROJECT_DIR/dist/hook-extensions.txt"
if [ -f "$GENERATED_EXT_LIST" ]; then
grep -qxF "$EXT" "$GENERATED_EXT_LIST" || exit 0
else
case "$EXT" in
.R|.bash|.c|.cc|.cjs|.clj|.cljc|.cljs|.cpp|.cs|.cu|.cuh|.cxx|.dart|.erl|.ex|.exs|.fs|.fsi|.fsx|.gemspec|.gleam|.go|.groovy|.gvy|.h|.hcl|.hpp|.hrl|.hs|.java|.jl|.js|.jsx|.kt|.kts|.lua|.m|.mjs|.ml|.mli|.php|.phtml|.py|.pyi|.r|.rake|.rb|.rs|.scala|.sh|.sol|.sv|.swift|.tf|.ts|.tsx|.v|.zig)
;;
*)
exit 0
;;
esac
fi

# Skip test fixtures — they're copied to tmp dirs anyway
if echo "$FILE_PATH" | grep -qE '(fixtures|__fixtures__|testdata)/'; then
exit 0
fi

# Guard: codegraph DB must exist (project has been built at least once)
PROJECT_DIR=$(git rev-parse --show-toplevel 2>/dev/null) || PROJECT_DIR="${CLAUDE_PROJECT_DIR:-.}"
DB_PATH="$PROJECT_DIR/.codegraph/graph.db"
if [ ! -f "$DB_PATH" ]; then
exit 0
Expand Down
8 changes: 5 additions & 3 deletions .claude/skills/titan-gate/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ codegraph check --staged --cycles --blast-radius 30 --boundaries -T --json

This checks: manifesto rules, new cycle introduction, blast radius threshold, and architecture boundary violations. Exit code 0 = pass, 1 = fail.

The `blast-radius` predicate is call-graph-shape-aware: a touched function's absolute transitive-caller count only counts toward the threshold if the diff actually changed that function's own declaration line or the set of call targets referenced in its body. A function whose body changed without touching a call expression or its own signature (e.g. an inline literal replaced by a named constant) is exempt even with a high absolute caller count — that fan-in is pre-existing risk already accepted by the codebase, not risk this diff introduced. This is the authoritative blast-radius pass/fail — see Step 8.

Also run detailed impact analysis:

```bash
Expand Down Expand Up @@ -302,9 +304,9 @@ Advisory — prevents jumping ahead and creating conflicts.

## Step 8 — Blast radius check

From diff-impact results:
- Transitive blast radius > 30 → FAIL
- Transitive blast radius > 15 → WARN
The FAIL/PASS decision comes from Step 1's `codegraph check --staged --blast-radius 30` predicate — do not re-derive it from diff-impact's raw numbers, which are absolute transitive-caller counts and are NOT shape-aware:
- Step 1's `blast-radius` predicate failed → FAIL (a touched function's own call graph shape genuinely changed and its transitive callers exceed 30)
- Step 1's `blast-radius` predicate passed but a changed function's raw `transitiveCallers` (from diff-impact) > 15 → WARN (worth a second look even though not gating — this may include functions Step 1 exempted as pre-existing fan-in)
- Historically coupled file NOT staged? → WARN ("consider also updating X")

---
Expand Down
9 changes: 5 additions & 4 deletions .claude/skills/titan-grind/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,9 @@ Forge shapes the metal. Grind smooths the rough edges. Your goal: find helpers t

12. **Capture dead-symbol baseline** (only if `grind.deadSymbolBaseline` is null):
```bash
codegraph roles --role dead -T --json | node -e "const d=[];process.stdin.on('data',c=>d.push(c));process.stdin.on('end',()=>{const items=JSON.parse(Buffer.concat(d));console.log(JSON.stringify({total:items.length,byRole:items.reduce((a,i)=>{a[i.role]=(a[i.role]||0)+1;return a},{})}));})"
codegraph roles --role dead -T --json | node -e "const d=[];process.stdin.on('data',c=>d.push(c));process.stdin.on('end',()=>{const data=JSON.parse(Buffer.concat(d));console.log(JSON.stringify({total:data.count,byRole:data.summary}));})"
```
`codegraph roles --json` returns `{ count, summary, symbols }` (not a bare array) — `summary` is already the per-role breakdown (e.g. `dead-leaf`, `dead-entry`, `dead-ffi`, `dead-unresolved`), so no manual reduce is needed.
Store the total in `grind.deadSymbolBaseline`. Write `titan-state.json` immediately.

13. **Drift detection.** Compare `titan-state.json → mainSHA` against current origin/main:
Expand Down Expand Up @@ -304,8 +305,8 @@ const tokens = helperName
.slice(0, 3);
const d=[];process.stdin.on('data',c=>d.push(c));
process.stdin.on('end',()=>{ try {
const items=JSON.parse(Buffer.concat(d));
const candidates = items.filter(i =>
const data=JSON.parse(Buffer.concat(d));
const candidates = (data.symbols || []).filter(i =>
i.name !== helperName &&
tokens.some(t => i.name.toLowerCase().includes(t))
);
Expand Down Expand Up @@ -579,7 +580,7 @@ After all targets in the phase are processed:

```bash
codegraph build
codegraph roles --role dead -T --json | node -e "const d=[];process.stdin.on('data',c=>d.push(c));process.stdin.on('end',()=>{const items=JSON.parse(Buffer.concat(d));console.log(JSON.stringify({total:items.length,byRole:items.reduce((a,i)=>{a[i.role]=(a[i.role]||0)+1;return a},{})}));})"
codegraph roles --role dead -T --json | node -e "const d=[];process.stdin.on('data',c=>d.push(c));process.stdin.on('end',()=>{const data=JSON.parse(Buffer.concat(d));console.log(JSON.stringify({total:data.count,byRole:data.summary}));})"
```

Store in `grind.deadSymbolCurrent`. Write `titan-state.json`.
Expand Down
12 changes: 9 additions & 3 deletions .github/workflows/claude.yml
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,11 @@ jobs:
uses: anthropics/claude-code-action@558b1d6cab4085c7753fe402c10bef0fbb92ac7a
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
model: claude-sonnet-4-6
direct_prompt: |
# claude-code-action v1 dropped the `model` input; model selection now goes
# through `claude_args` (see anthropics/claude-code-action migration guide).
claude_args: |
--model claude-sonnet-4-6
prompt: |
## Review this pull request

You are reviewing a PR for **codegraph** — a local code dependency graph CLI that parses
Expand Down Expand Up @@ -211,6 +214,9 @@ jobs:
uses: anthropics/claude-code-action@558b1d6cab4085c7753fe402c10bef0fbb92ac7a
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
model: claude-sonnet-4-6
# claude-code-action v1 dropped the `model` input; model selection now goes
# through `claude_args` (see anthropics/claude-code-action migration guide).
claude_args: |
--model claude-sonnet-4-6
additional_permissions: |
actions: read
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ crates/codegraph-core/*.node
.claude/worktrees/
generated/DEPENDENCIES.md
generated/DEPENDENCIES.json
token-benchmark.partial.json
artifacts/
pkg/
target/
Expand Down
6 changes: 4 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ npm run test:coverage # Coverage report
npx vitest run tests/parsers/javascript.test.ts # Single test file
npx vitest run -t "finds cycles" # Single test by name
npm run build:wasm # Rebuild WASM grammars from devDeps (built automatically on npm install)
npm run doctor # Check this worktree for a stale native binary / missing WASM grammars (runs automatically via pretest)
```

**Linter/Formatter:** [Biome](https://biomejs.dev/) — config in `biome.json`, scoped to `src/` and `tests/`.
Expand Down Expand Up @@ -103,6 +104,7 @@ Source is TypeScript in `src/`, compiled via `tsup`. The Rust native engine live
| `shared/paginate.ts` | Pagination helpers for bounded query results |
| **`infrastructure/`** | **Platform and I/O plumbing** |
| `infrastructure/config.ts` | `.codegraphrc.json` loading, env overrides, `apiKeyCommand` secret resolution |
| `infrastructure/doctor.ts` | Environment health checks — stale `better-sqlite3` native ABI, incomplete `grammars/`; see `npm run doctor` |
| `infrastructure/logger.ts` | Structured logging (`warn`, `debug`, `info`, `error`) |
| `infrastructure/native.ts` | Native napi-rs addon loader with WASM fallback |
| `infrastructure/registry.ts` | Global repo registry (`~/.codegraph/registry.json`) for multi-repo MCP |
Expand All @@ -126,7 +128,7 @@ Source is TypeScript in `src/`, compiled via `tsup`. The Rust native engine live
| `features/boundaries.ts` | Architecture boundary rules with onion architecture preset |
| `features/cfg.ts` | Control-flow graph generation |
| `features/check.ts` | CI validation predicates (cycles, complexity, blast radius, boundaries) |
| `features/communities.ts` | Louvain community detection, drift analysis (delegates to `graph/` subsystem) |
| `features/communities.ts` | Leiden community detection, drift analysis (delegates to `graph/` subsystem) |
| `features/complexity.ts` | Cognitive, cyclomatic, Halstead, MI computation from AST |
| `features/dataflow.ts` | Dataflow analysis |
| `features/export.ts` | Graph export orchestration: loads data from DB, delegates to `presentation/` serializers |
Expand All @@ -146,7 +148,7 @@ Source is TypeScript in `src/`, compiled via `tsup`. The Rust native engine live
| `presentation/sequence-renderer.ts` | Mermaid sequence diagram rendering |
| `presentation/table.ts`, `result-formatter.ts`, `colors.ts` | CLI table formatting, JSON/NDJSON output, color constants |
| **`graph/`** | **Unified graph model** |
| `graph/` | `CodeGraph` class (`model.ts`), algorithms (Tarjan SCC, Louvain, BFS, shortest path, centrality), classifiers (role, risk), builders (dependency, structure, temporal) |
| `graph/` | `CodeGraph` class (`model.ts`), algorithms (Tarjan SCC, Leiden, BFS, shortest path, centrality), classifiers (role, risk), builders (dependency, structure, temporal) |
| **`mcp/`** | **MCP server** |
| `mcp/` | MCP server exposing graph queries to AI agents; single-repo by default, `--multi-repo` to enable cross-repo access |
| `ast-analysis/` | Unified AST analysis framework: shared DFS walker (`visitor.ts`), engine orchestrator (`engine.ts`), extracted metrics (`metrics.ts`), and pluggable visitors for complexity, dataflow, and AST-store |
Expand Down
11 changes: 11 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ npm test # run the full test suite

**Requirements:** Node.js >= 20

**Working in multiple git worktrees?** Each worktree gets its own untracked
`node_modules/` and `grammars/` — neither is shared via git — so every fresh
`git worktree add` needs its own `npm install`. A worktree set up before a
host Node upgrade, or where `npm install` was interrupted, can be left with a
`better-sqlite3` binary compiled for the wrong Node ABI or an incomplete
`grammars/` directory; both fail in confusing ways deep inside a build or test
run. Run `npm run doctor` to check (or `npm run doctor -- --fix` to repair
in place, scoped to the current worktree) — it also runs automatically before
`npm test` via `pretest`.

## Contributor License Agreement (CLA)

All contributors must sign the [Contributor License Agreement](CLA.md) before
Expand Down Expand Up @@ -88,6 +98,7 @@ npm run test:coverage # Coverage report
npx vitest run tests/parsers/go.test.js # Single test file
npx vitest run -t "finds cycles" # Single test by name
npm run build:wasm # Rebuild WASM grammars
npm run doctor # Check for a stale native binary / missing WASM grammars
```

## Branch Naming Convention
Expand Down
153 changes: 153 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: &[],
};

/// 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,88 @@ 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_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);
}
}
Loading
Loading