From a9b112ae5f4e6543913be5bccd336b121a8934f4 Mon Sep 17 00:00:00 2001 From: Mick Cooney Date: Sat, 24 Oct 2026 13:33:11 +0100 Subject: [PATCH] fix(r): report chained receivers as unresolved instead of dropping them A member call whose receiver is itself a $ access or a call (a$b$m(), Cls$new()$m(), self$f$m()) had no call site, so it was invisible to the unresolved-receiver count. R6 fields and method results carry no declared type, so the chain is never followed: the site is minted with the shared codec's truncated receiver chain, which the shared fold refuses, and the call ends with a receiver-unresolved outcome and no edge. A chain whose first link is not a variable (get_user()$save(), pkg::Cls$new()$m(), x[[1]]$f$m()) mints no site at all and stays invisible. No shared code changes; unit and integration tests pin the reliance on the truncated marker. --- docs/languages/r-provider.md | 3 +- .../core/ingestion/languages/r/captures.ts | 54 ++++++- .../src/core/ingestion/languages/r/query.ts | 16 ++ .../r-chained-receivers/R/callers.R | 60 ++++++++ .../r-chained-receivers/R/decoys.R | 5 + .../r-chained-receivers/R/models.R | 45 ++++++ .../r/chained-receiver-same-name/after/save.R | 3 + .../chained-receiver-same-name/before/save.R | 3 + .../r/chained-receiver-same-name/case.json | 9 ++ .../integration/rename-provider-r.test.ts | 2 +- .../resolvers/r-chained-receivers.test.ts | 143 ++++++++++++++++++ .../r/r-receiver-chain.test.ts | 137 +++++++++++++++++ 12 files changed, 477 insertions(+), 3 deletions(-) create mode 100644 gitnexus/test/fixtures/lang-resolution/r-chained-receivers/R/callers.R create mode 100644 gitnexus/test/fixtures/lang-resolution/r-chained-receivers/R/decoys.R create mode 100644 gitnexus/test/fixtures/lang-resolution/r-chained-receivers/R/models.R create mode 100644 gitnexus/test/fixtures/rename-integration/r/chained-receiver-same-name/after/save.R create mode 100644 gitnexus/test/fixtures/rename-integration/r/chained-receiver-same-name/before/save.R create mode 100644 gitnexus/test/fixtures/rename-integration/r/chained-receiver-same-name/case.json create mode 100644 gitnexus/test/integration/resolvers/r-chained-receivers.test.ts create mode 100644 gitnexus/test/unit/scope-resolution/r/r-receiver-chain.test.ts diff --git a/docs/languages/r-provider.md b/docs/languages/r-provider.md index 78930623c8..0a17f9ac11 100644 --- a/docs/languages/r-provider.md +++ b/docs/languages/r-provider.md @@ -35,6 +35,7 @@ Imports: Calls: - Free calls, `obj$method()` calls (receiver typed as above), R6 `self$method()` calls, and calls inside native pipe (`|>`) chains. +- A chained member call, `a$b$m()`, `Cls$new()$m()` or `self$f$m()` (the receiver is itself a `$`/`@` access or a call), is never typed: R6 fields and method results carry no declared type, so the chain is not followed. The site is minted with the shared codec's `truncated` receiver chain, which the shared fold refuses, and the call ends with a `receiver-unresolved` outcome and no edge, instead of reaching a free function or a method of that name elsewhere (it counts toward the `impact` lower bound). The first link must be a plain variable: a chain based on a call (`get_user()$save()`, `pkg::Cls$new()$m()`), on `x[[1]]`, `x[1]` or `(x)`, or one the codec cannot encode (more steps than its depth limit, a name with a space) mints no site at all: no edge and no outcome. That shape is invisible, not unresolved. The shared fold's comment calls the `truncated` marker defence in depth that no producer mints; R relies on it, and `r-receiver-chain.test.ts` and `r-chained-receivers.test.ts` fail if upstream starts folding or refusing it. Renaming a function whose name is the last step of such a call (a free `save` beside `a$b$save()`) is refused as `ambiguous_reference`. - A replacement-function call, `foo(x) <- value`, is recorded as a call of `` `foo<-` ``, as R runs it (`=`, `<<-`, `->` and `->>` too, and `pkg::foo(x) <- v` as a call of ``pkg::`foo<-` ``, which passes the export check of the setter name: a NAMESPACE entry may be written ``export(`foo<-`)`` or `export("foo<-")`, and an unexported setter is dropped from outside the package, never replaced by the getter). A call is in a replacement position when it lies in the target chain, reached only through first arguments and the bases of `$`, `@`, `[` and `[[`; every call of the chain is recorded as its own setter (`foo(bar(x)) <- 1` calls `` `foo<-` `` and `` `bar<-` ``), so the getter half that R also evaluates (`bar(x)`) has no edge: a missing edge, not a wrong one. Other arguments (`foo(x, bar(1)) <- v`, the index of `foo(x)[bar(1)] <- v`) and the assigned value stay ordinary calls, and `x$a <- 1` or `x[i] <- 1` (a builtin setter) has no call site at all. A function defined as `` `foo<-` <- function(x, value) ... `` is now found by the call; a string-spelled definition (`"foo<-" <- function(...)`) and `setReplaceMethod()` / `setGeneric("foo<-")` define no node, so such a call has no edge (not even to the getter). An explicit `` `foo<-`(x, v) `` is unchanged. `rename` refuses both halves of a replacement pair (see Rename). - `self` in an R6 method is typed as the class: `self$m()` resolves through the class and its parents (`inherit =`) at the receiver-call confidence (0.85), never to a free function of that name. The class is the name the `R6Class` call is assigned to (`Child <- R6::R6Class(...)`, bare or `R6::`), and the method is a function in its `public`, `private` or `active` list. A closure inside a method sees the method's `self`. Where `self` is no R6 instance (a free function, a parameter called `self`, an `R6Class` call that is assigned to nothing, a `setRefClass` method) a `self$m()` call gets no edge and the resolution outcome is `receiver-owned-but-unbound`; a method that neither the class nor a parent defines (or a parent that is not indexed, as in `inherit = pkg::Base`) gets no edge and the outcome `member-lookup-ambiguous` (the closest label the shared pass offers for "member not found"). A file that binds `self` itself (`self <- Foo$new()` at top level) is exempt: its free functions read that object. - A call through a name that a function's formal or one of its `for` variables binds (`function(data, transform) transform(data)`) gets no edge, not even to a top-level function of that name. The scope publishes those names as lexical names: they stop the lookup and the unique-name fallback. Every named formal is a lexical name, whatever its default: a default (`n = 2`, `helper = NULL`) proves nothing about the argument a caller passes, which may be a function, so a call through the formal is never bound to a function of that name outside. A `for` loop outside every function binds nothing. @@ -52,7 +53,7 @@ Exports: ## Resolution model -The scope query (`languages/r/query.ts`) captures three call shapes only: `f(x)`, `pkg::f(x)` and `obj$f(x)`. A free or qualified call in the target of an assignment (`f(x) <- v`) is a call of the setter `` `f<-` `` (see the replacement-function bullet under Calls). +The scope query (`languages/r/query.ts`) captures four call shapes only: `f(x)`, `pkg::f(x)`, `obj$f(x)` and a chained `a$b$f(x)` (an `extract_operator` or a call as the receiver; see the chained-call bullet under Calls). A free or qualified call in the target of an assignment (`f(x) <- v`) is a call of the setter `` `f<-` `` (see the replacement-function bullet under Calls). - A bare call binds lexically first. `library()` and `require()` of a local package attach that package's exports, as R does for an installed package: every top-level name when the package has no NAMESPACE file, otherwise the names the NAMESPACE provably exports (`export()`, `exportClasses()`, `exportMethods()`, `S3method()`, a matching `exportPattern()`). A name the NAMESPACE does not export is not attached, and neither is a name it may export but cannot be proven to (an unreadable NAMESPACE, or an `exportPattern()` that was dropped or cut short by its work budget): the 0.85 edge a `library()` yields needs proof. The hook has no importer, so a `library(ownpkg)` issued from inside the package (its `tests/` included) attaches only the exports too. When two attached packages define the same name, the package attached last wins, as R masks it: of the `library()` calls whose package defines the name, the one that comes last in the file decides (calls inside a function are not told apart from top-level ones, and a package named by several calls counts at the first of them, because R leaves an attached package where it is: `library(a); library(b); library(a)` still lets `b` mask `a`). Two files of that one package that both define the name stay ambiguous, with no edge. This differs from `devtools::load_all()`, which attaches every top-level name; the earlier behaviour of this provider followed `load_all()`. `source()` binds no name; a call into a sourced file, or into another file of the same package, binds through a workspace-wide unique-name fallback at confidence 0.5 (`global-name-fallback`). That guess skips a candidate its package's readable, complete NAMESPACE does not export, unless the caller sits inside that package's directory tree (see Export status); a name that is not provably private (unreadable NAMESPACE, a cut-short `exportPattern()`) keeps the guess. An ambiguous name yields no edge, and a function defined inside another function is never a candidate (no other function can reach it by name). - A bare call never binds to a dotted definition, so `foo(x)` cannot reach `print.foo`. Dotted (S3-style) names are never import-resolved; a call that spells the full dotted name binds by qualified-name lookup. Dotted names are not bound through `importFrom()`. diff --git a/gitnexus/src/core/ingestion/languages/r/captures.ts b/gitnexus/src/core/ingestion/languages/r/captures.ts index 7f25c7fdbd..a864f99ba5 100644 --- a/gitnexus/src/core/ingestion/languages/r/captures.ts +++ b/gitnexus/src/core/ingestion/languages/r/captures.ts @@ -1,8 +1,10 @@ -import type { Capture, CaptureMatch } from 'gitnexus-shared'; +import type { Capture, CaptureMatch, MixedChainStep } from 'gitnexus-shared'; import { nodeToCapture, syntheticCapture } from '../../utils/ast-helpers.js'; import type { SyntaxNode } from '../../utils/ast-helpers.js'; import { getRParser, getRScopeQuery } from './query.js'; import { isRNonNamingScopeMatch } from './naming-argument.js'; +import { MAX_CHAIN_DEPTH } from '../../utils/call-analysis.js'; +import { encodeReceiverChain } from '../../utils/receiver-chain-codec.js'; import { getTreeSitterBufferSize } from '../../constants.js'; import { parseSourceSafe } from '../../../tree-sitter/safe-parse.js'; import { isRReplacementCall, rLexicalAssignedNames, rSetterName } from './assignment.js'; @@ -45,6 +47,7 @@ export function emitRScopeCaptures( let functionNode: SyntaxNode | undefined; let methodNode: SyntaxNode | undefined; let freeCallNode: SyntaxNode | undefined; + let chainedReceiver: SyntaxNode | undefined; for (const c of m.captures) { const tag = '@' + c.name; if (tag.startsWith('@_')) continue; @@ -53,6 +56,7 @@ export function emitRScopeCaptures( if (tag === '@scope.function' && c.node.type === 'function_definition') functionNode = c.node; if (tag === '@scope.function' && c.node.type === 'argument') methodNode = c.node; if (tag === '@reference.call.free') freeCallNode = c.node; + if (tag === '@reference.receiver' && c.node.type !== 'identifier') chainedReceiver = c.node; if (tag === '@scope.module' && c.node.type === 'program' && !bindsSelf) { grouped['@receiver-owner.self'] = syntheticCapture('@receiver-owner.self', c.node, 'self'); } @@ -61,6 +65,17 @@ export function emitRScopeCaptures( if (freeCallNode !== undefined && isRReplacementCall(freeCallNode)) { recordAsSetterCall(grouped, freeCallNode); } + // A member call whose receiver is itself a `$` access or a call (`a$b$m()`): mint the + // truncated chain, or drop the match when the chain has no variable base. + if (chainedReceiver !== undefined) { + const chain = rReceiverChain(chainedReceiver); + if (chain === undefined) continue; + grouped['@reference.receiver-chain'] = syntheticCapture( + '@reference.receiver-chain', + chainedReceiver, + chain, + ); + } // The function's own scope names what its formals and loop variables bind, so that a call // through one of them stops the lexical walk there instead of reaching a top-level function // of the same name. @@ -102,6 +117,43 @@ export function emitRScopeCaptures( return out; } +/** + * The receiver chain of a chained member call (`a$b$m()`, `Cls$new()$m()`), encoded with the + * shared codec's `truncated` marker, or `undefined` when the receiver has no variable base. + * + * The walk goes down `extract_operator` (`x$f`, `x@f`: a field step) and `call(function: + * extract_operator)` (`x$f()`: a call step) to an identifier, which is the base. R6 fields and + * method results carry no declared type, so a chain is never typed; the marker makes the shared + * fold refuse it, and the site ends as an unresolved receiver (an outcome, no edge) instead of + * falling to a free function or a method of the same name elsewhere. + * + * `undefined` (the caller drops the match, so the call is invisible: no edge, no outcome) when + * the base is not a variable (a call of a function or of `pkg::f`, `x[[1]]`, `x[1]`, `(x)`), a + * step is not an identifier (`a$"b"$m()`), or the codec cannot + * encode the chain (more steps than it allows, a name with a space). No honest outcome exists + * for a receiver that is not a variable, and the walk is bounded so a pathological chain costs + * a constant amount of work. + */ +export function rReceiverChain(receiverNode: SyntaxNode): string | undefined { + const outerToInner: MixedChainStep[] = []; + let node: SyntaxNode = receiverNode; + while (outerToInner.length <= MAX_CHAIN_DEPTH) { + if (node.type === 'identifier') { + const steps = outerToInner.reverse(); + return encodeReceiverChain(node.text, steps, { truncated: true }); + } + const isCall = node.type === 'call'; + const access = isCall ? node.childForFieldName('function') : node; + if (access?.type !== 'extract_operator') return undefined; + const lhs = access.childForFieldName('lhs'); + const rhs = access.childForFieldName('rhs'); + if (lhs === null || rhs?.type !== 'identifier') return undefined; + outerToInner.push({ kind: isCall ? 'call' : 'field', name: rhs.text }); + node = lhs; + } + return undefined; +} + /** * Rewrites the captures of a call in a replacement position (`foo(x) <- v`) so that the site names * the setter: `@reference.name` becomes `` `foo<-` `` and a qualified `pkg::foo` becomes diff --git a/gitnexus/src/core/ingestion/languages/r/query.ts b/gitnexus/src/core/ingestion/languages/r/query.ts index 4a8ed9a8f3..39d4e6a0c3 100644 --- a/gitnexus/src/core/ingestion/languages/r/query.ts +++ b/gitnexus/src/core/ingestion/languages/r/query.ts @@ -76,6 +76,13 @@ * `Type$new(...)` is R6's constructor spelling: captured separately as * `@type-binding.constructor` so `x <- Type$new(...)` types `x`. * + * - `a$b$m()` and `Cls$new()$m()` (the receiver is itself an `extract_operator` or a `call`) + * are chained member calls. R never types through a chain (R6 fields and results carry no + * declared type), so `emitRScopeCaptures` mints `@reference.receiver-chain` with the shared + * codec's `truncated` marker: the shared fold refuses it and the call ends as an unresolved + * receiver (an outcome, no edge) instead of reaching a same-named free function. A chain + * with no variable base mints nothing at all (an invisible gap, see `rReceiverChain`). + * * Exposes lazy `Parser` and `Query` singletons so callers don't pay * tree-sitter init cost per file. */ @@ -344,6 +351,15 @@ export const R_SCOPE_QUERY = ` function: (extract_operator lhs: (identifier) @reference.receiver rhs: (identifier) @reference.name)) @reference.call.member + +;; Chained member calls: a$b$m(), Cls$new()$m(). The receiver is itself an extract_operator or a +;; call; the pattern is disjoint from the one above (an identifier receiver), so no call is +;; matched twice. emitRScopeCaptures turns the receiver into a truncated chain, or drops the match +;; when the chain has no variable base (get_user()$m(), pkg::Cls$new()$m(), x[[1]]$f$m()). +(call + function: (extract_operator + lhs: [(extract_operator) (call)] @reference.receiver + rhs: (identifier) @reference.name)) @reference.call.member `; let _parser: Parser | null = null; diff --git a/gitnexus/test/fixtures/lang-resolution/r-chained-receivers/R/callers.R b/gitnexus/test/fixtures/lang-resolution/r-chained-receivers/R/callers.R new file mode 100644 index 0000000000..89151456e8 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/r-chained-receivers/R/callers.R @@ -0,0 +1,60 @@ +# Chains with an identifier base: the base's type is never followed. +chain_dollar_dollar <- function(a) { + a$b$c() +} + +chain_new_call <- function() { + Cls$new()$m() +} + +chain_typed_base <- function() { + u <- User$new() + u$save() +} + +chain_typed_base_chain <- function() { + u <- User$new() + u$next_user$save() +} + +chain_deep <- function(a) { + a$b$c$d$m() +} + +# The control: a plain receiver typed through its constructor. +control <- function() { + u <- User$new() + u$save() +} + +# Chains with no identifier base: no site at all. +base_call <- function() { + get_user()$save() +} + +base_namespace_new <- function() { + pkg::Cls$new()$m() +} + +base_subset <- function(x) { + x[[1]]$f$m() +} + +base_subset_single <- function(x) { + x[1]$save() +} + +base_paren <- function(x) { + (x)$f$save() +} + +# Chains through a field initialised with a constructor and through a method returning self. +chain_field_instance <- function() { + p <- Person$new() + p$addr$save() +} + +chain_method_result <- function() { + p <- Person$new() + p$me()$save() +} diff --git a/gitnexus/test/fixtures/lang-resolution/r-chained-receivers/R/decoys.R b/gitnexus/test/fixtures/lang-resolution/r-chained-receivers/R/decoys.R new file mode 100644 index 0000000000..7c6cfd0c14 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/r-chained-receivers/R/decoys.R @@ -0,0 +1,5 @@ +# Free functions named like the last step of each chained call. A chain whose base is not known +# must never be bound to one of these (or to a method of the same name). +c <- function() "free c" +m <- function() "free m" +save <- function() "free save" diff --git a/gitnexus/test/fixtures/lang-resolution/r-chained-receivers/R/models.R b/gitnexus/test/fixtures/lang-resolution/r-chained-receivers/R/models.R new file mode 100644 index 0000000000..9b3c05d29a --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/r-chained-receivers/R/models.R @@ -0,0 +1,45 @@ +library(R6) + +User <- R6Class("User", + public = list( + save = function() "User.save" + ) +) + +# An unrelated class whose methods share the names of the calls below. +Other <- R6Class("Other", + public = list( + c = function() "Other.c", + m = function() "Other.m" + ) +) + +Cls <- R6Class("Cls", + public = list( + m = function() "Cls.m" + ) +) + +Holder <- R6Class("Holder", + public = list( + f = NULL, + run = function() { + self$f$m() + } + ) +) + +# A field initialised with a constructor call, and a method returning self: the shapes where a +# typed walk of the chain could succeed. +Address <- R6Class("Address", + public = list( + save = function() "Address.save" + ) +) + +Person <- R6Class("Person", + public = list( + addr = Address$new(), + me = function() invisible(self) + ) +) diff --git a/gitnexus/test/fixtures/rename-integration/r/chained-receiver-same-name/after/save.R b/gitnexus/test/fixtures/rename-integration/r/chained-receiver-same-name/after/save.R new file mode 100644 index 0000000000..b2752da412 --- /dev/null +++ b/gitnexus/test/fixtures/rename-integration/r/chained-receiver-same-name/after/save.R @@ -0,0 +1,3 @@ +save <- function() 1 + +caller <- function(a) a$b$save() diff --git a/gitnexus/test/fixtures/rename-integration/r/chained-receiver-same-name/before/save.R b/gitnexus/test/fixtures/rename-integration/r/chained-receiver-same-name/before/save.R new file mode 100644 index 0000000000..b2752da412 --- /dev/null +++ b/gitnexus/test/fixtures/rename-integration/r/chained-receiver-same-name/before/save.R @@ -0,0 +1,3 @@ +save <- function() 1 + +caller <- function(a) a$b$save() diff --git a/gitnexus/test/fixtures/rename-integration/r/chained-receiver-same-name/case.json b/gitnexus/test/fixtures/rename-integration/r/chained-receiver-same-name/case.json new file mode 100644 index 0000000000..abba90a71d --- /dev/null +++ b/gitnexus/test/fixtures/rename-integration/r/chained-receiver-same-name/case.json @@ -0,0 +1,9 @@ +{ + "language": "r", + "description": "Refuse when a chained call of the same name exists (a$b$save()): the chain's receiver is never typed, so the call is an unresolved receiver site that cannot be proved not to reach the function, and the provider does not guess. Before chained calls were sites, the same rename was refused as an uncovered occurrence (incomplete_semantics).", + "categories": ["receiver", "negative", "unchanged-on-error"], + "target": { "name": "save", "kind": "Function", "file": "save.R", "startLine": 0 }, + "newName": "store", + "expect": { "status": "error", "code": "ambiguous_reference", "planningStatus": "blocked" }, + "edges": [] +} diff --git a/gitnexus/test/integration/rename-provider-r.test.ts b/gitnexus/test/integration/rename-provider-r.test.ts index 38d5ec3334..5fa4c31d9e 100644 --- a/gitnexus/test/integration/rename-provider-r.test.ts +++ b/gitnexus/test/integration/rename-provider-r.test.ts @@ -5,7 +5,7 @@ import { defineRenameFixtureTests, renameCases } from '../helpers/rename-integra // would define no test and stay green. Pin the number of R cases: adding one means raising it. describe('R rename fixtures', () => { it('are all discovered', () => { - expect(renameCases.filter((fixture) => fixture.language === 'r')).toHaveLength(71); + expect(renameCases.filter((fixture) => fixture.language === 'r')).toHaveLength(72); }); }); diff --git a/gitnexus/test/integration/resolvers/r-chained-receivers.test.ts b/gitnexus/test/integration/resolvers/r-chained-receivers.test.ts new file mode 100644 index 0000000000..69499dc3b9 --- /dev/null +++ b/gitnexus/test/integration/resolvers/r-chained-receivers.test.ts @@ -0,0 +1,143 @@ +/** + * R: a call through a chained receiver (`a$b$c()`, `Cls$new()$m()`, `self$f$m()`) is reported as + * an unresolved receiver, never bound to a free function or to a method of another class. + * + * R6 fields and method results carry no declared type, so the chain is never typed. The capture + * layer mints the chain with the shared codec's `truncated` marker, which makes the shared + * fold refuse it: the call has no edge and a `receiver-unresolved` outcome says why (the lower + * bound `impact` reports). A chain whose base is not a plain variable (`get_user()$save()`, + * `pkg::Cls$new()$m()`, `x[[1]]$f$m()`) mints no site at all: no edge and no outcome. + * + * Fixture `r-chained-receivers/R/`: `decoys.R` has free `c`, `m` and `save`; `models.R` an R6 + * `User` (with `save`), an unrelated `Other` (with `c` and `m`), `Cls` (with `m`) and `Holder` + * (whose method calls `self$f$m()`); `callers.R` one caller per shape. + */ +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import fs from 'fs'; +import path from 'path'; +import { + FIXTURES, + getRelationships, + getResolutionOutcomes, + runPipelineFromRepo, + type PipelineResult, +} from './helpers.js'; + +beforeAll(() => vi.stubEnv('GITNEXUS_WORKER_READY_TIMEOUT_MS', '60000')); +afterAll(() => vi.unstubAllEnvs()); + +let result: PipelineResult; +beforeAll(async () => { + result = await runPipelineFromRepo(path.join(FIXTURES, 'r-chained-receivers'), () => {}); +}, 120000); + +/** Every CALLS target out of `source` in `file`, as its node id, sorted. */ +const targets = (source: string, file = 'R/callers.R'): string[] => + getRelationships(result, 'CALLS') + .filter((e) => e.source === source && e.sourceFilePath === file) + .map((e) => e.rel.targetId) + .sort(); + +const lines = (file: string): string[] => + fs.readFileSync(path.join(FIXTURES, 'r-chained-receivers', file), 'utf8').split('\n'); + +/** 1-based line of the first line of `file` that contains `text`. */ +const lineOf = (file: string, text: string): number => { + const index = lines(file).findIndex((l) => l.includes(text)); + if (index < 0) throw new Error(`${text} not in ${file}`); + return index + 1; +}; + +/** The dropped-site outcomes of `file`, in source order (every outcome here is a drop). */ +const dropsIn = (file: string) => + getResolutionOutcomes(result) + .flatMap((o) => (o.kind === 'suppressed' && o.filePath === file ? [o] : [])) + .sort((a, b) => a.range.startLine - b.range.startLine); + +/** The outcomes recorded on one source line, as `reason:siteKind:name`. */ +const outcomesAt = (file: string, line: number): string[] => + dropsIn(file) + .filter((o) => o.range.startLine === line) + .map((o) => `${o.reason}:${o.siteKind}:${o.name}`); + +/** `reason:name` of every outcome in `file`, in source order. */ +const outcomesIn = (file: string): string[] => dropsIn(file).map((o) => `${o.reason}:${o.name}`); + +describe('a chain whose base is a variable: unresolved, with an outcome', () => { + it.each([ + ['a$b$c()', 'a$b$c()', 'chain_dollar_dollar', 'c'], + ['Cls$new()$m()', 'Cls$new()$m()', 'chain_new_call', 'm'], + ['a$b$c$d$m()', 'a$b$c$d$m()', 'chain_deep', 'm'], + ['u$next_user$save()', 'u$next_user$save()', 'chain_typed_base_chain', 'save'], + // Shapes where a typed walk could succeed: a field initialised with a constructor. + ['p$addr$save()', 'p$addr$save()', 'chain_field_instance', 'save'], + ])('%s: no edge, one receiver-unresolved outcome', (_shape, text, caller, name) => { + expect(targets(caller)).toEqual([]); + expect(outcomesAt('R/callers.R', lineOf('R/callers.R', text))).toEqual([ + `receiver-unresolved:call:${name}`, + ]); + }); + + it('p$me()$save(): the inner p$me() keeps its edge, the chained save() has an outcome and no edge', () => { + expect(targets('chain_method_result')).toEqual(['Method:R/models.R:Person.me#0']); + expect(outcomesAt('R/callers.R', lineOf('R/callers.R', 'p$me()$save()'))).toEqual([ + 'receiver-unresolved:call:save', + ]); + }); + + it('self$f$m() inside an R6 method: no edge, one receiver-unresolved outcome', () => { + expect(targets('run', 'R/models.R')).toEqual([]); + expect(outcomesAt('R/models.R', lineOf('R/models.R', 'self$f$m()'))).toEqual([ + 'receiver-unresolved:call:m', + ]); + }); + + it('no chained call reaches a free function or a method of another class', () => { + const decoys = getRelationships(result, 'CALLS').filter( + (e) => + e.sourceFilePath !== 'R/decoys.R' && + ['c', 'm'].includes(e.target) && + !e.rel.targetId.includes('Cls.m'), + ); + expect(decoys.map((e) => `${e.source} -> ${e.rel.targetId}`)).toEqual([]); + }); +}); + +describe('control: a plain receiver typed through its constructor still resolves', () => { + it('u$save() binds User.save exactly', () => { + expect(targets('control')).toEqual(['Method:R/models.R:User.save#0']); + expect(outcomesAt('R/callers.R', lineOf('R/callers.R', ' u$save()'))).toEqual([]); + }); + + it('a typed base followed by a plain call is unchanged (chain_typed_base)', () => { + expect(targets('chain_typed_base')).toEqual(['Method:R/models.R:User.save#0']); + }); +}); + +describe('a chain with no variable base mints no site (invisible: no edge, no outcome)', () => { + it.each([ + ['get_user()$save()', 'base_call'], + ['pkg::Cls$new()$m()', 'base_namespace_new'], + ['x[[1]]$f$m()', 'base_subset'], + ['(x)$f$save()', 'base_paren'], + ])('%s: no edge to the free decoy or to a class method, no outcome', (text, caller) => { + expect(targets(caller)).toEqual([]); + expect(outcomesAt('R/callers.R', lineOf('R/callers.R', text))).toEqual([]); + }); + + it('x[1]$save() (a subset receiver, not a chain) is not a site either', () => { + expect(targets('base_subset_single')).toEqual([]); + expect(outcomesAt('R/callers.R', lineOf('R/callers.R', 'x[1]$save()'))).toEqual([]); + }); + + it('the only outcomes in callers.R are the six chained calls with a variable base', () => { + expect(outcomesIn('R/callers.R')).toEqual([ + 'receiver-unresolved:c', + 'receiver-unresolved:m', + 'receiver-unresolved:save', + 'receiver-unresolved:m', + 'receiver-unresolved:save', + 'receiver-unresolved:save', + ]); + }); +}); diff --git a/gitnexus/test/unit/scope-resolution/r/r-receiver-chain.test.ts b/gitnexus/test/unit/scope-resolution/r/r-receiver-chain.test.ts new file mode 100644 index 0000000000..943327d1c8 --- /dev/null +++ b/gitnexus/test/unit/scope-resolution/r/r-receiver-chain.test.ts @@ -0,0 +1,137 @@ +/** + * R chained receivers (`a$b$c()`). + * + * `emitRScopeCaptures` mints the chain R-locally, with the shared codec's `truncated` marker: + * R never types through a chain (R6 fields and results have no declared type), so the marker's + * only job is to make the shared fold refuse the chain and leave the site unresolved, with a + * `receiver-unresolved` outcome. The shared comment on the fold calls the marker defence in + * depth and says the producer never mints one; the last block pins that reliance, so an + * upstream change that folds or refuses a truncated chain fails an R test. + * + * A chain with no variable base (`get_user()$save()`, `pkg::Cls$new()$m()`, `x[[1]]$f$m()`) + * mints no site at all. + */ +import { describe, expect, it } from 'vitest'; +import type { CaptureMatch } from 'gitnexus-shared'; +import { emitRScopeCaptures } from '../../../../src/core/ingestion/languages/r/captures.js'; +import { + decodeReceiverChain, + encodeReceiverChain, +} from '../../../../src/core/ingestion/utils/receiver-chain-codec.js'; +import { foldReceiverChain } from '../../../../src/core/ingestion/scope-resolution/passes/compound-receiver.js'; + +/** The member-call matches of `source`, as `{receiver, name, chain}`. */ +const memberCalls = (source: string) => + emitRScopeCaptures(source, 'a.R') + .filter((m: CaptureMatch) => m['@reference.call.member'] !== undefined) + .map((m) => ({ + receiver: m['@reference.receiver']?.text, + name: m['@reference.name']?.text, + chain: decodeReceiverChain(m['@reference.receiver-chain']?.text), + })); + +describe('a chain with a variable base is minted truncated', () => { + it.each([ + ['a$b$c()', 'a$b', 'c', 'a', [{ kind: 'field', name: 'b' }]], + ['Cls$new()$m()', 'Cls$new()', 'm', 'Cls', [{ kind: 'call', name: 'new' }]], + [ + 'a$b$c$d$m()', + 'a$b$c$d', + 'm', + 'a', + [ + { kind: 'field', name: 'b' }, + { kind: 'field', name: 'c' }, + { kind: 'field', name: 'd' }, + ], + ], + [ + 'a$b()$c$m()', + 'a$b()$c', + 'm', + 'a', + [ + { kind: 'call', name: 'b' }, + { kind: 'field', name: 'c' }, + ], + ], + ['self$f$m()', 'self$f', 'm', 'self', [{ kind: 'field', name: 'f' }]], + ['a@b$m()', 'a@b', 'm', 'a', [{ kind: 'field', name: 'b' }]], + ])('%s', (text, receiver, name, base, steps) => { + // The last member call is the outer one (`Cls$new()$m()` also holds the inner `Cls$new()`). + const outer = memberCalls(`f <- function(a) {\n ${text}\n}\n`).filter((c) => c.name === name); + expect(outer).toHaveLength(1); + expect(outer[0].receiver).toBe(receiver); + expect(outer[0].chain).toEqual({ baseReceiverName: base, steps, truncated: true }); + }); + + it('a plain receiver keeps its single site and gets no chain', () => { + const calls = memberCalls('f <- function(u) u$save()\n'); + expect(calls).toEqual([{ receiver: 'u', name: 'save', chain: undefined }]); + }); + + it('one member-call site per call: the inner field step is not a call of its own', () => { + expect(memberCalls('f <- function(a) a$b$c()\n').map((c) => c.name)).toEqual(['c']); + }); + + it('an inner call step keeps its own plain site (a$b() receiver a, no chain)', () => { + const calls = memberCalls('f <- function(a) a$b()$m()\n'); + expect(calls.map((c) => [c.name, c.receiver, c.chain === undefined])).toEqual([ + ['b', 'a', true], + ['m', 'a$b()', false], + ]); + }); +}); + +describe('a chain with no variable base mints no site', () => { + it.each([ + 'get_user()$save()', + 'pkg::Cls$new()$m()', + 'pkg:::Cls$new()$m()', + 'x[[1]]$f$m()', + 'x[1]$f$m()', + '(x)$f$m()', + 'g(x)$f$m()', + 'g(x)$m()', + 'a$b[[1]]$m()', + 'a$"b"$m()', + ])('%s', (text) => { + expect(memberCalls(`f <- function(x) {\n ${text}\n}\n`)).toEqual([]); + }); + + it('a chain longer than the codec accepts mints no site', () => { + const long = Array.from({ length: 40 }, (_, i) => `s${i}`).join('$'); + expect(memberCalls(`f <- function(a) a$${long}$m()\n`)).toEqual([]); + }); + + it('an unencodable name mints no site', () => { + expect(memberCalls('f <- function(a) a$`b c`$m()\n')).toEqual([]); + }); +}); + +describe('the shared fold refuses a truncated chain (the reliance behind the marker)', () => { + const wire = (truncated: boolean) => { + const encoded = encodeReceiverChain( + 'a', + [{ kind: 'field', name: 'b' }], + truncated ? { truncated } : undefined, + ); + const decoded = decodeReceiverChain(encoded); + if (decoded === undefined) throw new Error(`chain did not round-trip: ${String(encoded)}`); + return decoded; + }; + + it('decodes the marker', () => { + expect(wire(true).truncated).toBe(true); + expect(wire(false).truncated).toBe(false); + }); + + it('foldReceiverChain returns undefined for a truncated chain before reading any index', () => { + // A complete chain reaches into the indexes and throws on these empty stand-ins; the + // truncated one is refused first. If upstream stops refusing a truncated chain, this fails. + const scopes = {} as never; + const index = {} as never; + expect(foldReceiverChain(wire(true), 'scope' as never, scopes, index)).toBeUndefined(); + expect(() => foldReceiverChain(wire(false), 'scope' as never, scopes, index)).toThrow(); + }); +});