Skip to content

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

fix(php): keep enums with array consts in the graph (#152)

Frankie-Xu0dd6c1015f2a
diff --git a/src/graph/extract.ts b/src/graph/extract.ts
index d6f99ff2..be6b6a8c 100644
--- a/src/graph/extract.ts
+++ b/src/graph/extract.ts
@@ -322,7 +322,7 @@ export function extractFile(rel: string, source: string, lang: Language): Extrac
// childCtx, so a by-ref Set there would read as ordinary inherited context
// when it's actually accidental shared mutable state across the whole walk.
const minted = new Set<string>([rel]);
- for (const child of root.namedChildren) walk(child, ctx, nodes, rawEdges, minted);
+ walkNamedChildren(root.namedChildren, ctx, nodes, rawEdges, minted);
// nodes[0] is the file node; the rest are its symbols. Index the module-level
// residual on the file node so a term outside every symbol still surfaces it.
nodes[0].body_text = fileResidual(source, nodes.slice(1));
@@ -343,6 +343,113 @@ export function mintId(base: string, minted: Set<string>): string {
return id;
}
+/**
+ * tree-sitter-php 0.23.x cannot parse a `const` inside an enum body (#145). An
+ * array initializer collapses the whole `enum_declaration` into ERROR; the
+ * method is recovered as a sibling `function_definition`. 0.24.2 parses this
+ * natively but is ABI 15 and cannot load on Graft's tree-sitter 0.21.1.
+ *
+ * Bound: only an ERROR that already contains `enum_case` + `name` is treated as
+ * a collapsed enum. Only `const_declaration` / `function_definition` /
+ * `method_declaration` / ERROR siblings are absorbed, stopping at a `}` ERROR.
+ * Unknown ERROR nodes are still walked, never mapped to a type. Clean
+ * class/enum trees are `class_declaration` / `enum_declaration` and skip this.
+ */
+function phpCollapsedEnumName(node: Parser.SyntaxNode): string | null {
+ if (node.type !== "ERROR") return null;
+ if (!node.namedChildren.some((c) => c.type === "enum_case")) return null;
+ return node.namedChildren.find((c) => c.type === "name")?.text ?? null;
+}
+
+function phpCollapsedEnumHold(node: Parser.SyntaxNode): boolean {
+ return (
+ node.type === "const_declaration" ||
+ node.type === "function_definition" ||
+ node.type === "method_declaration" ||
+ node.type === "ERROR"
+ );
+}
+
+function phpCollapsedEnumClose(node: Parser.SyntaxNode): boolean {
+ return node.type === "ERROR" && node.text.trim() === "}";
+}
+
+function walkNamedChildren(
+ children: Parser.SyntaxNode[],
+ ctx: WalkCtx,
+ out: NodeV1[],
+ edges: RawEdge[],
+ minted: Set<string>,
+): void {
+ if (ctx.lang !== "php") {
+ for (const child of children) walk(child, ctx, out, edges, minted);
+ return;
+ }
+ for (let i = 0; i < children.length; ) {
+ const n = children[i]!;
+ const enumName = phpCollapsedEnumName(n);
+ if (enumName) {
+ const group: Parser.SyntaxNode[] = [n];
+ let j = i + 1;
+ while (j < children.length && phpCollapsedEnumHold(children[j]!)) {
+ const next = children[j]!;
+ group.push(next);
+ j++;
+ if (phpCollapsedEnumClose(next)) break;
+ }
+ emitPhpCollapsedEnum(enumName, n, group, ctx, out, edges, minted);
+ i = j;
+ continue;
+ }
+ walk(n, ctx, out, edges, minted);
+ i++;
+ }
+}
+
+function emitPhpCollapsedEnum(
+ name: string,
+ errorNode: Parser.SyntaxNode,
+ group: Parser.SyntaxNode[],
+ ctx: WalkCtx,
+ out: NodeV1[],
+ edges: RawEdge[],
+ minted: Set<string>,
+): void {
+ const last = group[group.length - 1]!;
+ const id = mintId(`${ctx.rel}#${[...ctx.scope, name].join(".")}`, minted);
+ const body = ctx.source.slice(errorNode.startIndex, last.endIndex);
+ out.push({
+ id,
+ name,
+ kind: "enum",
+ path: ctx.rel,
+ span: `L${errorNode.startPosition.row + 1}-L${last.endPosition.row + 1}`,
+ signature: `enum ${name}`,
+ exported: true,
+ origin: "ast",
+ body_hash: contentHash(body),
+ body_text: searchBody(body),
+ summary_state: "pending",
+ summary: null,
+ crux: null,
+ });
+ edges.push({ source: ctx.parentId, relation: "contains", targetId: id, file: ctx.rel });
+ const childCtx: WalkCtx = {
+ ...ctx,
+ scope: [...ctx.scope, name],
+ enclosingKind: "enum",
+ parentId: id,
+ };
+ for (const g of group) {
+ if (phpCollapsedEnumClose(g)) continue;
+ if (phpCollapsedEnumName(g)) {
+ walkNamedChildren(g.namedChildren, childCtx, out, edges, minted);
+ continue;
+ }
+ walk(g, childCtx, out, edges, minted);
+ }
+}
+
function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEdge[], minted: Set<string>): void {
const desc = describe(node, ctx);
if (desc) {
@@ -411,7 +518,7 @@ function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEd
? withoutShadowedImports(ctx.importedSymbols, node)
: ctx.importedSymbols,
};
- for (const child of node.namedChildren) walk(child, childCtx, out, edges, minted);
+ walkNamedChildren(node.namedChildren, childCtx, out, edges, minted);
return;
}
@@ -665,6 +772,12 @@ function describe(node: Parser.SyntaxNode, ctx: WalkCtx): DefDescriptor | null {
if (ctx.lang === "python" && mapped === "function" && ctx.enclosingKind === "class") {
kind = "method";
}
+ // tree-sitter-php 0.23.x recovers a collapsed enum method as function_definition
+ // at program scope; walkNamedChildren reparents it under the enum, and this
+ // promotion is what keeps the kind `method` rather than a leaked `function`.
+ if (ctx.lang === "php" && mapped === "function" && ctx.enclosingKind === "enum") {
+ kind = "method";
+ }
const body = node.childForFieldName("body");
return { name, kind, headerEnd: body ? body.startIndex : node.endIndex, hashNode: node };
}
diff --git a/test/graph-php.test.ts b/test/graph-php.test.ts
index e6faf005..14319534 100644
--- a/test/graph-php.test.ts
+++ b/test/graph-php.test.ts
@@ -273,6 +273,103 @@ test("PHP closures: `graft check` stays fresh after build (no name drift)", asyn
}
});
+// #145: tree-sitter-php 0.23.x cannot parse `const` inside an enum body. An
+// array value collapses the whole `enum_declaration` into ERROR and recovers
+// the method as a file-scope `function_definition`. Scalar const / class const
+// must keep working — those trees already have a real type node.
+const ENUM_ARRAY_CONST_PHP = `<?php
+
+enum Foo: string
+{
+ case A = 'a';
+ case B = 'b';
+
+ private const MAP = [
+ 'a' => 'Alpha',
+ 'b' => 'Beta',
+ ];
+
+ public static function nameFor(string $k): ?string
+ {
+ return self::MAP[$k] ?? null;
+ }
+}
+`;
+
+const ENUM_SCALAR_CONST_PHP = `<?php
+
+enum Foo: string
+{
+ case A = 'a';
+
+ private const LABEL = 'x';
+
+ public static function nameFor(string $k): ?string
+ {
+ return self::LABEL;
+ }
+}
+`;
+
+const CLASS_ARRAY_CONST_PHP = `<?php
+
+class Foo
+{
+ private const MAP = [
+ 'a' => 'Alpha',
+ 'b' => 'Beta',
+ ];
+
+ public static function nameFor(string $k): ?string
+ {
+ return self::MAP[$k] ?? null;
+ }
+}
+`;
+
+function symbolIds(nodes: NodeV1[]): string[] {
+ return nodes.filter((n) => n.kind !== "file").map((n) => `${n.kind}:${n.id}`);
+}
+
+test("PHP enum with array const keeps enum:Foo and method:Foo.nameFor (#145)", () => {
+ const { nodes } = extractFile("e.php", ENUM_ARRAY_CONST_PHP, "php");
+ const ids = symbolIds(nodes);
+ assert.equal(nodes.find((n) => n.id === "e.php#Foo")?.kind, "enum", `expected enum:Foo, got: ${ids.join(", ")}`);
+ const nameFor = nodes.find((n) => n.id === "e.php#Foo.nameFor");
+ assert.equal(nameFor?.kind, "method", `expected method:Foo.nameFor, got: ${ids.join(", ")}`);
+ assert.equal(nameFor?.name, "nameFor");
+ assert.ok(
+ !nodes.some((n) => n.kind === "function" && n.name === "nameFor"),
+ `nameFor must not leak as a top-level function, got: ${ids.join(", ")}`,
+ );
+});
+
+test("PHP enum with scalar const still emits enum + qualified method (#145 control)", () => {
+ const { nodes } = extractFile("e.php", ENUM_SCALAR_CONST_PHP, "php");
+ const ids = symbolIds(nodes);
+ assert.equal(nodes.find((n) => n.id === "e.php#Foo")?.kind, "enum", `expected enum:Foo, got: ${ids.join(", ")}`);
+ assert.equal(nodes.find((n) => n.id === "e.php#Foo.nameFor")?.kind, "method", `expected method:Foo.nameFor, got: ${ids.join(", ")}`);
+ assert.ok(!nodes.some((n) => n.kind === "function" && n.name === "nameFor"), `got: ${ids.join(", ")}`);
+});
+
+test("PHP class with array const is unchanged (#145 control)", () => {
+ const { nodes } = extractFile("e.php", CLASS_ARRAY_CONST_PHP, "php");
+ const ids = symbolIds(nodes);
+ assert.equal(nodes.find((n) => n.id === "e.php#Foo")?.kind, "class", `expected class:Foo, got: ${ids.join(", ")}`);
+ assert.equal(nodes.find((n) => n.id === "e.php#Foo.nameFor")?.kind, "method", `expected method:Foo.nameFor, got: ${ids.join(", ")}`);
+ assert.ok(!nodes.some((n) => n.kind === "function" && n.name === "nameFor"), `got: ${ids.join(", ")}`);
+});
+
+test("PHP enum array-const recovery does not swallow a following top-level function (#145)", () => {
+ const source = `${ENUM_ARRAY_CONST_PHP.trimEnd()}\n\nfunction topLevel(): int\n{\n return 1;\n}\n`;
+ const { nodes } = extractFile("e.php", source, "php");
+ const ids = symbolIds(nodes);
+ assert.equal(nodes.find((n) => n.id === "e.php#Foo")?.kind, "enum", `got: ${ids.join(", ")}`);
+ assert.equal(nodes.find((n) => n.id === "e.php#Foo.nameFor")?.kind, "method", `got: ${ids.join(", ")}`);
+ assert.equal(nodes.find((n) => n.id === "e.php#topLevel")?.kind, "function", `got: ${ids.join(", ")}`);
+ assert.ok(!nodes.some((n) => n.id === "e.php#Foo.topLevel"), `topLevel must stay file-scope, got: ${ids.join(", ")}`);
+});
+
test("PHP extraction: closures become nodes and own the calls inside them", async () => {
const dir = makeFixture();
try {