Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.
TypeScript ai-agentsanthropicclaude-codeclicode-graphcodexcontext-engineeringcursordeveloper-toolsgeminiknowledge-graphllmmcpmcp-serveropen-sourceopenaitree-sitter
fix: Java generic type arguments are not supertypes (#104) (#160)
Daniel Oliva26151c9796fd
diff --git a/src/graph/extract.ts b/src/graph/extract.tsindex be6b6a8c..1ef64c0b 100644--- a/src/graph/extract.ts+++ b/src/graph/extract.ts@@ -933,6 +933,7 @@ function heritageEdges(node: Parser.SyntaxNode, classId: string, ctx: WalkCtx):// `superclass` holds `extends X`; `super_interfaces` holds `implements A, B`// (and, on an interface declaration, `extends A, B` — which tree-sitter-java// still spells `extends_interfaces`).+ const typeParams = javaTypeParameterNames(node);for (const child of node.namedChildren) {const relation: Relation | null =child.type === "superclass"@@ -941,8 +942,16 @@ function heritageEdges(node: Parser.SyntaxNode, classId: string, ctx: WalkCtx):? "implements": null;if (!relation) continue;- for (const t of typeIdentifiersIn(child)) {- edges.push({ source: classId, relation, name: t, file: ctx.rel });+ for (const entry of javaSupertypeEntries(child)) {+ const name = javaSupertypeName(entry);+ // Belt-and-braces. A type VARIABLE is never a supertype, and erasing the+ // arguments already removes every case measured on gson and spring-petclinic+ // (identical output with this filter removed) — Java cannot extend or implement+ // a type variable, so a surviving `T` would have to come from a shape neither+ // repo contains. Kept because a wrong supertype is not a cosmetic edge: it+ // feeds `classParents` and from there call resolution.+ if (!name || typeParams.has(name)) continue;+ edges.push({ source: classId, relation, name, file: ctx.rel });}}return edges;@@ -989,15 +998,54 @@ function heritageEdges(node: Parser.SyntaxNode, classId: string, ctx: WalkCtx):return edges;}-/** Every `type_identifier` under a heritage clause, so `implements A, B<C>` yields- * each named type rather than the clause's raw text. */-function typeIdentifiersIn(node: Parser.SyntaxNode): string[] {- const out: string[] = [];+/**+ * The supertypes a heritage clause names, one node each — NOT every `type_identifier`+ * beneath it.+ *+ * `superclass` wraps a single type; `super_interfaces`/`extends_interfaces` wrap a+ * `type_list` of them. Descending blindly instead walked into `type_arguments`, so+ * `implements Comparable<Item>` reported `Item` as a supertype too.+ */+function javaSupertypeEntries(clause: Parser.SyntaxNode): Parser.SyntaxNode[] {+ const list = clause.namedChildren.find((c) => c.type === "type_list");+ return list ? [...list.namedChildren] : [...clause.namedChildren];+}++/**+ * What a supertype entry is CALLED, or null when this pass cannot say.+ *+ * Type arguments are erased, because they are not part of the supertype's identity:+ *+ * Base | Base<Item> -> Base+ *+ * A qualified name is kept WHOLE rather than reduced to its final segment:+ *+ * Outer.Inner | Outer.Inner<K> -> Outer.Inner+ *+ * Heritage keeps an unresolved base as the edge target by design ("usually an+ * external/imported type — keep the name"), so the full string is both truthful and+ * unable to false-match a node id, where a bare `Inner` could collide with an+ * unrelated in-repo type. That differs from construction (#103), which drops a+ * qualified name instead — construction has no keep-the-name contract to fall back on.+ */+function javaSupertypeName(node: Parser.SyntaxNode | null | undefined): string | null {+ if (!node) return null;+ if (node.type === "generic_type") return javaSupertypeName(node.namedChildren[0]);+ if (node.type === "scoped_type_identifier") return node.text;+ return node.type === "type_identifier" ? node.text : null;+}++/** The names a declaration binds as its own type parameters (`class C<T, U>` → T, U),+ * so they can never be mistaken for supertypes. */+function javaTypeParameterNames(decl: Parser.SyntaxNode): ReadonlySet<string> {+ const params = decl.childForFieldName("type_parameters");+ if (!params) return new Set();+ const out = new Set<string>();const visit = (n: Parser.SyntaxNode): void => {- if (n.type === "type_identifier") out.push(n.text);+ if (n.type === "type_identifier") out.add(n.text);for (const c of n.namedChildren) visit(c);};- visit(node);+ visit(params);return out;}diff --git a/src/graph/resolve.ts b/src/graph/resolve.tsindex f0def493..08fb51bf 100644--- a/src/graph/resolve.ts+++ b/src/graph/resolve.ts@@ -259,7 +259,12 @@ function resolveName(globalName: Map<string, NodeV1[]>,): { id: string; confidence: EdgeV1["confidence"] } | null {const local = (perFileName.get(file)?.get(name) ?? []).filter((n) => kinds.includes(n.kind));- if (local.length) return { id: local[0].id, confidence: "extracted" };+ // Same-file requires a UNIQUE match, exactly as the cross-file branch below does.+ // Returning `local[0]` meant a file holding two same-named types (`Alpha.Builder` and+ // `Beta.Builder`, `Alpha.Inner` and `Beta.Inner`) silently resolved to whichever came+ // first in document order — and labelled it `extracted`, i.e. certain. That is the+ // guess this module's header says it does not make.+ if (local.length === 1) return { id: local[0].id, confidence: "extracted" };const global = (globalName.get(name) ?? []).filter((n) => kinds.includes(n.kind));if (global.length === 1) return { id: global[0].id, confidence: "inferred" };return null;diff --git a/test/graph-java.test.ts b/test/graph-java.test.tsindex 87a3bd59..32cc7d49 100644--- a/test/graph-java.test.ts+++ b/test/graph-java.test.ts@@ -919,6 +919,347 @@ test("Java scopes: pom.xml, build.gradle, and build.gradle.kts are project marke}});+/**+ * Heritage fixture. Every supertype here is generic, qualified, or a type variable —+ * the three shapes that a naive walk of the clause turns into bogus supertypes. `Item`+ * carries a method no subclass has, so a wrong `extends` is visible as a wrong CALL:+ * `extends` feeds `classParents`, which `resolveTypedMember` walks up.+ */+const HER_ITEM = `package com.acme;++public class Item {+ public void poison() {}+}+`;++const HER_BASE = `package com.acme;++public class Base<T> {+ public void real() {}+}+`;++const HER_MARKER = `package com.acme;++public interface Marker {}+`;++const HER_OUTER = `package com.acme;++public class Outer {+ public interface Inner {}+}+`;++const HER_CHILD = `package com.acme;++public final class Child extends Base<Item> implements Marker {+ public void use() {+ Child c = new Child();+ c.poison();+ }+}+`;++const HER_HOLDER = `package com.acme;++public class Holder<T> extends Base<T> {}+`;++const HER_IMPL = `package com.acme;++public final class Impl implements Outer.Inner {}+`;++function heritageFixture(): string {+ const dir = mkdtempSync(join(tmpdir(), "graft-java-heritage-"));+ mkdirSync(join(dir, PKG), { recursive: true });+ writeFileSync(join(dir, PKG, "Item.java"), HER_ITEM);+ writeFileSync(join(dir, PKG, "Base.java"), HER_BASE);+ writeFileSync(join(dir, PKG, "Marker.java"), HER_MARKER);+ writeFileSync(join(dir, PKG, "Outer.java"), HER_OUTER);+ writeFileSync(join(dir, PKG, "Child.java"), HER_CHILD);+ writeFileSync(join(dir, PKG, "Holder.java"), HER_HOLDER);+ writeFileSync(join(dir, PKG, "Impl.java"), HER_IMPL);+ return dir;+}++test("Java heritage: a type ARGUMENT is not a supertype", async () => {+ // `implements Comparable<Item>` / `extends Base<Item>` used to walk into+ // `type_arguments` and report `Item` as a supertype of its own accord.+ const dir = heritageFixture();+ try {+ await buildGraph(dir);+ const graph = readGraph(wiringPath(join(dir, "graft")))!;+ const from = `${PKG}/Child.java#Child`;+ const her = graph.edges.filter(+ (e) => (e.relation === "extends" || e.relation === "implements") && e.source === from,+ );++ assert.ok(+ her.some((e) => e.relation === "extends" && e.target === `${PKG}/Base.java#Base`),+ "the named supertype still resolves",+ );+ assert.ok(+ her.some((e) => e.relation === "implements" && e.target === `${PKG}/Marker.java#Marker`),+ "a non-generic interface is unaffected",+ );+ assert.ok(+ !her.some((e) => e.target === `${PKG}/Item.java#Item` || e.target === "Item"),+ "the type argument must not become a supertype",+ );+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});++test("Java heritage: a bogus supertype no longer poisons call resolution", async () => {+ // The reason this outranks a cosmetic heritage fix. `extends` edges populate+ // `classParents`, so `Child extends Item` made `resolveTypedMember` walk `Item` as an+ // ancestor and resolve `c.poison()` — a method that does not compile on a `Child`.+ const dir = heritageFixture();+ try {+ await buildGraph(dir);+ const graph = readGraph(wiringPath(join(dir, "graft")))!;++ assert.ok(+ !graph.edges.some(+ (e) =>+ e.relation === "calls" &&+ e.source === `${PKG}/Child.java#Child.use` &&+ e.target === `${PKG}/Item.java#Item.poison`,+ ),+ "a method reachable only through a bogus ancestor must not resolve",+ );+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});++test("Java heritage: a type VARIABLE is never a supertype", async () => {+ // `class Holder<T> extends Base<T>` names `Base`. A `T` surviving to the edge list is+ // the declaration's own parameter, which erasure alone would not always remove.+ const dir = heritageFixture();+ try {+ await buildGraph(dir);+ const graph = readGraph(wiringPath(join(dir, "graft")))!;+ const from = `${PKG}/Holder.java#Holder`;+ const her = graph.edges.filter(+ (e) => (e.relation === "extends" || e.relation === "implements") && e.source === from,+ );++ assert.deepEqual(+ her.map((e) => e.target),+ [`${PKG}/Base.java#Base`],+ "Holder extends exactly Base — not T",+ );+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});++test("Java heritage: a QUALIFIED supertype keeps its whole name", async () => {+ // Heritage keeps an unresolved base as the edge target by design, so `Outer.Inner`+ // stays whole: truthful, and unable to false-match a bare `Inner` node elsewhere in+ // the repo. (Construction drops a qualified name instead — it has no such contract.)+ const dir = heritageFixture();+ try {+ await buildGraph(dir);+ const graph = readGraph(wiringPath(join(dir, "graft")))!;+ const her = graph.edges.filter(+ (e) => e.relation === "implements" && e.source === `${PKG}/Impl.java#Impl`,+ );++ assert.deepEqual(her.map((e) => e.target), ["Outer.Inner"]);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});++/** Two same-named nested types in ONE file, plus a construction of one of them. Split+ * across files the cross-file ambiguity check already drops it, so a same-file fixture+ * is the only one that can pin the same-file branch. */+const AMBIG = `package com.acme;++public final class Api {++ public static class AlphaB {+ public static class Builder {}+ }++ public static class BetaB {+ public static class Builder {}+ }++ public Object build() {+ return new Builder();+ }+}+`;++test("resolveName: a same-file name matching two nodes resolves to neither", async () => {+ // The same-file branch used to return `local[0]` — first in document order — and+ // label it `extracted`, i.e. certain, while the cross-file branch two lines below+ // required a unique match. A file with `AlphaB.Builder` and `BetaB.Builder` therefore+ // got a silent first-wins guess for a bare `new Builder()`. Language-agnostic: the+ // fixture is Java only because that is where it was found.+ const dir = mkdtempSync(join(tmpdir(), "graft-resolve-ambig-"));+ try {+ mkdirSync(join(dir, PKG), { recursive: true });+ writeFileSync(join(dir, PKG, "Api.java"), AMBIG);++ await buildGraph(dir);+ const graph = readGraph(wiringPath(join(dir, "graft")))!;+ const guesses = graph.edges.filter(+ (e) =>+ e.relation === "calls" &&+ e.source === `${PKG}/Api.java#Api.build` &&+ e.target.includes("Builder"),+ );++ assert.deepEqual(guesses, [], "two candidates in one file must resolve to neither");+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});++/**+ * Receiver fixture. `javaReceiver` recognises three shapes and refuses the rest, and+ * each branch resolves to a DIFFERENT method here, so a mutation that collapses one+ * into another changes which edge is emitted rather than merely losing one.+ *+ * `Repo` and `Helper` both declare `run()` so that picking the wrong receiver picks a+ * visibly wrong target instead of failing to resolve.+ */+const RCV_REPO = `package com.acme;++public final class Repo {+ public void run() {}+}+`;++const RCV_HELPER = `package com.acme;++public final class Helper {+ public void run() {}+}+`;++const RCV_SERVICE = `package com.acme;++public final class Service {++ private final Repo repo;++ public Service(Repo repo) {+ this.repo = repo;+ }++ public void viaField() {+ this.repo.run();+ }++ public void viaLocal() {+ Helper local = new Helper();+ local.run();+ }++ public void viaThis() {+ this.own();+ }++ public void viaChain(Repo[] all) {+ all[0].run();+ }++ public void own() {}+}+`;++function receiverFixture(): string {+ const dir = mkdtempSync(join(tmpdir(), "graft-java-receiver-"));+ mkdirSync(join(dir, PKG), { recursive: true });+ writeFileSync(join(dir, PKG, "Repo.java"), RCV_REPO);+ writeFileSync(join(dir, PKG, "Helper.java"), RCV_HELPER);+ writeFileSync(join(dir, PKG, "Service.java"), RCV_SERVICE);+ return dir;+}++test("Java receivers: `this.field.method()` resolves through the field's declared type", async () => {+ // The `field_access` branch of javaReceiver, which yields `this.repo` and is then+ // normalised to `self.repo` by resolveRecvType to meet the binding written by the+ // field pass. No fixture exercised it before: every receiver test used a bare local.+ const dir = receiverFixture();+ try {+ await buildGraph(dir);+ const graph = readGraph(wiringPath(join(dir, "graft")))!;+ const calls = graph.edges.filter((e) => e.relation === "calls");++ assert.ok(+ calls.some(+ (e) =>+ e.source === `${PKG}/Service.java#Service.viaField` &&+ e.target === `${PKG}/Repo.java#Repo.run`,+ ),+ "this.repo.run() should reach Repo.run",+ );+ assert.ok(+ !calls.some(+ (e) =>+ e.source === `${PKG}/Service.java#Service.viaField` &&+ e.target === `${PKG}/Helper.java#Helper.run`,+ ),+ "and must not reach the other class that also declares run()",+ );+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});++test("Java receivers: an explicit `this.method()` resolves to the enclosing type", async () => {+ // The `this` branch. Distinct from the implicit-this call already covered elsewhere:+ // that one has no `object` node at all and never reaches javaReceiver.+ const dir = receiverFixture();+ try {+ await buildGraph(dir);+ const graph = readGraph(wiringPath(join(dir, "graft")))!;++ assert.ok(+ graph.edges.some(+ (e) =>+ e.relation === "calls" &&+ e.source === `${PKG}/Service.java#Service.viaThis` &&+ e.target === `${PKG}/Service.java#Service.own`,+ ),+ "this.own() should reach Service.own",+ );+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});++test("Java receivers: an unrecognised receiver shape resolves to nothing", async () => {+ // `all[0].run()` is an array_access, none of the three shapes javaReceiver accepts.+ // Pinning the refusal matters more than pinning the acceptances: without it, widening+ // the function to "return something for any object node" would look free, and would+ // start resolving member calls against whatever type happened to match by name.+ const dir = receiverFixture();+ try {+ await buildGraph(dir);+ const graph = readGraph(wiringPath(join(dir, "graft")))!;++ assert.deepEqual(+ graph.edges.filter(+ (e) => e.relation === "calls" && e.source === `${PKG}/Service.java#Service.viaChain`,+ ),+ [],+ "an array-access receiver states no type, so the call must not resolve",+ );+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});+/*** Issue #161: a method inside an anonymous class body (`new Greeter() { … }`)* used to take the enclosing type's `owner`, so `ownerMethod["App.greet"]` held