Skip to content

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

feat: Java language support (tree-sitter-java)

Daniel4fd533044b04
diff --git a/package-lock.json b/package-lock.json
index 4cada95d..5f9d55b0 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -17,6 +17,7 @@
"openai": "^6.45.0",
"tree-sitter": "^0.21.1",
"tree-sitter-go": "^0.23.4",
+ "tree-sitter-java": "^0.23.5",
"tree-sitter-python": "^0.21.0",
"tree-sitter-typescript": "^0.23.2"
},
@@ -870,6 +871,25 @@
}
}
},
+ "node_modules/tree-sitter-java": {
+ "version": "0.23.5",
+ "resolved": "https://registry.npmjs.org/tree-sitter-java/-/tree-sitter-java-0.23.5.tgz",
+ "integrity": "sha512-Yju7oQ0Xx7GcUT01mUglPP+bYfvqjNCGdxqigTnew9nLGoII42PNVP3bHrYeMxswiCRM0yubWmN5qk+zsg0zMA==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "dependencies": {
+ "node-addon-api": "^8.2.2",
+ "node-gyp-build": "^4.8.2"
+ },
+ "peerDependencies": {
+ "tree-sitter": "^0.21.1"
+ },
+ "peerDependenciesMeta": {
+ "tree-sitter": {
+ "optional": true
+ }
+ }
+ },
"node_modules/tree-sitter-javascript": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/tree-sitter-javascript/-/tree-sitter-javascript-0.23.1.tgz",
diff --git a/package.json b/package.json
index a5328e98..02565a52 100644
--- a/package.json
+++ b/package.json
@@ -62,6 +62,7 @@
"openai": "^6.45.0",
"tree-sitter": "^0.21.1",
"tree-sitter-go": "^0.23.4",
+ "tree-sitter-java": "^0.23.5",
"tree-sitter-python": "^0.21.0",
"tree-sitter-typescript": "^0.23.2"
},
@@ -72,5 +73,13 @@
"esbuild": "^0.28.1",
"tsx": "^4.22.4",
"typescript": "^6.0.3"
+ },
+ "allowScripts": {
}
}
diff --git a/src/graph/bindings.ts b/src/graph/bindings.ts
index 07e9f1e8..017fb7fd 100644
--- a/src/graph/bindings.ts
+++ b/src/graph/bindings.ts
@@ -43,6 +43,9 @@ const FN_VALUE_TYPES = new Set(["arrow_function", "function", "function_expressi
* same scope key extract.ts's walk will look it up with), or null if `node`
* isn't a definition. */
export function defName(node: Parser.SyntaxNode, lang: Language): string | null {
+ if (lang === "java") {
+ return JAVA_DEF_TYPES.has(node.type) ? (node.childForFieldName("name")?.text ?? null) : null;
+ }
if (lang === "go") {
if (node.type === "method_declaration") {
const name = node.childForFieldName("name")?.text;
@@ -122,12 +125,33 @@ export function resolveRecvType(
function isClassNode(node: Parser.SyntaxNode, lang: Language): boolean {
if (lang === "python") return node.type === "class_definition";
+ if (lang === "java") return JAVA_TYPE_DECLS.has(node.type);
if (lang === "typescript" || lang === "tsx") {
return node.type === "class_declaration" || node.type === "abstract_class_declaration";
}
return false;
}
+/** Java declarations that push a scope segment — mirrors extract.ts's JAVA_KINDS. */
+const JAVA_DEF_TYPES: ReadonlySet<string> = new Set([
+ "class_declaration",
+ "interface_declaration",
+ "enum_declaration",
+ "record_declaration",
+ "annotation_type_declaration",
+ "method_declaration",
+ "constructor_declaration",
+]);
+
+/** The subset of the above that owns `this.field` bindings. */
+const JAVA_TYPE_DECLS: ReadonlySet<string> = new Set([
+ "class_declaration",
+ "interface_declaration",
+ "enum_declaration",
+ "record_declaration",
+ "annotation_type_declaration",
+]);
+
/** Pass 1 over a parsed file: collect variable->type bindings. Pure. */
export function collectBindings(root: Parser.SyntaxNode, lang: Language): FileBindings {
const bindings = new FileBindings();
@@ -169,6 +193,7 @@ function visit(
): void {
if (lang === "python") handlePy(node, scope, classScope, bindings, aliases);
else if (lang === "go") handleGo(node, scope, bindings);
+ else if (lang === "java") handleJava(node, scope, classScope, bindings);
else handleTs(node, scope, classScope, bindings, aliases);
const name = defName(node, lang);
@@ -284,6 +309,64 @@ function handleTs(
}
}
+/**
+ * Java bindings: locals, parameters, and fields.
+ *
+ * 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.
+ *
+ * Fields are recorded twice: bare (`repo.save()`) and `self.`-prefixed
+ * (`this.repo.save()`), since resolveRecvType normalizes `this.` to `self.`.
+ */
+function handleJava(
+ node: Parser.SyntaxNode,
+ scope: string[],
+ classScope: string | null,
+ bindings: FileBindings,
+): void {
+ const scopePath = scope.join(".");
+
+ if (node.type === "formal_parameter") {
+ const type = javaTypeName(node.childForFieldName("type"));
+ const name = node.childForFieldName("name");
+ 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;
+
+ for (const d of node.namedChildren) {
+ if (d.type !== "variable_declarator") continue;
+ const name = d.childForFieldName("name");
+ if (name?.type !== "identifier") continue;
+ bindings.set(target, name.text, type);
+ if (isField) bindings.set(target, `self.${name.text}`, type);
+ }
+}
+
+/** 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`). */
+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;
+ if (node.type === "generic_type") {
+ const base = node.namedChildren[0];
+ return base ? javaTypeName(base) : null;
+ }
+ if (node.type === "scoped_type_identifier") {
+ return node.namedChildren.at(-1)?.text ?? null;
+ }
+ return null;
+}
+
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 c800283d..1d84ce29 100644
--- a/src/graph/extract.ts
+++ b/src/graph/extract.ts
@@ -10,12 +10,13 @@ import Parser from "tree-sitter";
import TypeScript from "tree-sitter-typescript";
import Python from "tree-sitter-python";
import Go from "tree-sitter-go";
+import Java from "tree-sitter-java";
import { basename } from "node:path";
import { contentHash } from "../util/id.js";
import { collectBindings, goReceiverVarOf, resolveRecvType, type FileBindings } from "./bindings.js";
import type { Kind, NodeV1, Relation } from "./types.js";
-export type Language = "typescript" | "tsx" | "python" | "go";
+export type Language = "typescript" | "tsx" | "python" | "go" | "java";
/**
* Extension → the tree-sitter grammar that parses it, and the label a human expects
@@ -44,6 +45,7 @@ const EXTENSIONS: ReadonlyArray<{ ext: string; grammar: Language; label: string
{ ext: ".pyi", grammar: "python", label: "python" },
{ ext: ".py", grammar: "python", label: "python" },
{ ext: ".go", grammar: "go", label: "go" },
+ { ext: ".java", grammar: "java", label: "java" },
];
function entryFor(path: string): (typeof EXTENSIONS)[number] | undefined {
@@ -149,11 +151,44 @@ const GO_KINDS: Record<string, Kind> = {
method_declaration: "method",
};
+// Java: a record is a nominal data carrier, so it takes "struct" — the same role
+// Go's struct plays — rather than "class", which would make a service and a DTO
+// indistinguishable in a repo where DTOs are most of the type surface.
+const JAVA_KINDS: Record<string, Kind> = {
+ class_declaration: "class",
+ interface_declaration: "interface",
+ enum_declaration: "enum",
+ record_declaration: "struct",
+ annotation_type_declaration: "interface",
+ method_declaration: "method",
+ constructor_declaration: "method",
+};
+
+/** Java type declarations: they set `enclosingClass` for the methods nested in them,
+ * which "class"-only logic would miss for a record's or interface's members. */
+const JAVA_TYPE_KINDS: ReadonlySet<Kind> = new Set<Kind>(["class", "interface", "enum", "struct"]);
+
const KINDS_BY_LANG: Record<Language, Record<string, Kind>> = {
typescript: TS_KINDS,
tsx: TS_KINDS,
python: PY_KINDS,
go: GO_KINDS,
+ java: JAVA_KINDS,
+};
+
+/**
+ * The node type(s) that constitute a call site, per language.
+ *
+ * Java is the reason this is a set rather than a string: `method_invocation` and
+ * `object_creation_expression` (`new Foo()`) are separate node types, and a Java
+ * codebase's constructor calls are a large share of its real edges.
+ */
+const CALL_TYPES: Record<Language, ReadonlySet<string>> = {
+ typescript: new Set(["call_expression"]),
+ tsx: new Set(["call_expression"]),
+ python: new Set(["call"]),
+ go: new Set(["call_expression"]),
+ java: new Set(["method_invocation", "object_creation_expression"]),
};
const FUNCTION_VALUE_TYPES = new Set([
@@ -169,6 +204,7 @@ const GRAMMARS: Record<Language, unknown> = {
tsx: TypeScript.tsx,
python: Python,
go: Go,
+ java: Java,
};
export interface WalkCtx {
@@ -297,7 +333,9 @@ function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEd
? !desc.name.startsWith("_")
: ctx.lang === "go"
? goExported(desc.name)
- : tsExported(node),
+ : ctx.lang === "java"
+ ? javaExported(node)
+ : tsExported(node),
origin: "ast",
body_hash: contentHash(desc.hashNode.text),
body_text: searchBody(desc.hashNode.text),
@@ -308,10 +346,17 @@ function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEd
});
// structural containment
edges.push({ source: ctx.parentId, relation: "contains", targetId: id, file: ctx.rel });
- // class heritage
- if (desc.kind === "class") edges.push(...heritageEdges(node, id, ctx));
-
- const enclosingClass = desc.kind === "class" ? desc.name : isGoMethod ? goReceiverType(node) : ctx.enclosingClass;
+ // class heritage — in Java an interface may also `extends`, and a record/enum
+ // may `implements`, so every type declaration is a heritage site, not just a class.
+ const javaTypeDecl = ctx.lang === "java" && JAVA_TYPE_KINDS.has(desc.kind);
+ if (desc.kind === "class" || javaTypeDecl) edges.push(...heritageEdges(node, id, ctx));
+
+ const enclosingClass =
+ desc.kind === "class" || javaTypeDecl
+ ? desc.name
+ : isGoMethod
+ ? goReceiverType(node)
+ : ctx.enclosingClass;
const childCtx: WalkCtx = {
...ctx,
scope: [...ctx.scope, idPart],
@@ -329,8 +374,8 @@ function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEd
}
// not a definition — capture calls/imports/references, then descend with the same context
- const callType = ctx.lang === "python" ? "call" : "call_expression";
- if (node.type === callType) {
+ const callTypes = CALL_TYPES[ctx.lang];
+ if (callTypes.has(node.type)) {
const callee = calleeName(node, ctx.lang);
if (callee) {
const callEdge: RawEdge = {
@@ -351,7 +396,7 @@ function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEd
return;
} else if (
node.type === "identifier" &&
- !isDirectCallee(node, callType) &&
+ !isDirectCallee(node, callTypes) &&
!isDeclarationName(node)
) {
const imported = ctx.importedSymbols.get(node.text);
@@ -453,10 +498,13 @@ function isFunctionBoundary(node: Parser.SyntaxNode): boolean {
);
}
-/** A direct invocation already emits a stronger `calls` edge. */
-function isDirectCallee(node: Parser.SyntaxNode, callType: string): boolean {
+/** A direct invocation already emits a stronger `calls` edge. Java names the callee
+ * in a `name` field (there is no `function` field on `method_invocation`), so both
+ * spellings count. */
+function isDirectCallee(node: Parser.SyntaxNode, callTypes: ReadonlySet<string>): boolean {
const parent = node.parent;
- return parent?.type === callType && parent.childForFieldName("function") === node;
+ if (!parent || !callTypes.has(parent.type)) return false;
+ return parent.childForFieldName("function") === node || parent.childForFieldName("name") === node;
}
/** Definition/declaration identifiers name a new binding; they do not use one. */
@@ -469,6 +517,7 @@ function isDeclarationName(node: Parser.SyntaxNode): boolean {
* TS arrow-consts. */
function describe(node: Parser.SyntaxNode, ctx: WalkCtx): DefDescriptor | null {
if (ctx.lang === "go") return describeGo(node, ctx);
+ if (ctx.lang === "java") return describeJava(node, ctx);
const mapped = ctx.kinds[node.type];
if (mapped) {
@@ -543,6 +592,28 @@ function describeGo(node: Parser.SyntaxNode, _ctx: WalkCtx): DefDescriptor | nul
return null;
}
+/** Java definition shapes. Uniform in a way Go's are not: every declaration carries
+ * a `name` field and (for types and most members) a `body`, so one mapped lookup
+ * covers classes, interfaces, enums, records, methods, and constructors. Methods are
+ * lexically nested in their type, so — unlike Go — they need no receiver qualification. */
+function describeJava(node: Parser.SyntaxNode, ctx: WalkCtx): DefDescriptor | null {
+ const mapped = ctx.kinds[node.type];
+ if (!mapped) return null;
+ 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 };
+}
+
+/** Java visibility: `public` (or `protected`) on the declaration's own modifier list.
+ * A package-private or private member is not part of the API surface. Read off the
+ * `modifiers` child's tokens, ignoring annotations, which live in the same node. */
+function javaExported(node: Parser.SyntaxNode): boolean {
+ const mods = node.namedChildren.find((c) => c.type === "modifiers");
+ if (!mods) return false;
+ return mods.children.some((c) => c.type === "public" || c.type === "protected");
+}
+
/** The receiver's base type name for a Go method, unwrapping a pointer receiver
* (`func (u *User) …` → `User`). Null if it can't be read. */
function goReceiverType(node: Parser.SyntaxNode): string | null {
@@ -563,6 +634,24 @@ function goExported(name: string): boolean {
function heritageEdges(node: Parser.SyntaxNode, classId: string, ctx: WalkCtx): RawEdge[] {
const edges: RawEdge[] = [];
+ if (ctx.lang === "java") {
+ // `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`).
+ for (const child of node.namedChildren) {
+ const relation: Relation | null =
+ child.type === "superclass"
+ ? "extends"
+ : child.type === "super_interfaces" || child.type === "extends_interfaces"
+ ? "implements"
+ : null;
+ if (!relation) continue;
+ for (const t of typeIdentifiersIn(child)) {
+ edges.push({ source: classId, relation, name: t, file: ctx.rel });
+ }
+ }
+ return edges;
+ }
if (ctx.lang === "python") {
const supers = node.childForFieldName("superclasses"); // argument_list
for (const c of supers?.namedChildren ?? []) {
@@ -590,10 +679,44 @@ 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[] = [];
+ const visit = (n: Parser.SyntaxNode): void => {
+ if (n.type === "type_identifier") out.push(n.text);
+ for (const c of n.namedChildren) visit(c);
+ };
+ visit(node);
+ return out;
+}
+
function calleeName(
node: Parser.SyntaxNode,
lang: Language,
): { name: string; viaMember: boolean; receiver?: string } | null {
+ // Java first: `method_invocation` has NO `function` field (it splits the callee
+ // into `object` + `name`), so the shared lookup below would return null for every
+ // Java call site and the language would extract nodes with no call edges at all.
+ if (lang === "java") {
+ if (node.type === "object_creation_expression") {
+ // `new Foo()` — the constructed type is the call target.
+ const t = node.childForFieldName("type");
+ return t ? { name: t.text, viaMember: false } : null;
+ }
+ const nameNode = node.childForFieldName("name");
+ if (!nameNode) return null;
+ const obj = node.childForFieldName("object");
+ // No `object` means an implicit-`this` call (`decorate(name)`), which in Java is a
+ // method call, not a free function — Java has none. Reporting it as a plain call
+ // would send it to the function-only resolver and drop it, losing the most common
+ // intra-class edge there is. Spelling it as a `this` member call routes it through
+ // owner-qualified resolution, which also walks the superclass chain and stays
+ // conservative: an unmatched name (e.g. a static import) resolves to nothing.
+ if (!obj) return { name: nameNode.text, viaMember: true, receiver: "this" };
+ return { name: nameNode.text, viaMember: true, receiver: javaReceiver(obj) };
+ }
+
const fn = node.childForFieldName("function");
if (!fn) return null;
if (fn.type === "identifier") return { name: fn.text, viaMember: false };
@@ -615,6 +738,21 @@ function calleeName(
return null;
}
+/** 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. */
+function javaReceiver(obj: Parser.SyntaxNode | null | undefined): string | undefined {
+ if (!obj) return undefined;
+ if (obj.type === "identifier") return obj.text;
+ if (obj.type === "this") return "this";
+ if (obj.type === "field_access") {
+ const inner = obj.childForFieldName("object");
+ const field = obj.childForFieldName("field");
+ if (inner?.type === "this" && field) return `this.${field.text}`;
+ }
+ return undefined;
+}
+
/** py `attribute` node's receiver text: bare identifier, or `self.x` for a
* chained `self.x.y()`. Anything else (e.g. a chained call `f().g()`) → none. */
function pyReceiver(fn: Parser.SyntaxNode): string | undefined {
@@ -645,6 +783,7 @@ function isImport(node: Parser.SyntaxNode, lang: Language): boolean {
// Go: match the per-import leaf, so single (`import "fmt"`) and grouped
// (`import ( … )`) forms each yield one edge as the walk recurses into the list.
if (lang === "go") return node.type === "import_spec";
+ if (lang === "java") return node.type === "import_declaration";
return node.type === "import_statement" || node.type === "import_from_statement";
}
@@ -660,6 +799,15 @@ function importSpecifier(node: Parser.SyntaxNode, lang: Language): string | null
const path = node.childForFieldName("path") ?? node.namedChildren.at(-1);
return path ? path.text.replace(/^["`]|["`]$/g, "") : null;
}
+ if (lang === "java") {
+ // `import a.b.C;` / `import static a.b.C.d;` / `import a.b.*;` — the fully
+ // qualified name is the scoped_identifier; a wildcard `*` is a separate token
+ // and is dropped, leaving the package as the import target.
+ const id = node.namedChildren.find(
+ (c) => c.type === "scoped_identifier" || c.type === "identifier",
+ );
+ return id?.text ?? null;
+ }
const str = node.namedChildren.find((c) => c.type === "string");
if (!str) return null;
const frag = str.namedChildren.find((c) => c.type === "string_fragment");
diff --git a/src/graph/resolve.ts b/src/graph/resolve.ts
index ea69aacb..43b5812d 100644
--- a/src/graph/resolve.ts
+++ b/src/graph/resolve.ts
@@ -47,6 +47,11 @@ export function resolveEdges(
const ownerMethod = new Map<string, NodeV1[]>();
// Go package resolution: dir (posix) → its `.go` file node ids, for import mapping.
const goFilesByDir = new Map<string, string[]>();
+ // Java package resolution: a file's package-path suffix (`com/acme/Foo.java`) → its
+ // file node ids. A Java import names a type by its fully-qualified name, which by
+ // language convention mirrors the directory path under whatever source root the
+ // project uses (`src/main/java/`, `src/`, …) — so the suffix is the portable key.
+ const javaFilesBySuffix = new Map<string, string[]>();
const hasGoModules = !!opts.goModules?.length;
for (const n of nodes) {
if (n.kind === "file") {
@@ -54,6 +59,13 @@ export function resolveEdges(
const dir = posix.dirname(toPosixPath(n.path));
push(goFilesByDir, dir, n.id);
}
+ if (n.path.endsWith(".java")) {
+ // Index every directory-boundary suffix, since the source root is unknown:
+ // `src/main/java/com/acme/Foo.java` is reachable as `com/acme/Foo.java`,
+ // `acme/Foo.java`, and so on. The import's own FQN picks the right depth.
+ const parts = toPosixPath(n.path).split("/");
+ for (let i = 0; i < parts.length; i++) push(javaFilesBySuffix, parts.slice(i).join("/"), n.id);
+ }
continue;
}
push(globalName, n.name, n);
@@ -95,7 +107,9 @@ export function resolveEdges(
const target =
hasGoModules && e.file.endsWith(".go")
? resolveGoImport(e.specifier, opts.goModules!, goFilesByDir)
- : resolveImport(e.specifier, e.file, byId);
+ : e.file.endsWith(".java")
+ ? resolveJavaImport(e.specifier, javaFilesBySuffix)
+ : resolveImport(e.specifier, e.file, byId);
add(e.source, target, "imports", "extracted");
} else if (e.relation === "extends" || e.relation === "implements") {
const kinds: Kind[] = e.relation === "implements" ? ["interface"] : ["class", "interface"];
@@ -120,7 +134,14 @@ export function resolveEdges(
// method name is not evidence that this receiver has that method.
continue;
}
- const hit = resolveName(e.name!, e.file, ["function"], perFileName, globalName);
+ // Java emits only one kind of non-member call: `new Foo()`, whose target is a
+ // TYPE, not a function (Java has no free functions — an implicit-`this` call is
+ // spelled as a member call in extract.ts). Resolving it against the function
+ // index would drop every constructor edge.
+ const kinds: Kind[] = e.file.endsWith(".java")
+ ? ["class", "struct", "enum", "interface"]
+ : ["function"];
+ const hit = resolveName(e.name!, e.file, kinds, perFileName, globalName);
if (hit) add(e.source, hit.id, "calls", hit.confidence); // drop unresolved calls (too noisy)
}
}
@@ -219,6 +240,40 @@ function resolveImport(spec: string, file: string, byId: Map<string, NodeV1>): s
return spec;
}
+/**
+ * Resolve a Java import's fully-qualified type name to an in-repo file node;
+ * otherwise return the raw specifier (JDK or third-party type).
+ *
+ * Java names a *type*, not a path, and states no source root — `com.acme.Foo` may
+ * live under `src/main/java/`, `src/`, or a module dir. Matching on the path SUFFIX
+ * (`com/acme/Foo.java`) is therefore root-agnostic and needs no build-file parsing,
+ * which is what keeps this deterministic and dependency-free.
+ *
+ * `import static com.acme.Foo.bar` names a member, so when the full name misses, the
+ * last segment is dropped and the enclosing type retried. A wildcard (`com.acme.*`)
+ * names a package rather than one file and is deliberately left unresolved: picking a
+ * representative would invent an edge the source does not state.
+ *
+ * A suffix shared by two files (the same FQN under two source roots, e.g. a
+ * duplicated test tree) is ambiguous, so it stays unresolved rather than guessing.
+ */
+function resolveJavaImport(spec: string, filesBySuffix: Map<string, string[]>): string {
+ const hit = (fqn: string): string | null => {
+ const suffix = `${fqn.split(".").join("/")}.java`;
+ const files = filesBySuffix.get(suffix);
+ return files && files.length === 1 ? files[0] : null;
+ };
+ const direct = hit(spec);
+ if (direct) return direct;
+ // `import static a.b.C.member` → retry as `a.b.C`.
+ const dot = spec.lastIndexOf(".");
+ if (dot > 0) {
+ const enclosing = hit(spec.slice(0, dot));
+ if (enclosing) return enclosing;
+ }
+ return spec;
+}
+
/**
* Resolve a Go import package path to an in-repo file node when it points inside one of
* the repo's modules; otherwise return the raw specifier (stdlib or third-party package).
diff --git a/test/graph-java.test.ts b/test/graph-java.test.ts
new file mode 100644
index 00000000..c5b88806
--- /dev/null
+++ b/test/graph-java.test.ts
@@ -0,0 +1,349 @@
+/**
+ * Tests for Java extraction in the Tier-1 code graph. Builds a small Java source
+ * tree in a temp dir and asserts the emitted nodes (classes, interfaces, enums,
+ * records, methods, constructors) and edges (calls, heritage, package imports)
+ * match the AST walk in extract.ts.
+ *
+ * Three of these pin decisions that are Java-specific and easy to regress, because
+ * each one is invisible to the other languages' fixtures:
+ *
+ * - `method_invocation` has NO `function` field (it splits the callee into
+ * `object` + `name`), unlike every other grammar graft parses.
+ * - Java has no free functions, so an implicit-`this` call (`decorate(x)`) is a
+ * METHOD call. Resolved against the function index it would vanish — and it is
+ * the most common intra-class edge there is.
+ * - `new Foo()` targets a TYPE, so a constructor call resolved against the
+ * function index would vanish too.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, writeFileSync, mkdirSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import { buildGraph } from "../src/graph/build.js";
+import { readGraph, wiringPath } from "../src/graph/write.js";
+import type { GraphV1, NodeV1 } from "../src/graph/types.js";
+
+const PKG = "src/main/java/com/acme";
+
+const GREETER = `package com.acme;
+
+public interface Greeter {
+ String greet(String name);
+}
+`;
+
+const BASE = `package com.acme;
+
+public abstract class Base {
+ protected void audit(String event) {}
+}
+`;
+
+const POINT = `package com.acme;
+
+public record Point(int x, int y) {}
+`;
+
+const COLOR = `package com.acme;
+
+public enum Color {
+ RED,
+ GREEN
+}
+`;
+
+const STORE = `package com.acme;
+
+public final class Store {
+ public void save(Point point) {}
+}
+`;
+
+const APP = `package com.acme;
+
+import com.acme.Store;
+import java.util.List;
+
+public final class App extends Base implements Greeter {
+
+ private final Store store;
+
+ public App(Store store) {
+ this.store = store;
+ }
+
+ @Override
+ public String greet(String name) {
+ return decorate(name);
+ }
+
+ private String decorate(String raw) {
+ return raw;
+ }
+
+ public void persist() {
+ store.save(new Point(1, 2));
+ }
+
+ public void inferred() {
+ var local = new Store();
+ local.save(new Point(3, 4));
+ }
+
+ void packagePrivate() {}
+}
+`;
+
+function makeFixture(): string {
+ const dir = mkdtempSync(join(tmpdir(), "graft-java-"));
+ mkdirSync(join(dir, PKG), { recursive: true });
+ writeFileSync(join(dir, PKG, "Greeter.java"), GREETER);
+ writeFileSync(join(dir, PKG, "Base.java"), BASE);
+ writeFileSync(join(dir, PKG, "Point.java"), POINT);
+ writeFileSync(join(dir, PKG, "Color.java"), COLOR);
+ writeFileSync(join(dir, PKG, "Store.java"), STORE);
+ writeFileSync(join(dir, PKG, "App.java"), APP);
+ return dir;
+}
+
+function nodeById(graph: GraphV1, id: string): NodeV1 | undefined {
+ return graph.nodes.find((n) => n.id === id);
+}
+
+const APP_JAVA = `${PKG}/App.java`;
+
+test("Java extraction: classes, interfaces, enums, records, methods, constructors", async () => {
+ const dir = makeFixture();
+ try {
+ const result = await buildGraph(dir); // $0, Tier-1 only
+ assert.ok(result.languages.includes("java"), "languages should include java");
+
+ const graph = readGraph(wiringPath(join(dir, "graft")));
+ assert.ok(graph, "wiring graph should be written");
+
+ assert.equal(nodeById(graph!, `${APP_JAVA}#App`)?.kind, "class");
+ assert.equal(nodeById(graph!, `${PKG}/Greeter.java#Greeter`)?.kind, "interface");
+ assert.equal(nodeById(graph!, `${PKG}/Color.java#Color`)?.kind, "enum");
+
+ // A record is a nominal data carrier, so it takes "struct" — not "class", which
+ // would make a DTO and a service indistinguishable in a Java repo where DTOs are
+ // most of the type surface.
+ assert.equal(nodeById(graph!, `${PKG}/Point.java#Point`)?.kind, "struct");
+
+ // Methods nest under their type; a constructor is a method named for its class.
+ assert.equal(nodeById(graph!, `${APP_JAVA}#App.greet`)?.kind, "method");
+ assert.equal(nodeById(graph!, `${APP_JAVA}#App.App`)?.kind, "method");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Java extraction: visibility comes from the modifier list, not the name", async () => {
+ const dir = makeFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+
+ assert.equal(nodeById(graph, `${APP_JAVA}#App`)?.exported, true, "public class");
+ assert.equal(nodeById(graph, `${APP_JAVA}#App.greet`)?.exported, true, "public method");
+ assert.equal(
+ nodeById(graph, `${PKG}/Base.java#Base.audit`)?.exported,
+ true,
+ "protected is still API surface to a subclass",
+ );
+ assert.equal(
+ nodeById(graph, `${APP_JAVA}#App.decorate`)?.exported,
+ false,
+ "private method is not API surface",
+ );
+ assert.equal(
+ nodeById(graph, `${APP_JAVA}#App.packagePrivate`)?.exported,
+ false,
+ "package-private (no modifier) is not API surface",
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Java extraction: call edges — implicit `this`, typed field receiver, constructor", async () => {
+ const dir = makeFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ const calls = graph.edges.filter((e) => e.relation === "calls");
+
+ // Implicit-`this`: `decorate(name)` names no receiver but IS a method call.
+ // Java has no free functions, so resolving this against the function index
+ // would silently drop the commonest edge in the language.
+ assert.ok(
+ calls.some((e) => e.source === `${APP_JAVA}#App.greet` && e.target === `${APP_JAVA}#App.decorate`),
+ "greet should call decorate via implicit-this resolution",
+ );
+
+ // Typed field receiver: `store.save(...)` resolves through the declared field
+ // type `private final Store store`.
+ assert.ok(
+ calls.some(
+ (e) => e.source === `${APP_JAVA}#App.persist` && e.target === `${PKG}/Store.java#Store.save`,
+ ),
+ "persist should call Store.save via the field's declared type",
+ );
+
+ // `new Point(1, 2)` targets a TYPE, not a function.
+ assert.ok(
+ calls.some(
+ (e) => e.source === `${APP_JAVA}#App.persist` && e.target === `${PKG}/Point.java#Point`,
+ ),
+ "persist should have a constructor edge to Point",
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+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.
+ const dir = makeFixture();
+ 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 === `${APP_JAVA}#App.inferred` && e.target === `${PKG}/Store.java#Store.save`,
+ ),
+ "a var-typed receiver must not be guessed into a resolved edge",
+ );
+ 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",
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Java extraction: extends and implements", async () => {
+ const dir = makeFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+
+ assert.ok(
+ graph.edges.some(
+ (e) =>
+ e.relation === "extends" &&
+ e.source === `${APP_JAVA}#App` &&
+ e.target === `${PKG}/Base.java#Base`,
+ ),
+ "App extends Base",
+ );
+ assert.ok(
+ graph.edges.some(
+ (e) =>
+ e.relation === "implements" &&
+ e.source === `${APP_JAVA}#App` &&
+ e.target === `${PKG}/Greeter.java#Greeter`,
+ ),
+ "App implements Greeter",
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Java extraction: imports resolve by package path; external types stay strings", async () => {
+ const dir = makeFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ const imports = graph.edges.filter((e) => e.relation === "imports" && e.source === APP_JAVA);
+
+ // A Java import names a TYPE and states no source root, so resolution matches the
+ // fully-qualified name against a path suffix — root-agnostic, no build-file parsing.
+ assert.ok(
+ imports.some((e) => e.target === `${PKG}/Store.java`),
+ "com.acme.Store should resolve to the in-repo file under src/main/java/",
+ );
+
+ // The JDK is not in the repo; the specifier is kept verbatim rather than guessed at.
+ assert.ok(
+ imports.some((e) => e.target === "java.util.List"),
+ "java.util.List should remain an external type string",
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Java extraction: a static-member import resolves to its enclosing type", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "graft-java-static-"));
+ try {
+ mkdirSync(join(dir, PKG), { recursive: true });
+ writeFileSync(
+ join(dir, PKG, "Util.java"),
+ "package com.acme;\n\npublic final class Util {\n public static int twice(int n) {\n return n * 2;\n }\n}\n",
+ );
+ writeFileSync(
+ join(dir, PKG, "Caller.java"),
+ "package com.acme;\n\nimport static com.acme.Util.twice;\n\npublic final class Caller {\n public int run() {\n return twice(2);\n }\n}\n",
+ );
+
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+
+ // `com.acme.Util.twice` names a member; the file is the enclosing type's.
+ assert.ok(
+ graph.edges.some(
+ (e) =>
+ e.relation === "imports" &&
+ e.source === `${PKG}/Caller.java` &&
+ e.target === `${PKG}/Util.java`,
+ ),
+ "a static-member import should fall back to its enclosing type's file",
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Java extraction: an ambiguous package suffix stays unresolved rather than guessing", async () => {
+ // The same fully-qualified name under two source roots (main and a duplicated test
+ // tree) gives one suffix two files. Picking one would invent an edge the source
+ // does not state, so the specifier is kept.
+ const dir = mkdtempSync(join(tmpdir(), "graft-java-ambig-"));
+ try {
+ const main = "src/main/java/com/acme";
+ const test2 = "src/test/java/com/acme";
+ mkdirSync(join(dir, main), { recursive: true });
+ mkdirSync(join(dir, test2), { recursive: true });
+ const dup = "package com.acme;\n\npublic final class Dup {\n public void run() {}\n}\n";
+ writeFileSync(join(dir, main, "Dup.java"), dup);
+ writeFileSync(join(dir, test2, "Dup.java"), dup);
+ writeFileSync(
+ join(dir, main, "Uses.java"),
+ "package com.acme;\n\nimport com.acme.Dup;\n\npublic final class Uses {\n public void go() {}\n}\n",
+ );
+
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+
+ assert.ok(
+ graph.edges.some(
+ (e) =>
+ e.relation === "imports" && e.source === `${main}/Uses.java` && e.target === "com.acme.Dup",
+ ),
+ "an ambiguous suffix must stay an unresolved specifier",
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/test/graph-languages.test.ts b/test/graph-languages.test.ts
index a63fa44c..f66ac83f 100644
--- a/test/graph-languages.test.ts
+++ b/test/graph-languages.test.ts
@@ -27,6 +27,7 @@ const INDEXED = [
"a.tsx", "a.jsx",
"a.py", "a.pyi",
"a.go",
+ "a.java",
];
test("a file is labelled exactly when it is indexed", () => {
@@ -53,6 +54,7 @@ test("labels name the language, not the grammar that parses it", () => {
assert.equal(languageLabelOf("api/main.py"), "python");
assert.equal(languageLabelOf("api/main.pyi"), "python");
assert.equal(languageLabelOf("cmd/main.go"), "go");
+ assert.equal(languageLabelOf("src/main/java/com/acme/App.java"), "java");
// The grammar is unchanged — extraction, the extract cache and every `Language`
// switch still see exactly what they saw before.