Skip to content

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

feat: add R language support (#70)

Prof. Adam Kapelnercf37dda3ff3a
diff --git a/.claude/settings.json b/.claude/settings.json
deleted file mode 100644
index 4ec4913b..00000000
--- a/.claude/settings.json
+++ /dev/null
@@ -1,78 +0,0 @@
-{
- "statusLine": {
- "type": "command",
- "command": "node \"${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-statusline.cjs\""
- },
- "subagentStatusLine": {
- "type": "command",
- "command": "node \"${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-statusline.cjs\""
- },
- "footerLinksRegexes": [
- "graft/[\\w./-]+\\.md"
- ],
- "hooks": {
- "PostToolUse": [
- {
- "matcher": "Write|Edit|MultiEdit",
- "hooks": [
- {
- "type": "command",
- "command": "node \"${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-hooks.cjs\" post-edit",
- "timeout": 10000
- }
- ]
- },
- {
- "matcher": "Bash|mcp__graft__",
- "hooks": [
- {
- "type": "command",
- "command": "node \"${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-hooks.cjs\" tool-savings",
- "timeout": 8000
- }
- ]
- }
- ],
- "Stop": [
- {
- "hooks": [
- {
- "type": "command",
- "command": "node \"${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-hooks.cjs\" stop",
- "timeout": 8000
- }
- ]
- }
- ],
- "UserPromptSubmit": [
- {
- "hooks": [
- {
- "type": "command",
- "command": "node \"${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-hooks.cjs\" prompt",
- "timeout": 15000
- }
- ]
- }
- ],
- "SessionStart": [
- {
- "hooks": [
- {
- "type": "command",
- "command": "node \"${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/graft-hooks.cjs\" session-start",
- "timeout": 8000
- }
- ]
- }
- ]
- },
- "permissions": {
- "allow": [
- "Bash(graft:*)",
- "Bash(npx graft:*)",
- "Bash(graft-dev:*)",
- "Bash(node dist/cli.js:*)"
- ]
- }
-}
diff --git a/.github/workflows/blast-pages.yml b/.github/workflows/blast-pages.yml
index df2c6e1b..2a68369c 100644
--- a/.github/workflows/blast-pages.yml
+++ b/.github/workflows/blast-pages.yml
@@ -75,12 +75,19 @@ jobs:
run: npm ci && npm run build
# 2. The PR's code, as data only.
+ #
+ # actions/checkout refuses a fork's PR ref under `pull_request_target` unless
+ # the workflow opts in — the review that opt-in asks for is the header of this
+ # file: the checkout is credential-less, lands in its own directory, and
+ # nothing below executes anything from it (the CLI that reads it was built
+ # from the base commit above). Without the flag every fork PR fails here.
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
ref: refs/pull/${{ steps.pr.outputs.number }}/merge
path: pr
fetch-depth: 0
persist-credentials: false
+ allow-unsafe-pr-checkout: true
# Same cache the comment job reads (see blast-cache.yml). Both jobs name the
# same clusters, so sharing the cache is what keeps the page's bubbles worded
diff --git a/.gitignore b/.gitignore
index 2cd097c9..e5685282 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,3 +16,8 @@ graft/
# Session transcripts and prompt traces — local analysis, not product.
transcripts/
+
+# Claude Code settings — regenerated per machine by `graft init`, never shared
+# and never part of a PR diff (the hook helpers/skills alongside them stay tracked).
+.claude/settings.json
+.claude/settings.local.json
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a87a4507..8971c273 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,33 @@
# Changelog
+## Unreleased
+
+### Added
+
+- **R language support.** `tree-sitter-r` (`npm:@davisvaughan/tree-sitter-r`;
+ the unscoped npm name is a squatted placeholder) parses `.R`/`.r` files.
+ Plain functions: every `name <- function(...)` / `name = function(...)` /
+ `function(...) -> name` assignment becomes a `function` node (the grammar's
+ `function_definition` has no name field, so the name comes from the
+ enclosing assignment; right-assign has its own AST shape). Classes — R's
+ class systems are library convention, not syntax, so they are recognised by
+ call idiom: **R6** (`R6::R6Class(...)` — the class node, `public =`/
+ `private =`/`active =` entries as methods, `inherit =` heritage, and `self$`/
+ `private$`/`super$` calls resolving to the class or its parent), **S4**
+ (`setClass()`/`setMethod()` with `contains =` heritage), **S3**
+ (`generic.Class <- function()` only when `generic` is registered locally via
+ `UseMethod()` or is one of a small curated base-R set — false negatives over
+ false positives), and plain-list mixin bundles (`Foo <- list(public =
+ list(...), ...)`) that are spliced across classes instead of inherited. An
+ untyped `obj$method()` resolves by bare name to a uniquely-named method
+ (ambiguous drops). Visibility: a roxygen `#' @export` tag wins; a roxygen
+ block without it means "not exported"; no roxygen falls back to the
+ leading-dot convention; R6 `private =` members are unexported.
+ `library()`/`require()`/`source()` calls are the import edges. Known gaps:
+ S3 generics registered in another file aren't seen (per-file pass); S4
+ `signature()` multiple dispatch isn't handled; R6 active bindings are
+ ordinary methods.
+
## 0.12.0
### Added
diff --git a/README.md b/README.md
index 3946b2c0..760e1e1f 100644
--- a/README.md
+++ b/README.md
@@ -192,7 +192,9 @@ compiler-grade layer — all `$0` and deterministic (no model, no key):
- **Full-fidelity** — hand-written extractors with scope-aware, cross-file call
and import resolution:
- **TypeScript / JavaScript** (incl. JSX & TSX), **Python**, **Go**, **Java**.
+ **TypeScript / JavaScript** (incl. JSX & TSX), **Python**, **Go**, **Java**,
+ **R** (`.R`/`.r` — plain functions, S3/S4/R6 classes and methods, roxygen
+ `@export`, `library()`/`source()` imports).
- **Broad** — symbols (functions, classes, methods, types, …) plus name-resolved
call edges via a generic tree-sitter extractor, one grammar per language:
diff --git a/node_modules b/node_modules
deleted file mode 120000
index 9cf9293f..00000000
--- a/node_modules
+++ /dev/null
@@ -1 +0,0 @@
-/Users/shrishdwivedi/Documents/Context graphs/context-graph-engine/node_modules
\ No newline at end of file
diff --git a/package-lock.json b/package-lock.json
index 45a4d318..36a7ef6d 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -21,6 +21,7 @@
"tree-sitter-kotlin": "^0.3.8",
"tree-sitter-php": "^0.23.4",
"tree-sitter-python": "^0.21.0",
+ "tree-sitter-r": "npm:@davisvaughan/tree-sitter-r@^1.3.0",
"tree-sitter-typescript": "^0.23.2",
"tree-sitter-wasm": "^1.1.4",
"vscode-jsonrpc": "^8.2.1",
@@ -984,6 +985,26 @@
"integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==",
"license": "MIT"
},
+ "node_modules/tree-sitter-r": {
+ "name": "@davisvaughan/tree-sitter-r",
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/@davisvaughan/tree-sitter-r/-/tree-sitter-r-1.3.0.tgz",
+ "integrity": "sha512-IwQyWDNgWtTguaEaxKLOD4wuAfbbfpRdVIpMrEvErTQl6VaPGWwCDEJ3O3RpjwDG6pCDmiOQj88xnwb5j/M9fA==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "dependencies": {
+ "node-addon-api": "^8.2.1",
+ "node-gyp-build": "^4.8.2"
+ },
+ "peerDependencies": {
+ "tree-sitter": "^0.21.1"
+ },
+ "peerDependenciesMeta": {
+ "tree-sitter": {
+ "optional": true
+ }
+ }
+ },
"node_modules/tree-sitter-typescript": {
"version": "0.23.2",
"resolved": "https://registry.npmjs.org/tree-sitter-typescript/-/tree-sitter-typescript-0.23.2.tgz",
diff --git a/package.json b/package.json
index 82cbeaa0..2f4b33f8 100644
--- a/package.json
+++ b/package.json
@@ -66,6 +66,7 @@
"tree-sitter-kotlin": "^0.3.8",
"tree-sitter-php": "^0.23.4",
"tree-sitter-python": "^0.21.0",
+ "tree-sitter-r": "npm:@davisvaughan/tree-sitter-r@^1.3.0",
"tree-sitter-typescript": "^0.23.2",
"tree-sitter-wasm": "^1.1.4",
"vscode-jsonrpc": "^8.2.1",
@@ -90,6 +91,7 @@
}
}
diff --git a/src/graph/bindings.ts b/src/graph/bindings.ts
index 3bee685e..a9bb80c1 100644
--- a/src/graph/bindings.ts
+++ b/src/graph/bindings.ts
@@ -58,6 +58,7 @@ export function defName(node: Parser.SyntaxNode, lang: Language): string | null
}
return null;
}
+ if (lang === "r") return rDefName(node);
if (lang === "php") {
const phpDefTypes = new Set([
"class_declaration",
@@ -96,6 +97,45 @@ export function defName(node: Parser.SyntaxNode, lang: Language): string | null
return null;
}
+const R_ASSIGN_OPS = new Set(["<-", "<<-", "="]);
+const R_RIGHT_ASSIGN_OPS = new Set(["->", "->>"]);
+
+/**
+ * The bare name a `binary_operator` (left-assign) or `function_definition`
+ * (right-assign) node defines, for R's two plain-function assignment shapes —
+ * this file's own `defName` uses it directly. extract.ts's `describeR`
+ * duplicates the same op-filtering check rather than importing this (same
+ * reasoning as the Go receiver helpers below: bindings.ts can't take a value
+ * import back on extract.ts), and additionally needs to distinguish an S3
+ * `generic.Class` method and R6/S4 class/method shapes this function doesn't
+ * know about — bindings.ts has no equivalent need since no `handleR` binding
+ * collector exists yet (R6/S4/S3 don't get a member/receiver-type table in
+ * this pass; `self`/`private` resolve directly via `ctx.enclosingClass`
+ * instead, needing no lookup). See `describeR`'s doc comment for why
+ * right-assign's AST shape needs its own branch rather than mirroring
+ * left-assign's (empirically, not assumed — `->`'s low precedence means it's
+ * absorbed into the function's own `body` field, not an outer wrapper).
+ * Null if `node` isn't one of these two shapes.
+ */
+export function rDefName(node: Parser.SyntaxNode): string | null {
+ if (node.type === "binary_operator") {
+ const op = node.childForFieldName("operator")?.text;
+ if (!op || !R_ASSIGN_OPS.has(op)) return null;
+ const lhs = node.childForFieldName("lhs");
+ const rhs = node.childForFieldName("rhs");
+ return lhs?.type === "identifier" && rhs?.type === "function_definition" ? lhs.text : null;
+ }
+ if (node.type === "function_definition") {
+ const body = node.childForFieldName("body");
+ if (body?.type !== "binary_operator") return null;
+ const op = body.childForFieldName("operator")?.text;
+ if (!op || !R_RIGHT_ASSIGN_OPS.has(op)) return null;
+ const rhs = body.childForFieldName("rhs");
+ return rhs?.type === "identifier" ? rhs.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 {
@@ -118,14 +158,18 @@ function goReceiverTypeOf(node: Parser.SyntaxNode): string | 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. */
+ * var resolve directly to the enclosing class; R6's `super` (Phase 3) resolves
+ * to the PARENT class instead (`ctx.rSuperClass`, not `ctx.enclosingClass` —
+ * a `super$method()` call must climb past the current class's own same-named
+ * override, not find it); 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">,
+ ctx: Pick<WalkCtx, "scope" | "enclosingClass" | "goReceiverVar" | "lang" | "bindings" | "rSuperClass">,
): string | undefined {
if (!receiver) return undefined;
if (receiver === "self" || receiver === "cls" || receiver === "this") return ctx.enclosingClass ?? undefined;
+ if (receiver === "super") return ctx.rSuperClass ?? undefined;
if (receiver.startsWith("self.") || receiver.startsWith("this.")) {
return (
ctx.bindings.lookup(ctx.scope, receiver) ??
@@ -214,6 +258,9 @@ function visit(
): void {
if (lang === "python") handlePy(node, scope, classScope, bindings, aliases);
else if (lang === "go") handleGo(node, scope, bindings);
+ // R Phase 1 has no classes, so there's no member/receiver-type binding to
+ // collect yet (see extract.ts's calleeName R branch) — no handleR needed.
+ else if (lang === "r") void 0;
else if (lang === "java") handleJava(node, scope, classScope, bindings);
else if (lang === "php") handlePhp(node, scope, bindings);
else handleTs(node, scope, classScope, bindings, aliases);
diff --git a/src/graph/extract.ts b/src/graph/extract.ts
index 84f11387..e53c5371 100644
--- a/src/graph/extract.ts
+++ b/src/graph/extract.ts
@@ -10,6 +10,7 @@ import Parser from "tree-sitter";
import TypeScript from "tree-sitter-typescript";
import Python from "tree-sitter-python";
import Go from "tree-sitter-go";
+import R from "tree-sitter-r";
import Java from "tree-sitter-java";
import Kotlin from "tree-sitter-kotlin";
import PHP from "tree-sitter-php";
@@ -18,7 +19,7 @@ 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" | "java" | "kotlin" | "php";
+export type Language = "typescript" | "tsx" | "python" | "go" | "java" | "kotlin" | "php" | "r";
/**
* Extension → the tree-sitter grammar that parses it, and the label a human expects
@@ -51,6 +52,9 @@ const EXTENSIONS: ReadonlyArray<{ ext: string; grammar: Language; label: string
{ ext: ".kt", grammar: "kotlin", label: "kotlin" },
{ ext: ".kts", grammar: "kotlin", label: "kotlin" },
{ ext: ".php", grammar: "php", label: "php" },
+ // `entryFor` lower-cases the path before matching, so this one entry covers
+ // both `.R` (the conventional case in real R codebases) and `.r`.
+ { ext: ".r", grammar: "r", label: "r" },
];
function entryFor(path: string): (typeof EXTENSIONS)[number] | undefined {
@@ -92,6 +96,16 @@ export interface RawEdge {
/** calls with viaMember: the receiver's resolved type name (from bindings /
* self / this / Go receiver), when a confident local clue exists. */
recvType?: string;
+ /** calls without viaMember: which kinds the bare-name match may resolve to.
+ * Every other language's bare-name call is always a free function, so this
+ * is absent for them (resolve.ts defaults to `["function"]`). R (Phase 4) is
+ * the one exception: `obj$method()` with an untyped receiver (not
+ * self/private/super, which already resolve precisely via viaMember+recvType)
+ * still has a real shot at a correct match if the method name happens to be
+ * uniquely defined across the repo — R6 methods are kind "method", not
+ * "function", so without this override every such call would be
+ * unconditionally unresolvable rather than just occasionally ambiguous. */
+ kinds?: Kind[];
/** calls: the number of arguments at the CALL SITE. Only emitted for languages
* with overloading (Java), where a same-named sibling on the same class is
* otherwise indistinguishable — and picking wrong turns a delegating overload
@@ -166,6 +180,11 @@ const GO_KINDS: Record<string, Kind> = {
method_declaration: "method",
};
+// R: `function_definition` carries no name field at all (unlike every other
+// supported language) — its identifier always comes from context (an
+// assignment's other side), resolved dynamically in describeR(). Empty, like
+// Go's own table — never consulted, kept only to satisfy KINDS_BY_LANG's type.
+const R_KINDS: Record<string, Kind> = {};
// Java: a record is a nominal data carrier, so it takes "struct" — the same role
// Go's struct plays — rather than "class", which would make a service and a DTO
// indistinguishable in a repo where DTOs are most of the type surface.
@@ -215,6 +234,7 @@ const KINDS_BY_LANG: Record<Language, Record<string, Kind>> = {
tsx: TS_KINDS,
python: PY_KINDS,
go: GO_KINDS,
+ r: R_KINDS,
java: JAVA_KINDS,
kotlin: KOTLIN_KINDS,
php: PHP_KINDS,
@@ -242,6 +262,7 @@ const CALL_TYPES: Record<Language, ReadonlySet<string>> = {
"nullsafe_member_call_expression",
"scoped_call_expression",
]),
+ r: new Set(["call"]),
};
const FUNCTION_VALUE_TYPES = new Set([
@@ -251,12 +272,15 @@ const FUNCTION_VALUE_TYPES = new Set([
"generator_function",
]);
+const EMPTY_SET: ReadonlySet<string> = new Set();
+
const parser = new Parser();
const GRAMMARS: Record<Language, unknown> = {
typescript: TypeScript.typescript,
tsx: TypeScript.tsx,
python: Python,
go: Go,
+ r: R,
java: Java,
kotlin: Kotlin,
php: PHP.php,
@@ -274,6 +298,25 @@ export interface WalkCtx {
enclosingClass: string | null; // nearest enclosing class (py/ts `self`/`this`)
goReceiverVar: string | null; // Go receiver var, e.g. `w` in `func (w *Worker)`
importedSymbols: ReadonlyMap<string, { name: string; specifier: string }>;
+ // R6 (Phase 2): which list we're inside while walking an `R6Class(...)` call's
+ // arguments — set only for the direct span of a `public =`/`private =`/
+ // `active =` `list(...)`'s own entries (see walk()'s special-cased `argument`
+ // interception), null everywhere else including inside a method's own body.
+ rR6Access: "public" | "private" | "active" | null;
+ // R (Phase 2): S3 generics registered in THIS file via a local `UseMethod()`
+ // call, precomputed once per file (see collectRGenerics). A `name.Class`
+ // assignment only becomes an S3 method if `name` is in this set or the
+ // curated base-R generics list — see describeR's doc comment for the
+ // ambiguity this guards against (`read.csv` is not S3 dispatch).
+ rGenerics: ReadonlySet<string>;
+ // R6 (Phase 3): the immediate parent class's name (from `inherit =`) for the
+ // R6 class we're currently inside, so a `super$method()` call in any of its
+ // methods' bodies can resolve directly to the PARENT's method instead of
+ // (wrongly) the current class's own same-named override. Unlike rR6Access,
+ // this is NOT reset when descending into a method — it needs to stay live
+ // for the method's whole body, only changing when a genuinely different
+ // class is entered. Null outside any class, or for a class with no parent.
+ rSuperClass: string | null;
}
/** A definition we're about to emit, normalized across the shapes we handle. */
@@ -283,6 +326,13 @@ interface DefDescriptor {
kind: Kind;
headerEnd: number; // char index where the signature ends (body starts)
hashNode: Parser.SyntaxNode; // node whose text forms body_hash / span
+ // A method whose owner can't be read off ctx.enclosingClass because the
+ // definition doesn't lexically nest inside its class (R's S3/S4 methods sit
+ // at file/top scope, dispatched by name/argument rather than nesting — same
+ // idea as Go's receiver-qualified methods). R6 methods DO nest (inside the
+ // class-defining call's own public=/private=/active= lists) and rely on the
+ // ordinary ctx.enclosingClass fallback instead, so they leave this unset.
+ owner?: string;
arity?: number; // declared parameter count — overload disambiguation (Java)
variadic?: boolean; // last parameter is a vararg, so `arity` is a minimum
}
@@ -302,6 +352,7 @@ export function extractFile(rel: string, source: string, lang: Language): Extrac
const root = parseSource(source);
const bindings = collectBindings(root, lang);
const importedSymbols = collectImportedSymbols(root, lang);
+ const rGenerics = lang === "r" ? collectRGenerics(root) : EMPTY_SET;
const nodes: NodeV1[] = [
{
@@ -334,6 +385,9 @@ export function extractFile(rel: string, source: string, lang: Language): Extrac
enclosingClass: null,
goReceiverVar: null,
importedSymbols,
+ rR6Access: null,
+ rGenerics,
+ rSuperClass: null,
};
// Every id minted this file, seeded with the file node's own id (`rel`) so a
// top-level definition can never collide with it. Threaded as its own
@@ -480,11 +534,15 @@ function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEd
const isGoMethod = ctx.lang === "go" && node.type === "method_declaration";
// The bare name of this node's OWN immediate enclosing class/receiver — for a
// Go method that's its receiver type (methods aren't nested, so ctx.enclosingClass
- // wouldn't see it); for every other method it's simply what the nearest ancestor
- // class already set as ctx.enclosingClass. Only method nodes carry it — resolve.ts's
+ // wouldn't see it); for an R S3/S4 method it's the qualifier/class describeR
+ // already resolved (desc.owner — these don't lexically nest inside their class
+ // either); for every other method it's simply what the nearest ancestor class
+ // already set as ctx.enclosingClass. Only method nodes carry it — resolve.ts's
// ownerMethod index is the sole consumer (see NodeV1.owner's doc comment).
const owner: string | undefined =
- desc.kind === "method" ? (isGoMethod ? (goReceiverType(node) ?? undefined) : (ctx.enclosingClass ?? undefined)) : undefined;
+ desc.kind === "method"
+ ? (isGoMethod ? (goReceiverType(node) ?? undefined) : (desc.owner ?? ctx.enclosingClass ?? undefined))
+ : undefined;
out.push({
id,
name: desc.name,
@@ -497,13 +555,15 @@ function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEd
? !desc.name.startsWith("_")
: ctx.lang === "go"
? goExported(desc.name)
- : ctx.lang === "java"
- ? javaExported(node)
-: ctx.lang === "kotlin"
- ? kotlinExported(node)
- : ctx.lang === "php"
- ? phpExported(node)
- : tsExported(node),
+ : ctx.lang === "r"
+ ? rExported(desc.name, ctx, node)
+ : ctx.lang === "java"
+ ? javaExported(node)
+ : ctx.lang === "kotlin"
+ ? kotlinExported(node)
+ : ctx.lang === "php"
+ ? phpExported(node)
+ : tsExported(node),
origin: "ast",
body_hash: contentHash(desc.hashNode.text),
body_text: searchBody(desc.hashNode.text),
@@ -529,7 +589,7 @@ function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEd
? desc.name
: isGoMethod
? goReceiverType(node)
- : ctx.enclosingClass;
+ : (desc.owner ?? ctx.enclosingClass);
const childCtx: WalkCtx = {
...ctx,
scope: [...ctx.scope, idPart],
@@ -541,15 +601,76 @@ function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEd
desc.kind === "function" || desc.kind === "method"
? withoutShadowedImports(ctx.importedSymbols, node)
: ctx.importedSymbols,
+ // Reset on every new definition — this is a purely local marker for "we're
+ // still inside THIS class-defining call's own public=/private=/active=
+ // argument chain," not something that should leak into a nested definition
+ // (a method's own body, or — vanishingly rare but possible — another class
+ // defined inside one).
+ rR6Access: null,
+ // Unlike rR6Access, only reset when entering a genuinely new class (so it
+ // stays live through a method's whole body, where super$ calls actually
+ // happen) — inherited unchanged for every other definition kind.
+ rSuperClass: desc.kind === "class" ? (ctx.lang === "r" ? rR6ParentClass(node) : null) : ctx.rSuperClass,
};
walkNamedChildren(node.namedChildren, childCtx, out, edges, minted);
return;
}
+ // R6 (Phase 2): `public =`/`private =`/`active =` inside an R6Class(...) call's
+ // own arguments is a `list(...)` call whose named entries become methods —
+ // this is R's version of a class body, but structurally it's several levels of
+ // ordinary call/argument nodes rather than a dedicated grammar construct, so it
+ // needs its own interception (mirrors how every other stateful/pattern-matched
+ // R construct in this walk needs one). `ctx.enclosingKind === "class"` scopes
+ // this to the class-defining call's own direct structure — once we're inside
+ // an actual method's body, enclosingKind has moved on to "method" and an
+ // unrelated nested `list(public = list(fn = function() {}))` elsewhere won't
+ // be misread as another class body.
+ if (
+ ctx.lang === "r" &&
+ ctx.enclosingKind === "class" &&
+ ctx.rR6Access === null &&
+ node.type === "argument"
+ ) {
+ const argName = node.childForFieldName("name");
+ const value = node.childForFieldName("value");
+ if (
+ argName?.type === "identifier" &&
+ (argName.text === "public" || argName.text === "private" || argName.text === "active") &&
+ value?.type === "call" &&
+ rCalleeName(value) === "list"
+ ) {
+ const access = argName.text;
+ for (const entry of rCallArgs(value)) {
+ walk(entry, { ...ctx, rR6Access: access }, out, edges, minted);
+ }
+ return;
+ }
+ }
+
// not a definition — capture calls/imports/references, then descend with the same context
+ // R's `call` node is also its ONLY vehicle for library()/require()/source() —
+ // there's no separate import-statement grammar construct to key off, so isImport
+ // must be checked before the generic calls path or every import call would be
+ // captured as a (harmlessly unresolvable, but wrong) `calls` edge instead.
const callTypes = CALL_TYPES[ctx.lang];
- if (callTypes.has(node.type)) {
- const callee = calleeName(node, ctx.lang);
+ if (isImport(node, ctx.lang)) {
+ const spec = importSpecifier(node, ctx.lang);
+ if (spec) edges.push({ source: ctx.rel, relation: "imports", specifier: spec, file: ctx.rel });
+ // Imported identifiers are declarations, not uses. The import-binding pass
+ // above already recorded them, so do not descend and emit false references.
+ return;
+ } else if (callTypes.has(node.type)) {
+ // R6Class(...) / a Phase-5 mixin list(...) is already consumed by its
+ // enclosing binary_operator as the class definition (see describeR) — the
+ // walk still reaches this SAME call node again, recursing generically to
+ // find its public=/private=/active= arguments (there's no other path to
+ // them), and it must not ALSO be treated as an ordinary call to a
+ // function literally named "R6Class"/"list".
+ const consumedCallee = ctx.lang === "r" && node.type === "call" ? rCalleeName(node) : null;
+ const isConsumedRClassCall =
+ consumedCallee === "R6Class" || (consumedCallee === "list" && rIsMixinContainer(node));
+ const callee = isConsumedRClassCall ? null : calleeName(node, ctx.lang);
if (callee) {
const callEdge: RawEdge = {
source: ctx.parentId,
@@ -557,6 +678,7 @@ function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEd
name: callee.name,
viaMember: callee.viaMember,
file: ctx.rel,
+ ...(callee.kinds ? { kinds: callee.kinds } : {}),
};
// Java only: the call site's argument count, to pick the right overload.
const argCount = ctx.lang === "java" ? javaArgCount(node) : undefined;
@@ -564,12 +686,6 @@ function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEd
const recvType = resolveRecvType(callee.receiver, ctx);
edges.push(recvType ? { ...callEdge, recvType } : callEdge);
}
- } else if (isImport(node, ctx.lang)) {
- const spec = importSpecifier(node, ctx.lang);
- if (spec) edges.push({ source: ctx.rel, relation: "imports", specifier: spec, file: ctx.rel });
- // Imported identifiers are declarations, not uses. The import-binding pass
- // above already recorded them, so do not descend and emit false references.
- return;
} else if (ctx.lang === "php" && node.type === "use_declaration") {
// Trait composition inside a class body (`use HasFactory, Notifiable;`).
// Modelled as `implements`: like an interface, a trait is a contract of
@@ -878,6 +994,7 @@ function isDeclarationName(node: Parser.SyntaxNode): boolean {
* TS arrow-consts. */
function describe(node: Parser.SyntaxNode, ctx: WalkCtx): DefDescriptor | null {
if (ctx.lang === "go") return describeGo(node, ctx);
+ if (ctx.lang === "r") return describeR(node, ctx);
if (ctx.lang === "java") return describeJava(node, ctx);
if (ctx.lang === "kotlin") return describeKotlin(node, ctx);
@@ -990,6 +1107,434 @@ function describeGo(node: Parser.SyntaxNode, _ctx: WalkCtx): DefDescriptor | nul
return null;
}
+/**
+ * R definition shapes. `function_definition` carries no name field at all, so
+ * unlike every other supported language the name always comes from an
+ * enclosing assignment, detected here. The plain-function assignment check
+ * (op-filtering `binary_operator`, the right-assign body-swap) is duplicated
+ * in bindings.ts's own `rDefName` rather than imported — same reasoning as
+ * this file's Go receiver helpers: bindings.ts can't take a value import back
+ * on extract.ts. bindings.ts doesn't need the S3/S4/R6 half of this at all
+ * (no handleR binding collector exists — see bindings.ts's own doc comment).
+ *
+ * Phase 1 (flat extraction — every named function is a plain `function` node)
+ * plus Phase 2 (S3/S4/R6 class awareness, R's class systems being library
+ * *convention* rather than grammar syntax, unlike every other language graft
+ * supports):
+ * - left-assign (`<-`/`<<-`/`=`) / right-assign (`->`/`->>`) function
+ * assignment — Phase 1's shape, see the two `binary_operator`/
+ * `function_definition` branches below. Right-assign's AST shape does NOT
+ * mirror left-assign's the way it looks like it should (confirmed
+ * empirically, not assumed — R's `->` has low enough precedence that it's
+ * absorbed into the function's own `body` field as a `binary_operator`
+ * instead of the function sitting inside an outer wrapper); only an
+ * explicitly parenthesized `(function() {}) -> foo` produces the
+ * "expected" outer-wrapping shape, which isn't specially handled (falls
+ * through as an anonymous function).
+ * - `name.Class <- function() {}` — an S3 method, IF `name` is a known
+ * generic (registered locally via `UseMethod()` in this file, or one of a
+ * curated set of common base-R generics — see `rS3Split`'s doc comment
+ * for the false-positive risk this guards against).
+ * - `Foo <- R6::R6Class("Foo", public = list(...), private = list(...))` —
+ * an R6 class; its `public =`/`private =`/`active =` list entries become
+ * methods, handled by walk()'s own `argument`-node interception (this
+ * function only recognizes the class itself; the "a call defines a
+ * symbol" list-walking lives in walk() since it needs to mint several
+ * nodes, not describe a single one).
+ * - `Foo <- list(public = list(...), private = list(...))` (Phase 5) — a
+ * plain-list "mixin"/"extension" bundle, NOT wrapped in `R6::R6Class(...)`
+ * at all: a real, deliberate convention found dogfooding against a real
+ * R6-heavy corpus (25 files, 11 of them entirely invisible to the graph
+ * without this) for sharing method bundles across classes via splicing
+ * (`public = c(Foo$public, list(...))`) rather than `inherit =`. Only
+ * recognized when the list actually has a `public =`/`private =` entry
+ * (see `rIsMixinContainer`) — an ordinary data/config list never matches.
+ * Reuses kind "class" (nothing better-fitting exists, and everything
+ * downstream — the method-list walking, visibility — only cares that
+ * ctx.enclosingKind is "class", not how the container was spelled); no
+ * heritage edge, since splicing isn't `inherit =`-based inheritance.
+ * - `setClass("Foo", ...)` / `setMethod("generic", "Foo", function() {})`
+ * — S4 class/method calls, recognized as bare top-level `call` nodes
+ * (setClass/setMethod have side effects registering with the S4 system;
+ * they're essentially never assigned to a variable). `setGeneric()` is
+ * NOT specially extracted — it doesn't naturally map to a class or method
+ * kind, and the plan flags it as a case not worth the design risk.
+ */
+function describeR(node: Parser.SyntaxNode, ctx: WalkCtx): DefDescriptor | null {
+ if (node.type === "binary_operator") {
+ const op = node.childForFieldName("operator")?.text;
+ if (!op || !R_ASSIGN_OPS.has(op)) return null;
+ const lhs = node.childForFieldName("lhs");
+ const rhs = node.childForFieldName("rhs");
+ if (lhs?.type !== "identifier") return null;
+ if (rhs?.type === "function_definition") {
+ return rFunctionDescriptor(lhs.text, rhs, rhs.childForFieldName("body"), ctx);
+ }
+ if (rhs?.type === "call" && rCalleeName(rhs) === "R6Class") {
+ // The class node itself; its public=/private=/active= method lists are
+ // handled by walk()'s own `argument`-node interception, not here.
+ return { name: lhs.text, kind: "class", headerEnd: rhs.endIndex, hashNode: rhs };
+ }
+ if (rhs?.type === "call" && rCalleeName(rhs) === "list" && rIsMixinContainer(rhs)) {
+ // Phase 5: a plain-list mixin/extension bundle — same treatment as R6Class.
+ return { name: lhs.text, kind: "class", headerEnd: rhs.endIndex, hashNode: rhs };
+ }
+ return null;
+ }
+
+ if (node.type === "function_definition") {
+ // Right-assign (`function() {} -> foo`): see this function's own doc
+ // comment for why this doesn't mirror the binary_operator branch above.
+ const body = node.childForFieldName("body");
+ if (body?.type !== "binary_operator") return null;
+ const op = body.childForFieldName("operator")?.text;
+ if (!op || !R_RIGHT_ASSIGN_OPS.has(op)) return null;
+ const rhs = body.childForFieldName("rhs");
+ if (rhs?.type !== "identifier") return null;
+ return rFunctionDescriptor(rhs.text, node, body.childForFieldName("lhs"), ctx);
+ }
+
+ if (node.type === "call") {
+ return describeRTopLevelCall(node);
+ }
+
+ // R6 (Phase 2): reached via walk()'s own `argument`-node interception for a
+ // `public =`/`private =`/`active =` list entry — see the special case there
+ // for why this can't just be a flat kind-table/node-type check like every
+ // other definition shape.
+ if (node.type === "argument" && ctx.rR6Access !== null) {
+ const argName = node.childForFieldName("name");
+ const value = node.childForFieldName("value");
+ if (argName?.type !== "identifier" || value?.type !== "function_definition") return null;
+ const body = value.childForFieldName("body");
+ return {
+ name: argName.text,
+ kind: "method",
+ headerEnd: body ? body.startIndex : value.endIndex,
+ hashNode: value,
+ // owner deliberately unset — R6 methods DO lexically nest inside the
+ // class-defining call, so ctx.enclosingClass already has it.
+ };
+ }
+
+ return null;
+}
+
+const R_ASSIGN_OPS = new Set(["<-", "<<-", "="]);
+const R_RIGHT_ASSIGN_OPS = new Set(["->", "->>"]);
+
+/** A plain function assignment (left- or right-assign), OR — if `name` matches
+ * a known S3 generic's `generic.Class` pattern — an S3 method instead. `body`
+ * is the function's REAL content node (already resolved by the caller for
+ * either assignment direction), used only for `headerEnd`; `hashNode` is
+ * always the `function_definition` itself. */
+function rFunctionDescriptor(
+ name: string,
+ hashNode: Parser.SyntaxNode,
+ body: Parser.SyntaxNode | null | undefined,
+ ctx: WalkCtx,
+): DefDescriptor {
+ const headerEnd = body ? body.startIndex : hashNode.endIndex;
+ const s3 = rS3Split(name, ctx.rGenerics);
+ if (s3) {
+ return {
+ name: s3.generic,
+ idName: `${s3.className}.${s3.generic}`,
+ kind: "method",
+ headerEnd,
+ hashNode,
+ owner: s3.className,
+ };
+ }
+ return { name, kind: "function", headerEnd, hashNode };
+}
+
+/**
+ * S3 dispatch detection: does `name` split as `generic.Class` for some KNOWN
+ * generic? Tries the longest possible generic prefix first (so a dotted
+ * generic itself, like `as.character`, is found before a shorter false match)
+ * and only ever matches a generic that's either registered locally via
+ * `UseMethod()` in this file (see `collectRGenerics`) or in the small curated
+ * `R_BASE_GENERICS` set below.
+ *
+ * This is the genuinely ambiguous part of R support the plan calls out:
+ * `read.csv`, `data.frame`, and `as.character` used as an ordinary helper
+ * name are NOT S3 dispatch, and nothing in the grammar distinguishes them
+ * from `print.MyClass`. Erring toward the curated set staying small — a
+ * missed S3 method (false negative, falls back to an ordinary `function`
+ * node) is a much smaller problem than a false positive misfiling an
+ * unrelated dotted-name function as some other class's method.
+ */
+function rS3Split(name: string, generics: ReadonlySet<string>): { generic: string; className: string } | null {
+ const parts = name.split(".");
+ if (parts.length < 2) return null;
+ for (let i = parts.length - 1; i >= 1; i--) {
+ const generic = parts.slice(0, i).join(".");
+ if (generics.has(generic) || R_BASE_GENERICS.has(generic)) {
+ return { generic, className: parts.slice(i).join(".") };
+ }
+ }
+ return null;
+}
+
+/** Common base-R S3 generics worth assuming even without local evidence —
+ * print.Foo/format.Foo etc. are the single most common real-world S3
+ * pattern, and a local `UseMethod()` call will never exist for them (they
+ * ship in base/methods/stats, not the user's own repo). Deliberately small
+ * and unsurprising rather than exhaustive — see `rS3Split`'s doc comment. */
+const R_BASE_GENERICS = new Set([
+ "print",
+ "format",
+ "summary",
+ "plot",
+ "str",
+ "toString",
+ "as.character",
+ "as.list",
+ "as.data.frame",
+ "as.vector",
+ "as.numeric",
+ "as.matrix",
+ "length",
+ "dim",
+ "names",
+ "rev",
+ "sort",
+ "unique",
+ "predict",
+ "coef",
+ "residuals",
+ "fitted",
+ "update",
+ "merge",
+ "all.equal",
+ "anova",
+ "confint",
+ "vcov",
+ "logLik",
+]);
+
+/** Every S3 generic THIS file registers via a local `UseMethod()` call, so
+ * `rS3Split` can recognize `generic.Class` methods for a repo's own generics,
+ * not just the base-R ones. Runs once per file, ahead of the main walk (same
+ * pre-pass shape as `collectImportedSymbols`). Cross-file generics — a
+ * generic defined in one file, dispatched on in another — aren't found this
+ * way; that would need a whole-repo pass extractFile has no visibility into,
+ * the same limitation Go/C++'s per-file bindings already accept. */
+function collectRGenerics(root: Parser.SyntaxNode): Set<string> {
+ const generics = new Set<string>();
+ const visit = (node: Parser.SyntaxNode): void => {
+ let fnDef: Parser.SyntaxNode | null = null;
+ let ownName: string | null = null;
+ if (node.type === "binary_operator") {
+ const op = node.childForFieldName("operator")?.text;
+ const lhs = node.childForFieldName("lhs");
+ const rhs = node.childForFieldName("rhs");
+ if (op && R_ASSIGN_OPS.has(op) && lhs?.type === "identifier" && rhs?.type === "function_definition") {
+ fnDef = rhs;
+ ownName = lhs.text;
+ }
+ } else if (node.type === "function_definition") {
+ const body = node.childForFieldName("body");
+ if (body?.type === "binary_operator") {
+ const op = body.childForFieldName("operator")?.text;
+ const rhs = body.childForFieldName("rhs");
+ if (op && R_RIGHT_ASSIGN_OPS.has(op) && rhs?.type === "identifier") {
+ fnDef = node;
+ ownName = rhs.text;
+ }
+ }
+ }
+ if (fnDef && ownName) {
+ const arg = findUseMethodArg(fnDef.childForFieldName("body"));
+ if (arg !== undefined) generics.add(arg || ownName); // "" means UseMethod() with no args
+ }
+ for (const child of node.namedChildren) visit(child);
+ };
+ visit(root);
+ return generics;
+}
+
+/** Searches a function body for a `UseMethod(...)` call and returns its
+ * string-literal generic-name argument, `""` if called with no arguments
+ * (defaults to the enclosing function's own name), or `undefined` if no
+ * `UseMethod` call is found at all. */
+function findUseMethodArg(node: Parser.SyntaxNode | null | undefined): string | undefined {
+ if (!node) return undefined;
+ if (node.type === "call" && rCalleeName(node) === "UseMethod") {
+ const first = rCallArgs(node)[0]?.childForFieldName("value");
+ return first?.type === "string" ? (rStringContent(first) ?? "") : "";
+ }
+ for (const child of node.namedChildren) {
+ const found = findUseMethodArg(child);
+ if (found !== undefined) return found;
+ }
+ return undefined;
+}
+
+/** S4: `setClass("Foo", ...)` → a class; `setMethod("generic", "Foo",
+ * function() {})` → a method owned by "Foo". Both are ordinary top-level
+ * `call` nodes — S4's registration functions have side effects and are
+ * essentially never assigned to a variable, unlike R6Class. */
+function describeRTopLevelCall(node: Parser.SyntaxNode): DefDescriptor | null {
+ const callee = rCalleeName(node);
+ if (callee === "setClass") {
+ const first = rCallArgs(node)[0]?.childForFieldName("value");
+ const name = first?.type === "string" ? rStringContent(first) : null;
+ if (!name) return null;
+ return { name, kind: "class", headerEnd: node.endIndex, hashNode: node };
+ }
+ if (callee === "setMethod") {
+ const args = rCallArgs(node);
+ const generic = args[0] ? rStringContent(args[0].childForFieldName("value") ?? null) : null;
+ const className = args[1] ? rStringContent(args[1].childForFieldName("value") ?? null) : null;
+ const defArg = args.find((a) => a.childForFieldName("name")?.text === "definition") ?? args[2];
+ const fnDef = defArg?.childForFieldName("value");
+ if (!generic || !className || fnDef?.type !== "function_definition") return null;
+ const body = fnDef.childForFieldName("body");
+ return {
+ name: generic,
+ idName: `${className}.${generic}`,
+ kind: "method",
+ headerEnd: body ? body.startIndex : fnDef.endIndex,
+ hashNode: fnDef,
+ owner: className,
+ };
+ }
+ return null;
+}
+
+/** A call's callee name, whether bare (`R6Class(...)`) or namespace-qualified
+ * (`R6::R6Class(...)`). Null if the callee isn't a simple name (e.g. itself a
+ * call, or a `$`-based access). */
+function rCalleeName(node: Parser.SyntaxNode): string | null {
+ const fn = node.childForFieldName("function");
+ if (fn?.type === "identifier") return fn.text;
+ if (fn?.type === "namespace_operator") {
+ const rhs = fn.childForFieldName("rhs");
+ return rhs?.type === "identifier" ? rhs.text : null;
+ }
+ return null;
+}
+
+/** A call's positional/named `argument` children (skipping the `,`/`(`/`)`
+ * punctuation tokens that share the `arguments` node's child list). */
+function rCallArgs(node: Parser.SyntaxNode): Parser.SyntaxNode[] {
+ return node.childForFieldName("arguments")?.namedChildren.filter((c) => c.type === "argument") ?? [];
+}
+
+/** An R `string` node's unquoted text, or null if `node` isn't a string. */
+function rStringContent(node: Parser.SyntaxNode | null): string | null {
+ if (node?.type !== "string") return null;
+ const content = node.namedChildren.find((c) => c.type === "string_content");
+ return content?.text ?? null;
+}
+
+/** The value of a call's named argument (`setClass("Foo", contains = "Base")`
+ * → the `contains` argument), or null if absent. */
+function rNamedArg(node: Parser.SyntaxNode, argName: string): Parser.SyntaxNode | null {
+ const arg = rCallArgs(node).find((a) => a.childForFieldName("name")?.text === argName);
+ return arg?.childForFieldName("value") ?? null;
+}
+
+/** An R6 class-defining node's `inherit =` parent class name (a bare
+ * identifier — the parent's own generator variable, not a string), for
+ * `super$` call resolution (Phase 3). `node` is whatever describeR matched: a
+ * binary_operator for R6 (`Foo <- R6::R6Class(...)`) or, for any other kind of
+ * class (S4's setClass, which has no `super`), the call itself — always null
+ * there since `rCalleeName(call) !== "R6Class"`. */
+function rR6ParentClass(node: Parser.SyntaxNode): string | null {
+ const call = node.type === "binary_operator" ? node.childForFieldName("rhs") : node;
+ if (call?.type !== "call" || rCalleeName(call) !== "R6Class") return null;
+ const value = rNamedArg(call, "inherit");
+ return value?.type === "identifier" ? value.text : null;
+}
+
+/** Does this `list(...)` call look like a Phase-5 mixin/extension bundle —
+ * i.e. does it have a `public =` or `private =` entry whose own value is
+ * itself a `list(...)` call? This is the one check standing between "class-
+ * like container" and an ordinary data/config list (`list(a = 1, b = 2)`,
+ * or even one that happens to have a field named "public" holding something
+ * else) — real code never coincidentally shapes plain data this way, so it's
+ * a safe, precise signal without needing a naming-convention heuristic. */
+function rIsMixinContainer(node: Parser.SyntaxNode): boolean {
+ return rCallArgs(node).some((a) => {
+ const name = a.childForFieldName("name")?.text;
+ if (name !== "public" && name !== "private") return false;
+ const value = a.childForFieldName("value");
+ return value?.type === "call" && rCalleeName(value) === "list";
+ });
+}
+
+/** A base-class name list from either a bare string (`contains = "Base"`) or
+ * a `c(...)` call of strings (`contains = c("Base1", "Base2")`) — S4's
+ * multiple-inheritance form. */
+function rStringOrCVector(value: Parser.SyntaxNode | null): string[] {
+ if (!value) return [];
+ const single = rStringContent(value);
+ if (single) return [single];
+ if (value.type === "call" && rCalleeName(value) === "c") {
+ return rCallArgs(value)
+ .map((a) => rStringContent(a.childForFieldName("value")))
+ .filter((s): s is string => !!s);
+ }
+ return [];
+}
+
+/** R6 visibility follows the `public =`/`private =`/`active =` section a
+ * method was declared in (see walk()'s `argument`-node interception) —
+ * `ctx.rR6Access` is only set for that direct span, so a plain function or an
+ * S3/S4 method (neither of which has a real visibility concept) checks for a
+ * roxygen `@export` tag next (Phase 3), falling back to the leading-dot naming
+ * convention only when there's no roxygen evidence to go on at all. `node` is
+ * the exact node describeR matched — see `rRoxygenExported`'s doc comment for
+ * why that's always the right one to check for a preceding comment block. */
+function rExported(name: string, ctx: WalkCtx, node: Parser.SyntaxNode): boolean {
+ if (ctx.rR6Access !== null) return ctx.rR6Access !== "private";
+ const roxygen = rRoxygenExported(node);
+ if (roxygen !== null) return roxygen;
+ return !name.startsWith(".");
+}
+
+/**
+ * Roxygen `@export` detection (Phase 3): does `node` — a top-level definition
+ * statement (a `binary_operator` assignment, a right-assigned
+ * `function_definition`, or an S4 `setClass`/`setMethod` call) — have a
+ * roxygen doc block immediately preceding it, and if so, is it tagged
+ * `@export`?
+ *
+ * `comment` is a grammar EXTRA in this grammar (floats loosely between
+ * sibling nodes rather than attaching to "the next statement" via a field),
+ * so this walks backward through `previousNamedSibling` collecting a
+ * contiguous run of `comment` nodes — the run ends at the first non-comment
+ * sibling, or at the first comment that isn't itself a roxygen (`#'`) line,
+ * either of which is roxygen's own "this block documents the next statement"
+ * boundary.
+ *
+ * Returns:
+ * - `true` — a roxygen block was found and it contains `@export`.
+ * - `false` — a roxygen block was found but it does NOT contain `@export`.
+ * This is deliberately a confident "not exported," not "unknown": roxygen
+ * generates a package's NAMESPACE from exactly its `@export`-tagged items,
+ * so a documented-but-untagged function is an explicit "internal, for
+ * maintainers only" signal, not an absence of evidence.
+ * - `null` — no roxygen block at all, so the caller should fall back to the
+ * leading-dot naming convention instead of guessing.
+ */
+function rRoxygenExported(node: Parser.SyntaxNode): boolean | null {
+ let sib = node.previousNamedSibling;
+ let sawRoxygen = false;
+ let exported = false;
+ while (sib?.type === "comment") {
+ const text = sib.text.trim();
+ if (!text.startsWith("#'")) break; // an ordinary # comment ends the roxygen block
+ sawRoxygen = true;
+ if (/^#'\s*@export\b/.test(text)) exported = true;
+ sib = sib.previousNamedSibling;
+ }
+ return sawRoxygen ? exported : null;
+}
+
/** Java definition shapes. Uniform in a way Go's are not: every declaration carries
* a `name` field and (for types and most members) a `body`, so one mapped lookup
* covers classes, interfaces, enums, records, methods, and constructors. Methods are
@@ -1219,6 +1764,29 @@ function heritageEdges(node: Parser.SyntaxNode, classId: string, ctx: WalkCtx):
}
return edges;
}
+ if (ctx.lang === "r") {
+ // `node` is whatever describeR matched: a binary_operator for R6
+ // (`Foo <- R6::R6Class(...)`) or the call itself for S4 (`setClass(...)`
+ // is a bare top-level statement, essentially never assigned).
+ const call = node.type === "binary_operator" ? node.childForFieldName("rhs") : node;
+ if (call?.type !== "call") return edges;
+ const callee = rCalleeName(call);
+ if (callee === "R6Class") {
+ // `inherit = ParentClass` — a bare identifier (the parent's own
+ // generator variable), not a string; R6 supports single inheritance only.
+ const value = rNamedArg(call, "inherit");
+ if (value?.type === "identifier") {
+ edges.push({ source: classId, relation: "extends", name: value.text, file: ctx.rel });
+ }
+ } else if (callee === "setClass") {
+ // `contains = "Base"` or `contains = c("Base1", "Base2")` — S4 supports
+ // multiple inheritance.
+ for (const name of rStringOrCVector(rNamedArg(call, "contains"))) {
+ edges.push({ source: classId, relation: "extends", name, file: ctx.rel });
+ }
+ }
+ return edges;
+ }
if (ctx.lang === "php") {
// `class C extends B implements I, J` → base_clause (extends) +
// class_interface_clause (implements); names may be namespace-qualified.
@@ -1306,7 +1874,7 @@ function javaTypeParameterNames(decl: Parser.SyntaxNode): ReadonlySet<string> {
function calleeName(
node: Parser.SyntaxNode,
lang: Language,
-): { name: string; viaMember: boolean; receiver?: string } | null {
+): { name: string; viaMember: boolean; receiver?: string; kinds?: Kind[] } | null {
// Java first: `method_invocation` has NO `function` field (it splits the callee
// into `object` + `name`), so the shared lookup below would return null for every
// Java call site and the language would extract nodes with no call edges at all.
@@ -1369,6 +1937,47 @@ if (lang === "kotlin") {
const p = fn.childForFieldName("property") ?? fn.namedChildren.at(-1);
return p ? { name: p.text, viaMember: true, receiver: tsReceiver(fn) } : null;
}
+ if (lang === "r" && (fn.type === "extract_operator" || fn.type === "namespace_operator")) {
+ const rhs = fn.childForFieldName("rhs");
+ if (rhs?.type !== "identifier") return null;
+ if (fn.type === "extract_operator") {
+ const lhs = fn.childForFieldName("lhs");
+ if (lhs?.type === "identifier" && (lhs.text === "self" || lhs.text === "private")) {
+ // R6 (Phase 2): `self$method()` / `private$method()` — resolves directly to
+ // the enclosing class via ctx.enclosingClass, same mechanism (and same
+ // magic receiver string) as Python/TS's self/cls/this — see
+ // resolveRecvType, which already special-cases "self" generically.
+ return { name: rhs.text, viaMember: true, receiver: "self" };
+ }
+ if (lhs?.type === "identifier" && lhs.text === "super") {
+ // R6 (Phase 3): `super$method()` — R6's inheritance-dispatch keyword,
+ // resolves directly to the PARENT class via ctx.rSuperClass (NOT
+ // ctx.enclosingClass — that would wrongly find the current class's own
+ // same-named override instead of climbing to the parent).
+ return { name: rhs.text, viaMember: true, receiver: "super" };
+ }
+ // Any other `obj$method()` (Phase 4): still a PLAIN name match, not a
+ // typed member call — there's no general field-type-binding table for
+ // R6 composition (`private$other_obj$method()`), and a real codebase's
+ // dominant field-assignment shape (constructor-parameter pass-through,
+ // `do.call(class_var$new, ...)` dynamic dispatch) turned out to defeat
+ // the simple "field <- SomeClass$new()" pattern every other language's
+ // binding table relies on anyway — see plan_r_language_support.md's
+ // Phase 2 "known gaps" and the follow-up investigation against a real
+ // R6-heavy corpus. What DOES help: bare-name resolution must be allowed
+ // to match a "method" node here, not just "function" — R6 methods are
+ // always kind "method", so without `kinds` below, EVERY untyped `$`
+ // call would be unconditionally unresolvable rather than just
+ // occasionally ambiguous (resolve.ts already drops a genuinely
+ // ambiguous bare-name match rather than guessing, so this only adds
+ // resolutions for uniquely-named methods, never a wrong-class guess).
+ return { name: rhs.text, viaMember: false, kinds: ["function", "method"] };
+ }
+ // `pkg::fun()` (qualified call) — always a real function/exported symbol,
+ // never an R6 method (those are only ever reached via `$` on an instance),
+ // so no need to widen the match kinds here.
+ return { name: rhs.text, viaMember: false };
+ }
return null;
}
@@ -1504,10 +2113,22 @@ function tsReceiver(fn: Parser.SyntaxNode): string | undefined {
return undefined;
}
+/** R has no import statement at the grammar level — `library(x)`, `require(x)`,
+ * and `source("f.R")` are ordinary `call` nodes, indistinguishable from any other
+ * call except by their callee name. This is call-SITE pattern matching, a first
+ * for this function's normal node-type switch — every other language's import
+ * shape is a dedicated grammar construct. */
+const R_IMPORT_CALLS = new Set(["library", "require", "source"]);
+
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.
if (lang === "go") return node.type === "import_spec";
+ if (lang === "r") {
+ if (node.type !== "call") return false;
+ const fn = node.childForFieldName("function");
+ return fn?.type === "identifier" && R_IMPORT_CALLS.has(fn.text);
+ }
if (lang === "java") return node.type === "import_declaration";
if (lang === "kotlin") return node.type === "import_header";
// PHP: one edge per imported symbol — the clause leaf inside a (possibly
@@ -1533,6 +2154,13 @@ function importSpecifier(node: Parser.SyntaxNode, lang: Language): string | null
const path = node.childForFieldName("path") ?? node.namedChildren.at(-1);
return path ? path.text.replace(/^["`]|["`]$/g, "") : null;
}
+ if (lang === "r") {
+ // library(pkg) / library("pkg") / require(pkg) / source("f.R") — the target is
+ // always the first (and normally only) positional argument, bare symbol or string.
+ const value = rCallArgs(node)[0]?.childForFieldName("value") ?? null;
+ if (value?.type === "identifier") return value.text;
+ return rStringContent(value);
+ }
if (lang === "java") {
// `import a.b.C;` / `import static a.b.C.d;` / `import a.b.*;` — the fully
// qualified name is the scoped_identifier; a wildcard `*` is a separate token
diff --git a/src/graph/resolve.ts b/src/graph/resolve.ts
index ef8c4989..6ab414a5 100644
--- a/src/graph/resolve.ts
+++ b/src/graph/resolve.ts
@@ -207,6 +207,11 @@ export function resolveEdges(
// vs a compiler-grade oracle) for a 3x count inflation, i.e. noise. See #35.
continue;
}
+ // Every language's bare-name call is a free function, except R (Phase 4):
+ // an untyped `obj$method()` there sets e.kinds to also allow a "method"
+ // match — see extract.ts's calleeName R branch for why (R6 methods are
+ // never kind "function", so without this every such call would be
+ // unconditionally unresolvable rather than just occasionally ambiguous).
// Three cases, because "a bare call" means something different per tier:
//
// - generic (breadth tier): tags.scm captures ALL calls as bare names, since it
@@ -217,13 +222,17 @@ export function resolveEdges(
// extract.ts, so the only bare call reaching here is `new Foo()`, whose target
// is a TYPE. Against the function index every constructor edge would drop.
// - everything else: functions, exactly as before.
+ //
+ // R (depth tier, Phase 4) sets `e.kinds` itself for an untyped `obj$method()`
+ // (see above), and that explicit choice wins over the per-tier default.
const srcOrigin = byId.get(e.source)?.origin;
const callKinds: Kind[] =
- srcOrigin === "generic"
+ e.kinds ??
+ (srcOrigin === "generic"
? ["function", "method"]
: e.file.endsWith(".java")
? ["class", "struct", "enum", "interface"]
- : ["function"];
+ : ["function"]);
let hit = resolveName(e.name!, e.file, callKinds, perFileName, globalName);
// Python is the Java case without the `new` to mark it: `Widget()` is an
// ordinary call node, so a constructor edge dies against the function-only
diff --git a/test/claude-hooks.test.ts b/test/claude-hooks.test.ts
index 6a87538c..ab9cc9f3 100644
--- a/test/claude-hooks.test.ts
+++ b/test/claude-hooks.test.ts
@@ -19,7 +19,7 @@ test('post-edit marks dirty and records lastFile', async () => {
mkdirSync(join(d, 'graft', '.graph'), { recursive: true });
writeFileSync(join(d, 'graft', '.graph', 'wiring.json'),
JSON.stringify({ meta: { nodeCount: 0, edgeCount: 0, languages: [] }, nodes: [], edges: [] }));
- // graft check will fail (no dist/cli.js here) → staleCount falls back to 0, but dirty must still be set.
+ // post-edit no longer runs `graft check` at all (removed: too slow on large repos) — just dirty + lastFile.
process.env.CLAUDE_PROJECT_DIR = d;
const stdin = JSON.stringify({ tool_input: { file_path: join(d, 'src', 'auth.ts') } });
await runWithStdin(stdin, () => main('post-edit'));
diff --git a/test/graph-languages.test.ts b/test/graph-languages.test.ts
index 61357dff..4fc1e242 100644
--- a/test/graph-languages.test.ts
+++ b/test/graph-languages.test.ts
@@ -27,6 +27,7 @@ const INDEXED = [
"a.tsx", "a.jsx",
"a.py", "a.pyi",
"a.go",
+ "a.R", "a.r",
"a.java",
"a.kt", "a.kts",
"a.php",
@@ -56,6 +57,8 @@ test("labels name the language, not the grammar that parses it", () => {
assert.equal(languageLabelOf("api/main.py"), "python");
assert.equal(languageLabelOf("api/main.pyi"), "python");
assert.equal(languageLabelOf("cmd/main.go"), "go");
+ assert.equal(languageLabelOf("analysis/model.R"), "r");
+ assert.equal(languageLabelOf("analysis/model.r"), "r");
assert.equal(languageLabelOf("src/main/java/com/acme/App.java"), "java");
assert.equal(languageLabelOf("src/main/kotlin/com/acme/App.kt"), "kotlin");
assert.equal(languageLabelOf("scripts/main.kts"), "kotlin");
diff --git a/test/graph-r-classes.test.ts b/test/graph-r-classes.test.ts
new file mode 100644
index 00000000..3755fb71
--- /dev/null
+++ b/test/graph-r-classes.test.ts
@@ -0,0 +1,214 @@
+/**
+ * Tests for R Phase 2 (S3/S4/R6-aware) extraction. R's class systems are
+ * library *convention*, not grammar syntax — unlike every other language graft
+ * supports — so this is "pattern-match known call idioms -> sometimes a kind"
+ * rather than "one grammar construct -> one graph kind". Three separate risk
+ * areas, three separate fixtures: R6's public=/private=/active= list-walking
+ * (this repo's own dominant OOP style, per plan_r_language_support.md), S4's
+ * "a call defines a symbol" shape (setClass/setMethod), and S3's genuinely
+ * ambiguous name.Class dispatch detection (read.csv is NOT an S3 method).
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import { buildGraph } from "../src/graph/build.js";
+import { readGraph, wiringPath } from "../src/graph/write.js";
+import type { GraphV1, NodeV1 } from "../src/graph/types.js";
+
+function nodeById(graph: GraphV1, id: string): NodeV1 | undefined {
+ return graph.nodes.find((n) => n.id === id);
+}
+
+async function buildAndRead(files: Record<string, string>): Promise<{ dir: string; graph: GraphV1 }> {
+ const dir = mkdtempSync(join(tmpdir(), "graft-r-classes-"));
+ for (const [name, content] of Object.entries(files)) writeFileSync(join(dir, name), content);
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ return { dir, graph };
+}
+
+const R6_R = `Base <- R6::R6Class("Base",
+ public = list(
+ ping = function() { 1 }
+ )
+)
+
+Foo <- R6::R6Class("Foo",
+ inherit = Base,
+ public = list(
+ initialize = function(x) {
+ private$x_ <- x
+ },
+ greet = function() {
+ self$helper()
+ },
+ helper = function() {
+ 42
+ }
+ ),
+ private = list(
+ x_ = NULL,
+ secret = function() { 1 }
+ )
+)
+`;
+
+test("R6: class nodes, inherit heritage, public/private visibility", async () => {
+ const { dir, graph } = await buildAndRead({ "r6.R": R6_R });
+ try {
+ assert.equal(nodeById(graph, "r6.R#Base")?.kind, "class");
+ assert.equal(nodeById(graph, "r6.R#Foo")?.kind, "class");
+
+ assert.ok(
+ graph.edges.some(
+ (e) => e.relation === "extends" && e.source === "r6.R#Foo" && e.target === "r6.R#Base",
+ ),
+ "Foo should extend Base via inherit =",
+ );
+
+ const initialize = nodeById(graph, "r6.R#Foo.initialize");
+ assert.equal(initialize?.kind, "method");
+ assert.equal(initialize?.owner, "Foo");
+ assert.equal(initialize?.exported, true);
+
+ assert.equal(nodeById(graph, "r6.R#Foo.greet")?.exported, true);
+ assert.equal(nodeById(graph, "r6.R#Foo.helper")?.exported, true);
+
+ // private = list(...) methods are NOT exported.
+ assert.equal(nodeById(graph, "r6.R#Foo.secret")?.exported, false);
+
+ // A private FIELD (x_ = NULL, not a function) must not become a node —
+ // only function-valued list entries are methods.
+ assert.equal(
+ graph.nodes.some((n) => n.name === "x_"),
+ false,
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("R6: self$/private$ calls resolve directly to the enclosing class", async () => {
+ const { dir, graph } = await buildAndRead({ "r6.R": R6_R });
+ try {
+ const call = graph.edges.find(
+ (e) => e.relation === "calls" && e.source === "r6.R#Foo.greet" && e.target === "r6.R#Foo.helper",
+ );
+ assert.ok(call, "self$helper() inside Foo$greet should resolve to Foo$helper");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+const S4_R = `setClass("Animal", representation(name = "character"))
+
+setClass("Dog", contains = "Animal")
+
+setClass("Multi", contains = c("Animal", "Dog"))
+
+setGeneric("speak", function(x) standardGeneric("speak"))
+
+setMethod("speak", "Dog", function(x) {
+ cat("Woof")
+})
+`;
+
+test("S4: setClass classes, single + multiple contains heritage", async () => {
+ const { dir, graph } = await buildAndRead({ "s4.R": S4_R });
+ try {
+ assert.equal(nodeById(graph, "s4.R#Animal")?.kind, "class");
+ assert.equal(nodeById(graph, "s4.R#Dog")?.kind, "class");
+ assert.equal(nodeById(graph, "s4.R#Multi")?.kind, "class");
+
+ assert.ok(
+ graph.edges.some((e) => e.relation === "extends" && e.source === "s4.R#Dog" && e.target === "s4.R#Animal"),
+ "Dog should extend Animal via contains = \"Animal\"",
+ );
+ assert.ok(
+ graph.edges.some((e) => e.relation === "extends" && e.source === "s4.R#Multi" && e.target === "s4.R#Animal"),
+ "Multi should extend Animal via contains = c(...)",
+ );
+ assert.ok(
+ graph.edges.some((e) => e.relation === "extends" && e.source === "s4.R#Multi" && e.target === "s4.R#Dog"),
+ "Multi should extend Dog via contains = c(...)",
+ );
+
+ // setGeneric() is not specially extracted — no natural class/method mapping.
+ assert.equal(
+ graph.nodes.some((n) => n.name === "standardGeneric"),
+ false,
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("S4: setMethod becomes a method owned by its class", async () => {
+ const { dir, graph } = await buildAndRead({ "s4.R": S4_R });
+ try {
+ const speak = nodeById(graph, "s4.R#Dog.speak");
+ assert.equal(speak?.kind, "method");
+ assert.equal(speak?.owner, "Dog");
+ assert.equal(speak?.name, "speak");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+const S3_R = `summarizeThing <- function(x) UseMethod("summarizeThing")
+
+summarizeThing.Widget <- function(x) {
+ "widget summary"
+}
+
+print.Widget <- function(x, ...) {
+ cat("a widget")
+}
+
+read.csv <- function(path) {
+ path
+}
+`;
+
+test("S3: a locally-registered generic's name.Class dispatch becomes a method", async () => {
+ const { dir, graph } = await buildAndRead({ "s3.R": S3_R });
+ try {
+ const generic = nodeById(graph, "s3.R#summarizeThing");
+ assert.equal(generic?.kind, "function", "the generic itself (UseMethod caller) stays a plain function");
+
+ const method = nodeById(graph, "s3.R#Widget.summarizeThing");
+ assert.equal(method?.kind, "method");
+ assert.equal(method?.owner, "Widget");
+ assert.equal(method?.name, "summarizeThing");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("S3: a common base-R generic (print) is recognized without local UseMethod evidence", async () => {
+ const { dir, graph } = await buildAndRead({ "s3.R": S3_R });
+ try {
+ const method = nodeById(graph, "s3.R#Widget.print");
+ assert.equal(method?.kind, "method");
+ assert.equal(method?.owner, "Widget");
+ assert.equal(method?.name, "print");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("S3: an ordinary dotted function name is NOT misread as S3 dispatch (read.csv)", async () => {
+ const { dir, graph } = await buildAndRead({ "s3.R": S3_R });
+ try {
+ const fn = nodeById(graph, "s3.R#read.csv");
+ assert.equal(fn?.kind, "function", "read.csv is a plain helper, not Csv.read S3 dispatch");
+ assert.equal(
+ graph.nodes.some((n) => n.owner === "csv"),
+ false,
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/test/graph-r-phase3.test.ts b/test/graph-r-phase3.test.ts
new file mode 100644
index 00000000..889d5e43
--- /dev/null
+++ b/test/graph-r-phase3.test.ts
@@ -0,0 +1,142 @@
+/**
+ * Tests for R Phase 3: roxygen `@export` visibility detection and R6's
+ * `super$method()` inheritance-dispatch resolution. Both were scoped
+ * specifically for an R6-plus-roxygen setup (no S3/S4 involved) — see
+ * plan_r_language_support.md's Phase 2 section and the follow-up discussion.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import { buildGraph } from "../src/graph/build.js";
+import { extractFile } from "../src/graph/extract.js";
+import { readGraph, wiringPath } from "../src/graph/write.js";
+import type { GraphV1, NodeV1 } from "../src/graph/types.js";
+
+function nodeById(graph: GraphV1, id: string): NodeV1 | undefined {
+ return graph.nodes.find((n) => n.id === id);
+}
+
+async function buildAndRead(files: Record<string, string>): Promise<{ dir: string; graph: GraphV1 }> {
+ const dir = mkdtempSync(join(tmpdir(), "graft-r-phase3-"));
+ for (const [name, content] of Object.entries(files)) writeFileSync(join(dir, name), content);
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ return { dir, graph };
+}
+
+const ROXYGEN_R = `#' @title Widget Class
+#' @description a widget
+#' @export
+Widget <- R6::R6Class("Widget",
+ public = list(
+ #' @description does a thing
+ doThing = function() { 1 }
+ )
+)
+
+#' Documented but not exported
+#' @noRd
+internalHelper <- function() { 1 }
+
+#' @export
+publicHelper <- function() { 2 }
+
+plainHelper <- function() { 3 }
+
+.dotHelper <- function() { 4 }
+`;
+
+test("roxygen: @export tag marks a definition exported regardless of naming", async () => {
+ const { dir, graph } = await buildAndRead({ "roxygen.R": ROXYGEN_R });
+ try {
+ assert.equal(nodeById(graph, "roxygen.R#Widget")?.exported, true, "@export on the R6 class");
+ assert.equal(nodeById(graph, "roxygen.R#publicHelper")?.exported, true, "@export on a plain function");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("roxygen: a documented-but-untagged definition is explicitly NOT exported", async () => {
+ const { dir, graph } = await buildAndRead({ "roxygen.R": ROXYGEN_R });
+ try {
+ // Has a roxygen block (so it's NOT naming-convention "unknown"), but no
+ // @export tag — roxygen's own NAMESPACE-generation convention treats this
+ // as an explicit internal signal, not an absence of evidence.
+ assert.equal(nodeById(graph, "roxygen.R#internalHelper")?.exported, false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("roxygen: no roxygen block at all falls back to the leading-dot naming convention", async () => {
+ const { dir, graph } = await buildAndRead({ "roxygen.R": ROXYGEN_R });
+ try {
+ assert.equal(nodeById(graph, "roxygen.R#plainHelper")?.exported, true);
+ assert.equal(nodeById(graph, "roxygen.R#.dotHelper")?.exported, false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("roxygen: R6 method visibility still comes from public=/private=, not roxygen", async () => {
+ const { dir, graph } = await buildAndRead({ "roxygen.R": ROXYGEN_R });
+ try {
+ // doThing has its own roxygen block (@description, no @export — @export
+ // doesn't apply to individual R6 methods) but must still resolve via the
+ // public= section it's declared in, not fall through to "not exported".
+ assert.equal(nodeById(graph, "roxygen.R#Widget.doThing")?.exported, true);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+const SUPER_R = `Animal <- R6::R6Class("Animal",
+ public = list(
+ speak = function() {
+ "..."
+ }
+ )
+)
+
+Dog <- R6::R6Class("Dog",
+ inherit = Animal,
+ public = list(
+ speak = function() {
+ base <- super$speak()
+ paste(base, "Woof")
+ }
+ )
+)
+`;
+
+test("super$: resolves to the PARENT class's method, not the current class's own override", async () => {
+ const { dir, graph } = await buildAndRead({ "super.R": SUPER_R });
+ try {
+ const call = graph.edges.find(
+ (e) => e.relation === "calls" && e.source === "super.R#Dog.speak" && e.target === "super.R#Animal.speak",
+ );
+ assert.ok(call, "Dog$speak's super$speak() should resolve to Animal$speak, not Dog$speak itself");
+
+ const selfCall = graph.edges.find(
+ (e) => e.relation === "calls" && e.source === "super.R#Dog.speak" && e.target === "super.R#Dog.speak",
+ );
+ assert.equal(selfCall, undefined, "must not resolve to its own (same-named) method");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("R6Class(...) itself no longer produces a spurious raw calls-edge intent", () => {
+ // Checked at the extractFile/rawEdges level, not the resolved graph: an
+ // unresolved "calls" RawEdge (no function is ever really named "R6Class")
+ // gets silently dropped by resolve.ts regardless, so this fix has no effect
+ // on the final graph.edges — it only matters here, avoiding a wasted/
+ // incorrect raw-edge intent in the first place.
+ const { rawEdges } = extractFile("super.R", SUPER_R, "r");
+ assert.equal(
+ rawEdges.some((e) => e.relation === "calls" && e.name === "R6Class"),
+ false,
+ );
+});
diff --git a/test/graph-r-phase4.test.ts b/test/graph-r-phase4.test.ts
new file mode 100644
index 00000000..1d22e694
--- /dev/null
+++ b/test/graph-r-phase4.test.ts
@@ -0,0 +1,133 @@
+/**
+ * Tests for R Phase 4: bare-name resolution for untyped R6 `$` composition
+ * calls (`private$other_obj$method()`) also matching "method"-kind nodes, not
+ * just "function". Scoped after investigating a real R6-heavy corpus
+ * (matching_on_the_fly_designs_R_package_and_paper_repr/EDI/R) where this
+ * exact shape — one class holding another as a field, dynamically constructed
+ * (constructor-parameter pass-through / do.call dispatch, not a statically
+ * inferable `field <- SomeClass$new()` literal) — appears 41+ times. Without
+ * this, every one of those calls was unconditionally unresolvable, since
+ * viaMember:false calls used to only ever match kind "function".
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import { buildGraph } from "../src/graph/build.js";
+import { readGraph, wiringPath } from "../src/graph/write.js";
+import type { GraphV1 } from "../src/graph/types.js";
+
+async function buildAndRead(files: Record<string, string>): Promise<{ dir: string; graph: GraphV1 }> {
+ const dir = mkdtempSync(join(tmpdir(), "graft-r-phase4-"));
+ for (const [name, content] of Object.entries(files)) writeFileSync(join(dir, name), content);
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ return { dir, graph };
+}
+
+// Mirrors the real corpus's shape: Design is constructed dynamically (via
+// do.call on a runtime class-generator variable, and passed through the
+// Inference constructor as a plain parameter) — nothing in the assignment
+// syntactically names "Design", so no type-binding table could infer it.
+const COMPOSITION_R = `Design <- R6::R6Class("Design",
+ public = list(
+ get_n = function() { 100 }
+ )
+)
+
+FixedDesign <- R6::R6Class("FixedDesign",
+ inherit = Design,
+ public = list()
+)
+
+make_design <- function(design_gen) {
+ do.call(design_gen$new, list())
+}
+
+Inference <- R6::R6Class("Inference",
+ public = list(
+ initialize = function(des_obj) {
+ private$des_obj <- des_obj
+ },
+ summarize = function() {
+ private$des_obj$get_n()
+ }
+ ),
+ private = list(
+ des_obj = NULL
+ )
+)
+`;
+
+test("Phase 4: an untyped private$field$method() call resolves to a uniquely-named method", async () => {
+ const { dir, graph } = await buildAndRead({ "composition.R": COMPOSITION_R });
+ try {
+ const call = graph.edges.find(
+ (e) =>
+ e.relation === "calls" &&
+ e.source === "composition.R#Inference.summarize" &&
+ e.target === "composition.R#Design.get_n",
+ );
+ assert.ok(call, "private$des_obj$get_n() should resolve to Design$get_n, the only get_n in the repo");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+// A and B (each defining "run") live in a DIFFERENT file than the caller, so
+// resolveName's same-file-first shortcut doesn't apply and the cross-file
+// ambiguity check (global.length === 1) is what's actually exercised —
+// same-file duplicates are a separate, pre-existing "first match wins" rule
+// this phase doesn't touch (see resolveName's own doc comment).
+const CLASSES_R = `A <- R6::R6Class("A", public = list(run = function() { 1 }))
+B <- R6::R6Class("B", public = list(run = function() { 2 }))
+`;
+const HOLDER_R = `Holder <- R6::R6Class("Holder",
+ public = list(
+ go = function(obj) {
+ private$target$run()
+ }
+ ),
+ private = list(
+ target = NULL
+ )
+)
+`;
+
+test("Phase 4: a cross-file ambiguous method name (defined on multiple classes) is safely dropped, not guessed", async () => {
+ const { dir, graph } = await buildAndRead({ "classes.R": CLASSES_R, "holder.R": HOLDER_R });
+ try {
+ const calls = graph.edges.filter(
+ (e) => e.relation === "calls" && e.source === "holder.R#Holder.go",
+ );
+ assert.equal(calls.length, 0, "run() is defined on both A and B — must not guess either one");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Phase 4: pkg::fun() qualified calls are unaffected (still function-only)", async () => {
+ const src = `helper <- function() { 1 }
+
+Widget <- R6::R6Class("Widget",
+ public = list(
+ helper = function() { 2 },
+ useQualified = function() {
+ pkg::helper()
+ }
+ )
+)
+`;
+ const { dir, graph } = await buildAndRead({ "qualified.R": src });
+ try {
+ // pkg::helper() must resolve to the free function, never Widget$helper —
+ // qualified calls never widen to "method" kind.
+ const call = graph.edges.find(
+ (e) => e.relation === "calls" && e.source === "qualified.R#Widget.useQualified",
+ );
+ assert.equal(call?.target, "qualified.R#helper");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/test/graph-r-phase5.test.ts b/test/graph-r-phase5.test.ts
new file mode 100644
index 00000000..cd0ba120
--- /dev/null
+++ b/test/graph-r-phase5.test.ts
@@ -0,0 +1,100 @@
+/**
+ * Tests for R Phase 5: plain-list "mixin"/"extension" bundles
+ * (`Foo <- list(public = list(...), private = list(...))`, NOT wrapped in
+ * `R6::R6Class(...)`) recognized as class-like containers. Discovered
+ * dogfooding against a real R6-heavy corpus
+ * (matching_on_the_fly_designs_R_package_and_paper_repr/EDI/R), where this
+ * "Pattern-1 mixin/extension" convention — sharing method bundles across
+ * classes via splicing (`public = c(Mixin$public, list(...))`) rather than
+ * `inherit =` — is used in 25 files, 11 of which were entirely invisible to
+ * the graph (zero extracted symbols) without this.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import { buildGraph } from "../src/graph/build.js";
+import { extractFile } from "../src/graph/extract.js";
+import { readGraph, wiringPath } from "../src/graph/write.js";
+import type { GraphV1 } from "../src/graph/types.js";
+
+async function buildAndRead(files: Record<string, string>): Promise<{ dir: string; graph: GraphV1 }> {
+ const dir = mkdtempSync(join(tmpdir(), "graft-r-phase5-"));
+ for (const [name, content] of Object.entries(files)) writeFileSync(join(dir, name), content);
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ return { dir, graph };
+}
+
+// Mirrors the real corpus's InferenceMixinKKGLMMShared shape.
+const MIXIN_R = `InferenceMixinKKGLMMShared = list(
+ public = list(
+ compute_estimate = function(estimate_only = FALSE) {
+ private$shared(estimate_only = estimate_only)
+ }
+ ),
+ private = list(
+ shared = function() { 1 }
+ )
+)
+`;
+
+test("Phase 5: a plain-list mixin container is recognized as a class", async () => {
+ const { dir, graph } = await buildAndRead({ "mixin.R": MIXIN_R });
+ try {
+ const mixin = graph.nodes.find((n) => n.id === "mixin.R#InferenceMixinKKGLMMShared");
+ assert.equal(mixin?.kind, "class");
+
+ const publicMethod = graph.nodes.find((n) => n.id === "mixin.R#InferenceMixinKKGLMMShared.compute_estimate");
+ assert.equal(publicMethod?.kind, "method");
+ assert.equal(publicMethod?.owner, "InferenceMixinKKGLMMShared");
+ assert.equal(publicMethod?.exported, true);
+
+ const privateMethod = graph.nodes.find((n) => n.id === "mixin.R#InferenceMixinKKGLMMShared.shared");
+ assert.equal(privateMethod?.exported, false, "private = list(...) entries stay unexported");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Phase 5: self$/private$ calls inside a mixin's methods still resolve to the mixin itself", async () => {
+ const { dir, graph } = await buildAndRead({ "mixin.R": MIXIN_R });
+ try {
+ const call = graph.edges.find(
+ (e) =>
+ e.relation === "calls" &&
+ e.source === "mixin.R#InferenceMixinKKGLMMShared.compute_estimate" &&
+ e.target === "mixin.R#InferenceMixinKKGLMMShared.shared",
+ );
+ assert.ok(call, "private$shared() should resolve within the mixin container itself");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Phase 5: an ordinary data/config list is NOT mistaken for a mixin container", async () => {
+ const src = `EDI_MIXIN_CONTRACTS <- list(
+ allowed = c("a", "b"),
+ required = list(x = 1, y = 2)
+)
+`;
+ const { dir, graph } = await buildAndRead({ "config.R": src });
+ try {
+ assert.equal(
+ graph.nodes.some((n) => n.id === "config.R#EDI_MIXIN_CONTRACTS"),
+ false,
+ "a list with no public=/private= entry must not become a class node",
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("Phase 5: the mixin's list(...) call itself no longer produces a spurious raw calls-edge intent", () => {
+ const { rawEdges } = extractFile("mixin.R", MIXIN_R, "r");
+ assert.equal(
+ rawEdges.some((e) => e.relation === "calls" && e.name === "list"),
+ false,
+ );
+});
diff --git a/test/graph-r.test.ts b/test/graph-r.test.ts
new file mode 100644
index 00000000..bdbef97f
--- /dev/null
+++ b/test/graph-r.test.ts
@@ -0,0 +1,194 @@
+/**
+ * Tests for R extraction in the Tier-1 code graph (Phase 1: flat function
+ * extraction, no S3/S4/R6 awareness — see plan_r_language_support.md). Builds a
+ * small R module in a temp dir and asserts the emitted nodes (left-assign,
+ * `=`-assign, and right-assign function definitions) and edges (contains, calls,
+ * imports) match the AST walk in extract.ts. Right-assignment is the main risk
+ * area: `function() {} -> name`'s AST shape does not mirror left-assign's the
+ * way it looks like it should (see describeR's doc comment) — get it wrong and
+ * every right-assigned function in a real R codebase silently disappears.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import { buildGraph } from "../src/graph/build.js";
+import { readGraph, wiringPath } from "../src/graph/write.js";
+import type { GraphV1, NodeV1 } from "../src/graph/types.js";
+
+const MAIN_R = `library(dplyr)
+require(purrr)
+source("helpers.R")
+
+foo <- function(x) {
+ x + 1
+}
+
+.helper <- function() {
+ 1
+}
+
+bar = function(y) {
+ y * 2
+}
+
+function(z) {
+ z - 1
+} -> baz
+
+result <- lapply(1:3, function(n) n + 1)
+
+sibling <- function() {
+ 42
+}
+
+useQualified <- function() {
+ pkg::sibling()
+}
+
+useDollar <- function(obj) {
+ obj$sibling()
+}
+`;
+
+function makeFixture(): string {
+ const dir = mkdtempSync(join(tmpdir(), "graft-r-"));
+ writeFileSync(join(dir, "main.R"), MAIN_R);
+ writeFileSync(join(dir, "helpers.R"), "noop <- function() { NULL }\n");
+ return dir;
+}
+
+function nodeById(graph: GraphV1, id: string): NodeV1 | undefined {
+ return graph.nodes.find((n) => n.id === id);
+}
+
+test("R extraction: left-assign, =-assign, and right-assign function definitions", async () => {
+ const dir = makeFixture();
+ try {
+ const result = await buildGraph(dir);
+ assert.ok(result.languages.includes("r"), "languages should include r");
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+
+ const foo = nodeById(graph, "main.R#foo");
+ assert.equal(foo?.kind, "function");
+ assert.equal(foo?.exported, true);
+ assert.equal(foo?.signature, "function(x)");
+
+ const bar = nodeById(graph, "main.R#bar");
+ assert.equal(bar?.kind, "function");
+ assert.equal(bar?.exported, true);
+
+ // The critical assertion: right-assign's AST shape is NOT a mirror of
+ // left-assign's — `->`'s low precedence absorbs it into the function
+ // definition's own body field. Get this wrong and baz never appears.
+ const baz = nodeById(graph, "main.R#baz");
+ assert.equal(baz?.kind, "function");
+ assert.equal(baz?.exported, true);
+ assert.equal(baz?.signature, "function(z)");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("R extraction: leading-dot naming convention marks a function unexported", async () => {
+ const dir = makeFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ assert.equal(nodeById(graph, "main.R#.helper")?.exported, false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("R extraction: an anonymous callback function is NOT emitted as a node", async () => {
+ const dir = makeFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+
+ // Every real definition in the fixture, no more, no fewer — the anonymous
+ // `function(n) n + 1` passed to lapply() must not sneak in as an 8th.
+ const expected = ["foo", ".helper", "bar", "baz", "sibling", "useQualified", "useDollar"];
+ const functionNodes = graph.nodes.filter((n) => n.kind === "function" && n.path === "main.R");
+ assert.deepEqual(
+ functionNodes.map((n) => n.name).sort(),
+ [...expected].sort(),
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("R extraction: library()/require()/source() become imports edges", async () => {
+ const dir = makeFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+
+ assert.ok(
+ graph.edges.some((e) => e.relation === "imports" && e.source === "main.R" && e.target === "dplyr"),
+ "library(dplyr) should be captured",
+ );
+ assert.ok(
+ graph.edges.some((e) => e.relation === "imports" && e.source === "main.R" && e.target === "purrr"),
+ "require(purrr) should be captured",
+ );
+ assert.ok(
+ graph.edges.some((e) => e.relation === "imports" && e.source === "main.R" && e.target === "helpers.R"),
+ `source("helpers.R") should be captured`,
+ );
+
+ // library()/require()/source() must NOT also produce spurious `calls` edges
+ // to functions literally named "library"/"require"/"source" — isImport is
+ // checked before the generic calls path precisely to prevent this.
+ assert.equal(
+ graph.edges.some((e) => e.relation === "calls" && ["library", "require", "source"].includes(e.target)),
+ false,
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("R extraction: qualified (pkg::fn) and member-style ($) calls resolve by bare name", async () => {
+ const dir = makeFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+
+ const qualifiedCall = graph.edges.find(
+ (e) => e.relation === "calls" && e.source === "main.R#useQualified" && e.target === "main.R#sibling",
+ );
+ assert.ok(qualifiedCall, "pkg::sibling() should resolve to the in-repo sibling() by bare name");
+
+ const dollarCall = graph.edges.find(
+ (e) => e.relation === "calls" && e.source === "main.R#useDollar" && e.target === "main.R#sibling",
+ );
+ assert.ok(dollarCall, "obj$sibling() should resolve to the in-repo sibling() by bare name");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("R extraction: contains edges (file -> function)", async () => {
+ const dir = makeFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+
+ const foo = nodeById(graph, "main.R#foo")!;
+ assert.ok(
+ graph.edges.some((e) => e.relation === "contains" && e.source === "main.R" && e.target === foo.id),
+ "main.R should contain foo",
+ );
+ const baz = nodeById(graph, "main.R#baz")!;
+ assert.ok(
+ graph.edges.some((e) => e.relation === "contains" && e.source === "main.R" && e.target === baz.id),
+ "main.R should contain baz (right-assigned)",
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});