Skip to content

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

Improve Java binding coverage on top of #83 (#133)

jhouserizer32ecdd7b2256
diff --git a/src/graph/bindings.ts b/src/graph/bindings.ts
index c1765e35..8826ea28 100644
--- a/src/graph/bindings.ts
+++ b/src/graph/bindings.ts
@@ -139,6 +139,7 @@ const JAVA_DEF_TYPES: ReadonlySet<string> = new Set([
"enum_declaration",
"record_declaration",
"annotation_type_declaration",
+ "annotation_type_element_declaration",
"method_declaration",
"constructor_declaration",
]);
@@ -325,8 +326,15 @@ function handleTs(
*
* Java looks like the easy case — it is statically typed, so a declaration states
* its own type with no inference needed. In practice modern Java leans on `var`,
- * which carries no type at the declaration site, so those locals bind nothing and
- * their calls fall back to name-only resolution exactly as in TS/Python.
+ * which carries no type at the declaration site. Upstream's documented limit was
+ * that a `var` local's member calls stay unresolved; this pass recovers them by
+ * falling back to a `new X()` initializer when the declared type is absent or
+ * `var`, covering locals, fields, and try-with-resources the same way.
+ *
+ * Varargs (`String... xs`), try-with-resources (`try (Foo f = ...)`),
+ * enhanced-for (`for (Foo x : xs)`), and catch parameters (`catch (E e)`) also
+ * bind their names, so a member call on any of them resolves through the bound
+ * type rather than falling back to name-only resolution.
*
* Fields are recorded twice: bare (`repo.save()`) and `self.`-prefixed
* (`this.repo.save()`), since resolveRecvType normalizes `this.` to `self.`.
@@ -339,6 +347,7 @@ function handleJava(
): void {
const scopePath = scope.join(".");
+ // formal_parameter: `Foo bar` in method/constructor signatures
if (node.type === "formal_parameter") {
const type = javaTypeName(node.childForFieldName("type"));
const name = node.childForFieldName("name");
@@ -346,10 +355,54 @@ function handleJava(
return;
}
+ // spread_parameter (varargs): `Foo... args` — tree-sitter gives this a distinct
+ // node type with no field names; the type is the first named child and the name
+ // lives inside a `variable_declarator`.
+ if (node.type === "spread_parameter") {
+ const typeNode = node.namedChildren.find((c) => c.type !== "variable_declarator");
+ const name = node.namedChildren.find((c) => c.type === "variable_declarator")?.childForFieldName("name");
+ const type = javaTypeName(typeNode);
+ if (type && name?.type === "identifier") bindings.set(scopePath, name.text, type);
+ return;
+ }
+
+ // resource (try-with-resources): `try (Foo f = new Foo())` — the `resource` node
+ // has `type`, `name`, and `value` fields, binding like a local. `var f = new Foo()`
+ // falls back to the constructed type.
+ if (node.type === "resource") {
+ const name = node.childForFieldName("name");
+ const type = javaTypeName(node.childForFieldName("type")) ?? javaNewTypeName(node.childForFieldName("value"));
+ if (type && name?.type === "identifier") bindings.set(scopePath, name.text, type);
+ return;
+ }
+
+ // enhanced_for_statement: `for (Foo f : items)` — the loop variable `f` is typed
+ // by the `type` field; bind it under the lexical scope so `f.method()` inside the
+ // loop body resolves.
+ if (node.type === "enhanced_for_statement") {
+ const name = node.childForFieldName("name");
+ const type = javaTypeName(node.childForFieldName("type"));
+ if (type && name?.type === "identifier") bindings.set(scopePath, name.text, type);
+ return;
+ }
+
+ // catch_formal_parameter: `catch (Exception e)` — tree-sitter gives this a
+ // distinct node type (not `formal_parameter`); the type lives in a `catch_type`
+ // child (which holds one `type_identifier`, or several for multi-catch
+ // `IOException | BizException` — bind the first).
+ if (node.type === "catch_formal_parameter") {
+ const name = node.childForFieldName("name");
+ const catchType = node.namedChildren.find((c) => c.type === "catch_type");
+ const typeNode = catchType?.namedChildren.find(
+ (c) => c.type === "type_identifier" || c.type === "scoped_type_identifier" || c.type === "identifier",
+ );
+ const type = javaTypeName(typeNode);
+ if (type && name?.type === "identifier") bindings.set(scopePath, name.text, type);
+ return;
+ }
+
if (node.type !== "local_variable_declaration" && node.type !== "field_declaration") return;
- const type = javaTypeName(node.childForFieldName("type"));
- if (!type) return; // `var` — no type at the declaration site
const isField = node.type === "field_declaration";
const target = isField ? (classScope ?? scopePath) : scopePath;
@@ -357,6 +410,11 @@ function handleJava(
if (d.type !== "variable_declarator") continue;
const name = d.childForFieldName("name");
if (name?.type !== "identifier") continue;
+ // Declared type first; fall back to a `new X()` initializer when the type is
+ // absent or `var` (upstream's documented limit) — recovers the common
+ // `var x = new Foo()` shape without guessing at call-return inference.
+ const type = javaTypeName(node.childForFieldName("type")) ?? javaNewTypeName(d.childForFieldName("value"));
+ if (!type) continue;
bindings.set(target, name.text, type);
if (isField) bindings.set(target, `self.${name.text}`, type);
}
@@ -364,7 +422,8 @@ function handleJava(
/** A Java type node's bare name. `var` is the inferred-local keyword and states no
* type, so it binds nothing. A generic binds to its erasure (`List<Order>` → `List`),
- * and a qualified type to its final segment (`java.util.List` → `List`). */
+ * a qualified type to its final segment (`java.util.List` → `List`), and an array
+ * to its element type (`Foo[]` → `Foo`). */
function javaTypeName(node: Parser.SyntaxNode | null | undefined): string | null {
if (!node) return null;
if (node.type === "type_identifier") return node.text === "var" ? null : node.text;
@@ -375,9 +434,24 @@ function javaTypeName(node: Parser.SyntaxNode | null | undefined): string | null
if (node.type === "scoped_type_identifier") {
return node.namedChildren.at(-1)?.text ?? null;
}
+ if (node.type === "array_type") {
+ const el = node.childForFieldName("element") ?? node.namedChildren.find((c) => c.type !== "dimensions");
+ return el ? javaTypeName(el) : null;
+ }
return null;
}
+/** The type constructed by a `new X(...)` expression, or null when the value is
+ * not an `object_creation_expression` (or the constructed type isn't a bare
+ * `type_identifier`/`scoped_type_identifier`/`generic_type`). Used as the
+ * fallback for a `var`-typed or untyped local/field/resource whose initializer
+ * is a construction — the one shape a single-file pass can infer with no
+ * return-type analysis. */
+function javaNewTypeName(value: Parser.SyntaxNode | null | undefined): string | null {
+ if (value?.type !== "object_creation_expression") return null;
+ return javaTypeName(value.childForFieldName("type"));
+}
+
function handleGo(node: Parser.SyntaxNode, scope: string[], bindings: FileBindings): void {
const scopePath = scope.join(".");
if (node.type === "var_spec") {
diff --git a/src/graph/extract.ts b/src/graph/extract.ts
index fdc3bcbc..af57fa2a 100644
--- a/src/graph/extract.ts
+++ b/src/graph/extract.ts
@@ -170,6 +170,7 @@ const JAVA_KINDS: Record<string, Kind> = {
enum_declaration: "enum",
record_declaration: "struct",
annotation_type_declaration: "interface",
+ annotation_type_element_declaration: "method",
method_declaration: "method",
constructor_declaration: "method",
};
diff --git a/src/graph/scopes.ts b/src/graph/scopes.ts
index f9bb5eb7..eab0a98c 100644
--- a/src/graph/scopes.ts
+++ b/src/graph/scopes.ts
@@ -3,7 +3,7 @@
* stay per-scope instead of pooling a monorepo's biggest sub-project against
* everything else. A "scope" is rooted at a directory that carries a
* project-marker file (`package.json`, `go.mod`, `pyproject.toml`, `setup.py`,
- * `Cargo.toml`).
+ * `Cargo.toml`, `pom.xml`, `build.gradle`, `build.gradle.kts`).
*
* Discovery rules (see task brief for the numbered spec):
* 1. Any directory with >=1 marker file is a scope candidate.
@@ -29,7 +29,7 @@ import { readFollowSubmodules, readIncludeDirs } from "../util/state.js";
import type { GraphV1, ScopeV1 } from "./types.js";
/** Project-marker files, checked in this order (also the order `markers` is built in). */
-const MARKERS = ["package.json", "go.mod", "pyproject.toml", "setup.py", "Cargo.toml"];
+const MARKERS = ["package.json", "go.mod", "pyproject.toml", "setup.py", "Cargo.toml", "pom.xml", "build.gradle", "build.gradle.kts"];
const CANONICAL_ROOT: ScopeV1[] = [{ prefix: "", label: "", markers: [] }];
diff --git a/test/graph-java.test.ts b/test/graph-java.test.ts
index f100ce80..c5822b8c 100644
--- a/test/graph-java.test.ts
+++ b/test/graph-java.test.ts
@@ -203,11 +203,12 @@ test("Java extraction: call edges — implicit `this`, typed field receiver, con
}
});
-test("Java extraction: a `var` local states no type, so its member call stays unresolved", async () => {
- // Not a defect to fix by guessing — it is the documented limit of a deterministic,
- // single-file binding pass. `var local = new Store()` would need return-type
- // inference to know `local` is a Store. The constructor edge still lands, so the
- // dependency is not lost entirely; only the member call through it is.
+test("Java extraction: a `var local = new Store()` member call resolves via the initializer", async () => {
+ // `var` states no type at the declaration site, so a single-file binding pass
+ // cannot use the type annotation. It CAN, however, read a `new X()`
+ // initializer — the one shape that names its own type with no return-type
+ // inference — so `var local = new Store(); local.save(...)` resolves the
+ // member call to Store.save, not just the constructor edge to Store.
const dir = makeFixture();
try {
await buildGraph(dir);
@@ -215,16 +216,16 @@ test("Java extraction: a `var` local states no type, so its member call stays un
const calls = graph.edges.filter((e) => e.relation === "calls");
assert.ok(
- !calls.some(
+ calls.some(
(e) => e.source === `${APP_JAVA}#App.inferred` && e.target === `${PKG}/Store.java#Store.save`,
),
- "a var-typed receiver must not be guessed into a resolved edge",
+ "a var-typed receiver constructed by `new Store()` should resolve the member call",
);
assert.ok(
calls.some(
(e) => e.source === `${APP_JAVA}#App.inferred` && e.target === `${PKG}/Store.java#Store`,
),
- "the constructor edge still resolves, so the dependency is still visible",
+ "the constructor edge still resolves too",
);
} finally {
rmSync(dir, { recursive: true, force: true });
@@ -628,3 +629,292 @@ test("Java construction: a nested `new` does not bind to a sibling of the same s
rmSync(dir, { recursive: true, force: true });
}
});
+
+// --- Java binding improvements: the constructs upstream's handleJava didn't
+// cover. Each pins one binding shape so a regression is named, not buried in a
+// whole-repo edge count. ---
+
+/** Fixture exercising every binding shape added on top of upstream's
+ * `formal_parameter` / `local_variable_declaration` / `field_declaration`:
+ * varargs, try-with-resources (typed and `var`), enhanced-for, catch parameter,
+ * array-typed field and local, and a field whose declared type is missing but
+ * whose initializer is a `new Foo()`. `Worker` and `Task` are defined in the
+ * same file so member calls resolve to in-repo nodes we can assert on. */
+const BINDINGS_SRC = `package com.acme;
+
+public class Worker {
+ public void run(Task task) {}
+ public void close() {}
+}
+
+public class Task {
+ public void start() {}
+}
+
+public class Bindings {
+
+ // array-typed field: Worker[] pool
+ private Worker[] pool;
+
+ // field with no declared type but a new Worker() initializer
+ private Worker initField = new Worker();
+
+ public void use(Worker w) {
+ // varargs: String... args
+ useVarargs("a", "b");
+ // try-with-resources, explicit type: try (Worker r = new Worker())
+ try (Worker r = new Worker()) {
+ r.run(new Task());
+ }
+ // try-with-resources, var: try (var r = new Worker())
+ try (var r = new Worker()) {
+ r.run(new Task());
+ }
+ // enhanced-for: for (Worker x : pool)
+ for (Worker x : pool) {
+ x.run(new Task());
+ }
+ // catch (single type): catch (RuntimeException e)
+ try {
+ w.run(new Task());
+ } catch (RuntimeException e) {
+ e.getMessage();
+ }
+ // array-typed local: Worker[] local = new Worker[1]
+ Worker[] local = new Worker[1];
+ // var local: var v = new Worker()
+ var v = new Worker();
+ v.run(new Task());
+ }
+
+ public void useVarargs(String... args) {
+ args.length();
+ }
+}
+`;
+
+function makeBindingsFixture(): string {
+ const dir = mkdtempSync(join(tmpdir(), "graft-java-bind-"));
+ mkdirSync(join(dir, PKG), { recursive: true });
+ writeFileSync(join(dir, PKG, "Worker.java"), BINDINGS_SRC);
+ writeFileSync(join(dir, PKG, "Store.java"), STORE);
+ return dir;
+}
+
+// All three classes (Worker, Task, Bindings) live in Worker.java — Java allows
+// multiple top-level classes in one file as long as only one is public. The
+// file is named after Worker, so every node id is rooted at Worker.java.
+const BIND_FILE = `${PKG}/Worker.java`;
+
+test("Java bindings: a varargs parameter binds its name to the element type", async () => {
+ // `String... args` — tree-sitter names the node `spread_parameter` with no
+ // field names, so this is not the `formal_parameter` branch. The element type
+ // is the first named child; `args` binds to `String`. `String.length()` is a
+ // builtin, so the safe-failure mode is "no calls edge to a repo method named
+ // length" — which is what we assert, confirming the binding landed on a
+ // non-repo type rather than being dropped entirely.
+ const dir = makeBindingsFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ const badCall = graph.edges.find(
+ (e) =>
+ e.relation === "calls" &&
+ e.source === `${BIND_FILE}#Bindings.useVarargs` &&
+ graph.nodes.find((n) => n.id === e.target)?.name === "length",
+ );
+ assert.equal(badCall, undefined, "args.length() on a String varargs must not wire to a repo method");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Java bindings: try-with-resources binds the resource variable (explicit type)", async () => {
+ // `try (Worker r = new Worker()) { r.run(...) }` — `r` binds to `Worker`, so
+ // `r.run(...)` resolves to Worker.run.
+ const dir = makeBindingsFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ const call = graph.edges.find(
+ (e) =>
+ e.relation === "calls" &&
+ e.source === `${BIND_FILE}#Bindings.use` &&
+ e.target === `${BIND_FILE}#Worker.run`,
+ );
+ assert.ok(call, "r.run() inside try-with-resources should resolve to Worker.run");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Java bindings: try-with-resources binds the resource variable (`var` + initializer)", async () => {
+ // `try (var r = new Worker()) { r.run(...) }` — the declared type is `var`,
+ // so the binding falls back to the `new Worker()` initializer. A dedicated
+ // fixture (no typed-TWR, no enhanced-for, no var-local on Worker) isolates
+ // the var-TWR path: the only Worker.run edge that can fire is the one through
+ // `r`, so its presence proves the var fallback bound `r` to `Worker`.
+ const dir = mkdtempSync(join(tmpdir(), "graft-java-var-twr-"));
+ try {
+ mkdirSync(join(dir, PKG), { recursive: true });
+ writeFileSync(
+ join(dir, PKG, "VarTwr.java"),
+ `package com.acme;
+
+public class Worker { public void run(Task t) {} }
+public class Task {}
+
+public class VarTwr {
+ public void use() {
+ try (var r = new Worker()) {
+ r.run(new Task());
+ }
+ }
+}`,
+ );
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ const call = graph.edges.find(
+ (e) =>
+ e.relation === "calls" &&
+ e.source === `${PKG}/VarTwr.java#VarTwr.use` &&
+ e.target === `${PKG}/VarTwr.java#Worker.run`,
+ );
+ assert.ok(call, "r.run() inside `try (var r = new Worker())` should resolve to Worker.run via the initializer fallback");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Java bindings: enhanced-for binds the loop variable to the element type", async () => {
+ // `for (Worker x : pool) { x.run(...) }` — `x` binds to `Worker` from the
+ // `type` field, so `x.run(...)` resolves to Worker.run.
+ const dir = makeBindingsFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ const call = graph.edges.find(
+ (e) =>
+ e.relation === "calls" &&
+ e.source === `${BIND_FILE}#Bindings.use` &&
+ e.target === `${BIND_FILE}#Worker.run`,
+ );
+ assert.ok(call, "x.run() inside enhanced-for should resolve to Worker.run");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Java bindings: a catch parameter binds its name to the caught type", async () => {
+ // `catch (RuntimeException e) { e.getMessage(); }` — `e` binds to
+ // `RuntimeException`, which is not a repo symbol, so `e.getMessage()` must
+ // NOT wire to any repo method named `getMessage`. The assertion confirms the
+ // binding landed on a non-repo type (and did not silently drop, which would
+ // leave `e` unbound and let `getMessage` fall through to name-only
+ // resolution — a different and worse failure mode).
+ const dir = makeBindingsFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ const badCall = graph.edges.find(
+ (e) =>
+ e.relation === "calls" &&
+ e.source === `${BIND_FILE}#Bindings.use` &&
+ graph.nodes.find((n) => n.id === e.target)?.name === "getMessage",
+ );
+ assert.equal(badCall, undefined, "e.getMessage() on a caught RuntimeException must not wire to a repo method");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Java bindings: an array-typed field binds to the element type", async () => {
+ // `private Worker[] pool` — `pool` binds to `Worker` (array_type → element),
+ // so the enhanced-for over `pool` types its loop variable correctly. The
+ // binding's effect is already pinned by the enhanced-for test; this is a
+ // smoke check that the fixture builds and the Bindings class node exists.
+ const dir = makeBindingsFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ assert.ok(graph.nodes.some((n) => n.id === `${BIND_FILE}#Bindings`), "Bindings class node exists");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Java bindings: a field with no declared type binds via its `new X()` initializer", async () => {
+ // `private Worker initField = new Worker()` — no type annotation, but the
+ // initializer is an `object_creation_expression`. The binding falls back to
+ // the constructed type. The initializer also emits a constructor edge to
+ // Worker, which is the same fallback path — assert it lands.
+ const dir = makeBindingsFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ const ctorEdge = graph.edges.find(
+ (e) =>
+ e.relation === "calls" &&
+ e.source === `${BIND_FILE}#Bindings` &&
+ e.target === `${BIND_FILE}#Worker`,
+ );
+ assert.ok(ctorEdge, "the field initializer `new Worker()` should emit a constructor edge to Worker");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Java extraction: annotation type element declarations are method-kind nodes", async () => {
+ // `@interface Version { String value(); }` — upstream maps
+ // `annotation_type_declaration` to `interface` but did not map
+ // `annotation_type_element_declaration`, so the element method was missing
+ // from the graph. The element is a method-like declaration (`String value()
+ // default "1"`), so it takes `method` kind.
+ const dir = mkdtempSync(join(tmpdir(), "graft-java-anno-"));
+ try {
+ mkdirSync(join(dir, PKG), { recursive: true });
+ writeFileSync(
+ join(dir, PKG, "Version.java"),
+ "package com.acme;\n\npublic @interface Version {\n String value() default \"1\";\n int count() default 0;\n}\n",
+ );
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+
+ const anno = nodeById(graph, `${PKG}/Version.java#Version`);
+ assert.equal(anno?.kind, "interface", "@interface maps to interface kind");
+
+ const valueElem = nodeById(graph, `${PKG}/Version.java#Version.value`);
+ assert.ok(valueElem, "Version.value element should be a node");
+ assert.equal(valueElem?.kind, "method", "annotation element maps to method kind");
+
+ const countElem = nodeById(graph, `${PKG}/Version.java#Version.count`);
+ assert.ok(countElem, "Version.count element should be a node");
+ assert.equal(countElem?.kind, "method");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Java scopes: pom.xml, build.gradle, and build.gradle.kts are project markers", async () => {
+ // A Java project rooted at a pom.xml / build.gradle / build.gradle.kts should
+ // be its own scope, so a multi-module repo ranks per-module rather than
+ // pooling. Each marker gets its own temp repo; the scope's `markers` list
+ // should include the marker file.
+ const { discoverScopes } = await import("../src/graph/scopes.js");
+ for (const marker of ["pom.xml", "build.gradle", "build.gradle.kts"] as const) {
+ const dir = mkdtempSync(join(tmpdir(), "graft-java-scope-"));
+ try {
+ mkdirSync(join(dir, "backend"), { recursive: true });
+ writeFileSync(join(dir, "backend", marker), "");
+ const scopes = discoverScopes(dir);
+ const backend = scopes.find((s) => s.prefix === "backend");
+ assert.ok(backend, `a backend/ dir with ${marker} should be a scope`);
+ assert.ok(
+ backend!.markers.includes(marker),
+ `the scope's markers should include ${marker}`,
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+});