Skip to content

Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.

fix: disambiguate Java overloads by arity

Daniel226fbd66c9e9
diff --git a/src/graph/extract.ts b/src/graph/extract.ts
index 1d84ce29..a1bf3d66 100644
--- a/src/graph/extract.ts
+++ b/src/graph/extract.ts
@@ -82,6 +82,11 @@ export interface RawEdge {
/** calls with viaMember: the receiver's resolved type name (from bindings /
* self / this / Go receiver), when a confident local clue exists. */
recvType?: string;
+ /** calls: the number of arguments at the CALL SITE. Only emitted for languages
+ * with overloading (Java), where a same-named sibling on the same class is
+ * otherwise indistinguishable — and picking wrong turns a delegating overload
+ * into a self-loop. */
+ argCount?: number;
}
export interface ExtractResult {
@@ -228,6 +233,8 @@ interface DefDescriptor {
kind: Kind;
headerEnd: number; // char index where the signature ends (body starts)
hashNode: Parser.SyntaxNode; // node whose text forms body_hash / span
+ arity?: number; // declared parameter count — overload disambiguation (Java)
+ variadic?: boolean; // last parameter is a vararg, so `arity` is a minimum
}
/** tree-sitter's string `parse()` fails with "Invalid argument" on any input
@@ -343,6 +350,8 @@ function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEd
summary: null,
crux: null,
...(owner !== undefined ? { owner } : {}),
+ ...(desc.arity !== undefined ? { arity: desc.arity } : {}),
+ ...(desc.variadic ? { variadic: true } : {}),
});
// structural containment
edges.push({ source: ctx.parentId, relation: "contains", targetId: id, file: ctx.rel });
@@ -385,6 +394,9 @@ function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEd
viaMember: callee.viaMember,
file: ctx.rel,
};
+ // Java only: the call site's argument count, to pick the right overload.
+ const argCount = ctx.lang === "java" ? javaArgCount(node) : undefined;
+ if (argCount !== undefined) callEdge.argCount = argCount;
const recvType = resolveRecvType(callee.receiver, ctx);
edges.push(recvType ? { ...callEdge, recvType } : callEdge);
}
@@ -602,7 +614,25 @@ function describeJava(node: Parser.SyntaxNode, ctx: WalkCtx): DefDescriptor | nu
const name = node.childForFieldName("name")?.text;
if (!name) return null;
const body = node.childForFieldName("body");
- return { name, kind: mapped, headerEnd: body ? body.startIndex : node.endIndex, hashNode: node };
+ const desc: DefDescriptor = {
+ name,
+ kind: mapped,
+ headerEnd: body ? body.startIndex : node.endIndex,
+ hashNode: node,
+ };
+ // Only callables carry arity. A record declaration also has a `parameters` node,
+ // but its components are not an overload set and must never be filtered against.
+ if (node.type === "method_declaration" || node.type === "constructor_declaration") {
+ const params = node.childForFieldName("parameters");
+ if (params) {
+ const declared = params.namedChildren.filter(
+ (c) => c.type === "formal_parameter" || c.type === "spread_parameter",
+ );
+ desc.arity = declared.length;
+ if (declared.some((c) => c.type === "spread_parameter")) desc.variadic = true;
+ }
+ }
+ return desc;
}
/** Java visibility: `public` (or `protected`) on the declaration's own modifier list.
@@ -738,6 +768,15 @@ function calleeName(
return null;
}
+/** The number of arguments at a Java call site (`method_invocation` or
+ * `object_creation_expression`), read off the `arguments` list. Undefined when the
+ * list is absent, which keeps resolution at its previous name-only behavior rather
+ * than filtering on a count we never established. */
+function javaArgCount(node: Parser.SyntaxNode): number | undefined {
+ const args = node.childForFieldName("arguments");
+ return args ? args.namedChildren.length : undefined;
+}
+
/** A Java call's receiver text: a bare identifier (`repo.save()`), `this`, or
* `this.x` for a field access (`this.repo.save()`). A chained call or a qualified
* static reference yields none — there is no confident local clue to bind. */
diff --git a/src/graph/resolve.ts b/src/graph/resolve.ts
index 43b5812d..4002ddb2 100644
--- a/src/graph/resolve.ts
+++ b/src/graph/resolve.ts
@@ -127,7 +127,7 @@ export function resolveEdges(
} else if (e.relation === "calls") {
if (e.viaMember) {
if (!e.recvType) continue;
- const hit = resolveTypedMember(e.recvType, e.name!, e.file, ownerMethod, classParents);
+ const hit = resolveTypedMember(e.recvType, e.name!, e.file, ownerMethod, classParents, e.argCount);
if (hit === "ambiguous") continue; // drop — never guess past an ambiguous owner
if (hit) add(e.source, hit.id, "calls", hit.confidence);
// No owner-qualified match means the call is unresolved. A unique bare
@@ -185,20 +185,45 @@ function resolveName(
* - `null` — the whole chain (recvType + ancestors, breadth-first, depth ≤ 3,
* cycle-guarded) had zero candidates at every level.
*/
+/**
+ * Narrow an overload set to the candidates a call of `argCount` arguments could
+ * reach. Only Java emits `argCount`/`arity`, so for every other language this is
+ * the identity function and resolution is byte-for-byte what it was.
+ *
+ * Deliberately conservative in both directions:
+ * - A variadic candidate (`String... xs`) accepts anything from `arity - 1`
+ * upward, so it is never filtered out by count.
+ * - A candidate with no recorded arity (a graph built before this field) is
+ * kept, since absence of data is not evidence of a mismatch.
+ * - If narrowing leaves nothing, the ORIGINAL set is returned. An empty result
+ * would silently drop a real edge; handing the full set back lets the existing
+ * same-file / "ambiguous" logic make the call exactly as before.
+ */
+function narrowByArity(candidates: NodeV1[], argCount?: number): NodeV1[] {
+ if (argCount === undefined || candidates.length < 2) return candidates;
+ const fits = candidates.filter((c) => {
+ if (c.arity === undefined) return true;
+ return c.variadic ? argCount >= c.arity - 1 : c.arity === argCount;
+ });
+ return fits.length > 0 ? fits : candidates;
+}
+
function resolveTypedMember(
recvType: string,
name: string,
file: string,
ownerMethod: Map<string, NodeV1[]>,
classParents: Map<string, string[]>,
+ argCount?: number,
): { id: string; confidence: EdgeV1["confidence"] } | "ambiguous" | null {
const MAX_DEPTH = 3;
const visited = new Set<string>([recvType]);
let frontier = [recvType];
for (let depth = 0; depth <= MAX_DEPTH && frontier.length; depth++) {
for (const type of frontier) {
- const candidates = ownerMethod.get(`${type}.${name}`);
- if (!candidates || candidates.length === 0) continue; // try next ancestor
+ const all = ownerMethod.get(`${type}.${name}`);
+ if (!all || all.length === 0) continue; // try next ancestor
+ const candidates = narrowByArity(all, argCount);
if (candidates.length === 1) {
const c = candidates[0];
return { id: c.id, confidence: c.path === file ? "extracted" : "inferred" };
diff --git a/src/graph/types.ts b/src/graph/types.ts
index 2d8c8f17..bb580b60 100644
--- a/src/graph/types.ts
+++ b/src/graph/types.ts
@@ -60,6 +60,14 @@ export interface NodeV1 {
// the code — not just the name/signature — is findable; never
// emitted to the agent (that reads verbatim source via `--source`).
// Absent on file nodes and on graphs built before this field.
+ arity?: number; // declared parameter count (method/constructor nodes). Disambiguates
+ // OVERLOADS, which only Java has among the languages parsed here: two
+ // same-named methods on one class are otherwise separable only by
+ // arity, and picking the wrong one turns a delegating overload into a
+ // self-loop. Absent on graphs built before this field, and on
+ // languages that do not emit it — resolution then behaves as before.
+ variadic?: boolean; // the last parameter is a vararg (`String... xs`), so the declared
+ // arity is a MINIMUM, not an equality. Never arity-filtered out.
// meaning (Tier-2, one LLM call)
summary_state: SummaryState;
diff --git a/test/graph-java.test.ts b/test/graph-java.test.ts
index c5b88806..f7bbfd56 100644
--- a/test/graph-java.test.ts
+++ b/test/graph-java.test.ts
@@ -347,3 +347,110 @@ test("Java extraction: an ambiguous package suffix stays unresolved rather than
rmSync(dir, { recursive: true, force: true });
}
});
+
+/** Overload fixture: a 2-arg convenience method delegating to the 3-arg one — the
+ * commonest shape in Java, and the one that produced a self-loop before arity was
+ * recorded. `log` adds a variadic pair; `render` a same-arity pair. */
+const OVERLOADS = `package com.acme;
+
+public final class Svc {
+
+ public String join(String left, String right) {
+ return join(left, right, "-");
+ }
+
+ public String join(String left, String right, String separator) {
+ return left + separator + right;
+ }
+
+ public void log(String msg) {
+ log(msg, "a", "b");
+ }
+
+ public void log(String msg, String... rest) {}
+
+ public String render(String s) {
+ return render(s.length());
+ }
+
+ public String render(int n) {
+ return String.valueOf(n);
+ }
+}
+`;
+
+function overloadFixture(): string {
+ const dir = mkdtempSync(join(tmpdir(), "graft-java-overload-"));
+ mkdirSync(join(dir, PKG), { recursive: true });
+ writeFileSync(join(dir, PKG, "Svc.java"), OVERLOADS);
+ return dir;
+}
+
+test("Java overloads: a delegating call resolves to the other overload, not itself", async () => {
+ // Before arity was recorded, both `join` nodes were candidates, the same-file
+ // tiebreak picked the first, and the 2-arg method got a `calls` edge to ITSELF —
+ // marked `extracted`, i.e. confidently wrong. Overloading exists in none of the
+ // other languages graft parses, so no existing fixture could have caught this.
+ const dir = overloadFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ const svc = `${PKG}/Svc.java`;
+ const calls = graph.edges.filter((e) => e.relation === "calls");
+
+ assert.ok(
+ calls.some((e) => e.source === `${svc}#Svc.join` && e.target === `${svc}#Svc.join~2`),
+ "the 2-arg join should call the 3-arg overload",
+ );
+ assert.ok(
+ !calls.some((e) => e.source === `${svc}#Svc.join` && e.target === `${svc}#Svc.join`),
+ "and must not call itself",
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Java overloads: a variadic candidate is never filtered out by argument count", async () => {
+ // `log(String, String...)` has arity 2 but accepts 1..n arguments. Filtering on
+ // equality would exclude it from a 3-argument call and drop a real edge.
+ const dir = overloadFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ const svc = `${PKG}/Svc.java`;
+
+ const variadic = graph.nodes.find((n) => n.id === `${svc}#Svc.log~2`);
+ assert.equal(variadic?.arity, 2, "declared arity counts the vararg parameter");
+ assert.equal(variadic?.variadic, true, "and it is flagged variadic");
+
+ assert.ok(
+ graph.edges.some(
+ (e) => e.relation === "calls" && e.source === `${svc}#Svc.log` && e.target === `${svc}#Svc.log~2`,
+ ),
+ "a 3-argument call should still reach the variadic overload",
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Java overloads: same-arity overloads stay unresolved rather than guessing", async () => {
+ // `render(String)` and `render(int)` both have arity 1 — they differ only by
+ // parameter TYPE, which this pass does not model. The documented limit: narrowing
+ // cannot separate them, so the same-file tiebreak applies and no type-based guess
+ // is made. Pinned so a future type-aware change is a deliberate one.
+ const dir = overloadFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ const svc = `${PKG}/Svc.java`;
+
+ const a = graph.nodes.find((n) => n.id === `${svc}#Svc.render`);
+ const b = graph.nodes.find((n) => n.id === `${svc}#Svc.render~2`);
+ assert.equal(a?.arity, 1);
+ assert.equal(b?.arity, 1, "both render overloads have arity 1, so count cannot separate them");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});