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(graph): receiver-type binding pass — member calls carry their receiver's type
Shrish Dwivedi3cdb086980b1
diff --git a/src/graph/bindings.ts b/src/graph/bindings.tsnew file mode 100644index 00000000..4b462597--- /dev/null+++ b/src/graph/bindings.ts@@ -0,0 +1,288 @@+/**+ * Receiver-type binding pass: a pre-order walk over a parsed file that answers,+ * for every local variable / parameter / class field / `self`|`this` attribute,+ * "what type is this?" — so a later member-call site (`app.include_router()`)+ * can look up `app`'s bound type instead of resolving on the bare method name+ * alone. Pure and dependency-only: no LLM, no network, no mutation of the AST.+ *+ * Only `import type` from extract.ts (never a value) — extract.ts imports+ * `collectBindings` from here, so a value import back would be a cycle.+ */+import type Parser from "tree-sitter";+import type { Language, WalkCtx } from "./extract.js";++/** Variable/field → bare type name, keyed by scope. Scope keys mirror+ * extract.ts's own scope stack (`scope.join(".")`, `""` at module level) so a+ * lookup from extract.ts's walk finds exactly what was bound in the same+ * lexical position. */+export class FileBindings {+ private map = new Map<string, string>();++ set(scopePath: string, name: string, type: string): void {+ this.map.set(`${scopePath}|${name}`, type);+ }++ /** Innermost-first: for scope ["a","b"] name "x", tries `a.b|x`, `a|x`, `|x`. */+ lookup(scope: string[], name: string): string | null {+ for (let i = scope.length; i >= 0; i--) {+ const hit = this.map.get(`${scope.slice(0, i).join(".")}|${name}`);+ if (hit) return hit;+ }+ return null;+ }+}++const FN_VALUE_TYPES = new Set(["arrow_function", "function", "function_expression", "generator_function"]);++/** Definition-node types that push a new scope segment, mirroring extract.ts's+ * `describe()` closely enough to keep the two scope stacks in lockstep — but+ * duplicated here (not imported) to keep bindings.ts free of a value import on+ * extract.ts. Returns the bare def name, or null if `node` isn't a definition. */+export function defName(node: Parser.SyntaxNode, lang: Language): string | null {+ if (lang === "go") {+ if (node.type === "function_declaration" || node.type === "method_declaration" || node.type === "type_spec") {+ return node.childForFieldName("name")?.text ?? null;+ }+ return null;+ }+ const defTypes =+ lang === "python"+ ? new Set(["class_definition", "function_definition"])+ : new Set([+ "class_declaration",+ "abstract_class_declaration",+ "function_declaration",+ "generator_function_declaration",+ "method_definition",+ "interface_declaration",+ "type_alias_declaration",+ "enum_declaration",+ ]);+ if (defTypes.has(node.type)) return node.childForFieldName("name")?.text ?? null;+ if ((lang === "typescript" || lang === "tsx") && node.type === "variable_declarator") {+ const value = node.childForFieldName("value");+ if (value && FN_VALUE_TYPES.has(value.type)) return node.childForFieldName("name")?.text ?? null;+ }+ return null;+}++/** The receiver parameter's own variable name for a Go method (`func (w *Worker) …`+ * → `w`). Null if it can't be read. */+export function goReceiverVarOf(node: Parser.SyntaxNode): string | null {+ const recv = node.childForFieldName("receiver");+ const param = recv?.namedChildren.find((c) => c.type === "parameter_declaration");+ return param?.childForFieldName("name")?.text ?? null;+}++/** Resolves a call site's receiver text (from `calleeName`) to a bound type+ * name, given the enclosing walk state. `self`/`cls`/`this`/the Go receiver+ * var resolve directly to the enclosing class; anything else is a bindings-map+ * lookup, normalizing `this.` to `self.` since both are stored the same way. */+export function resolveRecvType(+ receiver: string | undefined,+ ctx: Pick<WalkCtx, "scope" | "enclosingClass" | "goReceiverVar" | "lang" | "bindings">,+): string | undefined {+ if (!receiver) return undefined;+ if (receiver === "self" || receiver === "cls" || receiver === "this") return ctx.enclosingClass ?? undefined;+ if (receiver.startsWith("self.") || receiver.startsWith("this.")) {+ return (+ ctx.bindings.lookup(ctx.scope, receiver) ??+ ctx.bindings.lookup(ctx.scope, receiver.replace(/^this\./, "self.")) ??+ undefined+ );+ }+ return (+ (ctx.lang === "go" && receiver === ctx.goReceiverVar ? ctx.enclosingClass : undefined) ??+ ctx.bindings.lookup(ctx.scope, receiver) ??+ undefined+ );+}++function isClassNode(node: Parser.SyntaxNode, lang: Language): boolean {+ if (lang === "python") return node.type === "class_definition";+ if (lang === "typescript" || lang === "tsx") {+ return node.type === "class_declaration" || node.type === "abstract_class_declaration";+ }+ return false;+}++/** Pass 1 over a parsed file: collect variable->type bindings. Pure. */+export function collectBindings(root: Parser.SyntaxNode, lang: Language): FileBindings {+ const bindings = new FileBindings();+ const aliases = new Map<string, string>();+ collectAliases(root, lang, aliases);+ visit(root, lang, [], null, bindings, aliases);+ return bindings;+}++/** Import aliases (`... as F`) can be declared anywhere relative to their use+ * textually, so this scans the whole tree once, ahead of the scope-aware walk. */+function collectAliases(node: Parser.SyntaxNode, lang: Language, aliases: Map<string, string>): void {+ if (lang === "python" && node.type === "aliased_import") {+ const nameNode = node.childForFieldName("name");+ const aliasNode = node.childForFieldName("alias");+ if (nameNode && aliasNode) {+ const orig = nameNode.type === "dotted_name" ? (nameNode.namedChildren.at(-1)?.text ?? nameNode.text) : nameNode.text;+ aliases.set(aliasNode.text, orig);+ }+ } else if ((lang === "typescript" || lang === "tsx") && node.type === "import_specifier") {+ const nameNode = node.childForFieldName("name");+ const aliasNode = node.childForFieldName("alias");+ if (nameNode && aliasNode) aliases.set(aliasNode.text, nameNode.text);+ }+ for (const child of node.namedChildren) collectAliases(child, lang, aliases);+}++/** `scope`/`classScope` mirror extract.ts's walk: `scope` is the enclosing+ * definition-name stack; `classScope` is the nearest enclosing class's scope+ * path (distinct from `scope` once we're inside one of its methods) — that's+ * where `self.attr`/`this.attr` bindings live. */+function visit(+ node: Parser.SyntaxNode,+ lang: Language,+ scope: string[],+ classScope: string | null,+ bindings: FileBindings,+ aliases: Map<string, string>,+): void {+ if (lang === "python") handlePy(node, scope, classScope, bindings, aliases);+ else if (lang === "go") handleGo(node, scope, bindings);+ else handleTs(node, scope, classScope, bindings, aliases);++ const name = defName(node, lang);+ let childScope = scope;+ let childClassScope = classScope;+ if (name !== null) {+ childScope = [...scope, name];+ if (isClassNode(node, lang)) childClassScope = childScope.join(".");+ }+ for (const child of node.namedChildren) visit(child, lang, childScope, childClassScope, bindings, aliases);+}++function pyTypeName(node: Parser.SyntaxNode | null | undefined): string | null {+ if (!node) return null;+ if (node.type === "identifier") return node.text;+ if (node.type === "type") {+ const inner = node.namedChildren[0];+ return inner?.type === "identifier" ? inner.text : null;+ }+ return null;+}++function callTypeName(node: Parser.SyntaxNode | null | undefined, aliases: Map<string, string>): string | null {+ if (node?.type !== "call") return null;+ const fn = node.childForFieldName("function");+ if (fn?.type !== "identifier") return null;+ return aliases.get(fn.text) ?? fn.text;+}++function handlePy(+ node: Parser.SyntaxNode,+ scope: string[],+ classScope: string | null,+ bindings: FileBindings,+ aliases: Map<string, string>,+): void {+ const scopePath = scope.join(".");+ if (node.type === "typed_parameter") {+ const nameNode = node.namedChildren.find((c) => c.type === "identifier");+ const typeName = pyTypeName(node.childForFieldName("type"));+ if (nameNode && typeName) bindings.set(scopePath, nameNode.text, typeName);+ return;+ }+ if (node.type !== "assignment") return;+ const left = node.childForFieldName("left");+ const right = node.childForFieldName("right");+ if (!left) return;+ if (left.type === "identifier") {+ const typeField = node.childForFieldName("type");+ const typeName = typeField ? pyTypeName(typeField) : callTypeName(right, aliases);+ if (typeName) bindings.set(scopePath, left.text, typeName);+ } else if (left.type === "attribute") {+ const obj = left.childForFieldName("object");+ const attr = left.childForFieldName("attribute");+ if (obj?.type === "identifier" && (obj.text === "self" || obj.text === "cls") && attr) {+ const typeName = callTypeName(right, aliases);+ if (typeName) bindings.set(classScope ?? scopePath, `self.${attr.text}`, typeName);+ }+ }+}++function tsAnnotationTypeName(typeAnn: Parser.SyntaxNode | null | undefined): string | null {+ if (!typeAnn || typeAnn.type !== "type_annotation") return null;+ const t = typeAnn.namedChildren[0];+ return t?.type === "type_identifier" ? t.text : null;+}++function tsNewTypeName(value: Parser.SyntaxNode | null | undefined, aliases: Map<string, string>): string | null {+ if (value?.type !== "new_expression") return null;+ const ctor = value.childForFieldName("constructor");+ if (ctor?.type !== "identifier") return null;+ return aliases.get(ctor.text) ?? ctor.text;+}++function handleTs(+ node: Parser.SyntaxNode,+ scope: string[],+ classScope: string | null,+ bindings: FileBindings,+ aliases: Map<string, string>,+): void {+ const scopePath = scope.join(".");+ if (node.type === "variable_declarator") {+ const value = node.childForFieldName("value");+ if (value && FN_VALUE_TYPES.has(value.type)) return; // a function def, not a type binding+ const name = node.childForFieldName("name");+ if (name?.type !== "identifier") return;+ const typeName = tsNewTypeName(value, aliases) ?? tsAnnotationTypeName(node.childForFieldName("type"));+ if (typeName) bindings.set(scopePath, name.text, typeName);+ } else if (node.type === "public_field_definition") {+ const name = node.childForFieldName("name");+ if (!name) return;+ const typeName =+ tsAnnotationTypeName(node.childForFieldName("type")) ?? tsNewTypeName(node.childForFieldName("value"), aliases);+ if (typeName) bindings.set(classScope ?? scopePath, `this.${name.text}`, typeName);+ } else if (node.type === "required_parameter") {+ const pattern = node.childForFieldName("pattern");+ if (pattern?.type !== "identifier") return;+ const typeName = tsAnnotationTypeName(node.childForFieldName("type"));+ if (typeName) bindings.set(scopePath, pattern.text, typeName);+ }+}++function handleGo(node: Parser.SyntaxNode, scope: string[], bindings: FileBindings): void {+ const scopePath = scope.join(".");+ if (node.type === "var_spec") {+ const name = node.childForFieldName("name");+ let type = node.childForFieldName("type");+ if (type?.type === "pointer_type") type = type.namedChildren.at(-1) ?? null;+ if (name?.type === "identifier" && type?.type === "type_identifier") {+ bindings.set(scopePath, name.text, type.text);+ }+ return;+ }+ if (node.type !== "short_var_declaration") return;+ const left = node.childForFieldName("left");+ const right = node.childForFieldName("right");+ if (!left || !right) return;+ const names = left.namedChildren;+ const exprs = right.namedChildren;+ for (let i = 0; i < names.length; i++) {+ const nameNode = names[i];+ let expr = exprs[i];+ if (!nameNode || nameNode.type !== "identifier" || !expr) continue;+ if (expr.type === "unary_expression") {+ expr = expr.namedChildren.find((c) => c.type === "composite_literal") ?? expr;+ }+ let typeName: string | null = null;+ if (expr.type === "composite_literal") {+ const t = expr.childForFieldName("type");+ typeName = t?.type === "type_identifier" ? t.text : null;+ } else if (expr.type === "call_expression") {+ const fn = expr.childForFieldName("function");+ // Go convention: NewX(...) binds to X.+ if (fn?.type === "identifier" && /^New[A-Z]/.test(fn.text)) typeName = fn.text.slice(3);+ }+ if (typeName) bindings.set(scopePath, nameNode.text, typeName);+ }+}diff --git a/src/graph/extract.ts b/src/graph/extract.tsindex 2b4e3826..63c2d6b0 100644--- a/src/graph/extract.ts+++ b/src/graph/extract.ts@@ -12,6 +12,7 @@ import Python from "tree-sitter-python";import Go from "tree-sitter-go";import { basename } from "node:path";import { contentHash } from "../util/id.js";+import { collectBindings, goReceiverVarOf, resolveRecvType, type FileBindings } from "./bindings.js";import type { Kind, NodeV1, Relation } from "./types.js";export type Language = "typescript" | "tsx" | "python" | "go";@@ -38,6 +39,9 @@ export interface RawEdge {specifier?: string; // module path to resolve (imports)name?: string; // symbol name to resolve (extends/implements/calls)viaMember?: boolean; // calls: was it `obj.foo()` (→ prefer method targets)?+ /** calls with viaMember: the receiver's resolved type name (from bindings /+ * self / this / Go receiver), when a confident local clue exists. */+ recvType?: string;}export interface ExtractResult {@@ -129,7 +133,7 @@ const GRAMMARS: Record<Language, unknown> = {go: Go,};-interface WalkCtx {+export interface WalkCtx {rel: string;source: string;lang: Language;@@ -137,6 +141,9 @@ interface WalkCtx {scope: string[]; // enclosing definition names, for id scopingenclosingKind: Kind | null; // kind of the nearest enclosing definitionparentId: string; // nearest enclosing definition id, or the file id+ bindings: FileBindings; // variable/field -> type, for receiver-type lookups+ enclosingClass: string | null; // nearest enclosing class (py/ts `self`/`this`)+ goReceiverVar: string | null; // Go receiver var, e.g. `w` in `func (w *Worker)`}/** A definition we're about to emit, normalized across the shapes we handle. */@@ -161,6 +168,7 @@ function parseSource(source: string): Parser.SyntaxNode {export function extractFile(rel: string, source: string, lang: Language): ExtractResult {parser.setLanguage(GRAMMARS[lang] as never);const root = parseSource(source);+ const bindings = collectBindings(root, lang);const nodes: NodeV1[] = [{@@ -189,6 +197,9 @@ export function extractFile(rel: string, source: string, lang: Language): Extracscope: [],enclosingKind: null,parentId: rel,+ bindings,+ enclosingClass: null,+ goReceiverVar: null,};for (const child of root.namedChildren) walk(child, ctx, nodes, rawEdges);// nodes[0] is the file node; the rest are its symbols. Index the module-level@@ -229,11 +240,15 @@ function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEd// class heritageif (desc.kind === "class") edges.push(...heritageEdges(node, id, ctx));+ const isGoMethod = ctx.lang === "go" && node.type === "method_declaration";+ const enclosingClass = desc.kind === "class" ? desc.name : isGoMethod ? goReceiverType(node) : ctx.enclosingClass;const childCtx: WalkCtx = {...ctx,scope: [...ctx.scope, idPart],enclosingKind: desc.kind,parentId: id,+ enclosingClass,+ goReceiverVar: isGoMethod ? goReceiverVarOf(node) : ctx.goReceiverVar,};for (const child of node.namedChildren) walk(child, childCtx, out, edges);return;@@ -244,13 +259,15 @@ function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEdif (node.type === callType) {const callee = calleeName(node, ctx.lang);if (callee) {- edges.push({+ const callEdge: RawEdge = {source: ctx.parentId,relation: "calls",name: callee.name,viaMember: callee.viaMember,file: ctx.rel,- });+ };+ const recvType = resolveRecvType(callee.receiver, ctx);+ edges.push(recvType ? { ...callEdge, recvType } : callEdge);}} else if (isImport(node, ctx.lang)) {const spec = importSpecifier(node, ctx.lang);@@ -388,26 +405,54 @@ function heritageEdges(node: Parser.SyntaxNode, classId: string, ctx: WalkCtx):function calleeName(node: Parser.SyntaxNode,lang: Language,-): { name: string; viaMember: boolean } | null {+): { name: string; viaMember: boolean; receiver?: string } | null {const fn = node.childForFieldName("function");if (!fn) return null;if (fn.type === "identifier") return { name: fn.text, viaMember: false };if (lang === "python" && fn.type === "attribute") {const a = fn.childForFieldName("attribute") ?? fn.namedChildren.at(-1);- return a ? { name: a.text, viaMember: true } : null;+ return a ? { name: a.text, viaMember: true, receiver: pyReceiver(fn) } : null;}if (lang === "go" && fn.type === "selector_expression") {// `pkg.Fn()` / `recv.Method()` — the called name is the trailing field.const p = fn.childForFieldName("field") ?? fn.namedChildren.at(-1);- return p ? { name: p.text, viaMember: true } : null;+ const operand = fn.childForFieldName("operand");+ const receiver = operand?.type === "identifier" ? operand.text : undefined;+ return p ? { name: p.text, viaMember: true, receiver } : null;}if ((lang === "typescript" || lang === "tsx") && fn.type === "member_expression") {const p = fn.childForFieldName("property") ?? fn.namedChildren.at(-1);- return p ? { name: p.text, viaMember: true } : null;+ return p ? { name: p.text, viaMember: true, receiver: tsReceiver(fn) } : null;}return null;}+/** py `attribute` node's receiver text: bare identifier, or `self.x` for a+ * chained `self.x.y()`. Anything else (e.g. a chained call `f().g()`) → none. */+function pyReceiver(fn: Parser.SyntaxNode): string | undefined {+ const obj = fn.childForFieldName("object");+ if (obj?.type === "identifier") return obj.text;+ if (obj?.type === "attribute") {+ const innerObj = obj.childForFieldName("object");+ const innerAttr = obj.childForFieldName("attribute");+ if (innerObj?.type === "identifier" && innerObj.text === "self" && innerAttr) return `self.${innerAttr.text}`;+ }+ return undefined;+}++/** ts `member_expression` node's receiver text: `this`, `this.x`, or a bare identifier. */+function tsReceiver(fn: Parser.SyntaxNode): string | undefined {+ const obj = fn.childForFieldName("object");+ if (obj?.type === "this") return "this";+ if (obj?.type === "identifier") return obj.text;+ if (obj?.type === "member_expression") {+ const innerObj = obj.childForFieldName("object");+ const innerProp = obj.childForFieldName("property");+ if (innerObj?.type === "this" && innerProp) return `this.${innerProp.text}`;+ }+ return undefined;+}+function isImport(node: Parser.SyntaxNode, lang: Language): boolean {// Go: match the per-import leaf, so single (`import "fmt"`) and grouped// (`import ( … )`) forms each yield one edge as the walk recurses into the list.diff --git a/test/graph-bindings.test.ts b/test/graph-bindings.test.tsnew file mode 100644index 00000000..70b3e606--- /dev/null+++ b/test/graph-bindings.test.ts@@ -0,0 +1,59 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { extractFile } from "../src/graph/extract.js";++function callEdges(src: string, lang: "python" | "typescript" | "go", file = `x.${lang === "python" ? "py" : lang === "go" ? "go" : "ts"}`) {+ return extractFile(file, src, lang).rawEdges.filter((e) => e.relation === "calls");+}++test("py: constructor assignment binds receiver type", () => {+ const edges = callEdges("class A:\n def m(self): pass\napp = A()\ndef f():\n app.m()\n", "python");+ const call = edges.find((e) => e.name === "m" && e.viaMember);+ assert.equal(call?.recvType, "A");+});++test("py: parameter annotation binds", () => {+ const edges = callEdges("def f(app: FastAPI):\n app.include_router()\n", "python");+ assert.equal(edges.find((e) => e.name === "include_router")?.recvType, "FastAPI");+});++test("py: self binds to enclosing class; self.attr via __init__ assignment", () => {+ const src = "class S:\n def __init__(self):\n self.q = Queue()\n def go(self):\n self.helper()\n self.q.put(1)\n";+ const edges = callEdges(src, "python");+ assert.equal(edges.find((e) => e.name === "helper")?.recvType, "S");+ assert.equal(edges.find((e) => e.name === "put")?.recvType, "Queue");+});++test("py: import alias resolves to original name", () => {+ const edges = callEdges("from fastapi import FastAPI as F\napp = F()\napp.get()\n", "python");+ assert.equal(edges.find((e) => e.name === "get")?.recvType, "FastAPI");+});++test("py: unknown receiver leaves recvType unset (chained call)", () => {+ const edges = callEdges("def f():\n factory().run()\n", "python");+ assert.equal(edges.find((e) => e.name === "run")?.recvType, undefined);+});++test("ts: new-expression + type annotation + this", () => {+ const src = "class S {\n q: Queue = new Queue();\n go() { this.helper(); this.q.put(1); }\n helper() {}\n}\nconst app = new FastAPI();\nfunction f(r: Router) { app.mount(); r.use(); }\n";+ const edges = callEdges(src, "typescript");+ assert.equal(edges.find((e) => e.name === "helper")?.recvType, "S");+ assert.equal(edges.find((e) => e.name === "put")?.recvType, "Queue");+ assert.equal(edges.find((e) => e.name === "mount")?.recvType, "FastAPI");+ assert.equal(edges.find((e) => e.name === "use")?.recvType, "Router");+});++test("go: composite literal, var decl, NewX convention, receiver var", () => {+ const src = "package m\nfunc f() {\n u := User{}\n var d *DB\n s := NewServer()\n u.Save()\n d.Query()\n s.Start()\n}\nfunc (w *Worker) run() { w.stop() }\n";+ const edges = callEdges(src, "go", "x.go");+ assert.equal(edges.find((e) => e.name === "Save")?.recvType, "User");+ assert.equal(edges.find((e) => e.name === "Query")?.recvType, "DB");+ assert.equal(edges.find((e) => e.name === "Start")?.recvType, "Server");+ assert.equal(edges.find((e) => e.name === "stop")?.recvType, "Worker");+});++test("scope shadowing: inner binding wins", () => {+ const src = "app = A()\ndef f():\n app = B()\n app.m()\n";+ const edges = callEdges(src, "python");+ assert.equal(edges.find((e) => e.name === "m")?.recvType, "B");+});