Skip to content

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

feat(graph): C/C++ #include → resolved file→file import edges (breadth tier)

Shrish Dwivedi90e4d257a334
diff --git a/src/graph/generic.ts b/src/graph/generic.ts
index e5857af6..675b11bb 100644
--- a/src/graph/generic.ts
+++ b/src/graph/generic.ts
@@ -215,9 +215,34 @@ export function extractGeneric(rel: string, source: string, langName: string): E
} else {
walkExtract(tree.rootNode as TsNode, mkDef); // no tags.scm → symbols only
}
+ // The preprocessor is invisible to tags.scm, but in C/C++ a local `#include "x.h"`
+ // IS the dependency graph — capture it as a file→file import.
+ if (langName === "c" || langName === "cpp") extractIncludes(tree.rootNode as TsNode, rel, rawEdges);
return { nodes, rawEdges };
}
+/** C/C++ `#include "header.h"` → a file→file `imports` raw edge. Only LOCAL includes
+ * (quoted) are captured; system includes (`<stdio.h>`) are skipped — high volume, and
+ * there is no in-repo target to navigate to. resolve.ts settles the quoted path to an
+ * in-repo header (relative to the including file, else a unique path-suffix match), and
+ * keeps it as an external string when it cannot — never a guessed edge. */
+function extractIncludes(root: TsNode, rel: string, rawEdges: RawEdge[]): void {
+ const visit = (n: TsNode): void => {
+ if (n.type === "preproc_include") {
+ const raw = n.childForFieldName?.("path")?.text ?? "";
+ if (raw.startsWith('"')) {
+ const spec = raw.replace(/^"|"$/g, "").trim();
+ if (spec) rawEdges.push({ source: rel, relation: "imports", specifier: spec, file: rel });
+ }
+ }
+ for (let i = 0; i < (n.namedChildCount ?? 0); i++) {
+ const c = n.namedChild?.(i);
+ if (c) visit(c);
+ }
+ };
+ visit(root);
+}
+
/** tags.scm path: @definition.<kind> → nodes, @reference.call/@reference.send →
* bare-name call edges attributed to the innermost enclosing definition. */
function tagsExtract(
diff --git a/src/graph/resolve.ts b/src/graph/resolve.ts
index 56d7c26b..99e59bb1 100644
--- a/src/graph/resolve.ts
+++ b/src/graph/resolve.ts
@@ -18,6 +18,8 @@ import type { EdgeV1, Kind, NodeV1, Relation } from "./types.js";
import type { RawEdge } from "./extract.js";
const IMPORT_EXTS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs", ".py"];
+/** C/C++ source + header extensions, for resolving `#include` targets. */
+const C_EXT = /\.(c|h|cc|cpp|cxx|hpp|hh|hxx|inl|ipp|c\+\+|h\+\+)$/i;
/** A Go module discovered in the repo: its `module` path from `go.mod` and the repo
* directory that `go.mod` lives in (posix, `.` for the repo root). A monorepo may hold
@@ -52,6 +54,10 @@ export function resolveEdges(
// 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[]>();
+ // C/C++ header resolution: a file's path-suffix (`net/socket.h`, `socket.h`) → its
+ // file node ids, so an `#include` reached through an `-I` dir (not relative to the
+ // including file) still resolves to the in-repo header when the suffix is unique.
+ const cFilesBySuffix = new Map<string, string[]>();
const hasGoModules = !!opts.goModules?.length;
for (const n of nodes) {
if (n.kind === "file") {
@@ -66,6 +72,10 @@ export function resolveEdges(
const parts = toPosixPath(n.path).split("/");
for (let i = 0; i < parts.length; i++) push(javaFilesBySuffix, parts.slice(i).join("/"), n.id);
}
+ if (C_EXT.test(n.path)) {
+ const parts = toPosixPath(n.path).split("/");
+ for (let i = 0; i < parts.length; i++) push(cFilesBySuffix, parts.slice(i).join("/"), n.id);
+ }
continue;
}
push(globalName, n.name, n);
@@ -109,7 +119,9 @@ export function resolveEdges(
? resolveGoImport(e.specifier, opts.goModules!, goFilesByDir)
: e.file.endsWith(".java")
? resolveJavaImport(e.specifier, javaFilesBySuffix)
- : resolveImport(e.specifier, e.file, byId);
+ : C_EXT.test(e.file)
+ ? resolveCInclude(e.specifier, e.file, byId, cFilesBySuffix)
+ : 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"];
@@ -322,6 +334,27 @@ function resolveJavaImport(spec: string, filesBySuffix: Map<string, string[]>):
return spec;
}
+/**
+ * Resolve a C/C++ `#include "path"` to an in-repo file node: relative to the including
+ * file first (the common case, and certain), else a UNIQUE path-suffix match — which
+ * covers a header reached through an `-I` include directory rather than a relative path.
+ * Anything ambiguous or not found stays the raw path (a system or out-of-repo header),
+ * never a guessed edge.
+ */
+function resolveCInclude(
+ spec: string,
+ file: string,
+ byId: Map<string, NodeV1>,
+ bySuffix: Map<string, string[]>,
+): string {
+ const dir = posix.dirname(toPosixPath(file));
+ const relJoin = posix.normalize(posix.join(dir, spec));
+ if (byId.has(relJoin)) return relJoin; // relative to the including file — certain
+ const hits = bySuffix.get(spec.replace(/^\.?\//, ""));
+ if (hits && hits.length === 1) return hits[0]; // unique suffix — an -I-reached header
+ return spec; // system/out-of-repo/ambiguous — keep the string, do not guess
+}
+
/**
* 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/generic-extract.test.ts b/test/generic-extract.test.ts
index 02bb4043..649a4180 100644
--- a/test/generic-extract.test.ts
+++ b/test/generic-extract.test.ts
@@ -145,6 +145,41 @@ test("breadth tier: Java extends/implements/new become resolved references edges
assert.ok(!refs.some((e) => e.source === e.target), "no self-loop references");
});
+// C/C++ #include is the dependency graph the tags.scm can't see (it's the
+// preprocessor). A local `#include "x.h"` becomes a file→file import the resolver
+// settles to an in-repo header — relative first, then a unique path-suffix (an
+// -I-reached header), and never a guess. System `<...>` includes are skipped.
+test("breadth tier: C #include becomes a resolved file→file import (local only, drop-rather-than-guess)", async () => {
+ await warmGenericGrammars(["c"]);
+ const files: Record<string, string> = {
+ "src/app.c": '#include "app.h"\n#include "net/sock.h"\n#include <stdio.h>\nint run(void){return 0;}\n',
+ "src/app.h": "int run(void);\n",
+ "src/net/sock.h": "int connect_sock(void);\n",
+ "include/uniq.h": "int uq(void);\n", // reachable only via -I, unique basename
+ "src/uses.c": '#include "uniq.h"\n',
+ "a/util.h": "int a_u(void);\n", // two util.h → an ambiguous basename
+ "b/util.h": "int b_u(void);\n",
+ "src/amb.c": '#include "util.h"\n',
+ };
+ const nodes = [], raw = [];
+ for (const [rel, src] of Object.entries(files)) {
+ const r = extractGeneric(rel, src, "c");
+ nodes.push(...r.nodes); raw.push(...r.rawEdges);
+ }
+ const imports = resolveEdges(nodes, raw).filter((e) => e.relation === "imports");
+ const targetsOf = (src: string) => imports.filter((e) => e.source === src).map((e) => e.target);
+
+ // relative include → the in-repo header (exact; same dir and a subdir)
+ assert.ok(targetsOf("src/app.c").includes("src/app.h"), "app.c → app.h (same dir)");
+ assert.ok(targetsOf("src/app.c").includes("src/net/sock.h"), "app.c → net/sock.h (subdir)");
+ // system <stdio.h> is skipped entirely — no import edge minted
+ assert.ok(!imports.some((e) => String(e.target).includes("stdio")), "system include is not captured");
+ // a unique basename reached via -I resolves by suffix
+ assert.ok(targetsOf("src/uses.c").includes("include/uniq.h"), "unique -I header resolves by suffix");
+ // an ambiguous basename is NOT guessed — kept as the raw string, resolving to neither file
+ assert.deepEqual(targetsOf("src/amb.c"), ["util.h"], "ambiguous include kept external, never guessed");
+});
+
test("buildGraph + checkGraph handle a breadth-tier (.rs) repo end-to-end", async () => {
const dir = mkdtempSync(join(tmpdir(), "graft-rust-"));
mkdirSync(join(dir, "src"), { recursive: true });