From a6930139503323e554c5cfb6506041463b97e418 Mon Sep 17 00:00:00 2001 From: Mick Cooney Date: Sat, 24 Oct 2026 23:12:18 +0100 Subject: [PATCH] fix(r): keep self typed through field writes and off private members An R6 method that wrote through self (`self$count <- 1`, `self$x[[i]] <- v`, `self[["x"]] <- v`, `names(self$x) <- v`) made `self` a lexical name of the method, so later `self$m()` calls lost the receiver type: an own method fell to 0.51 and an inherited or missing one bound a free function of that name at 0.49. A write through self no longer binds the name; only a plain `self <- v` (or a formal or loop variable called `self`) does, and a function that rebinds self that way now owns it, so `self$m()` there is unresolved unless the new binding is typed. `self$m()` also reached methods of the `private` list. self is the public interface, so private members are now skipped: a private-only name is unresolved and a parent's public method wins over a private one of the class. The definitions carry no section, so the capture pass records the private members per file and hands them to the main thread through the capture side channel (worker and parse-cache safe). exportPattern() now refuses any backslash inside a bracket expression, which TRE reads as a literal member (`[a\-z]` is a range from `\` to `z`), instead of reading it as a JavaScript escape. The common `^[^\\.]` is dropped too. Also removes the dead rOwnAssignedNames helper and restores prettier 3.8.1 formatting (the lockfile version) on files reformatted by a newer local prettier, including the unrelated union in the shared scope-resolver.ts. --- docs/languages/r-provider.md | 6 +- gitnexus/src/core/ingestion/languages/r.ts | 3 + .../core/ingestion/languages/r/assignment.ts | 38 ++------ .../core/ingestion/languages/r/captures.ts | 35 +++++-- .../ingestion/languages/r/export-pattern.ts | 49 +++++++++- .../ingestion/languages/r/linear-regex.ts | 3 +- .../languages/r/namespace-imports.ts | 4 +- .../src/core/ingestion/languages/r/r6-self.ts | 93 +++++++++++++++++-- .../ingestion/languages/r/scope-resolver.ts | 8 +- .../contract/scope-resolver.ts | 3 +- .../r-receiver-corpus/R/decoys.R | 2 + .../r-receiver-corpus/R/models.R | 14 ++- .../lang-resolution/r-self-binding/R/c14.R | 51 ++++++++++ .../lang-resolution/r-self-binding/R/c15.R | 28 ++++++ .../resolvers/r-receiver-corpus.test.ts | 36 ++++++- .../resolvers/r-self-binding.test.ts | 74 +++++++++++++++ .../test/unit/r-export-pattern-safety.test.ts | 81 +++++++--------- .../r/r-lexical-names.test.ts | 12 +++ .../r/r-r6-private-members.test.ts | 81 ++++++++++++++++ 19 files changed, 512 insertions(+), 109 deletions(-) create mode 100644 gitnexus/test/fixtures/lang-resolution/r-self-binding/R/c14.R create mode 100644 gitnexus/test/fixtures/lang-resolution/r-self-binding/R/c15.R create mode 100644 gitnexus/test/unit/scope-resolution/r/r-r6-private-members.test.ts diff --git a/docs/languages/r-provider.md b/docs/languages/r-provider.md index d6b1654faa..e385f6aaa6 100644 --- a/docs/languages/r-provider.md +++ b/docs/languages/r-provider.md @@ -39,7 +39,7 @@ 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. +- `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 private method has a typed `self` too). `self` is the public interface, so `self$m()` reaches only public and active members: a method in a `private` list, of the class or a parent, is skipped, and a parent's public method of that name is the target even when the class has a private one (`private$m()` itself is not resolved). A closure inside a method sees the method's `self`. Writing through `self` (`self$count <- 1`, `self[["x"]] <- v`, `self$items[[i]] <- v`, `names(self$items) <- v`) leaves it the instance. Where `self` is no R6 instance (a free function, a parameter called `self`, a plain `self <- other()` in the method or function, 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`, unless that binding is itself typed (`self <- Foo$new()` makes `self` a `Foo`); a method that neither the class nor a parent defines as a public member (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. - An ordinary assignment in a function's own body is a lexical name too, when its value may be a function (`helper <- identity`, `helper = some_fn()`, `identity -> helper`): a call of the name in that function, or in a closure nested in it, gets no edge to a top-level function of the same name. A function literal (`helper <- function(y) 2`) is a real definition and the call resolves to it; a constant (`helper <- 2`, a string, `TRUE`) is skipped by R at a call, so the call still reaches the outer function; `<<-` and `->>` assign outward and bind nothing in the frame. A complex target binds its base (`names(x) <- v`, `x$a <- v` bind `x`, never the called name). The rule is flow-insensitive, a deliberate trade for a conservative result: a call written before the assignment, or under an `if` that may skip it, is left unresolved too. Not modelled, so the call still reaches the outer function: `assign()`, `delayedAssign()`, `list2env()` and `with()` (R-02; pinned by `r-assignment-locals`), and a string target (`"helper" <- identity`). The braces of `local({ ... })` are read as part of the function body, so an assignment inside them makes the name lexical (the call gets no edge). Module-level assignments are not modelled either: a top-level `helper <- identity` (or `helper <- 5`) in the caller's own file still lets the unique-name fallback reach another file's `helper` at 0.5. A qualified call is decided by its qualifier alone: `function(f) mypkg::f()` and `helper <- identity; pkga::helper(x)` still bind `mypkg`'s `f` and `pkga`'s `helper` (the shared free-call pass resolves the qualifier before it applies a lexical name claim). - Named nested functions (closures) are indexed, and calls inside attribute to the nested function, which can shadow a top-level name; a nested function reads the lexical names of the function around it. Top-level script calls outside any function are attributed to the File node. @@ -68,7 +68,7 @@ The scope query (`languages/r/query.ts`) captures four call shapes only: `f(x)`, - `::` and `:::` differ. `pkg:::name` binds to the definition whether or not the package exports it. `pkg::name` binds only when the package has no NAMESPACE file or exports the name, or when the caller sits inside the package's directory tree (see Export status); a `::` to a private name (or one not provably exported) from outside gets no edge, as R errors there. - Package discovery is bounded to depth 3 and 200 directories (when the bound may have hidden a package this is flagged internally and nothing is logged), reads directories in code-unit order, ranks duplicate package names by shallowest then by whole path, and never searches the directories the indexer itself ignores (dot-directories, `vendor`, `build`, `dist`, `lib64`, `fixtures` and the rest of its built-in list) or those named exactly `renv`, `packrat`, `revdep` or `.Rcheck`. A `DESCRIPTION` with a `Built:` field is an installed library package (`lib/`, `library/`) and registers nothing. `DESCRIPTION` and `NAMESPACE` are read only as regular files (a symlink is not followed) and only up to 4 MiB; a larger `DESCRIPTION` leaves its package undiscovered (discovery counts as incomplete) and a larger `NAMESPACE`, or one that is a symlink, is treated as absent. The shared file scanner has no `renv`, `packrat`, `revdep` or `.Rcheck` entries, so `.R` files inside those trees are still parsed even though discovery skips them. - Export status: the language-level export check treats every symbol as public. The NAMESPACE pass then marks the remaining `R/` symbols of a NAMESPACE-bearing package non-exported. Symbols outside `R/` (`tests/`, `vignettes/`, `inst/`) are not package members and stay public; files in `R/` subdirectories are treated as `R/` files although R itself does not load them. A package without a NAMESPACE stays fully public, and a nested package without one does not inherit its enclosing package's. roxygen2 `@export` tags are not consulted by the index (`rename` does read them, see Rename). The refinement changes the graph nodes' `isExported` only; the definitions scope resolution works from carry no export verdict (`isExported` stays undefined there, since a `false` would drop the name from wildcard providers). Resolution instead computes a visibility per top-level name from the same NAMESPACE reading, once per pass: `public` (the package has no NAMESPACE file, or exports the name), `private` (a readable, complete NAMESPACE does not export it) or `unknown` (not exported, but the NAMESPACE is unreadable or an `exportPattern()` was dropped or cut short). `library()` and `pkg::name` need `public` (strict); the global-name fallback vetoes only `private` (a guess is vetoed only when impossible). The inputs are tested in sorted order and completeness is read after the whole batch, so a work-budget cutoff gives the same verdicts whatever the order of files or call sites. A caller is inside package P when the longest package directory (a package with a `DESCRIPTION` or a NAMESPACE) that is a path prefix of its file is P's: `tests/`, `inst/` and `vignettes/` of P count as inside, a nested package claims its own files, and for a root-level package every file outside a nested package counts as inside (so the private-name exemption is broad there). Callers inside P reach P's private names through `pkg::name` and the name guess. -- `exportPattern()` text comes from the analysed repository, so patterns are compiled to a linear-time automaton (`linear-regex.ts`) with a work budget. Constructs with no linear-time algorithm (back-references, look-around), constructs TRE reads differently from JavaScript (`\<` `\>`, `\a`, `\e`, `\Q`, `\E`, `\x{`, `\u`, a letter class escape such as `\d` inside `[...]`, `[.x.]` and `[=x=]`, `{,n}`, a leading `]` in a bracket expression that has no POSIX class) and oversized patterns are dropped with one logged warning per pattern per package, and `rename` then reports `incomplete_semantics`. Character classes use ASCII semantics. A directive argument the NAMESPACE reader cannot read at all is dropped without a warning: an R 4.0 raw string (`exportPattern(r"(^[^.])")`, `export(r"(foo)")`) and any string that spans lines. It exports nothing, so the names it was meant to cover read as non-exported in the index. The reader records that it dropped something that may hide an export (this, a conditional `export()` below, or a malformed directive that swallowed one), and `rename` refuses on that record (see Rename). +- `exportPattern()` text comes from the analysed repository, so patterns are compiled to a linear-time automaton (`linear-regex.ts`) with a work budget. Constructs with no linear-time algorithm (back-references, look-around), constructs TRE reads differently from JavaScript (`\<` `\>`, `\a`, `\e`, `\Q`, `\E`, `\x{`, `\u`, any backslash inside `[...]` (TRE reads it as a literal member, so `[a\-z]` is a range from `\` to `z` and `[\n]` holds `n`; this drops the common `exportPattern("^[^\\.]")`, whose names then read as not provably exported; write `"^[^.]"`), `[.x.]` and `[=x=]`, `{,n}`, a leading `]` in a bracket expression that has no POSIX class) and oversized patterns are dropped with one logged warning per pattern per package, and `rename` then reports `incomplete_semantics`. Character classes use ASCII semantics. A directive argument the NAMESPACE reader cannot read at all is dropped without a warning: an R 4.0 raw string (`exportPattern(r"(^[^.])")`, `export(r"(foo)")`) and any string that spans lines. It exports nothing, so the names it was meant to cover read as non-exported in the index. The reader records that it dropped something that may hide an export (this, a conditional `export()` below, or a malformed directive that swallowed one), and `rename` refuses on that record (see Rename). ## Limits and known gaps @@ -92,7 +92,7 @@ Known gaps in call resolution and class handling. Those that decide which target - R6 members named by a string (`"c d" = function() ...`, `'e' = 3`) are dropped; backticked names are kept with their backticks. A class or owner name read from a string keeps its escapes undecoded, so `setClass("Hello\x41")` is a different class from `setClass("HelloA")`, which R treats as one. - A function nested in an R6, RefClass or `setMethod()` body has an id such as `Counter.function.bump@7:21`: the enclosing function's name is a placeholder and the line and column keep ids apart, so ids change when lines shift. - A base class named by `inherit =` or `contains =` that is defined more than once in the repository (in two files, or twice in one) gets no `EXTENDS` edge from a class in another file; a base defined in the deriving class's own file is found. -- Export patterns use JavaScript regular-expression syntax where R uses TRE. The constructs where the two differ are refused, not guessed (see the NAMESPACE bullet above). One silent difference remains: a backslash before punctuation inside `[...]` (`[^\\.]`) is an escape, where TRE reads it as a literal member; the two readings differ only for names that contain a backslash. +- Export patterns use JavaScript regular-expression syntax where R uses TRE. The constructs where the two differ are refused, not guessed (see the NAMESPACE bullet above), including every backslash inside `[...]`: `exportPattern("^[^\\.]")` is dropped although TRE and JavaScript disagree on it only for names that contain a backslash, because `[a\-z]`, `[\n]` and `[\]]` differ for ordinary names and no narrower rule has been checked against R. - NAMESPACE `if (...)` and `else` bodies are skipped, so a function exported only conditionally (`if (getRversion() >= "4.1.0") export(new)`) reads as not exported in the index. So does anything after a malformed directive up to the next line that starts with `name(` in column 0. Skipping a body or a malformed directive that names an export-family directive (`export`, `exportClasses`, `exportMethods`, `S3method`, `exportPattern`) is recorded, and `rename` refuses a function of such a package; the persisted `isExported` is not changed by it. A class name that is not unique: a member attaches to the class of its own file when several classes share the name (the same helper class in `R/` and `tests/`, a class defined twice in one file counts once). When the member's file defines none of them, or several, the member stays unowned with its `ownerNameHint`, and one warning for methods and one for fields name the class names concerned (at most five each). diff --git a/gitnexus/src/core/ingestion/languages/r.ts b/gitnexus/src/core/ingestion/languages/r.ts index 5be1def615..d0df960abc 100644 --- a/gitnexus/src/core/ingestion/languages/r.ts +++ b/gitnexus/src/core/ingestion/languages/r.ts @@ -17,6 +17,7 @@ import { R_QUERIES } from '../tree-sitter-queries.js'; import { RFieldExtractor } from '../field-extractors/r.js'; import { rMethodExtractor } from '../method-extractors/r.js'; import { emitRScopeCaptures, rScopeOwnsReceivers } from './r/captures.js'; +import { collectRCaptureSideChannel } from './r/r6-self.js'; import { interpretRImport, interpretRTypeBinding } from './r/interpret.js'; import { rPostParse } from './r/post-parse.js'; import { @@ -193,6 +194,8 @@ export const rProvider = defineLanguage({ methodExtractor: rMethodExtractor, builtInNames: R_BUILT_INS, emitScopeCaptures: emitRScopeCaptures, + // Where the R6 private members are (`self$m()` never reaches one), carried to the main thread. + collectCaptureSideChannel: collectRCaptureSideChannel, scopeOwnsReceivers: rScopeOwnsReceivers, interpretImport: interpretRImport, interpretTypeBinding: interpretRTypeBinding, diff --git a/gitnexus/src/core/ingestion/languages/r/assignment.ts b/gitnexus/src/core/ingestion/languages/r/assignment.ts index b5f9e4137c..a0076f85ea 100644 --- a/gitnexus/src/core/ingestion/languages/r/assignment.ts +++ b/gitnexus/src/core/ingestion/languages/r/assignment.ts @@ -62,30 +62,6 @@ export function rBoundName(node: SyntaxNode): string | null { return target?.type === 'identifier' ? rBareName(target.text) : null; } -const ownAssignments = new WeakMap>>(); - -/** - * Names bound by an assignment or `for` loop in a function's own body, one entry per function. - * A nested function's assignments bind its own variables and are not included. - */ -export function rOwnAssignedNames(fn: SyntaxNode): ReadonlySet { - let byFunction = ownAssignments.get(fn.tree); - if (byFunction === undefined) ownAssignments.set(fn.tree, (byFunction = new Map())); - const known = byFunction.get(fn.id); - if (known !== undefined) return known; - const names = new Set(); - const body = fn.childForFieldName('body'); - const pending = body === null ? [] : [body]; - for (let node = pending.pop(); node !== undefined; node = pending.pop()) { - if (node.type === 'function_definition') continue; - const bound = rBoundName(node); - if (bound !== null) names.add(bound); - for (const child of node.namedChildren) pending.push(child); - } - byFunction.set(fn.id, names); - return names; -} - /** * Whether assigning `value` to a name binds something a call of that name may reach. * @@ -115,7 +91,7 @@ function firstArgumentValue(call: SyntaxNode): SyntaxNode | null { * the called name). Null for a target with no identifier at its base (`f()$a`, a string). */ function assignmentBase(target: SyntaxNode): SyntaxNode | null { - for (let node: SyntaxNode | null = target; node !== null;) { + for (let node: SyntaxNode | null = target; node !== null; ) { switch (node.type) { case 'identifier': return node; @@ -157,9 +133,12 @@ function lexicalAssignmentOf(node: SyntaxNode): string | null { return isLexicalAssignment(value) && target.text.length > 0 ? target.text : null; } // `x$a <- v`, `names(x) <- v`: R evaluates `x`, modifies it and binds the result to `x` here, - // whatever the value. + // whatever the value. Not for `self`: writing a field of an R6 instance (`self$count <- 1`, + // `self$items[[i]] <- v`) leaves `self` the same instance, so it stays the method's typed + // receiver. Only a plain `self <- v` (above) rebinds it. const base = assignmentBase(target); - return base !== null && base.text.length > 0 ? base.text : null; + if (base === null || base.text.length === 0 || base.text === 'self') return null; + return base.text; } const lexicalAssigned = new WeakMap>>(); @@ -168,7 +147,8 @@ const lexicalAssigned = new WeakMap x`, and the base identifier of a complex target (`x$a <- v`, `names(x) <- v`, never the - * called name, so `foo(x) <- 1` binds `x`). Flow-insensitive: a name counts when ANY assignment + * called name, so `foo(x) <- 1` binds `x`; a complex target based on `self` binds nothing, see + * `lexicalAssignmentOf`). Flow-insensitive: a name counts when ANY assignment * of it in the body does. A nested function binds its own variables and is not read; `<<-` and * `->>` assign outward; `assign()`, `delayedAssign()`, `list2env()`, `local()` and `with()` are not * modelled (`local({ x <- f })` is read as an assignment in this frame, which only costs an edge). @@ -219,7 +199,7 @@ export function assignmentTarget(node: SyntaxNode): SyntaxNode | null { * ordinary reads. */ export function isRReplacementCall(call: SyntaxNode): boolean { - for (let node = call; ;) { + for (let node = call; ; ) { const parent: SyntaxNode | null = node.parent; if (parent === null) return false; switch (parent.type) { diff --git a/gitnexus/src/core/ingestion/languages/r/captures.ts b/gitnexus/src/core/ingestion/languages/r/captures.ts index a864f99ba5..256cc21960 100644 --- a/gitnexus/src/core/ingestion/languages/r/captures.ts +++ b/gitnexus/src/core/ingestion/languages/r/captures.ts @@ -8,7 +8,13 @@ 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'; -import { createSelfOwnerClassifier, fileBindsSelf, rR6MethodClassName } from './r6-self.js'; +import { + createSelfOwnerClassifier, + fileBindsSelf, + rDefinitionPositionKey, + recordRR6PrivateMembers, + rR6Method, +} from './r6-self.js'; /** * Emit R scope captures — a single tree-sitter query run against the R @@ -37,6 +43,8 @@ export function emitRScopeCaptures( const bindsSelf = fileBindsSelf(tree.rootNode); const functionOwnsSelf = createSelfOwnerClassifier(); const typedMethods = new Set(); + // Where the R6 private members are, for `rResolveSelfMember` (`self$m()` never reaches one). + const privateMembers = new Set(); for (const m of rawMatches) { // The scope query captures every candidate argument of setClass/library/require/ @@ -88,7 +96,10 @@ export function emitRScopeCaptures( JSON.stringify(names), ); } - if (!bindsSelf && functionOwnsSelf(functionNode)) { + // A function that binds `self` itself (`self <- other()`, a formal or loop variable called + // `self`) owns it, R6 method or not: the method's typed `self` is no longer the receiver + // there, so `self$m()` is unresolved unless that binding is typed (`self <- Foo$new()`). + if (names.includes('self') || (!bindsSelf && functionOwnsSelf(functionNode))) { grouped['@receiver-owner.self'] = syntheticCapture( '@receiver-owner.self', functionNode, @@ -102,18 +113,25 @@ export function emitRScopeCaptures( // class scope, which every method of the class shares). if (methodNode !== undefined && !typedMethods.has(methodNode.id)) { typedMethods.add(methodNode.id); - const className = rR6MethodClassName(methodNode); + const method = rR6Method(methodNode); const methodName = methodNode.childForFieldName('name'); - if (className !== null && methodName !== null) { + if (method !== null && methodName !== null) { out.push({ '@type-binding.self': syntheticCapture('@type-binding.self', methodName, 'self'), '@type-binding.name': syntheticCapture('@type-binding.name', methodName, 'self'), - '@type-binding.type': syntheticCapture('@type-binding.type', methodName, className), + '@type-binding.type': syntheticCapture( + '@type-binding.type', + methodName, + method.className, + ), }); + // The method's definition is anchored on this same `argument` node. + if (method.section === 'private') privateMembers.add(rDefinitionPositionKey(methodNode)); } } } + recordRR6PrivateMembers(filePath, privateMembers); return out; } @@ -227,9 +245,10 @@ export function rFunctionLexicalNames(fn: SyntaxNode): string[] { } /** - * `LanguageProvider.scopeOwnsReceivers` for R: the module scope and each function frame that is - * not an R6 method (and not nested in a function) bind `self` themselves, with no type, which - * makes a `self$m()` call there a definitive negative. The tag is written by + * `LanguageProvider.scopeOwnsReceivers` for R: the module scope, each function frame that is + * not an R6 method (and not nested in a function), and any function that binds `self` itself + * (`self <- other()`, a formal called `self`) bind `self` with no type of their own, which makes + * a `self$m()` call there a definitive negative unless that binding is typed. The tag is written by * `emitRScopeCaptures`, where the tree is at hand. */ const R_SELF_OWNER: ReadonlySet = Object.freeze(new Set(['self'])); diff --git a/gitnexus/src/core/ingestion/languages/r/export-pattern.ts b/gitnexus/src/core/ingestion/languages/r/export-pattern.ts index 34e940c103..b9de4ff38c 100644 --- a/gitnexus/src/core/ingestion/languages/r/export-pattern.ts +++ b/gitnexus/src/core/ingestion/languages/r/export-pattern.ts @@ -20,9 +20,9 @@ import { compileLinearRegexDetailed, type SharedWorkBudget } from './linear-rege * pattern such as `^(a+)+$` hang the analyzer (R itself uses the non-backtracking * TRE). See `linear-regex.ts` for the supported subset; a pattern outside it * (including one that uses a construct TRE reads differently from JavaScript, such as - * `\<`, `{,n}` or a leading `]`) compiles to null and therefore matches nothing. A - * leading `]` is a literal member when the pattern also has a POSIX class, because the - * translation below escapes it. Callers that care why use + * `\<`, `{,n}`, a leading `]` or any backslash inside `[...]`) compiles to null and therefore + * matches nothing. A leading `]` is a literal member when the pattern also has a POSIX class, + * because the translation below escapes it. Callers that care why use * {@link compileRExportPatternDetailed}, so that a dropped pattern is reported * rather than silently treated as an empty export list. * @@ -92,6 +92,40 @@ function translateBracket(src: string, start: number): { text: string; end: numb return null; } +/** + * Whether `src` has a backslash inside a bracket expression. TRE (POSIX) reads a backslash there + * as a literal member; JavaScript, the translation above and `linear-regex.ts` read it as an + * escape. The readings differ for more than names that contain a backslash (`[a\-z]` is a range + * from `\` to `z` in TRE, `[\n]` holds `n`, `[\]]` ends at the first `]`), so such a pattern is + * refused. Brackets are found as TRE finds them: a `[` opens one unless it is escaped, a `]` + * straight after `[` or `[^` is a member, and the `]` that ends a `[:name:]`, `[.x.]` or `[=x=]` + * element does not close it. This checks the pattern as written, before the translation adds + * escapes of its own. + */ +function hasBackslashInBracket(src: string): boolean { + for (let i = 0; i < src.length; i++) { + if (src[i] === '\\') { + i++; + continue; + } + if (src[i] !== '[') continue; + let j = i + 1; + if (src[j] === '^') j++; + if (src[j] === ']') j++; + for (; j < src.length && src[j] !== ']'; j++) { + if (src[j] === '\\') return true; + const kind = src[j + 1]; + if (src[j] === '[' && (kind === ':' || kind === '.' || kind === '=')) { + const close = src.indexOf(kind + ']', j + 2); + if (close === -1) return false; // unterminated: refused by the parser instead + j = close + 1; + } + } + i = j; + } + return false; +} + function translatePosixClasses(src: string): string | null { let out = ''; let i = 0; @@ -129,7 +163,8 @@ export interface RExportMatcher { /** The outcome of {@link compileRExportPatternDetailed}: a matcher, or why there is none. */ export type RExportPatternResult = - { readonly matcher: RExportMatcher } | { readonly matcher: null; readonly reason: string }; + | { readonly matcher: RExportMatcher } + | { readonly matcher: null; readonly reason: string }; /** * Compile an `exportPattern()` argument, saying why when it cannot be compiled safely. @@ -142,6 +177,12 @@ export function compileRExportPatternDetailed( shared?: SharedWorkBudget, ): RExportPatternResult { try { + if (hasBackslashInBracket(source)) { + return { + matcher: null, + reason: 'backslash inside a bracket expression (TRE reads it as a literal member)', + }; + } let translated = source; if (source.includes('[:')) { const posix = translatePosixClasses(source); diff --git a/gitnexus/src/core/ingestion/languages/r/linear-regex.ts b/gitnexus/src/core/ingestion/languages/r/linear-regex.ts index 662cd37e05..2180c8e3a3 100644 --- a/gitnexus/src/core/ingestion/languages/r/linear-regex.ts +++ b/gitnexus/src/core/ingestion/languages/r/linear-regex.ts @@ -1081,7 +1081,8 @@ function inSet(set: CharSet, c: number): boolean { /** The outcome of {@link compileLinearRegexDetailed}: a matcher, or why there is none. */ export type LinearRegexResult = - { readonly regex: LinearRegex } | { readonly regex: null; readonly reason: string }; + | { readonly regex: LinearRegex } + | { readonly regex: null; readonly reason: string }; /** * Compile a JavaScript-syntax pattern to a linear-time matcher. When the pattern is diff --git a/gitnexus/src/core/ingestion/languages/r/namespace-imports.ts b/gitnexus/src/core/ingestion/languages/r/namespace-imports.ts index 5aa55a9a77..f93dd25df2 100644 --- a/gitnexus/src/core/ingestion/languages/r/namespace-imports.ts +++ b/gitnexus/src/core/ingestion/languages/r/namespace-imports.ts @@ -146,7 +146,7 @@ function parseArgs(text: string, openIdx: number): { args: string[]; end: number const args: string[] = []; let current = ''; let depth = 0; - for (let i = openIdx; i < text.length;) { + for (let i = openIdx; i < text.length; ) { if (i > openIdx && isDirectiveLineStart(text, i)) return null; const ch = text[i]; if (ch === '#') { @@ -288,7 +288,7 @@ class BraceBlocks { const { text } = this; const ends = new Map(); const open: number[] = []; - for (let i = 0; i < text.length;) { + for (let i = 0; i < text.length; ) { const ch = text[i]; if (ch === '#') { i = skipLineComment(text, i); diff --git a/gitnexus/src/core/ingestion/languages/r/r6-self.ts b/gitnexus/src/core/ingestion/languages/r/r6-self.ts index 2bd2fb30ff..f524bcc4b8 100644 --- a/gitnexus/src/core/ingestion/languages/r/r6-self.ts +++ b/gitnexus/src/core/ingestion/languages/r/r6-self.ts @@ -8,9 +8,17 @@ * Anywhere else `self` is no R6 instance: a free function, an `R6Class` call that is assigned to * nothing, a `setRefClass` method (which uses `.self`). The scope there owns `self` without a * type, and a `self$m()` call is left unresolved rather than matched to a free function `m`. + * + * `self` is the public interface of the instance: a member of the `private` list is reached + * through `private$m()`, never through `self$m()`. The definitions carry no section, so the + * capture pass records where the private members are (`recordRR6PrivateMembers`), per file, and + * the record crosses the worker boundary as the file's capture side channel. */ +import type { ParsedFile, SymbolDefinition } from 'gitnexus-shared'; import type { SyntaxNode } from '../../utils/ast-helpers.js'; import type { ScopeResolver } from '../../scope-resolution/contract/scope-resolver.js'; +import { definitionIdPosition } from '../../scope-resolution/utils/definition-id.js'; +import { assertCloneable } from '../../workers/clone-safety.js'; import { isRLeftAssignment, rBoundName } from './assignment.js'; const R6_SECTIONS: ReadonlySet = new Set(['public', 'private', 'active']); @@ -45,6 +53,13 @@ const callOf = (argument: SyntaxNode): SyntaxNode | null => { * the `Class` definition keeps it. */ export function rR6MethodClassName(argument: SyntaxNode): string | null { + return rR6Method(argument)?.className ?? null; +} + +/** {@link rR6MethodClassName} and the section (`public`, `private`, `active`) the method is in. */ +export function rR6Method( + argument: SyntaxNode, +): { readonly className: string; readonly section: string } | null { if (argument.type !== 'argument') return null; if (argument.childForFieldName('name')?.type !== 'identifier') return null; if (argument.childForFieldName('value')?.type !== 'function_definition') return null; @@ -67,7 +82,8 @@ export function rR6MethodClassName(argument: SyntaxNode): string | null { if (assignment === null || !isRLeftAssignment(assignment)) return null; if (assignment.childForFieldName('rhs')?.id !== r6Call.id) return null; const target = assignment.childForFieldName('lhs'); - return target?.type === 'identifier' && target.text.length > 0 ? target.text : null; + if (target?.type !== 'identifier' || target.text.length === 0) return null; + return { className: target.text, section: sectionName }; } /** @@ -119,17 +135,68 @@ export function createSelfOwnerClassifier(): (fn: SyntaxNode) => boolean { }; } +/** The capture side channel of an R file: where its R6 private members are defined. */ +interface RCaptureSideChannel { + readonly kind: 'r'; + /** `line:column` of each private member's definition anchor, as its definition id encodes it. */ + readonly r6PrivateMembers: readonly string[]; +} + +const r6PrivateMembersByFile = new Map>(); + +/** The `line:column` key of a node, as `nodeToCapture` and the definition id write it. */ +export const rDefinitionPositionKey = (node: SyntaxNode): string => + `${node.startPosition.row + 1}:${node.startPosition.column}`; + /** - * `ScopeResolver.resolveReceiverMember` for R, for a typed `self` only: when neither the class nor - * a parent defines the member, report an ambiguous lookup with no candidate. + * Record the private R6 members of `filePath` (keys from {@link rDefinitionPositionKey}), + * replacing what an earlier parse of a file at that path recorded. + */ +export function recordRR6PrivateMembers(filePath: string, keys: ReadonlySet): void { + if (keys.size === 0) r6PrivateMembersByFile.delete(filePath); + else r6PrivateMembersByFile.set(filePath, keys); +} + +/** `LanguageProvider.collectCaptureSideChannel` for R. */ +export function collectRCaptureSideChannel(filePath: string): RCaptureSideChannel | undefined { + const keys = r6PrivateMembersByFile.get(filePath); + if (keys === undefined) return undefined; + return assertCloneable({ kind: 'r', r6PrivateMembers: [...keys] }); +} + +/** `ScopeResolver.applyCaptureSideChannel` for R: restore the record of a reused file. */ +export function applyRCaptureSideChannel(parsed: ParsedFile): void { + const facts = parsed.captureSideChannel as RCaptureSideChannel | undefined; + recordRR6PrivateMembers( + parsed.filePath, + new Set(facts?.kind === 'r' ? facts.r6PrivateMembers : []), + ); +} + +/** Whether `def` is a member of an R6 class's `private` list. */ +function isRR6PrivateMember(def: SymbolDefinition): boolean { + const position = definitionIdPosition(def.nodeId, def.filePath); + if (position === undefined) return false; + const keys = r6PrivateMembersByFile.get(def.filePath); + return keys?.has(`${position.line}:${position.column}`) === true; +} + +/** + * `ScopeResolver.resolveReceiverMember` for R, for a typed `self` only. + * + * `self$m()` reads `m` off the public interface of the instance: the public (and active) members + * of the class and its parents. A private member is not on `self`, so it is skipped, and a + * parent's public member of that name is the answer even when the class has a private one. When + * no public member is found, the lookup is reported ambiguous with no candidate. * * The generic lookup keeps a lexical route for `self` (a class body binds its own members, so the * name is also looked up in the enclosing scopes), and in R that walk reaches a free function of * the same name: `self$nothere()` would bind a top-level `nothere`. R reads `nothere` off the * instance, so a free function is never the answer. Answering `ambiguous` makes the pass record a * suppressed outcome and mark the site handled, which stops that fallback; the outcome reason is - * `member-lookup-ambiguous`, where `member-not-found` would be more exact. A member that the - * class or a parent does define is left to the generic MRO walk (`undefined`). + * `member-lookup-ambiguous`, where `member-not-found` would be more exact. A member found before + * any private one was skipped is left to the generic MRO walk (`undefined`), which finds the same + * one; past a skipped private member the answer is given here, because that walk would stop at it. */ export const rResolveSelfMember: NonNullable = ( owner, @@ -139,9 +206,21 @@ export const rResolveSelfMember: NonNullable { if (site.kind !== 'call' || site.explicitReceiver?.name !== 'self') return undefined; + let skippedPrivate = false; for (const ownerId of [owner.nodeId, ...scopes.methodDispatch.mroFor(owner.nodeId)]) { - if (model.methods.lookupAllByOwner(ownerId, name).length > 0) return undefined; - if (model.fields.lookupAllByOwner(ownerId, name).length > 0) return undefined; + const methods = model.methods.lookupAllByOwner(ownerId, name); + const visible = methods.filter((def) => !isRR6PrivateMember(def)); + if (visible.length < methods.length) skippedPrivate = true; + if (visible.length > 0) { + if (!skippedPrivate) return undefined; + const [only] = visible; + return visible.length === 1 && only !== undefined + ? { kind: 'resolved', definition: only } + : { kind: 'ambiguous', candidateIds: visible.map((def) => def.nodeId) }; + } + if (model.fields.lookupAllByOwner(ownerId, name).length > 0) { + return skippedPrivate ? { kind: 'ambiguous', candidateIds: [] } : undefined; + } } return { kind: 'ambiguous', candidateIds: [] }; }; diff --git a/gitnexus/src/core/ingestion/languages/r/scope-resolver.ts b/gitnexus/src/core/ingestion/languages/r/scope-resolver.ts index 3bd7409323..e3c28bbc30 100644 --- a/gitnexus/src/core/ingestion/languages/r/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/languages/r/scope-resolver.ts @@ -40,7 +40,7 @@ import { rSymbolVisibility, } from './package-config.js'; import { rBareName } from './bare-name.js'; -import { rResolveSelfMember } from './r6-self.js'; +import { applyRCaptureSideChannel, rResolveSelfMember } from './r6-self.js'; import { perFileSet } from '../../utils/per-file-set.js'; import { resolveRImportTarget } from './import-target.js'; import { @@ -242,9 +242,11 @@ export const rScopeResolver: ScopeResolver = { emitHeritageEdges: (graph, parsedFiles, nodeLookup, scopes) => emitRVirtualHeritageEdges(graph, parsedFiles, nodeLookup, scopes), - // `self$m()` where neither the class nor a parent defines `m` is unresolved, not a call of a - // free function `m`. + // `self$m()` reaches the public members of the class and its parents; where none defines `m` + // the call is unresolved, not a call of a free function `m`. resolveReceiverMember: rResolveSelfMember, + // Restores which R6 members are private for a file reused from a worker or the parse cache. + applyCaptureSideChannel: applyRCaptureSideChannel, // R6's `super$method()` is not resolved: nothing binds `super` to the parent class, so there // is no receiver type to walk from. Off, rather than answering a wrong parent. (`self` is diff --git a/gitnexus/src/core/ingestion/scope-resolution/contract/scope-resolver.ts b/gitnexus/src/core/ingestion/scope-resolution/contract/scope-resolver.ts index 81f19b43fd..9dd4a91823 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/contract/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/contract/scope-resolver.ts @@ -332,7 +332,8 @@ export type { ConstraintContext } from 'gitnexus-shared'; /** How a container's element was reached in the source. */ export type ElementAccessRoute = - { readonly kind: 'index' } | { readonly kind: 'accessor'; readonly name: string }; + | { readonly kind: 'index' } + | { readonly kind: 'accessor'; readonly name: string }; /** One structurally-detected implementor plus the receiver form in which it * satisfies the interface (see `detectInterfaceImplementations`). */ diff --git a/gitnexus/test/fixtures/lang-resolution/r-receiver-corpus/R/decoys.R b/gitnexus/test/fixtures/lang-resolution/r-receiver-corpus/R/decoys.R index d2db572f6c..ca21c199ab 100644 --- a/gitnexus/test/fixtures/lang-resolution/r-receiver-corpus/R/decoys.R +++ b/gitnexus/test/fixtures/lang-resolution/r-receiver-corpus/R/decoys.R @@ -5,3 +5,5 @@ greet <- function() "free greet" climb_up <- function() "free climb_up" nothere <- function() "free nothere" log_decoy <- function(x) "free log_decoy" +secret <- function() "free secret" +hello <- function() "free hello" diff --git a/gitnexus/test/fixtures/lang-resolution/r-receiver-corpus/R/models.R b/gitnexus/test/fixtures/lang-resolution/r-receiver-corpus/R/models.R index e35e882980..b3114e6175 100644 --- a/gitnexus/test/fixtures/lang-resolution/r-receiver-corpus/R/models.R +++ b/gitnexus/test/fixtures/lang-resolution/r-receiver-corpus/R/models.R @@ -21,7 +21,8 @@ Address <- R6Class("Address", Base <- R6Class("Base", public = list( - greet = function() "Base.greet" + greet = function() "Base.greet", + hello = function() "Base.hello" ) ) @@ -34,10 +35,17 @@ Child <- R6Class("Child", self_inherited = function() self$greet(), self_missing = function() self$nothere(), super_call = function() super$greet(), - private_call = function() private$secret() + private_call = function() private$secret(), + self_field_write = function() { + self$visits <- 1 + self$greet() + }, + self_private = function() self$secret(), + self_public_over_private = function() self$hello() ), private = list( - secret = function() "Child.secret" + secret = function() "Child.secret", + hello = function() "Child.hello" ) ) diff --git a/gitnexus/test/fixtures/lang-resolution/r-self-binding/R/c14.R b/gitnexus/test/fixtures/lang-resolution/r-self-binding/R/c14.R new file mode 100644 index 0000000000..17b08d99f3 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/r-self-binding/R/c14.R @@ -0,0 +1,51 @@ +# c14: writing through self (`self$x <- v`, `self[["x"]] <- v`, `self$x[[i]] <- v`, +# `names(self$x) <- v`) leaves self the instance; a plain `self <- ...` rebinds it. +C14Base <- R6::R6Class("C14Base", + public = list( + c14_greet = function() 1 + ) +) +C14Child <- R6::R6Class("C14Child", + inherit = C14Base, + public = list( + count = 0, + items = NULL, + c14_own = function() 1, + c14_run_own = function() { + self$count <- 1 + self$c14_own() + }, + c14_run_inherited = function() { + self$count <- 1 + self$c14_greet() + }, + c14_run_missing = function() { + self$count <- 1 + self$c14_nothere() + }, + c14_run_elem = function(i, v) { + self$items[[i]] <- v + self$c14_own() + }, + c14_run_dbl = function(v) { + self[["count"]] <- v + self$c14_own() + }, + c14_run_repl = function(v) { + names(self$items) <- v + self$c14_own() + }, + c14_rebind = function() { + self <- c14_other() + self$c14_own() + }, + c14_rebind_ctor = function() { + self <- C14Base$new() + self$c14_own() + } + ) +) +c14_own <- function() 2 +c14_greet <- function() 2 +c14_nothere <- function() 2 +c14_other <- function() 2 diff --git a/gitnexus/test/fixtures/lang-resolution/r-self-binding/R/c15.R b/gitnexus/test/fixtures/lang-resolution/r-self-binding/R/c15.R new file mode 100644 index 0000000000..3cb1838ff6 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/r-self-binding/R/c15.R @@ -0,0 +1,28 @@ +# c15: self$ reads the public members only; a private method is reached through private$. +C15Base <- R6::R6Class("C15Base", + public = list( + c15_shared = function() 1 + ), + private = list( + c15_hidden = function() 2 + ) +) +C15Child <- R6::R6Class("C15Child", + inherit = C15Base, + public = list( + c15_pub = function() 3, + c15_call_pub = function() self$c15_pub(), + c15_call_shared = function() self$c15_shared(), + c15_call_hidden = function() self$c15_hidden(), + c15_call_mine = function() self$c15_mine(), + c15_priv_mine = function() private$c15_mine() + ), + private = list( + c15_shared = function() 4, + c15_mine = function() 5, + c15_from_private = function() self$c15_pub() + ) +) +c15_hidden <- function() 6 +c15_mine <- function() 7 +c15_shared <- function() 8 diff --git a/gitnexus/test/integration/resolvers/r-receiver-corpus.test.ts b/gitnexus/test/integration/resolvers/r-receiver-corpus.test.ts index 6a14ef6882..7c2ac6cc39 100644 --- a/gitnexus/test/integration/resolvers/r-receiver-corpus.test.ts +++ b/gitnexus/test/integration/resolvers/r-receiver-corpus.test.ts @@ -55,7 +55,10 @@ interface Cell { readonly target: string | null; /** Reasons recorded at the call, or `none`. */ readonly outcome: - 'none' | 'receiver-unresolved' | 'receiver-owned-but-unbound' | 'member-lookup-ambiguous'; + | 'none' + | 'receiver-unresolved' + | 'receiver-owned-but-unbound' + | 'member-lookup-ambiguous'; readonly kind: Kind; /** The `resolves` row (by caller) that shows the shape works nearby. Required unless it resolves. */ readonly control?: string; @@ -150,6 +153,37 @@ const RECEIVER_CELLS: readonly Cell[] = [ control: 'self_own', note: 'a free nothere() exists and is not reached; the label is the shared pass closest one', }, + { + shape: 'self$x <- v, then self$inherited() in an R6 method', + file: M, + caller: 'self_field_write', + site: 'self$greet()', + target: 'Method:R/models.R:Base.greet#0', + outcome: 'none', + kind: 'resolves', + note: 'writing a field keeps self the instance (not a rebinding); a free greet() exists', + }, + { + shape: 'self$m() where the parent has a public m and the class a private one', + file: M, + caller: 'self_public_over_private', + site: 'self$hello()', + target: 'Method:R/models.R:Base.hello#0', + outcome: 'none', + kind: 'resolves', + note: 'Child.hello is private, so not on self; a free hello() exists', + }, + { + shape: 'self$private() in an R6 method: a private method is not on self', + file: M, + caller: 'self_private', + site: 'self$secret()', + target: null, + outcome: 'member-lookup-ambiguous', + kind: 'unresolved', + control: 'self_own', + note: 'Child.secret is reached through private$, not self$; a free secret() exists and is not reached', + }, { shape: 'self$m() in a free function', file: S, diff --git a/gitnexus/test/integration/resolvers/r-self-binding.test.ts b/gitnexus/test/integration/resolvers/r-self-binding.test.ts index d7b5876067..de483d7f72 100644 --- a/gitnexus/test/integration/resolvers/r-self-binding.test.ts +++ b/gitnexus/test/integration/resolvers/r-self-binding.test.ts @@ -19,6 +19,10 @@ * - c11 the argument count differs from the method's formals * - c12 a class name in backticks, an R6Class call inside a function, a dotted class name * - c13 a file that binds self itself; c13b a file that reads a self bound in another file + * - c14 a method that writes through self (`self$x <- v` and its element and replacement forms) + * before calling through it, and one that rebinds self plainly (`self <- other()`) + * - c15 self$ reaches public members only: a private method of the class or a parent is not on + * self, and a child's private method does not hide a parent's public one */ import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; import path from 'path'; @@ -93,6 +97,34 @@ describe('R6 self$method() binds the enclosing class and its parents', () => { 'R/c13.R', 'Method:R/c13.R:C13Global.c13_global_m#0', ], + [ + 'c14 self$x <- v, then an own method', + 'c14_run_own', + 'R/c14.R', + 'Method:R/c14.R:C14Child.c14_own#0', + ], + [ + 'c14 self$x <- v, then an inherited method', + 'c14_run_inherited', + 'R/c14.R', + 'Method:R/c14.R:C14Base.c14_greet#0', + ], + ['c14 self$x[[i]] <- v', 'c14_run_elem', 'R/c14.R', 'Method:R/c14.R:C14Child.c14_own#0'], + ['c14 self[["x"]] <- v', 'c14_run_dbl', 'R/c14.R', 'Method:R/c14.R:C14Child.c14_own#0'], + ['c14 names(self$x) <- v', 'c14_run_repl', 'R/c14.R', 'Method:R/c14.R:C14Child.c14_own#0'], + ['c15 a public method', 'c15_call_pub', 'R/c15.R', 'Method:R/c15.R:C15Child.c15_pub#0'], + [ + 'c15 a public parent method, not the private one of the same name in the child', + 'c15_call_shared', + 'R/c15.R', + 'Method:R/c15.R:C15Base.c15_shared#0', + ], + [ + 'c15 a private method calling a public one through self', + 'c15_from_private', + 'R/c15.R', + 'Method:R/c15.R:C15Child.c15_pub#0', + ], ])('%s', (_label, source, file, expected) => { expect(targets(source, file)).toEqual([expected]); }); @@ -105,6 +137,21 @@ describe('R6 self$method(): the edge it gets', () => { 'Method:R/c1b_base.R:C1bBase.c1b_greet#0:import-resolved:0.85', ]); }); + + it('c14 a write through self keeps the receiver-call confidence', () => { + expect(callsFrom('c14_run_own', 'R/c14.R')).toEqual([ + 'Method:R/c14.R:C14Child.c14_own#0:global:0.85', + ]); + expect(callsFrom('c14_run_inherited', 'R/c14.R')).toEqual([ + 'Method:R/c14.R:C14Base.c14_greet#0:global:0.85', + ]); + }); + + it('c15 a public parent method is an in-file MRO hit, past the child private one', () => { + expect(callsFrom('c15_call_shared', 'R/c15.R')).toEqual([ + 'Method:R/c15.R:C15Base.c15_shared#0:global:0.85', + ]); + }); }); describe('R6 self$method() with a dotted class name keeps the generic lexical route', () => { @@ -134,6 +181,10 @@ describe('R6 self$method() never reaches a free function', () => { ['c9 a free function using self', 'c9_free', 'R/c9.R'], ['c9 a parameter named self', 'c9_param', 'R/c9.R'], ['c9 a method that does not exist', 'c9_missing', 'R/c9.R'], + ['c14 self$x <- v, then a method that does not exist', 'c14_run_missing', 'R/c14.R'], + ['c15 a private parent method through self', 'c15_call_hidden', 'R/c15.R'], + ['c15 a private own method through self', 'c15_call_mine', 'R/c15.R'], + ['c15 private$m() (private$ is not modelled)', 'c15_priv_mine', 'R/c15.R'], ])('%s: no edge', (_label, source, file) => { expect(callsFrom(source, file)).toEqual([]); }); @@ -156,6 +207,12 @@ describe('R6 self$method() never reaches a free function', () => { 'c11_two', 'c11_dots', 'c11_none', + 'c14_own', + 'c14_greet', + 'c14_nothere', + 'c15_hidden', + 'c15_mine', + 'c15_shared', ]); expect( getRelationships(result, 'CALLS') @@ -177,6 +234,15 @@ describe('R6 self$method() that cannot be bound is an outcome, not silence', () it.each([ ['c4', 'R/c4.R', 'c4_nothere', 4], ['c9 a method that does not exist', 'R/c9.R', 'c9_nothere', 12], + ['c14 self$x <- v, then a method that does not exist', 'R/c14.R', 'c14_nothere', 24], + [ + 'c14 self <- C14Base$new(): typed as the parent, which lacks the method', + 'R/c14.R', + 'c14_own', + 44, + ], + ['c15 a private parent method is not on self', 'R/c15.R', 'c15_hidden', 16], + ['c15 a private own method is not on self', 'R/c15.R', 'c15_mine', 17], ])( '%s: a typed self whose class and parents lack the method is a suppressed lookup with no candidate', (_label, file, name, line) => { @@ -201,6 +267,14 @@ describe('R6 self$method() that cannot be bound is an outcome, not silence', () expect(reasons).toEqual(['receiver-owned-but-unbound', 'receiver-owned-but-unbound']); }); + it('c14 a plain `self <- other()` in a method rebinds self: owned and untyped, no edge', () => { + expect(targets('c14_rebind', 'R/c14.R')).toEqual(['Function:R/c14.R:c14_other']); + const reasons = outcomesFor('R/c14.R', 'c14_own') + .filter((o) => 'range' in o && o.range.startLine === 40) + .map((o) => (o.kind === 'suppressed' ? o.reason : o.kind)); + expect(reasons).toEqual(['receiver-owned-but-unbound']); + }); + it('c13 a file that binds self records no suppression for its free function', () => { expect(outcomesFor('R/c13.R', 'c13_global_m')).toEqual([]); }); diff --git a/gitnexus/test/unit/r-export-pattern-safety.test.ts b/gitnexus/test/unit/r-export-pattern-safety.test.ts index 31e2d638f2..7efa14ea7c 100644 --- a/gitnexus/test/unit/r-export-pattern-safety.test.ts +++ b/gitnexus/test/unit/r-export-pattern-safety.test.ts @@ -84,43 +84,8 @@ const CHARACTERISATION: ReadonlyArray // parser): a mismatch fails loudly and is fixed in whichever side is wrong. Refused: `\<` `\>` // `\a` `\e` `\Q` `\E` `\u` `\x{` anywhere; `{,n}` outside a bracket expression; and inside // one, a `]` straight after `[` or `[^`, `[.` / `[=` elements and a letter class escape - // (`\d \D \w \W \s \S \b`). A `[` inside a bracket expression is a plain member. + // (`\d \D \w \W \s \S \b`), or any other backslash: TRE reads it there as a literal member. A + // `[` inside a bracket expression is a plain member. const ALWAYS_REFUSED_ESCAPES = /^\\(?:[<>aeQEu]|x\{)/; function c2Refused(source: string): boolean { let inClass = false; @@ -660,7 +626,7 @@ describe('compileRExportPattern agrees with RegExp on generated patterns', () => const ch = source[i]; if (ch === '\\') { if (ALWAYS_REFUSED_ESCAPES.test(source.slice(i, i + 3))) return true; - if (inClass && /^\\[dDwWsSb]/.test(source.slice(i, i + 2))) return true; + if (inClass) return true; i++; } else if (inClass) { if (ch === ']') inClass = false; @@ -674,7 +640,7 @@ describe('compileRExportPattern agrees with RegExp on generated patterns', () => } return false; } - // Hand-checked: `[\d-z]` -> true, `^[^\\.]` -> false, `\bfoo\b` -> false, `[[]` -> false. + // Hand-checked: `[\d-z]` -> true, `^[^\\.]` -> true, `\bfoo\b` -> false, `[[]` -> false. const NAME_ALPHABET = ['a', 'b', '1', '_', '.', ' ', 'c', '\t']; function lcg(seed: number): () => number { @@ -768,16 +734,37 @@ describe('compileRExportPattern: unsupported TRE constructs fail closed', () => '[[.a.]]', '[[=a=]]', '[a[.x.]]', + // Any backslash inside a bracket expression: TRE reads it as a literal member, so `[a\-z]` is + // a range from `\` to `z`, `[\n]` holds `n` and `[\]]` ends at the first `]`. + '^[a\\-z]', + '^[^\\.]', + '[\\.]', + '[ab\\n]', + '[\\t]', + '^[\\]]', + '[\\\\]', + '^[[:alpha:]\\-_]', + '[[:digit:]\\.]', + '[]\\.]', + '[^]\\.]', ])('%s compiles to null', (source) => { expect(compileRExportPattern(source)).toBeNull(); }); - it.each(['^[[:alpha:]]', '\\d+', '\\bfoo\\b', '^[^\\\\.]', '\\D\\w\\W\\s\\S\\B', 'a{1,2}'])( - '%s still compiles', - (source) => { - expect(compileRExportPattern(source)).not.toBeNull(); - }, - ); + it.each([ + '^[[:alpha:]]', + '\\d+', + '\\bfoo\\b', + '^[^.]', + '^\\.', + '\\[a]', + '[a]\\.', + '\\D\\w\\W\\s\\S\\B', + 'a{1,2}', + '^[[:space:][:punct:]]', + ])('%s still compiles', (source) => { + expect(compileRExportPattern(source)).not.toBeNull(); + }); it('keeps the POSIX-translated leading ] (a literal member, as in TRE)', () => { expect(compileRExportPattern('[]a[:digit:]]')).not.toBeNull(); diff --git a/gitnexus/test/unit/scope-resolution/r/r-lexical-names.test.ts b/gitnexus/test/unit/scope-resolution/r/r-lexical-names.test.ts index 36e3519113..bdfed07bbf 100644 --- a/gitnexus/test/unit/scope-resolution/r/r-lexical-names.test.ts +++ b/gitnexus/test/unit/scope-resolution/r/r-lexical-names.test.ts @@ -106,6 +106,18 @@ describe('rFunctionLexicalNames: ordinary assignments', () => { ).toEqual(['w', 'x', 'y', 'z']); }); + it('does not read a write through self as a binding of self; a plain rebinding is one', () => { + // An R6 method that sets a field (`self$count <- 1`) keeps self the instance: only `self <- v` + // replaces it. Other bases keep the rule above (`z$a <- v` binds `z`). + expect( + namesOf( + 'f <- function(v) { self$a <- v; self[["b"]] <- v; self$c[[1]] <- v; names(self$d) <- v; self@e <- v }', + ), + ).toEqual(['v']); + expect(namesOf('f <- function() { self <- other() }')).toEqual(['self']); + expect(namesOf('f <- function() { other() -> self }')).toEqual(['self']); + }); + it('does not read `<<-` or `->>`: they assign outward', () => { expect(namesOf('f <- function() { a <<- identity; identity ->> b }')).toEqual([]); }); diff --git a/gitnexus/test/unit/scope-resolution/r/r-r6-private-members.test.ts b/gitnexus/test/unit/scope-resolution/r/r-r6-private-members.test.ts new file mode 100644 index 0000000000..4270e4f1a6 --- /dev/null +++ b/gitnexus/test/unit/scope-resolution/r/r-r6-private-members.test.ts @@ -0,0 +1,81 @@ +/** + * `self$m()` reaches only the public members of an R6 class, so the capture pass records where + * the private members are. The definitions carry no section, so the record is keyed by the + * position their definition id encodes, and it crosses the worker boundary (and the parse cache) + * as the file's capture side channel. This pins the keys against the real definition ids and the + * round trip through `collectCaptureSideChannel` / `applyCaptureSideChannel`. + */ +import { describe, expect, it } from 'vitest'; +import type { ParsedFile } from 'gitnexus-shared'; +import { extractParsedFile } from '../../../../src/core/ingestion/scope-extractor-bridge.js'; +import { rProvider } from '../../../../src/core/ingestion/languages/r.js'; +import { rScopeResolver } from '../../../../src/core/ingestion/languages/r/scope-resolver.js'; +import { definitionIdPosition } from '../../../../src/core/ingestion/scope-resolution/utils/definition-id.js'; + +const SOURCE = [ + 'Foo <- R6::R6Class("Foo",', + ' public = list(', + ' pub = function() 1', + ' ),', + ' private = list(', + ' hidden = function() 2,', + ' count = 0', + ' ),', + ' active = list(', + ' size = function(value) 3', + ' )', + ')', + 'free <- function() 4', + '', +].join('\n'); + +const collect = (filePath: string) => rProvider.collectCaptureSideChannel?.(filePath); + +function parse(source: string, filePath: string): ParsedFile { + const file = extractParsedFile(rProvider, source, filePath); + if (file === undefined) throw new Error('no ParsedFile'); + return file; +} + +describe('R6 private members: the capture side channel', () => { + it('records exactly the private methods, at the position their definition id encodes', () => { + const file = parse(SOURCE, 'R/privacy.R'); + const channel = collect('R/privacy.R') as { kind: string; r6PrivateMembers: string[] }; + expect(channel.kind).toBe('r'); + const keyOf = (name: string): string => { + const def = file.localDefs.find((d) => d.nodeId.endsWith(`:Method:${name}`)); + const position = definitionIdPosition(def?.nodeId, 'R/privacy.R'); + if (position === undefined) throw new Error(`no Method ${name}`); + return `${position.line}:${position.column}`; + }; + expect(channel.r6PrivateMembers).toEqual([keyOf('hidden')]); + expect(channel.r6PrivateMembers).not.toContain(keyOf('pub')); + expect(channel.r6PrivateMembers).not.toContain(keyOf('size')); + }); + + it('is plain data that survives a structured clone', () => { + parse(SOURCE, 'R/privacy.R'); + const channel = collect('R/privacy.R'); + expect(structuredClone(channel)).toEqual(channel); + }); + + it('records nothing for a file without private members, and a re-parse replaces the record', () => { + parse(SOURCE, 'R/reparsed.R'); + expect(collect('R/reparsed.R')).toBeDefined(); + parse('free <- function() 4\n', 'R/reparsed.R'); + expect(collect('R/reparsed.R')).toBeUndefined(); + }); + + it('a reused ParsedFile restores its record, and one without a channel clears a stale one', () => { + const file = parse(SOURCE, 'R/reused.R'); + const channel = collect('R/reused.R'); + parse('free <- function() 4\n', 'R/reused.R'); + expect(collect('R/reused.R')).toBeUndefined(); + + rScopeResolver.applyCaptureSideChannel?.({ ...file, captureSideChannel: channel }); + expect(collect('R/reused.R')).toEqual(channel); + + rScopeResolver.applyCaptureSideChannel?.({ ...file, captureSideChannel: undefined }); + expect(collect('R/reused.R')).toBeUndefined(); + }); +});