Skip to content

Commit fdf1089

Browse files
authored
fix(ast-analysis): stop misattributing complexity/CFG across same-line anonymous functions (#2265) (#2446)
Root cause was two compounding bugs, both fixed: 1. handleVarFnAssignment/handleVarFnCapture (extractors/javascript.ts) and handle_var_decl (Rust) set a var/const-assigned function's Definition.line from the enclosing declaration statement, not the function value's own node. `const a = fn1, b = fn2;` gave every declarator but the first the wrong line, so `b`'s Definition collided with `a`'s real (correctly line-keyed) complexity/CFG result once storeComplexityResults/storeCfgResults (ast-analysis/apply-results.ts) indexed by each function node's own line. 2. matchResultToDef's only disambiguation signal was `name` — always null for an arrow function, and never the function expression's own internal name for a var-assigned one — so it could never break a same-line tie for this whole Definition category, fix #1 or not. Added `column`, populated only for this category, and threaded a column-first tier into both matchResultToDef (WASM/visitor path, apply-results.ts) and matchNativeResult (native-standalone fallback path, engine.ts) — a structurally separate but algorithmically identical copy of the same matching logic, not consolidated into one function since one operates on live tree-sitter nodes and the other on native-computed POJOs with no such node. Rust's own inline full-pipeline complexity/CFG attachment (handle_var_decl) was never vulnerable to the misattribution itself — it computes and attaches each Definition's complexity/CFG directly from its own value node, never by a later line-keyed re-match — but still needed the line fix, since Definition.line feeds contentHash/incremental-rebuild reconnection and `codegraph where`, not just this matching path. column is added narrowly to FunctionComplexityResult/FunctionCfgResult (the two NAPI-crossing structs the native-standalone fallback path already returns), not to the widely literal-constructed shared Definition struct in Rust, which has ~200 unrelated construction sites across every language extractor and does not need it for this JS/TS-only bug. docs check acknowledged: internal extractor/ast-analysis fix, no language support, CLI, or architecture-table changes. Impact: 12 functions changed, 0 affected
1 parent 599a4f0 commit fdf1089

10 files changed

Lines changed: 374 additions & 17 deletions

File tree

‎crates/codegraph-core/src/ast_analysis/engine.rs‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,10 +89,12 @@ pub fn analyze_complexity_standalone(
8989
let metrics = compute_all_metrics(&node, source_bytes, lang_id)?;
9090
let name = function_name(&node, source_bytes);
9191
let line = node.start_position().row as u32 + 1;
92+
let column = Some(node.start_position().column as u32);
9293
let end_line = Some(node.end_position().row as u32 + 1);
9394
Some(FunctionComplexityResult {
9495
name,
9596
line,
97+
column,
9698
end_line,
9799
complexity: metrics,
98100
})
@@ -132,10 +134,12 @@ pub fn build_cfg_standalone(
132134
let cfg = build_function_cfg(&node, lang_id, source_bytes)?;
133135
let name = function_name(&node, source_bytes);
134136
let line = node.start_position().row as u32 + 1;
137+
let column = Some(node.start_position().column as u32);
135138
let end_line = Some(node.end_position().row as u32 + 1);
136139
Some(FunctionCfgResult {
137140
name,
138141
line,
142+
column,
139143
end_line,
140144
cfg,
141145
})
@@ -153,3 +157,38 @@ pub fn extract_dataflow_standalone(
153157
let (tree, lang) = parse_source(source, file_path, lang_id)?;
154158
extract_dataflow(&tree, source.as_bytes(), lang.lang_id_str())
155159
}
160+
161+
#[cfg(test)]
162+
mod tests {
163+
use super::*;
164+
165+
/// Issue #2265: `matchNativeResult` (JS side, engine.ts) needs each
166+
/// standalone result's own column to disambiguate two anonymous
167+
/// functions that share a line — confirms the native standalone
168+
/// analysis functions actually populate it.
169+
#[test]
170+
fn analyze_complexity_standalone_populates_column() {
171+
let results = analyze_complexity_standalone(
172+
"const a = (x) => x, b = (x) => x;",
173+
"test.js",
174+
Some("javascript"),
175+
);
176+
assert_eq!(results.len(), 2);
177+
assert_eq!(results[0].column, Some(10));
178+
assert_eq!(results[1].column, Some(24));
179+
assert_ne!(results[0].column, results[1].column);
180+
}
181+
182+
#[test]
183+
fn build_cfg_standalone_populates_column() {
184+
let results = build_cfg_standalone(
185+
"function outer() { if (true) {} }\nconst a = (x) => x, b = (x) => x;",
186+
"test.js",
187+
Some("javascript"),
188+
);
189+
let a = results.iter().find(|r| r.line == 2 && r.column == Some(10));
190+
let b = results.iter().find(|r| r.line == 2 && r.column == Some(24));
191+
assert!(a.is_some(), "expected a result at line 2, column 10");
192+
assert!(b.is_some(), "expected a result at line 2, column 25");
193+
}
194+
}

‎crates/codegraph-core/src/extractors/javascript.rs‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2521,7 +2521,12 @@ fn handle_var_decl(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
25212521
symbols.definitions.push(Definition {
25222522
name: node_text(&name_n, source).to_string(),
25232523
kind: "function".to_string(),
2524-
line: start_line(node),
2524+
// #2265: the function VALUE's own start line, not the
2525+
// enclosing statement's — `node` spans the whole
2526+
// `const a = fn1, b = fn2;` declaration, so every declarator
2527+
// in a multi-binding statement previously got the identical
2528+
// (wrong, for every declarator but the first) line.
2529+
line: start_line(&value_n),
25252530
end_line: Some(end_line(&value_n)),
25262531
decorators: None,
25272532
complexity: compute_all_metrics(&value_n, source, "javascript"),
@@ -7137,6 +7142,23 @@ mod tests {
71377142
assert_eq!(s.definitions[0].kind, "function");
71387143
}
71397144

7145+
/// Issue #2265: a multi-declarator `const a = fn1, b = fn2;` statement
7146+
/// previously gave every declarator the SAME `line` (the whole
7147+
/// statement's start, not each function value's own start) — misleading
7148+
/// for anything keyed on line, including the JS-side complexity/CFG
7149+
/// matcher this mirrors (`matchResultToDef` in apply-results.ts).
7150+
#[test]
7151+
fn multi_declarator_var_fn_assignment_uses_each_functions_own_line() {
7152+
let s = parse_js(
7153+
"const a = (x) => {\n if (x) { return 1; }\n return 0;\n}, b = (x) => {\n return 2;\n};\n",
7154+
);
7155+
let a = s.definitions.iter().find(|d| d.name == "a").unwrap();
7156+
let b = s.definitions.iter().find(|d| d.name == "b").unwrap();
7157+
assert_eq!(a.line, 1);
7158+
assert_eq!(b.line, 4);
7159+
assert_ne!(a.line, b.line);
7160+
}
7161+
71407162
#[test]
71417163
fn finds_class_with_methods() {
71427164
let s = parse_js("class Foo { bar() {} baz() {} }");

‎crates/codegraph-core/src/types.rs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -614,6 +614,17 @@ impl FileSymbols {
614614
pub struct FunctionComplexityResult {
615615
pub name: String,
616616
pub line: u32,
617+
/// 0-based source column of this function node's own start position —
618+
/// mirrors tree-sitter's own convention directly (unlike `line`, never
619+
/// `+1`-adjusted for display), since this is purely an internal
620+
/// disambiguation key for `matchNativeResult` (issue #2265), never
621+
/// rendered to users. Lets the JS engine's line-keyed match fall back to
622+
/// an exact line+column match when a `Definition`'s own column is known
623+
/// (currently only for JS/TS var/const-assigned anonymous function
624+
/// values, where two such functions can share a `Definition.line` but
625+
/// never share a column) — the same-line ambiguity a name-only
626+
/// disambiguator can never resolve for an anonymous function.
627+
pub column: Option<u32>,
617628
#[napi(js_name = "endLine")]
618629
pub end_line: Option<u32>,
619630
pub complexity: ComplexityMetrics,
@@ -624,6 +635,8 @@ pub struct FunctionComplexityResult {
624635
pub struct FunctionCfgResult {
625636
pub name: String,
626637
pub line: u32,
638+
/// See `FunctionComplexityResult.column`'s doc comment.
639+
pub column: Option<u32>,
627640
#[napi(js_name = "endLine")]
628641
pub end_line: Option<u32>,
629642
pub cfg: CfgData,

‎src/ast-analysis/apply-results.ts‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,13 +72,32 @@ export function indexByLine<T extends { funcNode: TreeSitterNode }>(
7272
return byLine;
7373
}
7474

75-
/** Find the best matching result for a definition by line + name. */
75+
/**
76+
* Find the best matching result for a definition by line + name, preferring
77+
* an exact column match when available.
78+
*
79+
* `name` can only disambiguate a *named* function/method Definition — an
80+
* arrow function has no name field at all, and a function *expression*'s
81+
* own internal name (if any) is not the variable it was assigned to, so
82+
* `name` never disambiguates a var/const-assigned closure (issue #2265).
83+
* `defColumn` (only populated for exactly that Definition category — see
84+
* `Definition.column`'s doc comment) closes that gap: two functions can
85+
* share a `line` — a multi-declarator statement collapsed onto one
86+
* (now-fixed) line, or two genuinely same-line closures — but never share
87+
* both line AND column. Checked before the name fallback since it's a
88+
* strictly more precise signal whenever it's available on both sides.
89+
*/
7690
export function matchResultToDef<T extends { funcNode: TreeSitterNode }>(
7791
candidates: T[] | undefined,
7892
defName: string,
93+
defColumn?: number,
7994
): T | undefined {
8095
if (!candidates) return undefined;
8196
if (candidates.length === 1) return candidates[0];
97+
if (defColumn != null) {
98+
const byColumn = candidates.find((r) => r.funcNode.startPosition.column === defColumn);
99+
if (byColumn) return byColumn;
100+
}
82101
return (
83102
candidates.find((r) => {
84103
const n = r.funcNode.childForFieldName('name');
@@ -111,7 +130,7 @@ export function storeComplexityResults(
111130
!def.complexity &&
112131
def.bodyless !== true
113132
) {
114-
const funcResult = matchResultToDef(byLine.get(def.line), def.name);
133+
const funcResult = matchResultToDef(byLine.get(def.line), def.name, def.column);
115134
if (!funcResult) continue;
116135
const { metrics } = funcResult;
117136
const loc = computeLOCMetrics(funcResult.funcNode, langId);
@@ -155,7 +174,7 @@ export function storeCfgResults(results: WalkResults, defs: Definition[]): void
155174
!def.cfg?.blocks?.length &&
156175
def.bodyless !== true
157176
) {
158-
const cfgResult = matchResultToDef(byLine.get(def.line), def.name);
177+
const cfgResult = matchResultToDef(byLine.get(def.line), def.name, def.column);
159178
if (!cfgResult) continue;
160179
def.cfg = { blocks: cfgResult.blocks, edges: cfgResult.edges };
161180
}

‎src/ast-analysis/engine.ts‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -210,12 +210,25 @@ function indexNativeByLine<T extends { line: number; name: string }>(
210210
return byLine;
211211
}
212212

213-
function matchNativeResult<T extends { name: string }>(
213+
/**
214+
* See `matchResultToDef`'s (apply-results.ts) doc comment for the full
215+
* rationale — this is the structurally-identical fix applied to the
216+
* separate native-standalone-analysis matching copy (issue #2265): `name`
217+
* never disambiguates a var/const-assigned anonymous function, so an exact
218+
* column match (when both the native result and the Definition carry one)
219+
* is checked first.
220+
*/
221+
function matchNativeResult<T extends { name: string; column?: number | null }>(
214222
candidates: T[] | undefined,
215223
defName: string,
224+
defColumn?: number,
216225
): T | undefined {
217226
if (!candidates) return undefined;
218227
if (candidates.length === 1) return candidates[0];
228+
if (defColumn != null) {
229+
const byColumn = candidates.find((r) => r.column === defColumn);
230+
if (byColumn) return byColumn;
231+
}
219232
return candidates.find((r) => r.name === defName) ?? candidates[0];
220233
}
221234

@@ -228,7 +241,7 @@ function storeNativeComplexityResults(
228241

229242
for (const def of defs) {
230243
if ((def.kind === 'function' || def.kind === 'method') && def.line && !def.complexity) {
231-
const match = matchNativeResult(byLine.get(def.line), def.name);
244+
const match = matchNativeResult(byLine.get(def.line), def.name, def.column);
232245
if (!match) continue;
233246
const { complexity: c } = match;
234247
def.complexity = {
@@ -281,7 +294,7 @@ function storeNativeCfgResults(results: NativeFunctionCfgResult[], defs: Definit
281294
def.cfg !== null &&
282295
!def.cfg?.blocks?.length
283296
) {
284-
const match = matchNativeResult(byLine.get(def.line), def.name);
297+
const match = matchNativeResult(byLine.get(def.line), def.name, def.column);
285298
if (!match) continue;
286299
def.cfg = match.cfg;
287300
}

‎src/extractors/javascript.ts‎

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -134,15 +134,27 @@ function handleFnCapture(c: Record<string, TreeSitterNode>, definitions: Definit
134134
});
135135
}
136136

137-
/** Handle variable_declarator with arrow_function / function_expression capture. */
137+
/**
138+
* Handle variable_declarator with arrow_function / function_expression capture.
139+
*
140+
* Uses the function VALUE's own start position — not the enclosing
141+
* declaration statement's — for `line`/`column` (issue #2265): a
142+
* `const a = fn1, b = fn2;` multi-declarator statement previously gave
143+
* every declarator the identical statement-start line, so any declarator
144+
* but the first collided with a sibling's real complexity/CFG result once
145+
* `matchResultToDef` (apply-results.ts) indexed by each function node's own
146+
* (correct) line. `column` additionally survives even a genuine same-line
147+
* collision (two anonymous closures both starting on one physical line),
148+
* which `name`-based disambiguation can never resolve for an anonymous
149+
* function/arrow value.
150+
*/
138151
function handleVarFnCapture(c: Record<string, TreeSitterNode>, definitions: Definition[]): void {
139-
const declNode = c.varfn_name!.parent?.parent;
140-
const line = declNode ? nodeStartLine(declNode) : nodeStartLine(c.varfn_name!);
141152
const varFnChildren = extractParameters(c.varfn_value!);
142153
definitions.push({
143154
name: c.varfn_name!.text,
144155
kind: 'function',
145-
line,
156+
line: nodeStartLine(c.varfn_value!),
157+
column: c.varfn_value!.startPosition.column,
146158
endLine: nodeEndLine(c.varfn_value!),
147159
children: varFnChildren.length > 0 ? varFnChildren : undefined,
148160
});
@@ -1848,7 +1860,7 @@ function handleVariableDeclarator(
18481860
valType === 'function' ||
18491861
valType === 'generator_function'
18501862
) {
1851-
handleVarFnAssignment(node, nameN, valueN, ctx);
1863+
handleVarFnAssignment(nameN, valueN, ctx);
18521864
} else if (isConst && nameN.type === 'identifier' && !hasFunctionScopeAncestor(node)) {
18531865
// Any other initializer shape becomes a 'constant' Definition, regardless of
18541866
// complexity (call/member/parenthesized expressions, etc.) — mirroring how
@@ -1875,9 +1887,20 @@ function handleVariableDeclarator(
18751887
}
18761888
}
18771889

1878-
/** Handle `const/let fn = (...) => {...}` — a function/arrow value assigned to a variable. */
1890+
/**
1891+
* Handle `const/let fn = (...) => {...}` — a function/arrow value assigned
1892+
* to a variable.
1893+
*
1894+
* Uses `valueN`'s (the function itself) own start position, not `node`'s
1895+
* (the enclosing declaration statement) — issue #2265: `node` spans the
1896+
* whole `const a = fn1, b = fn2;` statement, so every declarator got the
1897+
* identical statement-start line, colliding with a sibling declarator's
1898+
* real complexity/CFG result once `matchResultToDef` (apply-results.ts)
1899+
* indexed by each function node's own (correct) line. See
1900+
* `handleVarFnCapture`'s fuller comment (query path) for the rest of the
1901+
* rationale — `column` mirrors the same fix there.
1902+
*/
18791903
function handleVarFnAssignment(
1880-
node: TreeSitterNode,
18811904
nameN: TreeSitterNode,
18821905
valueN: TreeSitterNode,
18831906
ctx: ExtractorOutput,
@@ -1886,7 +1909,8 @@ function handleVarFnAssignment(
18861909
ctx.definitions.push({
18871910
name: nameN.text,
18881911
kind: 'function',
1889-
line: nodeStartLine(node),
1912+
line: nodeStartLine(valueN),
1913+
column: valueN.startPosition.column,
18901914
endLine: nodeEndLine(valueN),
18911915
children: varFnChildren.length > 0 ? varFnChildren : undefined,
18921916
});

‎src/types.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,20 @@ export interface Definition {
464464
name: string;
465465
kind: SymbolKind;
466466
line: number;
467+
/**
468+
* 0-based source column of this Definition's own node — mirrors
469+
* tree-sitter's own convention directly (unlike `line`, never
470+
* `+1`-adjusted for display), since this is purely an internal
471+
* disambiguation key for `matchResultToDef`/`matchNativeResult` (issue
472+
* #2265), never rendered to users. Only populated for var/const-assigned
473+
* anonymous function values (`handleVarFnAssignment`/`handleVarFnCapture`
474+
* in extractors/javascript.ts) — the one Definition category where two
475+
* distinct functions can legitimately share `line` (a multi-declarator
476+
* statement, or two genuinely same-line closures) and where `name`
477+
* (the variable bound, not the function's own — usually absent —
478+
* internal name) can never disambiguate them.
479+
*/
480+
column?: number;
467481
endLine?: number;
468482
children?: SubDeclaration[];
469483
visibility?: 'public' | 'private' | 'protected';
@@ -2692,6 +2706,8 @@ export interface NativeAddon {
26922706
export interface NativeFunctionComplexityResult {
26932707
name: string;
26942708
line: number;
2709+
/** See `Definition.column`'s doc comment (issue #2265). */
2710+
column?: number | null;
26952711
endLine: number | null;
26962712
complexity: {
26972713
cognitive: number;
@@ -2718,6 +2734,8 @@ export interface NativeFunctionComplexityResult {
27182734
export interface NativeFunctionCfgResult {
27192735
name: string;
27202736
line: number;
2737+
/** See `Definition.column`'s doc comment (issue #2265). */
2738+
column?: number | null;
27212739
endLine: number | null;
27222740
cfg: { blocks: CfgBlock[]; edges: CfgEdge[] };
27232741
}

0 commit comments

Comments
 (0)