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
feat(php): wire attribute usage as references edges (#144 part 1) (#155)
Frankie-Xu177591e530df
diff --git a/src/graph/extract.ts b/src/graph/extract.tsindex 1ef64c0b..5b870c5f 100644--- a/src/graph/extract.ts+++ b/src/graph/extract.ts@@ -499,6 +499,7 @@ function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEd// 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));+ if (ctx.lang === "php") edges.push(...phpAttributeReferenceEdges(node, id, ctx));const enclosingClass =desc.kind === "class" || javaTypeDecl@@ -634,14 +635,30 @@ function collectImportedSymbols(root: Parser.SyntaxNode,lang: Language,): Map<string, { name: string; specifier: string }> {- const out = new Map<string, { name: string; specifier: string }>();- if (lang !== "typescript" && lang !== "tsx") return out;+ if (lang === "typescript" || lang === "tsx") {+ const out = new Map<string, { name: string; specifier: string }>();+ const visit = (node: Parser.SyntaxNode): void => {+ if (node.type === "import_statement") {+ const specifier = importSpecifier(node, lang);+ if (!specifier) return;+ collectTsImportBindings(node, specifier, out);+ return;+ }+ for (const child of node.namedChildren) visit(child);+ };+ visit(root);+ return out;+ }+ if (lang === "php") return collectPhpImportedSymbols(root);+ return new Map();+}+/** PHP `use` bindings: local alias → { exported name, FQN specifier }. */+function collectPhpImportedSymbols(root: Parser.SyntaxNode): Map<string, { name: string; specifier: string }> {+ const out = new Map<string, { name: string; specifier: string }>();const visit = (node: Parser.SyntaxNode): void => {- if (node.type === "import_statement") {- const specifier = importSpecifier(node, lang);- if (!specifier) return;- collectTsImportBindings(node, specifier, out);+ if (node.type === "namespace_use_declaration") {+ collectPhpUseDeclaration(node, out);return;}for (const child of node.namedChildren) visit(child);@@ -650,6 +667,96 @@ function collectImportedSymbols(return out;}+function collectPhpUseDeclaration(+ decl: Parser.SyntaxNode,+ out: Map<string, { name: string; specifier: string }>,+): void {+ const prefix = decl.namedChildren.find((c) => c.type === "namespace_name")?.text.replace(/\\$/, "") ?? "";+ const clauses: Parser.SyntaxNode[] = [];+ for (const child of decl.namedChildren) {+ if (child.type === "namespace_use_clause") clauses.push(child);+ if (child.type === "namespace_use_group") {+ for (const c of child.namedChildren) {+ if (c.type === "namespace_use_clause") clauses.push(c);+ }+ }+ }+ for (const clause of clauses) {+ const binding = phpUseClauseBinding(clause, prefix);+ if (binding) out.set(binding.local, { name: binding.name, specifier: binding.specifier });+ }+}++function phpUseClauseBinding(+ clause: Parser.SyntaxNode,+ prefix: string,+): { local: string; name: string; specifier: string } | null {+ const names = clause.namedChildren.filter((c) => c.type === "name");+ const qualified = clause.namedChildren.find((c) => c.type === "qualified_name");+ let fqn: string;+ let importedName: string;+ if (qualified) {+ fqn = qualified.text.replace(/^\\/, "");+ importedName = fqn.replace(/^.*\\/, "");+ } else if (names[0]) {+ importedName = names[0].text;+ fqn = prefix ? `${prefix}\\${importedName}` : importedName;+ } else {+ return null;+ }+ const alias =+ qualified && names.length >= 1+ ? names[names.length - 1].text+ : names.length >= 2+ ? names[1].text+ : undefined;+ const local = alias ?? importedName;+ return { local, name: importedName, specifier: fqn };+}++/** PHP 8 attributes on a definition → `references` edges to the attribute class. */+function phpAttributeReferenceEdges(node: Parser.SyntaxNode, sourceId: string, ctx: WalkCtx): RawEdge[] {+ const edges: RawEdge[] = [];+ for (const child of node.namedChildren) {+ if (child.type !== "attribute_list") continue;+ for (const group of child.namedChildren) {+ if (group.type !== "attribute_group") continue;+ for (const attr of group.namedChildren) {+ if (attr.type !== "attribute") continue;+ const ref = phpAttributeClassRef(attr, ctx);+ if (ref) {+ edges.push({+ source: sourceId,+ relation: "references",+ name: ref.name,+ ...(ref.specifier ? { specifier: ref.specifier } : {}),+ file: ctx.rel,+ });+ }+ }+ }+ }+ return edges;+}++function phpAttributeClassRef(+ attr: Parser.SyntaxNode,+ ctx: WalkCtx,+): { name: string; specifier?: string } | null {+ const nameNode =+ attr.childForFieldName("name") ??+ attr.namedChildren.find((c) => c.type === "name" || c.type === "qualified_name");+ if (!nameNode) return null;+ if (nameNode.type === "qualified_name") {+ const fqn = nameNode.text.replace(/^\\/, "");+ return { name: fqn.replace(/^.*\\/, ""), specifier: fqn };+ }+ const bare = nameNode.text;+ const imported = ctx.importedSymbols.get(bare);+ if (imported) return { name: imported.name, specifier: imported.specifier };+ return { name: bare };+}+function collectTsImportBindings(node: Parser.SyntaxNode,specifier: string,diff --git a/src/graph/resolve.ts b/src/graph/resolve.tsindex 08fb51bf..ef8c4989 100644--- a/src/graph/resolve.ts+++ b/src/graph/resolve.ts@@ -174,10 +174,17 @@ export function resolveEdges(// A named import gives both halves needed for sound resolution: the module// it came from and the exported name. Resolve inside that file only, so a// same-named symbol elsewhere in the repo cannot become a false edge.- const targetFile = resolveImport(e.specifier, e.file, byId);+ const targetFile = e.file.endsWith(".php")+ ? resolvePhpUse(e.specifier, phpFilesBySuffix)+ : resolveImport(e.specifier, e.file, byId);if (!byId.has(targetFile)) continue; // external or unresolved moduleconst candidates = perFileName.get(targetFile)?.get(e.name) ?? [];if (candidates.length === 1) add(e.source, candidates[0].id, "references", "extracted");+ } else if (e.file.endsWith(".php") && byId.get(e.source)?.origin === "ast") {+ // PHP attribute without a `use` import (same-file or globally unique class).+ 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 (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. Resolvediff --git a/test/graph-php.test.ts b/test/graph-php.test.tsindex 14319534..074cd38f 100644--- a/test/graph-php.test.ts+++ b/test/graph-php.test.ts@@ -6,7 +6,7 @@*/import { test } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, writeFileSync, rmSync } from "node:fs";+import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from "node:fs";import { join } from "node:path";import { tmpdir } from "node:os";import { buildGraph } from "../src/graph/build.js";@@ -403,3 +403,78 @@ test("PHP extraction: closures become nodes and own the calls inside them", asynrmSync(dir, { recursive: true, force: true });}});++// Issue #144: PHP 8 attributes are metadata, not call sites — wire them as+// `references` edges from the annotated symbol to the attribute class.+const ATTR_ROUTE_PHP = `<?php+namespace Poc\\Attr;++#[\\Attribute]+class Route+{+ public function __construct(public string $path, public string $method = 'GET') {}+}+`;++const ATTR_DEPRECATED_PHP = `<?php+namespace Poc\\Attr;++#[\\Attribute]+class Deprecated+{+ public function __construct(public string $message) {}+}+`;++const ATTR_WIDGET_PHP = `<?php+namespace Poc;+use Poc\\Attr\\Route;+use Poc\\Attr\\Deprecated;++#[Deprecated('use NewWidget')]+class Widget {+ #[Route('/widgets', method: 'GET')]+ public function index(): void { $this->load(); }+ private function load(): void {}+}+`;++function makeAttributeFixture(): string {+ const dir = mkdtempSync(join(tmpdir(), "graft-php-attr-"));+ writeFileSync(join(dir, "composer.json"), `{"name": "poc/app"}\n`);+ mkdirSync(join(dir, "Poc", "Attr"), { recursive: true });+ writeFileSync(join(dir, "Poc", "Attr", "Route.php"), ATTR_ROUTE_PHP);+ writeFileSync(join(dir, "Poc", "Attr", "Deprecated.php"), ATTR_DEPRECATED_PHP);+ writeFileSync(join(dir, "Poc", "Widget.php"), ATTR_WIDGET_PHP);+ return dir;+}++test("PHP extraction: attribute usage resolves to references edges (#144)", async () => {+ const dir = makeAttributeFixture();+ try {+ await buildGraph(dir);+ const graph = readGraph(wiringPath(join(dir, "graft")))!;++ assert.ok(+ graph.edges.some(+ (e) =>+ e.relation === "references" &&+ e.source === "Poc/Widget.php#Widget" &&+ e.target === "Poc/Attr/Deprecated.php#Deprecated",+ ),+ "Widget class should reference the Deprecated attribute class",+ );++ assert.ok(+ graph.edges.some(+ (e) =>+ e.relation === "references" &&+ e.source === "Poc/Widget.php#Widget.index" &&+ e.target === "Poc/Attr/Route.php#Route",+ ),+ "index method should reference the Route attribute class",+ );+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});