Skip to content

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

feat(java): wire annotation usage as references edges (#89) (#207)

Frankie-Xu10f5aab89953
diff --git a/scripts/graph-quality.mjs b/scripts/graph-quality.mjs
index caea44d5..cc0813dc 100644
--- a/scripts/graph-quality.mjs
+++ b/scripts/graph-quality.mjs
@@ -48,8 +48,8 @@ for (const n of nodes) {
else if (Number(m[1]) > Number(m[2])) problems.push(`inverted span ${n.span}: ${n.id}`);
}
// an edge target may be a node id OR a deliberately-unresolved external string
-// (import specifier / bare heritage name); only calls/references/contains must
-// point at real nodes.
+// (import specifier / bare heritage name / unresolved Java annotation type);
+// only calls/contains must point at real nodes.
let dangling = 0, selfLoops = 0, unresolvedExternal = 0;
for (const e of edges) {
if (!RELATIONS.has(e.relation)) problems.push(`bad relation '${e.relation}'`);
@@ -57,7 +57,7 @@ for (const e of edges) {
if (!ids.has(e.source)) { problems.push(`dangling source: ${e.source}`); dangling++; }
const targetIsNode = ids.has(e.target);
if (!targetIsNode) {
- if (e.relation === "imports" || e.relation === "extends" || e.relation === "implements") unresolvedExternal++;
+ if (e.relation === "imports" || e.relation === "extends" || e.relation === "implements" || e.relation === "references") unresolvedExternal++;
else { problems.push(`dangling ${e.relation} target: ${e.source} → ${e.target}`); dangling++; }
}
if (e.relation === "calls" && e.source === e.target) selfLoops++;
diff --git a/src/graph/extract.ts b/src/graph/extract.ts
index e53c5371..caa84665 100644
--- a/src/graph/extract.ts
+++ b/src/graph/extract.ts
@@ -583,6 +583,7 @@ function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEd
if (desc.kind === "class" || javaTypeDecl || kotlinTypeDecl)
edges.push(...heritageEdges(node, id, ctx));
if (ctx.lang === "php") edges.push(...phpAttributeReferenceEdges(node, id, ctx));
+ if (ctx.lang === "java") edges.push(...javaAnnotationReferenceEdges(node, id, ctx));
const enclosingClass =
desc.kind === "class" || javaTypeDecl || kotlinTypeDecl
@@ -896,6 +897,36 @@ function phpAttributeClassRef(
return { name: bare };
}
+/** Java annotations on a definition → `references` edges to the annotation type. */
+function javaAnnotationReferenceEdges(node: Parser.SyntaxNode, sourceId: string, ctx: WalkCtx): RawEdge[] {
+ const edges: RawEdge[] = [];
+ const mods = node.namedChildren.find((c) => c.type === "modifiers");
+ if (!mods) return edges;
+ for (const child of mods.namedChildren) {
+ if (child.type !== "marker_annotation" && child.type !== "annotation") continue;
+ const name = javaAnnotationTypeName(child);
+ if (name) {
+ edges.push({
+ source: sourceId,
+ relation: "references",
+ name,
+ file: ctx.rel,
+ });
+ }
+ }
+ return edges;
+}
+
+/** The type named by `@Foo` / `@a.b.Foo(...)`. Arguments are ignored (issue #89).
+ * A scoped name is kept whole, matching heritage: a bare last segment would
+ * false-match an unrelated in-repo type (#103). */
+function javaAnnotationTypeName(anno: Parser.SyntaxNode): string | null {
+ const nameNode = anno.childForFieldName("name");
+ if (!nameNode) return null;
+ if (nameNode.type === "identifier" || nameNode.type === "scoped_identifier") return nameNode.text;
+ return null;
+}
+
function collectTsImportBindings(
node: Parser.SyntaxNode,
specifier: string,
diff --git a/src/graph/invariants.ts b/src/graph/invariants.ts
index 2fb2bbe6..4ebdc80e 100644
--- a/src/graph/invariants.ts
+++ b/src/graph/invariants.ts
@@ -8,8 +8,9 @@
* - edge relations and confidences are in the allowed sets
* - every edge source is a real node
* - every edge target is a real node, EXCEPT the relations that deliberately keep
- * an unresolved external string (an import specifier, or a bare heritage name for
- * an out-of-repo supertype) — those are a feature of "drop rather than guess",
+ * an unresolved external string (an import specifier, a bare heritage name for
+ * an out-of-repo supertype, or a Java annotation type with no in-repo
+ * `@interface`) — those are a feature of "drop rather than guess",
* not a dangling edge.
*
* Self-loop `calls` are NOT a violation: direct recursion is a real edge a function
@@ -33,9 +34,12 @@ const CONFIDENCE = new Set<string>([
"lsp_resolved", "lsp_dispatch", "extracted", "inferred",
]);
// Relations whose target may be a deliberately-unresolved external string rather
-// than an in-repo node id: an import's module specifier, or a heritage clause naming
-// a supertype defined outside the repo (or a generic type parameter).
-const TARGET_MAY_BE_EXTERNAL = new Set<string>(["imports", "extends", "implements"]);
+// than an in-repo node id: an import's module specifier, a heritage clause naming
+// a supertype defined outside the repo (or a generic type parameter), or a Java
+// annotation whose type is not declared in-repo. The set is language-agnostic —
+// no other producer currently leaves an unresolved `references` target, so a
+// future bug elsewhere would be masked here.
+const TARGET_MAY_BE_EXTERNAL = new Set<string>(["imports", "extends", "implements", "references"]);
export interface InvariantResult {
/** One human-readable line per violation; empty when the graph is well-formed. */
diff --git a/src/graph/resolve.ts b/src/graph/resolve.ts
index e9ed5709..00b70136 100644
--- a/src/graph/resolve.ts
+++ b/src/graph/resolve.ts
@@ -234,6 +234,22 @@ export function resolveEdges(
const refKinds: Kind[] = ["class", "interface", "trait", "enum"];
const hit = resolveName(e.name, e.file, refKinds, perFileName, globalName);
if (hit && hit.id !== e.source) add(e.source, hit.id, "references", hit.confidence);
+ } else if (e.file.endsWith(".java") && byId.get(e.source)?.origin === "ast") {
+ // Java annotation without a specifier (same-file or globally unique
+ // `@interface`). Annotation types are `interface` kind — a class of the
+ // same name is not a match, so `@Entity` cannot collapse onto an in-repo
+ // `class Entity` (#103). Kind alone still cannot tell `@interface Service`
+ // from `interface Service`, so only accept a candidate whose header
+ // contains the literal `@interface` (`includes`, not `startsWith`: a
+ // meta-annotated type is `@Documented @Retention(...) public @interface
+ // JsonAdapter`). Unresolved targets keep the bare name, matching
+ // heritage, rather than dropping the way PHP attributes do.
+ const refKinds: Kind[] = ["interface"];
+ const hit = resolveName(e.name, e.file, refKinds, perFileName, globalName);
+ const anno = hit ? byId.get(hit.id) : undefined;
+ if (hit && hit.id !== e.source && anno?.signature?.includes("@interface"))
+ add(e.source, hit.id, "references", hit.confidence);
+ else add(e.source, e.name, "references", "inferred");
} else if (byId.get(e.source)?.origin === "generic") {
// Breadth tier: a bare-name structural reference (extends / implements /
// object-creation / module alias) the grammar marked but cannot type. Resolve
diff --git a/test/graph-invariants.test.ts b/test/graph-invariants.test.ts
index 980e7c04..1bc8f2e2 100644
--- a/test/graph-invariants.test.ts
+++ b/test/graph-invariants.test.ts
@@ -104,13 +104,19 @@ test("Tier-0: the invariant checker actually catches malformed graphs (not vacuo
assert.ok(problems.some((p) => p.includes("dangling calls target")), "flags the dangling target");
assert.ok(problems.some((p) => p.includes("dangling source")), "flags the dangling source");
assert.ok(problems.some((p) => p.includes("bad confidence")), "flags the bad confidence");
- // an unresolved imports/extends/implements target is NOT flagged (drop-rather-than-guess)
+ // an unresolved imports/extends/implements/references target is NOT flagged
const okExternal = checkGraphInvariants({
...bad,
nodes: [bad.nodes[0]],
edges: [{ source: "a.ts#Foo", target: "com.external.Base", relation: "extends", confidence: "inferred" }],
});
assert.deepEqual(okExternal.problems, [], "an external heritage/import string target is allowed, not dangling");
+ const okAnno = checkGraphInvariants({
+ ...bad,
+ nodes: [bad.nodes[0]],
+ edges: [{ source: "a.ts#Foo", target: "Override", relation: "references", confidence: "inferred" }],
+ });
+ assert.deepEqual(okAnno.problems, [], "an external annotation string target is allowed, not dangling");
});
test("Tier-0: the build is deterministic — two cold builds produce the identical graph", async () => {
diff --git a/test/graph-java.test.ts b/test/graph-java.test.ts
index 32cc7d49..b0301551 100644
--- a/test/graph-java.test.ts
+++ b/test/graph-java.test.ts
@@ -1353,3 +1353,176 @@ test("Java anonymous class: methods do not take the enclosing type's owner (#161
rmSync(dir, { recursive: true, force: true });
}
});
+
+// Issue #89: Java annotations are metadata, not call sites — wire them as
+// `references` edges from the annotated symbol to the annotation type (the
+// same shape as PHP 8 attributes in #155). Field annotations are out of
+// scope: fields are not nodes.
+const ANNO_MYANNO = `package com.acme;
+
+public @interface MyAnno {
+ String value() default "";
+}
+`;
+
+const ANNO_FOO = `package com.acme;
+
+@Entity
+@MyAnno
+public class Foo {
+ @Transient
+ private String field;
+
+ @MyAnno
+ public void tagged() {}
+
+ @MyAnno(value = "x")
+ public void parameterized() {}
+
+ @Override
+ public String toString() {
+ return "foo";
+ }
+}
+`;
+
+const ANNO_ENTITY_CLASS = `package com.other;
+
+public class Entity {}
+`;
+
+function annotationFixture(): string {
+ const dir = mkdtempSync(join(tmpdir(), "graft-java-annoref-"));
+ mkdirSync(join(dir, PKG), { recursive: true });
+ mkdirSync(join(dir, "src/main/java/com/other"), { recursive: true });
+ writeFileSync(join(dir, PKG, "MyAnno.java"), ANNO_MYANNO);
+ writeFileSync(join(dir, PKG, "Foo.java"), ANNO_FOO);
+ writeFileSync(join(dir, "src/main/java/com/other/Entity.java"), ANNO_ENTITY_CLASS);
+ return dir;
+}
+
+test("Java extraction: in-repo annotation usage resolves to references edges (#89)", async () => {
+ const dir = annotationFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ const foo = `${PKG}/Foo.java#Foo`;
+ const myAnno = `${PKG}/MyAnno.java#MyAnno`;
+
+ assert.equal(nodeById(graph, myAnno)?.kind, "interface", "@interface maps to interface kind");
+
+ assert.ok(
+ graph.edges.some(
+ (e) => e.relation === "references" && e.source === foo && e.target === myAnno,
+ ),
+ "Foo class should reference the in-repo MyAnno annotation type",
+ );
+
+ assert.ok(
+ graph.edges.some(
+ (e) =>
+ e.relation === "references" &&
+ e.source === `${PKG}/Foo.java#Foo.tagged` &&
+ e.target === myAnno,
+ ),
+ "tagged method should reference the in-repo MyAnno annotation type",
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Java extraction: annotation arguments do not emit extra edges (#89)", async () => {
+ const dir = annotationFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ const myAnno = `${PKG}/MyAnno.java#MyAnno`;
+ const tagged = graph.edges.filter(
+ (e) => e.relation === "references" && e.source === `${PKG}/Foo.java#Foo.tagged`,
+ );
+ const parameterized = graph.edges.filter(
+ (e) => e.relation === "references" && e.source === `${PKG}/Foo.java#Foo.parameterized`,
+ );
+
+ assert.ok(
+ tagged.some((e) => e.target === myAnno),
+ "marker @MyAnno on tagged should resolve",
+ );
+ assert.deepEqual(
+ tagged.map((e) => e.target).sort(),
+ parameterized.map((e) => e.target).sort(),
+ "@MyAnno(value = \"x\") must emit the same references as marker @MyAnno",
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Java extraction: external annotation keeps its bare name (#89)", async () => {
+ // Heritage keeps an unresolved supertype as the edge target rather than
+ // minting a node or collapsing onto a same-named in-repo type (#103).
+ // @Entity / @Override are the annotation equivalent: no in-repo @interface,
+ // and a class named Entity elsewhere must not steal the edge.
+ const dir = annotationFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ const foo = `${PKG}/Foo.java#Foo`;
+ const refs = graph.edges.filter((e) => e.relation === "references");
+
+ assert.ok(
+ refs.some((e) => e.source === foo && e.target === "Entity"),
+ "unresolved @Entity should keep the bare name",
+ );
+ assert.ok(
+ !refs.some((e) => e.source === foo && e.target.endsWith("#Entity")),
+ "@Entity must not false-match the in-repo class Entity",
+ );
+ assert.ok(
+ refs.some((e) => e.source === `${PKG}/Foo.java#Foo.toString` && e.target === "Override"),
+ "unresolved @Override should keep the bare name",
+ );
+ assert.ok(
+ !refs.some((e) => e.source === foo && (e.target === "Transient" || e.target.endsWith("#Transient"))),
+ "field annotations are not class-level references",
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Java extraction: external @Service does not collapse onto a plain interface Service (#89)", async () => {
+ // #103 in interface form: `@interface` and `interface` both mint kind
+ // `interface`, so `@Service` (external Spring annotation) must not resolve
+ // onto an in-repo `interface Service`. The edge stays a bare name.
+ const dir = mkdtempSync(join(tmpdir(), "graft-java-service-anno-"));
+ mkdirSync(join(dir, PKG), { recursive: true });
+ writeFileSync(
+ join(dir, PKG, "Service.java"),
+ "package com.acme;\n\npublic interface Service {}\n",
+ );
+ writeFileSync(
+ join(dir, PKG, "Foo.java"),
+ "package com.acme;\n\n@Service\npublic class Foo {}\n",
+ );
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ const foo = `${PKG}/Foo.java#Foo`;
+ const service = `${PKG}/Service.java#Service`;
+ const refs = graph.edges.filter((e) => e.relation === "references" && e.source === foo);
+
+ assert.equal(nodeById(graph, service)?.kind, "interface", "plain Service is an in-repo interface");
+ assert.ok(
+ refs.some((e) => e.target === "Service"),
+ "unresolved @Service should keep the bare name",
+ );
+ assert.ok(
+ !refs.some((e) => e.target === service || e.target.endsWith("#Service")),
+ "@Service must not false-match the in-repo interface Service",
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});