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(php): resolve trait-inherited method calls via implements edges (#141) (#158)
Frankie-Xub58cac1abad8
diff --git a/src/graph/resolve.ts b/src/graph/resolve.tsindex 21483603..295001ba 100644--- a/src/graph/resolve.ts+++ b/src/graph/resolve.ts@@ -99,8 +99,9 @@ export function resolveEdges(let fileMap = perFileName.get(n.path);if (!fileMap) perFileName.set(n.path, (fileMap = new Map()));push(fileMap, n.name, n);- if (n.kind === "method" && n.owner) {- push(ownerMethod, `${n.owner}.${n.name}`, n);+ if (n.kind === "method") {+ const owner = n.owner ?? ownerFromMethodId(n.id);+ if (owner) push(ownerMethod, `${owner}.${n.name}`, n);}}@@ -118,6 +119,17 @@ export function resolveEdges(push(classParents, ownName, e.name);}+ // classTraits: class name → trait names from raw `implements` edges in PHP files.+ // PHP models `use SomeTrait;` as implements; trait methods live on the trait owner,+ // not the using class, so resolveTypedMember walks these after the class lookup fails.+ const classTraits = new Map<string, string[]>();+ for (const e of rawEdges) {+ if (e.relation !== "implements" || !e.name || !e.file.endsWith(".php")) continue;+ const ownName = byId.get(e.source)?.name;+ if (!ownName) continue;+ push(classTraits, ownName, e.name);+ }+const out: EdgeV1[] = [];const seen = new Set<string>();const add = (source: string, target: string, relation: Relation, confidence: EdgeV1["confidence"]) => {@@ -173,7 +185,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, e.argCount);+ const hit = resolveTypedMember(e.recvType, e.name!, e.file, ownerMethod, classParents, classTraits, e.argCount);if (hit === "ambiguous") continue; // drop — never guess past an ambiguous ownerif (hit) add(e.source, hit.id, "calls", hit.confidence);// No owner-qualified match means the call is unresolved. A unique bare@@ -212,6 +224,14 @@ function push<T>(map: Map<string, T[]>, key: string, val: T): void {else map.set(key, [val]);}+/** Derive a method's owner from its dotted id when extract did not stamp `owner`+ * (PHP trait/interface methods today). `app.php#Loggable.log` → `Loggable`. */+function ownerFromMethodId(id: string): string | undefined {+ const post = id.includes("#") ? id.split("#")[1] : id;+ const segs = post.split(".");+ return segs.length >= 2 ? segs[segs.length - 2] : undefined;+}+/*** Resolve a bare symbol name: same-file match first (certain → `extracted`),* else a unique cross-file match (→ `inferred`), else null (ambiguous/unknown).@@ -272,6 +292,7 @@ function resolveTypedMember(file: string,ownerMethod: Map<string, NodeV1[]>,classParents: Map<string, string[]>,+ classTraits: Map<string, string[]>,argCount?: number,): { id: string; confidence: EdgeV1["confidence"] } | "ambiguous" | null {const MAX_DEPTH = 3;@@ -280,15 +301,19 @@ function resolveTypedMember(for (let depth = 0; depth <= MAX_DEPTH && frontier.length; depth++) {for (const type of frontier) {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" };+ if (all && all.length > 0) {+ const candidates = narrowByArity(all, argCount);+ if (candidates.length === 1) {+ const c = candidates[0];+ return { id: c.id, confidence: c.path === file ? "extracted" : "inferred" };+ }+ const sameFile = candidates.find((c) => c.path === file);+ if (sameFile) return { id: sameFile.id, confidence: "extracted" };+ return "ambiguous"; // several, none same-file — drop and stop}- const sameFile = candidates.find((c) => c.path === file);- if (sameFile) return { id: sameFile.id, confidence: "extracted" };- return "ambiguous"; // several, none same-file — drop and stop+ const traitHit = resolveTraitMember(type, name, file, ownerMethod, classTraits, argCount);+ if (traitHit === "ambiguous") return "ambiguous";+ if (traitHit) return traitHit;}const next: string[] = [];for (const type of frontier) {@@ -303,6 +328,31 @@ function resolveTypedMember(return null; // chain exhausted, no candidate anywhere}+/** Resolve a member call against methods declared on PHP traits used by `type`. */+function resolveTraitMember(+ type: string,+ name: string,+ file: string,+ ownerMethod: Map<string, NodeV1[]>,+ classTraits: Map<string, string[]>,+ argCount?: number,+): { id: string; confidence: EdgeV1["confidence"] } | "ambiguous" | null {+ const traits = classTraits.get(type);+ if (!traits?.length) return null;+ const matches: NodeV1[] = [];+ for (const trait of traits) {+ const all = ownerMethod.get(`${trait}.${name}`);+ if (!all?.length) continue;+ matches.push(...narrowByArity(all, argCount));+ }+ if (matches.length === 0) return null;+ if (matches.length === 1) {+ const c = matches[0];+ return { id: c.id, confidence: c.path === file ? "extracted" : "inferred" };+ }+ return "ambiguous";+}+/*** Resolve a module specifier to a file node id when it points inside the repo;* otherwise return the raw specifier (external package or unresolved path).diff --git a/test/graph-php.test.ts b/test/graph-php.test.tsindex b208ccc5..e6faf005 100644--- a/test/graph-php.test.ts+++ b/test/graph-php.test.ts@@ -26,6 +26,7 @@ class Widget extends Base implements Runnablepublic function run(): int{+ $this->log();return $this->helper();}@@ -42,7 +43,10 @@ class Widget extends Base implements Runnableinterface Runnable {}-trait Loggable {}+trait Loggable+{+ protected function log(): void {}+}enum Color: string{@@ -140,6 +144,14 @@ test("PHP extraction: call, extends, and implements edges", async () => {"Widget should have a resolved implements edge to Runnable",);+ // `$this->log()` resolves to the used trait's method (trait-use → implements edge)+ assert.ok(+ graph.edges.some(+ (e) => e.relation === "calls" && e.source === "app.php#Widget.run" && e.target === "app.php#Loggable.log",+ ),+ "run should have a resolved calls edge to Loggable.log via trait use",+ );+// `$this->helper()` resolves to the receiver method (self → enclosing class)assert.ok(graph.edges.some(diff --git a/test/graph-resolve-typed.test.ts b/test/graph-resolve-typed.test.tsindex f7ad9dfa..4382dfac 100644--- a/test/graph-resolve-typed.test.ts+++ b/test/graph-resolve-typed.test.ts@@ -160,6 +160,41 @@ test("A2: extractFile sets NodeV1.owner to the immediate enclosing class/receiveassert.equal(goNodes.find((x) => x.id === "c.go#Server.Start")?.owner, "Server");});+test("PHP trait method: $this->m() resolves via implements (trait-use) edge", () => {+ const nodes = [+ n("app.php", "file"),+ n("app.php#Widget", "class"),+ n("app.php#Widget.run", "method"),+ n("app.php#Loggable", "trait"),+ n("app.php#Loggable.log", "method"),+ ];+ const edges = resolveEdges(nodes, [+ { source: "app.php#Widget", relation: "implements", name: "Loggable", file: "app.php" },+ { source: "app.php#Widget.run", relation: "calls", name: "log", viaMember: true, recvType: "Widget", file: "app.php" },+ ]);+ const call = edges.find((e) => e.relation === "calls");+ assert.equal(call?.target, "app.php#Loggable.log");+ assert.equal(call?.confidence, "extracted");+});++test("PHP trait method: ambiguous when two traits provide the same method", () => {+ const nodes = [+ n("app.php", "file"),+ n("app.php#Widget", "class"),+ n("app.php#Widget.run", "method"),+ n("app.php#T1", "trait"),+ n("app.php#T1.log", "method"),+ n("app.php#T2", "trait"),+ n("app.php#T2.log", "method"),+ ];+ const edges = resolveEdges(nodes, [+ { source: "app.php#Widget", relation: "implements", name: "T1", file: "app.php" },+ { source: "app.php#Widget", relation: "implements", name: "T2", file: "app.php" },+ { source: "app.php#Widget.run", relation: "calls", name: "log", viaMember: true, recvType: "Widget", file: "app.php" },+ ]);+ assert.equal(edges.filter((e) => e.relation === "calls").length, 0);+});+test("A2: owner-keyed ownerMethod/classParents resolve identically to the old id-slicing scheme (mixed fixture: sibling classes + inheritance)", () => {const src = ["class Base {",