Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
52 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
50ab50f
fix: resolve merge conflicts with main
carlos-alm Jul 8, 2026
892572c
test: add cross-engine parity check for LUA_BUILTIN_GLOBALS (#1912)
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
161 changes: 161 additions & 0 deletions crates/codegraph-core/src/extractors/lua.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,21 @@ use crate::types::*;
use super::helpers::*;
use super::SymbolExtractor;

/// Lua base-library global function names and standard-library module
/// tables. Mirrors `LUA_BUILTIN_GLOBALS` in `src/extractors/lua.ts` — see
/// `handle_lua_assignment_statement` (this file) and that file's
/// `handleLuaAssignmentStatement` for the full rationale (issue #1776).
const LUA_BUILTIN_GLOBALS: &[&str] = &[
"assert", "collectgarbage", "dofile", "error", "getfenv", "getmetatable",
"ipairs", "load", "loadfile", "loadstring", "module", "next", "pairs",
"pcall", "print", "rawequal", "rawget", "rawlen", "rawset", "require",
"select", "setfenv", "setmetatable", "tonumber", "tostring", "type",
"unpack", "xpcall",
// Standard-library module tables — wholesale replacement (e.g. sandboxing)
// is the same "escapes local scope" shape as a single builtin function.
"string", "table", "math", "io", "os", "coroutine", "debug", "utf8", "bit32",
];
Comment on lines +12 to +21

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 Duplicated allowlist has no automated parity check

LUA_BUILTIN_GLOBALS is defined identically in both lua.rs and lua.ts, linked only by a prose comment. The next time someone adds an entry (e.g., warn added in Lua 5.4) they must update both files manually. If one drifts, the native and WASM engines silently disagree: a builtin reassigned in Lua code would be emitted as a value-ref edge by one engine and ignored by the other. Consider a codegen-step or CI lint that asserts the two lists are byte-for-byte identical, or canonicalise the list in a shared data file loaded by both build steps.

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 a cross-engine parity test (tests/parsers/lua.test.ts) that reads the Rust list as text and diffs it against the exported TS Set, so any future one-sided edit fails CI. Went with a test over a shared data file / codegen step to keep this PR's scope contained (no new build-pipeline dependency for a single language's allowlist) in 892572cb.


pub struct LuaExtractor;

impl SymbolExtractor for LuaExtractor {
Expand All @@ -20,6 +35,7 @@ fn match_lua_node(node: &Node, source: &[u8], symbols: &mut FileSymbols, _depth:
match node.kind() {
"function_declaration" => handle_lua_function_decl(node, source, symbols),
"function_call" => handle_lua_function_call(node, source, symbols),
"assignment_statement" => handle_lua_assignment_statement(node, source, symbols),
_ => {}
}
}
Expand Down Expand Up @@ -88,6 +104,52 @@ fn extract_lua_params(func_node: &Node, source: &[u8]) -> Vec<Definition> {
params
}

/// Detect `<builtin> = <identifier>` assignments — a locally declared
/// function bound to a Lua global/builtin identifier (e.g.
/// `require = traced_require`), the monkey-patch pattern from issue #1776.
/// Mirrors `handleLuaAssignmentStatement` in `src/extractors/lua.ts` — see
/// that function's doc comment for the full rationale.
///
/// Emits a dynamic `value-ref` call for the RHS identifier, restricted to
/// plain `identifier = identifier` pairs where the LHS matches
/// `LUA_BUILTIN_GLOBALS`. `value-ref` is resolved downstream
/// (build_edges.rs) against function/method-kind targets only, so a
/// builtin reassigned to a non-function value is silently dropped rather
/// than fabricating a nonsensical edge.
///
/// Multi-assignment (`a, b = f, g`) is handled positionally: each side is
/// indexed independently by position (not pre-filtered to identifiers
/// first), so mixed variable kinds (`t.b, a = f, g`) do not shift the
/// pairing.
fn handle_lua_assignment_statement(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
let Some(variable_list) = find_child(node, "variable_list") else { return };
let Some(expression_list) = find_child(node, "expression_list") else { return };

let pair_count = variable_list
.named_child_count()
.min(expression_list.named_child_count());

for i in 0..pair_count {
let Some(lhs) = variable_list.named_child(i) else { continue };
let Some(rhs) = expression_list.named_child(i) else { continue };
if lhs.kind() != "identifier" || rhs.kind() != "identifier" {
continue;
}
let lhs_text = node_text(&lhs, source);
let rhs_text = node_text(&rhs, source);
if !LUA_BUILTIN_GLOBALS.contains(&lhs_text) || LUA_BUILTIN_GLOBALS.contains(&rhs_text) {
continue;
}
symbols.calls.push(Call {
name: rhs_text.to_string(),
line: start_line(&rhs),
dynamic: Some(true),
dynamic_kind: Some("value-ref".to_string()),
..Default::default()
});
}
}

fn handle_lua_function_call(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
let name_node = match node.child_by_field_name("name") {
Some(n) => n,
Expand Down Expand Up @@ -199,3 +261,102 @@ fn handle_lua_function_call(node: &Node, source: &[u8], symbols: &mut FileSymbol
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use tree_sitter::Parser;

fn parse_lua(code: &str) -> FileSymbols {
let mut parser = Parser::new();
parser
.set_language(&tree_sitter_lua::LANGUAGE.into())
.unwrap();
let tree = parser.parse(code.as_bytes(), None).unwrap();
LuaExtractor.extract(&tree, code.as_bytes(), "test.lua")
}

// ── #1776: builtin/global reassignment value-ref extraction ─────────────

#[test]
fn extracts_value_ref_call_for_function_assigned_to_builtin_global() {
let s = parse_lua(
"local function traced_require(modname)\n return modname\nend\nrequire = traced_require",
);
let value_refs: Vec<_> = s
.calls
.iter()
.filter(|c| c.dynamic_kind.as_deref() == Some("value-ref"))
.collect();
assert!(value_refs.iter().any(|c| c.name == "traced_require"));
assert!(value_refs.iter().all(|c| c.dynamic == Some(true)));
}

#[test]
fn extracts_value_ref_call_for_local_shadow_of_builtin() {
let s = parse_lua(
"local function traced_require(modname)\n return modname\nend\nlocal require = traced_require",
);
assert!(s
.calls
.iter()
.any(|c| c.name == "traced_require" && c.dynamic_kind.as_deref() == Some("value-ref")));
}

#[test]
fn no_value_ref_call_when_lhs_is_not_a_recognized_builtin() {
let s = parse_lua("local function helper() end\nmyCustomGlobal = helper");
assert!(s.calls.iter().all(|c| c.dynamic_kind.as_deref() != Some("value-ref")));
}

#[test]
fn no_value_ref_call_when_rhs_is_itself_a_builtin() {
let s = parse_lua("print = tostring");
assert!(s.calls.iter().all(|c| c.dynamic_kind.as_deref() != Some("value-ref")));
}

#[test]
fn no_value_ref_call_for_local_non_builtin_alias() {
let s = parse_lua("local function helper() end\nlocal orig_helper = helper");
assert!(s.calls.iter().all(|c| c.dynamic_kind.as_deref() != Some("value-ref")));
}

#[test]
fn no_value_ref_call_when_rhs_is_a_call_expression() {
let s = parse_lua("require = wrapRequire(require)");
assert!(s.calls.iter().all(|c| c.dynamic_kind.as_deref() != Some("value-ref")));
}

#[test]
fn no_value_ref_call_when_rhs_is_a_member_expression() {
let s = parse_lua("require = mymodule.customRequire");
assert!(s.calls.iter().all(|c| c.dynamic_kind.as_deref() != Some("value-ref")));
}

#[test]
fn pairs_multi_assignment_positionally() {
// `t.b` occupies position 0 (a dot_index_expression, not a plain
// identifier) — pairing must not shift, or `require` (position 1)
// would incorrectly pair with `helperA` (position 0).
let s = parse_lua(
"local function helperA() end\nlocal function helperB() end\nt.b, require = helperA, helperB",
);
let value_refs: Vec<&str> = s
.calls
.iter()
.filter(|c| c.dynamic_kind.as_deref() == Some("value-ref"))
.map(|c| c.name.as_str())
.collect();
assert!(value_refs.contains(&"helperB"));
assert!(!value_refs.contains(&"helperA"));
}

#[test]
fn extracts_value_ref_call_for_stdlib_module_table_reassignment() {
let s = parse_lua("local function fakeOs() end\nos = fakeOs");
assert!(s
.calls
.iter()
.any(|c| c.name == "fakeOs" && c.dynamic_kind.as_deref() == Some("value-ref")));
}
}
21 changes: 18 additions & 3 deletions docs/architecture/decisions/002-dynamic-call-resolution.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,12 @@ export type DynamicKind =
| 'reflection' // .call/.apply/.bind, getattr, Method.invoke, $obj->$m()
| 'eval' // eval(), new Function() — undecidable
| 'unresolved-dynamic' // detected dynamic call we cannot resolve
| 'value-ref'; // bare identifier used as an object-literal property value
// (dispatch tables, e.g. `{ resolve: someFn }`) — resolvable
// against function/method-kind targets only (#1771)
| 'value-ref'; // bare identifier used as a value reference, not a call site —
// object-literal property value (dispatch tables, e.g.
// `{ resolve: someFn }`, #1771) or assignment to a Lua
// global/builtin identifier (e.g. `require = tracedRequire`,
// #1776) — resolvable against function/method-kind targets
// only
```

`dynamic?: boolean` is kept to avoid churning every `call.dynamic ? 1 : 0` site.
Expand All @@ -90,6 +93,18 @@ plain data reference like `{ name: SOME_CONSTANT }`), that's the common case, no
an undecidable dynamic call site — so it's silently dropped rather than flagged,
unlike `eval`/`computed-key`/`unresolved-dynamic`.

`value-ref` is deliberately syntax-position-agnostic: any bare identifier that
names a known function/method and appears somewhere other than a call site
qualifies, regardless of which language or grammar shape produced it.
Object-literal property values (#1771) and Lua assignment to a
global/builtin identifier (#1776, `require = tracedRequire` — a builtin name
isn't a locally-scoped variable that alias/points-to resolution could ever
observe, so this is the narrow, language-specific case where a plain
reference edge is the correct substitute for real alias tracking) are two
independent extraction sites feeding the same resolution/filtering logic
downstream; new languages/positions can add a third without touching
`build-edges.ts` / `incremental.ts` / `build_edges.rs` again.

### Sink edges reuse `kind='calls'`, not a new edge kind

A new `EdgeKind` would ripple through every edge-kind switch, role classifier, exporter, MCP tool, and the viewer — high blast radius. Instead: DB migration adds `dynamic_kind TEXT` column to `edges`; sink edges use `kind='calls'`, `dynamic=1`, `dynamic_kind=<kind>`, `confidence=0.0`. Confidence below `DEFAULT_MIN_CONFIDENCE=0.5` means they never pollute normal queries or exports but remain queryable when explicitly requested.
Expand Down
120 changes: 119 additions & 1 deletion src/extractors/lua.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,60 @@ import type {
TreeSitterNode,
TreeSitterTree,
} from '../types.js';
import { findChild, nodeEndLine } from './helpers.js';
import { findChild, nodeEndLine, nodeStartLine } from './helpers.js';

/**
* Lua base-library global function names and standard-library module
* tables. A plain `identifier = identifier` assignment whose LHS is one of
* these escapes local/lexical scoping entirely: the LHS names a language
* builtin rather than a locally declared variable that scope-based tracking
* could follow, so a function assigned here (`require = tracedRequire`, the
* monkey-patch pattern from issue #1776) becomes reachable through every
* later unqualified use of the builtin name — anywhere in the codebase,
* since it's a genuine global, not just within this file's call graph.
* Mirrors `LUA_BUILTIN_GLOBALS` in `crates/codegraph-core/src/extractors/lua.rs`.
*/
export const LUA_BUILTIN_GLOBALS: Set<string> = new Set([
'assert',
'collectgarbage',
'dofile',
'error',
'getfenv',
'getmetatable',
'ipairs',
'load',
'loadfile',
'loadstring',
'module',
'next',
'pairs',
'pcall',
'print',
'rawequal',
'rawget',
'rawlen',
'rawset',
'require',
'select',
'setfenv',
'setmetatable',
'tonumber',
'tostring',
'type',
'unpack',
'xpcall',
// Standard-library module tables — wholesale replacement (e.g. sandboxing)
// is the same "escapes local scope" shape as a single builtin function.
'string',
'table',
'math',
'io',
'os',
'coroutine',
'debug',
'utf8',
'bit32',
]);

/**
* Extract symbols from Lua files.
Expand Down Expand Up @@ -35,6 +88,9 @@ function walkLuaNode(node: TreeSitterNode, ctx: ExtractorOutput): void {
case 'function_call':
handleLuaFunctionCall(node, ctx);
break;
case 'assignment_statement':
handleLuaAssignmentStatement(node, ctx);
break;
}

for (let i = 0; i < node.childCount; i++) {
Expand Down Expand Up @@ -128,6 +184,68 @@ function checkForRequire(node: TreeSitterNode, ctx: ExtractorOutput): void {
}
}

/**
* Detect `<builtin> = <identifier>` assignments — a locally declared
* function bound to a Lua global/builtin identifier (e.g.
* `require = tracedRequire`), the monkey-patch pattern from issue #1776.
* Every later unqualified call to the builtin name (`require(...)`)
* anywhere in the codebase actually invokes the RHS function, but that call
* site names the builtin, never the RHS function directly — so without
* this, the RHS function has no inbound edge at all and is misclassified
* dead-unresolved.
*
* Emits a dynamic `value-ref` call for the RHS identifier — the same
* classification #1771 uses for bare identifiers referenced as
* object-literal property values: a bare identifier used in a value
* position, not a call site. Resolution downstream (build-edges.ts /
* incremental.ts / build_edges.rs) already restricts `value-ref` calls to
* function/method-kind targets only, so a builtin reassigned to a
* non-function value (`unpack = someTable`) is silently dropped rather than
* fabricating a nonsensical edge — no further changes needed there.
*
* Scoped narrowly to plain `identifier = identifier` pairs where the LHS
* matches a known Lua builtin/stdlib-module name (`LUA_BUILTIN_GLOBALS`).
* General local-to-local variable aliasing (`local a = someFunc; a()`) is a
* much larger points-to/alias-tracking problem this fix does not attempt to
* solve — see #1776 for the scoping rationale.
*
* Handles both the bare top-level form (`require = tracedRequire`, a
* standalone `assignment_statement`) and the `local`-declared form
* (`local require = tracedRequire`, an `assignment_statement` nested inside
* `variable_declaration`) identically: shadowing a builtin name with
* `local` is the same "redirect every later unqualified use" idiom, just
* lexically scoped rather than truly global.
*
* Multi-assignment (`a, b = f, g`) is handled positionally, matching Lua's
* own assignment semantics — mixed variable kinds (`t.b, a = f, g`) do not
* shift the pairing, since each side is indexed independently by position
* rather than pre-filtered to identifiers first.
*/
function handleLuaAssignmentStatement(node: TreeSitterNode, ctx: ExtractorOutput): void {
const variableList = findChild(node, 'variable_list');
const expressionList = findChild(node, 'expression_list');
if (!variableList || !expressionList) return;

const variables = variableList.namedChildren;
const expressions = expressionList.namedChildren;
const pairCount = Math.min(variables.length, expressions.length);

for (let i = 0; i < pairCount; i++) {
const lhs = variables[i];
const rhs = expressions[i];
if (!lhs || !rhs) continue;
if (lhs.type !== 'identifier' || rhs.type !== 'identifier') continue;
if (!LUA_BUILTIN_GLOBALS.has(lhs.text) || LUA_BUILTIN_GLOBALS.has(rhs.text)) continue;

ctx.calls.push({
name: rhs.text,
line: nodeStartLine(rhs),
dynamic: true,
dynamicKind: 'value-ref',
});
}
}

function handleLuaFunctionCall(node: TreeSitterNode, ctx: ExtractorOutput): void {
const nameNode = node.childForFieldName('name');
if (!nameNode) return;
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,7 @@ export type DynamicKind =
| 'reflection' // .call/.apply/.bind / Reflect.* / callable-ref — resolved when target is in codebase; sink edge emitted if unresolved
| 'eval' // eval() / new Function() — undecidable; always flagged
| 'unresolved-dynamic' // any other detected dynamic pattern; flagged
| 'value-ref'; // bare identifier used as an object-literal property value (dispatch-table pattern, e.g. `{ resolve: someFn }`) — resolved only against function/method-kind targets; unresolved (e.g. plain data references) are dropped silently, NOT flagged
| 'value-ref'; // bare identifier used as a value reference rather than a call site — object-literal property value (dispatch-table pattern, e.g. `{ resolve: someFn }`, #1771) or assignment to a Lua global/builtin identifier (e.g. `require = tracedRequire`, #1776) — resolved only against function/method-kind targets; unresolved (e.g. plain data references) are dropped silently, NOT flagged

/** A function/method call detected by an extractor. */
export interface Call {
Expand Down
Loading
Loading