diff --git a/crates/codegraph-core/src/domain/graph/builder/stages/build_edges.rs b/crates/codegraph-core/src/domain/graph/builder/stages/build_edges.rs index 1c113bc24..9a648c4aa 100644 --- a/crates/codegraph-core/src/domain/graph/builder/stages/build_edges.rs +++ b/crates/codegraph-core/src/domain/graph/builder/stages/build_edges.rs @@ -1765,6 +1765,31 @@ fn resolve_call_targets<'a>( attach_constructor_targets(ctx, targets, class_name) } +/// True when `caller_name`'s class-name prefix is a real class/struct/ +/// interface/etc.-kind declaration in the same file — i.e. a `super` call +/// inside it is syntactically guaranteed to have a real `extends` target +/// `resolve_method_via_ancestors`' CHA ancestor walk can verify (issue +/// #2244). False for an object-literal method using dynamic prototype +/// linkage (`Object.setPrototypeOf`, `obj.__proto__ = ...`) — those have no +/// static `extends` clause for CHA to check at all, so the bare/global +/// fallback remains the only signal available and must still apply. +/// Mirrors call-resolver.ts's callerHasRealClassAncestor. +fn caller_has_real_class_ancestor(ctx: &EdgeContext, caller_name: &str, rel_path: &str) -> bool { + let Some(dot_idx) = caller_name.rfind('.') else { + return false; + }; + if dot_idx == 0 { + return false; + } + let caller_class = &caller_name[..dot_idx]; + ctx.nodes_by_name_and_file + .get(&(caller_class, rel_path)) + .is_some_and(|v| { + v.iter() + .any(|n| ctx.receiver_kinds.contains(n.kind.as_str())) + }) +} + /// Core multi-strategy call target resolution — see `resolve_call_targets` for /// the public entry point (which additionally applies constructor attribution). fn resolve_call_targets_core<'a>( @@ -1915,11 +1940,23 @@ fn resolve_call_targets_core<'a>( // invocation, which legitimately targets a class-kind definition — // kind-filtering it would break constructor-call resolution (#1888). // Mirrors resolveCallTargets in call-resolver.ts. - let bare_matches = ctx - .nodes_by_name_and_file - .get(&(call.name.as_str(), rel_path)) - .cloned() - .unwrap_or_default(); + // `super` inside a REAL class is excluded from the bare same-file + // lookup entirely (issue #2244) — a coincidentally same-named same-file + // declaration has no static relationship to the caller's real ancestor + // and must never satisfy super/super.method(); only + // resolve_method_via_ancestors' CHA ancestor walk (run as a post-pass) + // can verify that relationship. See caller_has_real_class_ancestor for + // why this does NOT apply to a non-class caller. + let bare_matches = if call.receiver.as_deref() == Some("super") + && caller_has_real_class_ancestor(ctx, caller_name, rel_path) + { + Vec::new() + } else { + ctx.nodes_by_name_and_file + .get(&(call.name.as_str(), rel_path)) + .cloned() + .unwrap_or_default() + }; let bare_targets: Vec<&NodeInfo> = if call.receiver.is_some() { bare_matches .into_iter() @@ -2194,11 +2231,21 @@ fn resolve_call_targets_core<'a>( return bare_targets; } - // 4. Scoped fallback (this/self/super or no receiver) + // 4. Scoped fallback (this/self, no receiver, or a super call whose + // caller isn't a real class). `super` inside a real class is excluded + // (issue #2244) — mirrors resolveByMethodOrGlobal's early return in + // call-resolver.ts: none of the tiers below (accessor this-dispatch, + // exact-name global match, class-scoped exact lookup) verify any + // relationship to the caller's real ancestor, so they must never + // resolve such a super call — only resolve_method_via_ancestors' CHA + // ancestor walk can. See caller_has_real_class_ancestor for why this + // does NOT apply to a non-class caller (object-literal dynamic + // prototype linkage). if call.receiver.is_none() || call.receiver.as_deref() == Some("this") || call.receiver.as_deref() == Some("self") - || call.receiver.as_deref() == Some("super") + || (call.receiver.as_deref() == Some("super") + && !caller_has_real_class_ancestor(ctx, caller_name, rel_path)) { // Phase 8.3f: accessor this-dispatch via Object.defineProperty. // When a plain function (no class prefix in caller_name) is registered as a get/set diff --git a/src/domain/graph/builder/call-resolver.ts b/src/domain/graph/builder/call-resolver.ts index 1d923c080..d6f4953e4 100644 --- a/src/domain/graph/builder/call-resolver.ts +++ b/src/domain/graph/builder/call-resolver.ts @@ -359,6 +359,28 @@ export function findCaller( * (#1825). `resolveByGlobal` has no receiver-qualifier lookups, so it does * not need it. */ +/** + * True when `callerName`'s class-name prefix is a real class/struct/ + * interface/etc.-kind declaration in the same file — i.e. a `super` call + * inside it is syntactically guaranteed to have a real `extends` target + * `resolveThisDispatch`'s CHA ancestor walk (cha.ts) can verify (issue + * #2244). False for an object-literal method using dynamic prototype + * linkage (`Object.setPrototypeOf`, `obj.__proto__ = ...`) — those have no + * static `extends` clause for CHA to check at all, so the bare/global + * fallback below remains the only signal available and must still apply. + */ +function callerHasRealClassAncestor( + callerName: string | null | undefined, + relPath: string, + lookup: CallNodeLookup, +): boolean { + if (!callerName) return false; + const dotIdx = callerName.lastIndexOf('.'); + if (dotIdx <= 0) return false; + const callerClass = callerName.slice(0, dotIdx); + return lookup.byNameAndFile(callerClass, relPath).some((n) => RECEIVER_KINDS.has(n.kind ?? '')); +} + export function resolveByMethodOrGlobal( lookup: CallNodeLookup, call: { name: string; receiver?: string | null }, @@ -367,6 +389,24 @@ export function resolveByMethodOrGlobal( callerName?: string | null, importedOriginalNames?: ReadonlyMap, ): ReadonlyArray { + // `super`/`super.method()` inside a REAL class is never resolvable by a + // same-name/global lookup (resolveByGlobal): unlike `this`, where a + // same-file or best-confidence same-named declaration is often genuinely + // correct, `super` specifically means "the caller's real ancestor's + // method" — a coincidentally same-named declaration anywhere else has no + // static relationship to that ancestor and must never win. Only + // `resolveThisDispatch`'s CHA-aware ancestor walk (cha.ts, run as a + // post-pass) can verify that relationship, so super is deferred to it + // entirely rather than resolved (possibly wrongly) here (issue #2244). + // + // This does NOT apply when the caller isn't a real class at all (an + // object-literal method linked to its "ancestor" via + // `Object.setPrototypeOf`/`__proto__ =`, jelly-micro's super/super3 + // fixtures) — CHA has no static `extends` clause to walk there, so the + // fallback below is the only heuristic available and must still run. + if (call.receiver === 'super' && callerHasRealClassAncestor(callerName, relPath, lookup)) { + return []; + } if ( call.receiver && call.receiver !== 'this' && @@ -500,7 +540,15 @@ export function resolveCallTargets( // ClassName()` constructor invocation, which legitimately targets a // class-kind definition — kind-filtering it would break constructor-call // resolution (#1888). - const bareMatches = lookup.byNameAndFile(call.name, relPath); + // `super` inside a REAL class is excluded from the bare same-file lookup + // entirely (issue #2244) — see resolveByMethodOrGlobal's matching + // comment for why a coincidentally same-named same-file declaration + // must never satisfy it there, and for why that exclusion does NOT + // apply to a non-class caller (object-literal dynamic prototype linkage). + const bareMatches = + call.receiver === 'super' && callerHasRealClassAncestor(callerName, relPath, lookup) + ? [] + : lookup.byNameAndFile(call.name, relPath); const kindFilteredBare = call.receiver ? bareMatches.filter((n) => CALLABLE_SYMBOL_KINDS.has(n.kind ?? '')) : bareMatches; diff --git a/tests/integration/issue-2244-super-constructor-pseudo-class.test.ts b/tests/integration/issue-2244-super-constructor-pseudo-class.test.ts new file mode 100644 index 000000000..70d582cf0 --- /dev/null +++ b/tests/integration/issue-2244-super-constructor-pseudo-class.test.ts @@ -0,0 +1,132 @@ +/** + * Regression test for #2244: `class D extends A { constructor(y) { + * super(y); } }` where `A` is an ES5-style function-based pseudo-class + * (`function A(x) { ... }`, not an ES6 `class`) caused `resolveCallTargets` + * (`call-resolver.ts`, mirrored by `resolve_call_targets_core` in + * `build_edges.rs`) to fabricate a `calls` edge from `D.constructor` to any + * unrelated same-named `constructor` declaration reachable via the bare + * same-file lookup or the project-wide "exact global match" fallback tier — + * because `A` has no qualified `A.constructor` node for `resolveThisDispatch` + * (cha.ts's CHA ancestor walk) to find, and neither engine's `super` + * resolution excluded coincidental same-name matches the way `this`/`self` + * dispatch legitimately can. + * + * The fix excludes `super` from those non-CHA-aware fallback tiers — but + * ONLY when the caller is inside a REAL class (RECEIVER_KINDS-kind + * declaration), where `super` is syntactically guaranteed to have a real + * `extends` target CHA can verify. An object-literal method using dynamic + * prototype linkage (`Object.setPrototypeOf`, `obj.__proto__ = ...`) has no + * static `extends` clause for CHA to check at all, so the bare/global + * fallback must still apply there (jelly-micro's `super`/`super3` fixtures + * — `resolveThisDispatch` has zero information about the runtime-only + * prototype link `q2 → q1`, so this is the ONLY way `super.m1()` inside + * `q2.m2` ever resolves to `q1.m1`). + */ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import Database from 'better-sqlite3'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { buildGraph } from '../../src/domain/graph/builder.js'; +import type { EngineMode } from '../../src/types.js'; + +const FIXTURE_SOURCE = ` +function A(x) { + this.f = x; +} +A.prototype.speak = function () { + return 'A'; +}; + +class D extends A { + constructor(y) { + super(y); + } +} + +// Unrelated anonymous class with its own bare (unqualified) constructor — +// the exact repro shape that let D.constructor's super(y) fabricate an edge. +const _c3 = class { + constructor() {} + speak() { + return 'anonymous'; + } +}; + +var q1 = { + m1() { + return 'q1.m1'; + }, +}; +var q2 = { + m2() { + super.m1(); + }, +}; +Object.setPrototypeOf(q2, q1); +q2.m2(); +`; + +interface CallEdgeRow { + caller: string; + callee: string; + calleeFile: string; + technique: string | null; +} + +function readCallEdges(dbPath: string): CallEdgeRow[] { + const db = new Database(dbPath, { readonly: true }); + try { + return db + .prepare( + `SELECT n1.name AS caller, n2.name AS callee, n2.file AS calleeFile, e.technique + FROM edges e + JOIN nodes n1 ON e.source_id = n1.id + JOIN nodes n2 ON e.target_id = n2.id + WHERE e.kind = 'calls' + ORDER BY n1.name, n2.name`, + ) + .all() as CallEdgeRow[]; + } finally { + db.close(); + } +} + +const ENGINES: EngineMode[] = ['wasm', 'native']; + +describe.each(ENGINES)( + 'super() dispatch with a function-style pseudo-class (%s, #2244)', + (engine) => { + let tmpDir: string; + let edges: CallEdgeRow[]; + + beforeAll(async () => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), `codegraph-2244-${engine}-`)); + fs.writeFileSync(path.join(tmpDir, 'main.js'), FIXTURE_SOURCE); + await buildGraph(tmpDir, { incremental: false, skipRegistry: true, engine }); + edges = readCallEdges(path.join(tmpDir, '.codegraph', 'graph.db')); + }, 60_000); + + afterAll(() => { + if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true }); + }); + + it('D.constructor -> super(y) does not fabricate an edge to an unrelated same-named constructor', () => { + const wrong = edges.filter((e) => e.caller === 'D.constructor'); + expect( + wrong, + `Expected no calls edges from D.constructor.\nActual edges:\n${JSON.stringify(wrong, null, 2)}`, + ).toEqual([]); + }); + + it('q2.m2 -> super.m1() still resolves to q1.m1 via the dynamic-prototype fallback', () => { + // Object-literal methods extract as bare (unqualified) names — m2/m1, + // not q2.m2/q1.m1 — unlike class methods. + const edge = edges.find((e) => e.caller === 'm2' && e.callee === 'm1'); + expect( + edge, + `Expected m2 -> m1 edge (dynamic Object.setPrototypeOf linkage).\nActual edges:\n${JSON.stringify(edges, null, 2)}`, + ).toBeDefined(); + }); + }, +);