* docs(r): document that namespace-qualified S4 constructors are not recognised
Review finding: `methods::setClass(...)` is ignored by the S4 field detector.
Confirmed by test, and wider than fields: every S4/RefClass pattern
(setClass, setRefClass, setGeneric, setMethod in R_QUERIES, plus the field and
method extractors) requires a bare identifier callee, so a namespace_operator
callee creates no class, slot, generic or method. R6::R6Class is supported.
Widening touches nine files (queries, naming-argument, captures, owner hooks,
post-parse, scope resolver, both extractors) and the qualifier-veto logic, so
it is not a trivial change. Documented as a known limit in
docs/languages/r-provider.md and pinned by characterisation tests in
r-definition-anchors.test.ts (each paired with its unqualified control).
* fix(r): charge the start-state filter to the matcher work budget
LinearRegex.seed() filtered the closure's character states against the start
character before charging only 1 + (accepting states), so the range scans of
the failed state tests were free. A pattern of a few large character classes
could be probed with distinct start characters (each a filter miss, memoised
only up to 4096 keys) at almost no recorded cost.
Reproduction: for 20 alternated classes of 200 ranges, one miss on a
non-matching name recorded work 1 (expected >= 4000 range checks); a loop of
600 distinct start characters never exhausted a 1,000,000 budget. The filter
now charges 1 + ranges.length per examined state on a cache miss; hits stay
cheap. New tests in r-export-pattern-shared-budget.test.ts.
* fix(r): skip the body of an `else if` in NAMESPACE as conditional
skipConditionalBody returned just after the `if` of `else if (cond) body`, so
the main scan then read `(cond)` as stray text and emitted the body's
importFrom, S3method, export, exportClasses, exportMethods and exportPattern
directives as unconditional (the same for `if (a) if (b) body`).
Reproduction: 12 new cases in r-namespace-parser.test.ts failed on the
unfixed scanner (e.g. `if (a) {} else if (b) importFrom(x, y)` returned x::y;
`else if (b) export(hidden)` exported `hidden`). The nested `if (cond)` is now
stepped over iteratively (no recursion, tested with 50,000 nested ifs) and the
body that follows it is skipped.
* fix(r): decode string literals in the rename dynamic-lookup guard
The R rename guard compared the raw text of each `string_content` node with the
old and new name. An escaped spelling (`"f\u006fo"`, `'f\x6fo'`, octal) keeps
its escape inside string_content, and a raw string (`r"(foo)"`) has no
string_content node at all, so renaming `foo` proceeded while a get() or
do.call() on the escaped or raw spelling still resolved the old name.
Reproduction: 10 cases in the new test/unit/r-rename-string-guard.test.ts
returned 'ok' instead of unsupported_occurrence on the unfixed provider, and the
two new fixtures string-lookup-escaped and string-lookup-raw (rename-provider-r)
renamed successfully on the unfixed build. The guard now decodes each `string`
node (escapes, octal, raw strings) and compares the value.
docs/languages/r-provider.md said "spelled as a string literal"; it now states
the whole-value rule and what is still not detected (substring, paste0(),
non-indexed files).
* fix(r): limit library() wildcard expansion to top-level definitions
expandRWildcardNames walked the flat localDefs of the target file and filtered
only dotted names, so a function nested inside another function
(`outer <- function() { helper <- function() 1 }`) was offered as a
package-level name to every file that calls library()/require() on the package.
Reproduction: two new cases in r-dotted-s3-hooks.test.ts failed on the
unfixed code (['outer', 'helper', 'top'] instead of ['outer', 'top'];
['a', 'b', 'c', 'd'] instead of ['a']). The expansion now keeps only names bound
at module scope (rFileTopLevel().names, which already feeds the dotted-tail
guard); top-level functions and bare-call S4/R6 classes are still listed
(controls added; test/integration/resolvers/r.test.ts unchanged and green).
* fix(r): bind roxygen @param types for dotted formal names
parseRoxygenParams read the parameter name with `\w+`, which stops at the first
dot, so `#' @param na.rm Data` documented nothing and the formal got no type
(the old unit test pinned that as "does not bind a dotted parameter name").
Reproduction: four new cases in type-env-r.test.ts (na.rm, .data,
max_n.rows, braced form with a continuation line) returned undefined instead of
'Data' on the unfixed pattern. The name pattern is now `[\w.]*\w[\w.]*`, so a
dotted identifier matches while `...` and `x,y` stay unbound; the former
"does not bind" case is replaced by positive cases plus a not-a-formal control.
* docs: count the audited tree-sitter peers as nine
AUDITED_PEERS in scripts/prepare-tree-sitter-bundle.cjs lists nine manifests
since @eagleoutice/tree-sitter-r was added (r, c, cpp, java, php, ruby, rust,
javascript, typescript); CONTRIBUTING still said eight.
* docs(r): mention CFG and rename in the README R paragraphs
Both R paragraphs now say that --pdg builds a control-flow graph for R and that
rename is conservative. The shared Control flow paragraph no longer implies
reaching definitions for R, which has control flow only.
* chore(deps): record the audited 0.25.1 tree-sitter peer for the R grammar
CONTRIBUTING.md (Native tree-sitter npm packages) requires the lockfile to pin
the audited grammars' tree-sitter peer to exactly 0.25.1, as it already does for
c, cpp, java, php, ruby, rust and typescript. The R grammar entry still carried
upstream's ^0.21.0. Only the peer range changes; the upstream peerDependenciesMeta
(including its tree_sitter key typo) is untouched.
Checked: npm ci --dry-run --ignore-scripts passes in the repository root and in
gitnexus/, npm ls --depth=0 reports nothing invalid, and a fresh npm pack
(including prepack) installed into an isolated prefix passes
scripts/assert-native-parsers.mjs (20 grammars, R included) with the R
manifest's peer at 0.25.1.
* test(r): raise the worker readiness timeout in R worker-backed tests
A reviewer's focused R run hit two worker-startup timeouts and had to rerun
with a 30-second readiness setting. The worker pool waits only 5 seconds by
default (GITNEXUS_WORKER_READY_TIMEOUT_MS), and every R test that parses
through the real worker pool started cold against that budget, unlike
csharp-razor-view-components and structural-pair-coverage, which already
raise it.
Apply the same idiom to the R tests that spawn the pool: stub the variable to
60000 in beforeAll and restore it with vi.unstubAllEnvs() in afterAll. Covers
r-worker-owner-absence, cfg/r-cfg-join, r-post-parse-gating, and the
resolvers/r*.test.ts files. rename-provider-r goes through
rename-integration-cases.ts, which already passes a 15-second budget to its
child process, so it is unchanged.
Tests only; no production code, schema or parse-cache change.
* perf(r): binary-search character classes in the linear regex matcher
inSet() scanned a class's ranges from the front on every state visit, but the
search loop charged one unit per visit regardless of class size, so a wide
class multiplied real work the budget never counted. Ranges are sorted,
merged and disjoint for every CharSet (normalise() for written classes,
constants and complement() for escapes), so a binary search is equivalent.
Charged work is unchanged.
Tests pin the reads per visit, the edges of a large class and the charged
work counters.
* fix(r): make the roxygen @param name and package qualifier parsing linear
The @param name pattern [\w.]*\w[\w.]* backtracks quadratically on a long
name followed by anything but a blank (32,000 characters took about half a
second per line), and parseRQualifier's lazy [\s\S]*? does the same on a
long run of blanks. Match [\w.]+ and require a word character separately,
and take the text before the first '::' directly. Accepted inputs and
results are unchanged (checked against the old patterns on two million
generated strings).
Tests cover large adversarial inputs and the dotted formal names.
* docs(r): correct stale wildcard-expansion and escape-digit comments
Three comments named rProvider.expandsWildcardTo, which does not exist for R:
the pipeline consumes the hook from the ScopeResolver, so point them at
rScopeResolver.expandsWildcardTo. State the \x, \u and \U digit limits in
unescapeRString's comment, which are those of R's own parser.
Comments only.
* docs(r): correct the R provider guide and the type-resolution matrix
r-provider.md: state that an empty or missing if arm is the header's seq
edge (control dependence labels it as the complement of the other arm);
extend the bare-callee limit to library(), require() and source(); say that
NAMESPACE raw strings and strings spanning lines are dropped without a
warning, which the logged-warning sentence did not cover; name the language
registrations that do mention R; give the devtools::load_all() rationale for
the unfiltered library() wildcard.
type-resolution-system.md: R binds no declaration, call-result or
method-call-result types (extractDeclaration is empty and there is no
extractPendingAssignment), and its cross-file propagation is partial, with a
test cited. Drop R from the footnote about synthesizeWildcardImportBindings(),
which does not exist.
* fix(r): qualify R6, RefClass and S4 member ids with their class
Member ids carried no owner, so a second class in one file that shared a
member name with an earlier one (push, items, a setMethod generic, a slot)
minted the same id as the first and lost the member, along with its
HAS_METHOD or HAS_PROPERTY edge.
Register resolveDetachedOwnerName for R. It names the class declared by an
ancestor R6Class assignment, setClass or setRefClass call, or the signature
class of a setMethod call, so ids become Method:<file>:Stack.push#n and
Property:<file>:Stack.items. The owner edge is still attached by postParse
through ownerNameHint. The change is R-only: the hook is optional and
undefined for every other language.
The r-packages characterisation counts now include Child.greet, the member
the id collision used to drop.
* fix(r): read the formals of R6 and RefClass methods
extractRParameters tested for identifier and argument nodes, but the grammar
emits one parameter node per formal, so it always returned an empty list.
Every R6 and RefClass method therefore had parameterCount 0 and a #0 id, and
a variadic method was not marked variadic.
Read the parameter nodes: the name field gives the formal, a default makes it
optional, and a dots name makes it variadic (such a method has no count and
no arity tag in its id).
* fix(r): attach R members only to classes defined in R
attachDeferredROwners resolved the owner hint through the class registry,
which every language shares. A Python class Circle next to an R Circle made
the name ambiguous, so the R methods and slots lost their HAS_METHOD and
HAS_PROPERTY edges; and with no R Circle, an R setMethod attached to the
Python class.
Keep only candidates whose graph node is an R class before the uniqueness
test. The change is inside R's postParse hook, so shared code is untouched.
* fix(r): read slots and fields given as c(...) vectors
The slot pattern matched only list(...) and representation(...), although
the field extractor accepts any call, so setClass("A", slots = c(a =
"numeric")) and setRefClass("R", fields = c(...)) created no Property nodes.
Accept c(...) for both. An unnamed string in slots = c("a", "b") or
fields = c("a", "b") names an untyped member, as in R; an unnamed string in
representation(...) or list(...) is still not a member. The new pattern
captures its callee as @_vecOwner, so the class-naming capture filter does
not mistake these strings for the class name.
* fix(r): match backtick-quoted definitions against NAMESPACE export entries
export(`%+%`) names the symbol %+%, while the definition node keeps its
spelling `%+%`, so the export check never matched and the function was
flagged as not exported (the same for exportPattern()). Compare the symbol
through one shared helper, rBareName.
* fix(r): bind roxygen @param tags to formals written in backticks
A formal written `data` in backticks never matched the tag @param data, so
its documented type was dropped. Look the tag up by the symbol.
* fix(r): rename functions through their backtick-quoted spellings
A backticked name is an identifier whose text keeps its backticks, so the
rename provider never matched `helper`(x) with helper. The call was left
behind, and a local `helper` <- function(...) was not seen as a shadow, so
a call to the local function was silently renamed. Match occurrences,
claims and bindings on the symbol, and compare the symbol in the safety
checks.
* fix(r): strip backticks from NAMESPACE export entries in linear time
The pattern /^`+|`+$/g is quadratic on an entry such as x, a long run of
backticks, then y; the entry is repository-controlled text read on every
importFrom lookup of a name the package does not export. Trim with two scans.
* perf(r): scan NAMESPACE conditional blocks in linear time
An unterminated `{` after an `if` scanned to the end of the file, and the
resynchronisation then landed inside the region just scanned, so a file of
`if (a) {` lines with no `}` was quadratic (300 KB took 8.8 s, and the file is
parsed several times per analysis). Index where every block ends in one pass
and answer each block from the index. Parsing results are unchanged.
* fix(r): reject POSIX class names that Object.prototype also has
[[:constructor:]], [[:toString:]] and [[:__proto__:]] resolved on the
prototype chain and spliced function source text into the pattern, so the
pattern compiled to garbage instead of being rejected as an unknown class
and reported as dropped. Look classes up as own properties.
* fix(r): read the DESCRIPTION Package field past a byte-order mark
A UTF-8 byte-order mark before `Package:` hid the package, so its qualified
calls were dropped as external. And `\s*` crossed a newline, so an empty
`Package:` field captured the next line's `Version:` as the package name.
Strip the mark and keep the value on the field's own line.
* fix(r): type R6 field defaults that are typed NA constants
The grammar parses NA, NA_integer_, NA_real_, NA_character_ and NA_complex_
as `na` nodes, not identifiers, so the identifier branch never ran and no
type was inferred. Type them as integer, numeric, character and complex, and
plain NA as logical.
* perf(r): look up a wildcard import's target file in a per-pass index
expandRWildcardNames scanned every parsed file with find() for each
library() edge (450,000 edges over 3,000 files took 5.9 s). Build the
module-scope lookup once per pass, as the C, C++ and Python providers do.
* docs(r): list exportClassPattern() as not read
The directive is not tokenised, so a class exported only through it reads as
not exported. Say so under the NAMESPACE limits.
* fix(r): order merged bindings by code unit, not by locale
rMergeBindings sorted same-tier bindings with localeCompare, whose order
follows the machine's locale. Compare node ids by code unit, as the package
discovery does.
* fix(r): read RefClass methods of an unassigned setRefClass call
The method patterns required `A <- setRefClass(...)`, so a bare
`setRefClass("A", methods = list(...))` produced the Class and its fields
but no Method. The method extractor and the class owner lookup never needed
the assignment; match the call itself in both queries.
* docs(r): state how backtick-quoted names resolve
A call and its definition must spell a backticked name alike to be linked,
and importFrom() of a backtick-defined function does not bind. NAMESPACE
exports and rename match the symbol either way.
* fix(r): bind importFrom() of a backtick-quoted definition
A function written in backticks keeps them in its binding key and on its
node, while NAMESPACE entries and importFrom() carry the bare symbol, so
importFrom(pkg, `%||%`) found no defining file and the call degraded to
the name-based guess, which cannot tell two packages' `%||%` apart.
rFileTopLevel now keys the top-level names by symbol (rBareName) and
records the spellings it saw. resolveRNamedImport looks files up by
symbol, populateRNamespaceImports synthesises the import with the
definition's own spelling (one per spelling the provider uses) and lets
a backtick-defined function of the caller package mask its import. The
global-name-fallback veto and the pkg::name() lookups compare symbols.
The dotted-tail guard still compares the name as written, which is how
finalize indexes it. Names without backticks answer exactly as before,
pinned by a characterisation snapshot recorded before the change.
* fix(r): refuse a rename target name that registers an S3 method at any dot
The guard looked only at the text before the first dot, so
to.json.foo (a method of the dotted generic to.json) passed, and base
generics such as print, format, summary and plot were never checked
unless the sources defined them. Every dot-separated prefix of the new
name is now tested against the functions the indexed sources define and
a small list of base generics.
* fix(r): refuse renaming a function that is also assigned with <<-
A <<- inside a function is a global re-definition that the scope graph
keeps as a second declaration of the same name. A rename dropped the
selected function and its calls but left the superassignment, so after
the rename the function wrote a new global of the old name instead of
replacing the renamed one. The top-level form was already refused by
the engine; checkSafety now refuses any <<- or ->> to the name, in or
out of a function, with the same ambiguous_reference code.
* fix(r): rename a call that a non-function parameter of the same name does not shadow
R skips a binding that is not a function when it looks up the callee of
f(x), but the rename provider claimed every parameter, so a call under
function(x, helper = 2) was left unrenamed and failed after the rename.
A parameter whose default is a constant and which the body never assigns
is no longer claimed, so the call is renamed with the function it
reaches. A parameter that may hold a function (a function or computed
default, or an assignment to it in the body) is claimed as before, and
a call of the name under it is refused as ambiguous_reference, since it
may reach either. A parameter without a default that is called stays a
function-valued parameter and its call is left alone.
* fix: name the published grammar package in the parser-unavailable hint
The warning for a language whose grammar could not be loaded told the
user to run npm rebuild tree-sitter-<language>. R's grammar is published
as @eagleoutice/tree-sitter-r, so the hint named a package that does not
exist. The grammar loader now keeps a small map of grammars published
under another name, and every other language gets the same hint as
before.
* docs: count 19 providers in the local import scoping guide
The guide said 18-provider registry. The providers table in
languages/index.ts has 19 entries with R, one per SupportedLanguages
value (counted from the built registry: Object.keys(providers).length).
* docs: link the R provider guide from ARCHITECTURE.md related docs
The Objective-C provider guide is listed there; the R guide, which
AGENTS.md and both READMEs already link, was not.
* test(r): state the real CI behaviour of the worker owner-absence guard
The header said the suite hard-fails on CI like the other worker-backed
suites. Only object-literal-owner-resolution shares that tripwire; the
others skip silently when dist/ is missing. The header now says so, and
that the integration tier builds dist/ first.
* test(r): count 23 hinted members in r-packages
Member ids carry their class since fc32e539, so the two greet methods of
Parent and Child in s4_and_r6.R are two nodes instead of one. The
owner-absence test sits outside the R test set script and kept the old
count of 22.
* test(r): pin the cross-file and R6 method rename refusals
The guide documents ambiguous_reference for an unqualified call into
another file and a refusal for R6 methods, but no fixture covered
either. Add both. The R6 method is refused by the provider as a class
member (unsupported_occurrence); the guide wrongly listed it among the
shared engine's stale_graph refusals, which now name only dotted
functions and S4 classes.
* test(r): size the argument-scaling guard so the small run is measurable
The ratio guard divided by a 15 ms floor on the small run, so shapes whose
small run took 1 to 2 ms (comments before the naming argument) could hide
a quadratic regression that cost less than 150 ms at 8,000 arguments. The
small size now doubles from 2,000 until its fastest run lasts 20 ms, and
the large run stays four times that size, so the ratio is taken between
runs long enough to measure. The largest shape runs for about 2.4 s.
* test: count the bundled R grammar in the ARM64 bundle repair test
* test(cache): allow scoped grammar packages in the packageName audit
* docs(r): point parser-change guidance at the automatic cache identity
* fix(r): treat only <-, <<- and = as assignments when reading definitions
The R grammar gives every infix operator one binary_operator node. The
definition and scope queries, the R6 owner checks and the type-binding
scanners matched it on shape alone, so x + R6Class(...), x == function() 1
and obj == Foo$new() declared a class, a function and a type binding.
Constrain every binary_operator query pattern to operator
["<-" "<<-" "="] and check the same operator in the field and method
extractors' R6 owner test, the constructor scanner, the roxygen formal
binder and the local class-name collector.
* fix(r): decode octal escapes in NAMESPACE strings and unify the decoder
unescapeRString handled the single-character, hex and unicode escapes but
not R's \nnn octal escape, so exportPattern("^\101") reached the matcher as
^\101 (refused as a legacy octal escape) instead of ^A, and the pattern was
dropped. The rename string guard carried its own copy of the decoder that
did handle octal.
Decode one to three octal digits in unescapeRString (the low byte, with the
NUL escape kept verbatim as R rejects it), make the rename guard use it, and
apply it to quoted names in export() and S3method() as well so a NAMESPACE
string means what R reads. Backticked names keep an escaped backtick as
written, as before.
* test(r): pin that $ ends at the name and \8 stays a back-reference
The matcher refuses \1 to \9 because TRE reads them as back-references
whether or not the group exists, and $ matches only at the end of the name
as it does in JavaScript and TRE. Both are deliberate, so say so in the
header and the escape reader and pin them with tests, including the
RegExp oracle for $ before a final line terminator.
* docs(r): say that NAMESPACE refines graph nodes, not scope definitions
refineRExportStatus flips isExported on graph nodes only. The scope
definitions that finalization reads carry no export verdict for R
(undefined means unknown), which is deliberate: library() attaches every
top-level name, as devtools::load_all() does. State that in the provider
guide and pin it with a test, so a later change that stamps a verdict
onto scope definitions is a conscious one.
* fix(r): treat only functions as S3 generics in the rename guard
checkSafety collected every local definition into the set of possible
generics, so renaming a function to Widget.foo was refused when Widget was
an R6 or S4 class, or area.circle when area was only an R6 method. The
final NAMESPACE-export check likewise matched a member of the same name in
the same file. A class, method or property is not an S3 generic and has no
NAMESPACE export entry of its own; match functions only.
* fix(r): limit the VIRTUAL placeholder edge to S4 classes
emitRVirtualHeritageEdges treated every inherits reference named VIRTUAL
as the S4 sentinel contains = "VIRTUAL", so an R6 class with
inherit = VIRTUAL, an ordinary base class, also got an EXTENDS edge to the
synthetic placeholder node. Only a class declared by a naming call
(setClass, setRefClass) can carry the sentinel; require that of the
deriving class.
* fix(ci): encode the slash of a scoped package in the registry URL
npm_view_json interpolated the package name into the registry path, so
@eagleoutice/tree-sitter-r was requested as /@eagleoutice/tree-sitter-r/latest.
The registry serves that spelling today, but a scoped package is one path
segment with the slash encoded (@scope%2Fname). Quote the name, keeping the
leading @, and pin both the scoped and unscoped URLs in the tests.
* fix(r): accept only a syntactic name as a bare NAMESPACE argument
normaliseArg rejected whitespace, quotes, parentheses and = in a bare
directive argument, so foo+bar, x[1] or a$b was returned as a symbol name.
R reads a bare argument as a symbol; an operator or indexing expression is
not one, and only a quoted or backticked argument can spell such a name.
Accept a letter or dot followed by letters, digits, dots and underscores.
* docs(r): name the one other backtick normaliser in the bare-name header
The header said every comparison of a definition spelling with a symbol
goes through rBareName. The NAMESPACE export check in import-resolvers/r.ts
compares through its own stripBackticks, which removes every leading and
trailing backtick, not one pair. Say so. Comment only.
* fix(r): refuse a rename on the indexed NAMESPACE verdict, not on a flag the planner never saw
The rename planner built its graph from rows that carried no isExported, so the
provider's NAMESPACE check saw undefined for every node and refused every function
under R/, private ones included. The rows now carry the indexed isExported flag
when the column holds a boolean (no key otherwise), and the provider refuses only
a function the index did not prove private.
Positive fixtures rename a private package function (also under exportPattern);
negative fixtures cover exportPattern and an S3method third-argument registration.
A unit test runs the real refinement pass on a real graph, and a characterisation
test pins the row shape the planner receives.
* fix(r): refuse to rename an infix function or operator
An a %+% b use is an operator token, not an identifier, so renaming the
definition of a %op% function edited only the definition and left every infix
use calling a function that no longer exists. The old or the new name being an
infix function or an operator (`%+%`, `[[`) is now refused.
Fixtures cover an infix function used at top level and inside a function; a unit
test covers the operator spellings and a backticked name that stays renamable.
* fix(r): refuse a rename that would strand a replacement function
helper(z) <- 5 calls the replacement function helper<-, not helper, so renaming
the getter renamed the call in the assignment target and left the setter
unreachable under the new name, and renaming helper<- itself left every
helper(z) <- v calling a function that no longer exists.
Refused now: a call of the name anywhere in an assignment target (plain, nested
in $, [[, names(), attr(), or the -> forms), an old or new name ending in <-, and
a string-defined setter of either name. Four fixtures and a unit test cover each
form beside calls that are only read.
* fix(r): refuse a new name that is already a global
assertDeclarationCollisions is per file and function-only, so a rename onto a name
that a top-level variable already held (or assigned later) overwrote or was
overwritten by it, and a function of that name in another file became a second
global whose survivor depended on load order.
The provider now refuses a new name that is assigned at top level (<-, =, ->, a
for variable), assigned with <<- or ->> anywhere, or defined as a function in
another file. Local assignments, parameters and members of that name are still
allowed. Five fixtures and a positive control cover each form.
* fix(r): refuse a new name that the sources already read as a value
The engine protects the call form of a new name, but R's reference sites are calls,
so a plain read was invisible: sapply(x, paste), Reduce(max, x), x <- letters or a
default f = assist all kept compiling and silently started to mean the renamed
global.
The provider now refuses any identifier read of the new name that is not bound
locally: a parameter of an enclosing function covers a read, and covers a call only
when it has no default. Bound names, argument names, members ($, @) and qualified
names are not reads. Four fixtures and unit tests cover values, callees, formulas
and the allowed spellings.
* fix(r): refuse a new name that registers a method of a group or common generic
BASE_GENERICS missed the S3 group generics and many dispatching base functions, so
sum.items, Ops.money, Math.money, abs.diff, is.numeric.foo, as.complex.foo and
unlist.foo were accepted and silently registered as methods.
The list now has the Ops, Math, Summary, Complex and matrixOps groups with each
member, the is.* and as.* generics, and the common base, stats, graphics and utils
generics. Unit tests walk the documented group members, and two fixtures cover
Ops.money and sum.items.
* test(r): run the rename guard unit tests on a real knowledge graph
Four unit files handed checkSafety a graph whose forEachNode did nothing, so the
NAMESPACE branch could never be reached from them. They now build a real graph
(empty, or with one node of a chosen label for the member-versus-function case).
* docs(r): list the final rename refusals and the PDG answers R cannot give
The rename section now names each refusal the provider makes (NAMESPACE export
read from the indexed flag, infix functions and operators, replacement functions,
new-name collisions and value reads, group and common generics). The control-flow
section records that pdg_query flows, explain and impact --mode pdg return empty
answers for R without saying that R has no def/use harvest; the shared tools carry
no per-language capability signal, so this is documented rather than patched.
* fix(r): attach members to a class whose name is shared or defined twice
attachDeferredROwners left every member of a class unowned when more than one
class of that name was registered, including a class defined twice in one file
(one graph node registered twice) and the same helper class in R/ and tests/.
Candidates are now de-duplicated by node id. When several distinct classes
share the name, the member attaches to the one defined in its own file; if its
file defines none or several of them the member stays unowned, as before, and
one warning per call names the class names affected.
* fix(r): own a setMethod() written with signature() or c() by its first class
setMethod("show", signature("A"), ...) and c("A", "B") signatures named no
owner, so the methods of one generic on different classes collapsed into one
node and none had a HAS_METHOD edge.
The owner is the string in the first argument of a signature() or c() value,
named or not. A multi-class signature therefore belongs to its first class; a
first argument that is not a string still names no owner.
* fix(r): make the export-pattern nesting limit independent of JIT warm-up
MAX_NESTING was 2048, beyond what a cold process can recurse: a deeply nested
pattern failed with a stack overflow in a fresh process and compiled after a
warm-up, so whether a NAMESPACE pattern was in effect depended on the machine
and on what ran before it, and the reason given was misleading.
The limit is now 256, which still compiles on a quarter of the default stack,
so the verdict is the same cold or warm and carries the right reason.
* fix(r): charge a remembered export-pattern verdict to the work budget
A matcher answered a name it had already decided from its memo without any
charge, so asking thousands of matchers about the same few names (initialize,
print, show across many classes) cost time that no budget counted: 5,000
repeat calls over 12,000 matchers took 612 ms and charged nothing.
A memo hit now costs one visit, so the repeat is bounded by the shared budget
like every other cost, and the verdict itself is unchanged.
* fix(r): charge export patterns that are refused after their NFA was built
A pattern that expanded past the state cap was refused only after building up
to 16,384 states, yet it reserved no states, charged no work and did not close
the allowance, so the next such pattern started from scratch: 98 KB of
exportPattern("(a|b){8000}...") lines took 4.2 s while the budget counted
nothing, against the documented bound of about a second.
A refusal is now charged for what was built (eight visits per state or build
step), and a spent work budget refuses later patterns before they are parsed.
The guide also says that budget exhaustion while resolving importFrom() names
is not reported, because the scope resolver loads its own configuration.
* fix(r): name an S3method() of another package's generic after the generic
S3method(pkg::generic, class), the delayed-registration form roxygen2 writes
for @exportS3Method pkg::generic, registered no method at all when written
bare and the nonexistent "pkg::generic.class" when quoted, so the function
generic.class read as not exported and an importFrom() of it did not bind.
The generic is the text after the last :: or ::: outside quotes and
backticks, so the method is generic.class as R registers it.
* fix(r): keep installed libraries and ignored trees out of package discovery
Discovery read the disk on its own and skipped only renv, packrat, revdep and
.Rcheck, so an installed library under lib/, library/, .Rlibs/, vendor/ or
build/ registered its packages as repository packages (their qualified calls
then fell to the name-based guess instead of reading as external), and a tree
of ignored directories spent the 5,000-directory hidden-package budget and
made discovery read as incomplete.
Discovery now skips dot-directories and the directories the indexer itself
ignores (isHardcodedIgnoredDirectory), and a DESCRIPTION with a Built: field,
which only an installed package has, registers nothing and hides nothing. The
depth-3 and 200-directory bounds are pinned with their boundary values.
* fix(r): look up backticked NAMESPACE exports from a set built once
Resolving an importFrom() name that the provider's NAMESPACE does not export
walked every export entry before giving up, so a provider with 20,000 exports
and a caller importing 20,000 names took about two seconds, and NAMESPACE text
is the only bound.
The walk only looked for entries that start or end with a backtick (a quoted
"`%+%`" entry keeps them). Those are now collected in one pass per export set,
and a lookup is a set membership test; the answers are unchanged.
* fix(r): refuse a closure-local function as the unique-name fallback target
A function bound inside another function lives in that call's frame, so no
other function in its file or another can call it by its bare name. The
unique-name fallback ignored that: when the name was unique in the repository,
a bare call elsewhere bound to the closure-local function at 0.5.
The R fallback veto now refuses a function or class that the file's scope
model holds below the top level. A candidate the scope model does not hold, and
every top-level definition, are judged as before.
* fix(r): let the package attached last mask a name two library() calls define
Two library() calls that attach packages defining the same name bound the call
to whichever package file sorted first by id, so a script that attached lp2
after lp reached lp's function while R reaches lp2's.
rMergeBindings now keeps, within the wildcard tier, only the bindings of the
library() call that comes last in the file. A package of several files that
defines the name twice stays ambiguous, and a binding with no call position
leaves the tier as it was.
* fix(r): stop a call through a formal or loop variable at that name
A formal or a for variable bound no name in the scope model, so
function(data, transform) transform(data) was credited with a call of a
top-level transform() at 0.85, and the unique-name fallback made the same guess
across files.
Each function scope now publishes the names its formals and for loops bind as
lexical names, the shadowing barrier the scope model already has for a
parameter. A formal with a constant default that the body never assigns is left
out, because R skips a value that is not a function when it looks up a callee
(the rename provider reads it the same way).
* perf(r): answer package locality from an index of unowned package directories
rQualifierLocality scanned every parsed file path once per distinct pkg::
qualifier, so a run's work was qualifiers x files (4,000 x 5,000 took 0.84 s).
populateRQualifiedCalls now builds the set of <name>/R/ directory names that no
discovered package owns once, and each qualifier is a set lookup. The answers
are unchanged, and a call without the index still scans.
* docs: say that a new extension point is the one reason to touch shared code
The scope-resolution section says adding a language needs no changes to shared
code. R added two optional LanguageProvider hooks (postParse and
resolveMemberOwnerNode) that no other language implements, so the sentence now
names that case and points at the hook table.
* chore(deps): group the scoped tree-sitter-r grammar with the other grammars
The tree-sitter-grammars group matched tree-sitter-* only, so
@eagleoutice/tree-sitter-r would have been bumped in a pull request of its own
instead of with the other grammars.
* chore(r): drop an eslint-disable directive that suppresses nothing
ESLint reports it as unused with --report-unused-disable-directives; no other
file carries it above an ES import.
* docs(r): correct comments that contradict the code
The R provider header said library() and source() bring everything into scope
with no named imports and that imports are standard import nodes: source()
binds no name, NAMESPACE importFrom() produces named imports, and the import
captures come from the R scope query. The scope resolver said a bare member
call never reaches an R5 method and that R has no super, but RefClass methods
call siblings by bare name (unresolved today) and R6 has super$method().
* perf(r): read the roxygen block of a function once, not once per formal
extractParameter runs for each formal and re-collected and re-parsed the whole
comment block above the function every time, so work grew as formals x block
lines (2,000 formals under 2,000 @param lines took 11.9 s).
The parsed block is now kept per assignment node in the tree, as the file's
class names already are.
* refactor(r): state the R export default in the provider, not in shared code
rExportChecker was a shared export that only the R provider used, and it made
export-detection.ts differ from upstream for a function that returns true.
ObjectiveC already writes the same checker inline.
The provider now carries it as () => true with the reason beside it, and
export-detection.ts is byte-identical to upstream again.
* docs(r): list the call-resolution and class-handling gaps that are left as is
Each statement was reproduced against the code before it was written: self$m()
without a type binding, RefClass sibling calls, calls to generics and
generators, source() suffix matching, the library() edge fan-out, same-named
helpers in two packages, METHOD_OVERRIDES on parameter counts, calls inside
setMethod bodies, inherit = pkg::Base, string-named R6 members, nested function
ids, the TRE differences in export patterns and conditional NAMESPACE bodies.
Also says how a class name shared by several classes is owned and reported.
* docs(r): say which class owns a setMethod() written with a multi-class signature
* test(r): pin the documented export-pattern and discovery caps by literal
The caps in r-provider.md were asserted through the constants themselves, so changing a
cap, or the number the document gives, failed nothing. Pin each cap, check that the
document states the same number, and test the state cap, the pattern length cap, the
hidden-package scan budget and a spent matcher at their exact boundaries. Also pin the
backslash-u fallback to the letter u when fewer than four hex digits follow.
* fix(r): read contains= case-sensitively, and pin the VIRTUAL heritage edge
R matches argument names case-sensitively, so setClass("A", CONTAINS = "B") names no
base; the scope query linked it anyway. Drop the CONTAINS spelling from both predicates.
Pin the VIRTUAL placeholder: a class naming both a real base and VIRTUAL gets both edges
(the dedup set must be seeded only from edges that target the placeholder), the edge keeps
its confidence and reason, and running the heritage hook twice mints one node and one edge.
* test(r): pin the arity hook, the missing-config paths and the rebuild hint
rArityCompatibility had no test at all. populateRQualifiedCalls and
rFileBelongsToDiscoveredPackage are reached with no package config, and a run must not see
the previous run's answers; neither was asserted. The npm rebuild hint for the R grammar
names the scoped package; nothing checked it.
* test(r): compare a warm durable-cache run with a cold one
The deferred-owner pass and the NAMESPACE export refinement only ever ran cold in the R
tests. Analyse r-packages and r-package-layout twice, the second time from the saved parse
cache with no worker pool, and require the same definitions (isExported, ownerId) and the
same CALLS, EXTENDS, IMPORTS and member edges.
* test(r): pin the whole CALLS edge set of r-package-layout and r-packages
The layout fixture already holds callers in tests/, scripts/, vignettes/ and inst/, but only
their export status was asserted. Pin every CALLS edge, with reason and confidence, for both
projects, so a misdirected edge that keeps the count fails.
* test(r): pin the documented no-edge call shapes and the R6 dispatch limits end to end
Add the r-call-shapes fixture, a package that contains each shape r-provider.md says creates
no edge or node: lapply/Map/do.call/match.fun/get/registry/pkg::f as values, infix operators,
obj@slot, UseMethod/NextMethod, super$ and private$, inherit = pkg::Base, an inherited
self$ call, setClassUnion/setValidity/setReplaceMethod/Class$methods, roxygen @export,
exportClassPattern, renv parsing and the unread import forms. Positive controls sit beside
them, and the whole CALLS set is pinned.
* test(r): pin a cross-file rename, the paste0 gap and the number of R rename cases
The documented claim that a rename succeeds across files had only same-file successes behind
it, and the undetected paste0() lookup was unpinned. Add a qualified pkg::name() cross-file
rename and a run-time-built lookup name, and count the R cases so that an emptied fixture
directory cannot leave the suite green with no test.
* test(r): pin the control flow the CFG visitor documents as not modelled
Control flow inside an expression (y <- if, switch, &&, ||, ifelse, return() or break inside
tryCatch/local), stop(), on.exit() and tryCatch handlers stay one block, and a break or next
outside a loop falls back to EXIT. Nothing exercised these forms.
* test(r): record that a NAMESPACE-only edit leaves isExported stale until --force
r-provider.md documents this as a limitation of the shared incremental write path. Pin the
current behaviour (stale after an incremental analyse, correct after a forced one) so a fix
there shows up and the document is updated with it.
* test(r): narrow the regex and rename-safety results so typecheck:tests passes
* fix(ci): weight the R rename suite by its measured Windows cost
rename-provider-r.test.ts was charged 100 s in WINDOWS_WEIGHTS_SEC but
takes 600-750 s on the Windows runner (49 persisted fixtures, each a
native analyze). The shard packer therefore placed it on shard 5/10 with
the go and dml-gate suites, which exhausted the 20-minute watchdog on
two consecutive attempts.
Charge it 620 s, add a regression test that keeps it off the go and
dml-gate shards, and raise the recorded-workload ceiling from 17 to 18
minutes: the table total grew by about 520 s, so a perfect ten-way
split now averages about 1047 s per shard.
* fix(r): let the later library() call win when one package is bound twice
rMergeBindings kept the first binding of a node, so a batched call with a
package named by several library() calls was order-sensitive. Keep the
binding whose call starts later, add a unit case and pin the ABA and BAB
shapes through the pipeline.
* test(r): let the rename verdict helper read <<- and = function definitions
The helper listed only 'name <- function', while the indexer also lists
<<- and = definitions, so a generic defined with = never reached the S3
guard. Add cases that go through the helper with each operator.
* test(r): name the wrapped namespace directive test by its shape
* test(r): tell the R6 owner walk from a non-class with a discriminating assertion
getRTopLevelMethodOwnerName is the setMethod helper and returns null for any
argument node, so the negative assertion could not fail. Use the owner lookup
the R6 path uses, in the positive and the negative case.
* test(r): assert the pattern length cap accepts a pattern of exactly that length
Build the pattern from empty groups so only the length rule is in play, and
check that it compiles, matches 'aa' and not 'a', and that one more
character is refused.
* fix(r): keep the whitespace inside a quoted NAMESPACE name
normaliseArg trimmed the text inside quotes and backticks, so export(" a ")
named the symbol a instead of the symbol ' a ', which is what R reads. Trim
only around the argument, and pin it with a parser test and a pipeline case
where a package defines both a and ` a `.
* fix(r): keep a matched export-pattern answer after the work budget is spent
rExportPatternMatches answered false for every name once the budget was
spent, so a duplicate definition of a name that had been exported earlier
flipped to private. Remember the names matched while the budget lasted and
answer them from that set; undecided names still read as unexported, which
the documentation now says.
* fix(r): read a NULL default as a formal that may hold a function
A formal defaulting to NULL is the usual placeholder of an optional
callback, so classing it as constant let a rename edit the call of the
parameter and drew a false edge to a same-named top-level function. Treat it
as 'maybe': the rename refuses the call and the scope publishes the formal
as a lexical name. Update the provider guide and pin both paths.
* fix(r): say what is wrong with a rejected rename name
validateName let ... and ..N through to a misleading name_collision. Reject
them as reserved, say in the message that new names are ASCII-only by design,
and report an old name made only of non-ASCII characters as an unsupported
identifier rather than an infix function or operator.
* fix(r): keep a repeated library() package at its first attachment
R leaves an already attached package where it is, so library(a);
library(b); library(a) still lets b mask a. The merger counted the last
call as a fresh attachment, and because the pipeline folds the bindings of
a name in one at a time, a package masked at one step was forgotten at the
next. Remember each package's first attachment, masked ones included, on
the surviving bindings, and flip the expectations that pinned the other
direction (A/B/A -> B, B/A/B -> A) in the unit and pipeline tests.
* fix(r): make rename re-read NAMESPACE and fail closed on a stale export flag
After an edit of NAMESPACE alone, the unchanged R/ files are not
re-processed, so the persisted isExported of a newly exported function
stays false and rename read that as proof of privacy. The rename guard now
also uses the NAMESPACE the planner has just loaded from disk (recorded by
the R workspace hook against each parsed file): it refuses when NAMESPACE
exports the name by export(), exportPattern() or S3method(), and fails
closed (incomplete_semantics) when NAMESPACE is gone or unreadable, when
an exportPattern() was dropped or ran out of budget, or when no config was
recorded. The persisted flag remains a second, additive check. The
incremental test now asserts the refusal on the stale index and after
--force; unit cases cover each way NAMESPACE can change. Docs updated.
* fix(r): record the rename NAMESPACE config before the populate passes replace parsed files
populateRNamespaceImports and populateRQualifiedCalls replace entries of the
ParsedFile array (import synthesis; any dropped external pkg::fn site), but the
rename guard looks the recorded config up by the original ParsedFile object. A
package file that called stats::sd(), or whose package importFrom()ed a name from
another repository package, therefore read as 'NAMESPACE was not read' and every
rename in it was refused with incomplete_semantics.
Record the config against the objects as received and again against the final
array. Adds rename fixtures for a private and an exported function in a file
with an external qualified call, a private function in a package with a local
importFrom(), and extends the incremental NAMESPACE test with an external call
and an incremental run that reuses the parse cache.
* fix(r): make rename refuse when the NAMESPACE reader may have hidden an export
The NAMESPACE scanner skipped conditional (if/else) bodies, dropped raw-string and
multi-line arguments, and discarded a malformed directive together with everything up
to the next column-0 directive, all silently. Rename treated 'not in the export lists'
as proof of privacy, so it could rename a function whose export() entry the reader had
never seen and leave NAMESPACE naming a missing function.
The scanner now reports when a skipped or discarded region names an export-family
directive, and parseRNamespaceExports also flags an argument of one that it cannot
read. loadRPackageConfig stores that as RNamespaceInfo.exportsUnreadable and rename
refuses with incomplete_semantics. An ordinary NAMESPACE, including conditional
imports, does not set it. The indexed isExported is unchanged. r-provider.md updated.
* fix(r): load the R grammar lazily so a native load failure disables only R
parse-worker.ts and languages/r/query.ts imported @eagleoutice/tree-sitter-r
statically. A binding that cannot load (no prebuild, ABI mismatch) therefore
crashed every worker and every module importing the R provider, failing analyze
for all languages. The worker now loads it behind the same guard as the vendored
grammars, through the shared grammar loader, and the query module resolves it on
first use as the Kotlin one does. With the binding removed, analyze indexes the
other languages and skips R files with one logged error.
* fix(r): refuse a rename of a function that a roxygen2 @export tag exports
roxygen2 rebuilds NAMESPACE from @export* tags, so renaming a tagged function
changes the package's public API on the next document() even when the NAMESPACE on
disk and the persisted isExported say it is private. checkSafety now refuses a
top-level function whose directly preceding #' block has an @export* tag. Documents
that a successful rename leaves .Rmd/.qmd/.Rd/pkgdown/roxygen cross-reference
consumers unchanged; the rename result has no provider-owned note field.
* fix(r): rename functions with a leading dot and refuse R's hook functions
The rename engine reads a definition's simple name as the text after the last '.'
of its qualified name, so the graph symbol .helper never matched the definition
'helper' and every leading-dot rename failed with a misleading stale_graph. The R
provider's canonicalName now keeps a one-word leading-dot name whole (names with a
dot inside, such as area.circle, keep the engine's reading and stay refused).
That would also have let .onLoad, .onAttach and the other functions R calls by
name through, so checkSafety refuses them explicitly.
* docs(r): document replacement-function calls, package-less R/ directories and unparseable files
Pins the rename behaviour with two fixtures (an R/ directory without a package is
refused; a syntax error in an unrelated indexed file refuses with parse_error) and
adds the replacement-function CALLS limitation to the Limits section.
* test(r): type the refusal in the leading-dot rename test for the strict:false typecheck
* test(r): make the wall-clock guards in the R tests robust to a loaded runner
The argument-scaling ratio gate now repeats a measurement whose ratio is over the
limit (a quadratic query is over it every time, a noisy runner is not). The
absolute bounds take the fastest of up to three attempts that each build their own
state, so a cache warmed by an earlier attempt cannot hide a regression. The
named-import lookup test counts walks of the export set instead of timing 20,000
lookups, as its sibling tests already do.
* docs(r): count R among the retained import providers in local-import-scoping.md
The registry count was raised to 19 but the retained-provider table stopped at Dart
and the text still said eleven, so the two tables summed to 18.
* fix(r): read NAMESPACE only as a regular file and cap DESCRIPTION and NAMESPACE size
NAMESPACE was opened by name, so a symlink in the analysed repository was followed,
unlike DESCRIPTION which is read only when the directory read lists a regular file.
Neither manifest had a size cap (the walker's cap covers source files only). Both
now go through one reader that rejects anything over 4 MiB: a DESCRIPTION that
cannot be read leaves discovery marked incomplete, a NAMESPACE that cannot be read
is treated as absent (rename then refuses).
* test(r): revert the unrelated cleanup helper swap in the tree-sitter bundle test
The R rows the test needs are unchanged; the rmSync to cleanupTempDirSync change was
not required by R and widened the diff against upstream.
* test(r): pin that a UTF-8 BOM at the start of an R file indexes and renames
The grammar skips the mark, so the first-line definition, its CALLS edge and the
rename all work and the mark is kept. Added as a rename fixture; no code change.
* docs(r): correct the shared-code registration list and say why the persisted export flag stays
R registers its export checker on its own provider, not in a shared table, so the
provider guide no longer lists one. The Rename section now states that the persisted
isExported is kept as a second, fail-closed check beside the plan-time NAMESPACE read.
* test(r): drop non-null assertions from the new timing helpers
* test(r): keep the Windows rename suite small by testing guard logic in unit tests
The hook, roxygen, conditional-export and package-less R/ cases exercise checkSafety
only, which the unit tests already drive with a real NAMESPACE load. Each rename
fixture runs a native analyse (about 12 s on Windows), so only the cases that need
the engine stay as fixtures (external-call and local-import NAMESPACE reads,
leading-dot identity, unparseable file, BOM). Adds the package-less R/ unit case.
* ci(r): raise the Windows shard weight of the R rename suite for the six fixtures added
* fix(r): read DESCRIPTION and NAMESPACE through one opened handle
readManifestFile checked the size with fs.stat(path) and then read with
fs.readFile(path), which CodeQL reports as a file system race (js/file-system-race).
The file is now opened once (O_NOFOLLOW and O_NONBLOCK where the platform has them),
and the regular-file check, the size cap and the read all use that handle; one byte
past the checked size is read so a file that grows is refused. The DESCRIPTION read
for hidden packages in skipped subtrees now goes through the same reader, so it has
the same cap and fails closed (cannot rule a package out). Tests that spied on
readFile now spy on open; new cases cover the cap boundary, empty file, directory,
symlink and FIFO.
* fix(r): cache the R parser only after its language is set
getRParser assigned the module-level parser before setLanguage ran, so a
failed grammar load left a language-less parser that the next call returned.
Build it locally and cache it once setLanguage has succeeded, as the C#
provider does.
* fix(r): match a backticked R6 class name against its roxygen type
declaredClassName kept the backticks of an R6 class name, so a class written
with backticks never matched the roxygen type naming it, unlike a backticked
formal. Compare the bare name.
* fix(r): reject an empty quoted source in interpretRImport
The capture keeps its quotes, so source("") arrived as two characters and
passed the empty-source guard. Test emptiness after stripping the quotes;
targetRaw is unchanged.
* docs(r): document that a same-name parameter suppresses a pkg::f() edge
A function parameter or for variable named like the target of pkg::f() makes
the shared free-call fallback refuse the call before the qualified lookup
runs, so the call gets no CALLS edge. Record it under the known limits and
soften the qualified-call header, which claimed the qualifier outranks every
lexical tier. No shared code is changed.
* docs(r): state the exportPattern remembered-name cap and fastestWithin's minimum
rExportPatternMatches remembers at most 100,000 matched names per package, so
past that a name reads as not exported once the budget is spent; say so in the
function comment and the provider guide. fastestWithin always runs one attempt,
even when tries is below 1; word the comment to match.
* refactor(r): move R import target into languages/r
Move import-resolvers/r.ts to languages/r/import-target.ts (pure rename plus
import repoints, comments and docs) so the file already sits where upstream
#3670 expects per-language import targets, ahead of merging upstream/main.
No behaviour change.
* fix(r): strip backticks from R6 class name when typing $new() receivers
The R grammar yields an identifier whose text keeps its backticks, so
`Foo`$new() produced calleeName "`Foo`" while the class-name set holds the
bare name. Apply rBareName, as declaredClassName already does. Found in bot
review round 5 (PR #3513, comment 4348423277).
* docs(r): correct isExported comment in local-backend
The indexed isExported verdict is read by R rename's second privacy check, so
"never consulted by the engine" was wrong. Found in bot review round 5
(PR #3513, comment 4348423305).
* fix(ci): read package.json as utf-8 in tree-sitter readiness test
* docs(ci): describe cross-platform shard measurement without a run link
* fix(r): never treat a parameter default as proof of function-ness
A default says nothing about the argument a caller passes, so
`function(x, helper = 2) helper(x)` reaches the parameter when the caller
passes a function and the outer function when it does not, and
`function(x, helper) helper(x)` may reach either too. The rename provider and
the scope captures read the default as proof; every named formal is now treated
alike ("maybe").
Claim A (constant default): `role()` no longer marks a constant-default formal
'unrelated', so the call under it is not renamed with the function, and
checkSafety refuses it with ambiguous_reference.
Claim B (no default): the same call under a default-less formal is refused the
same way (it used to be left behind silently).
New-name side: a call of the NEW name under a same-named formal is a read of
the new name (name_collision) for every formal, not only those with a default;
a plain read of the formal is still not a read.
Call-side twin: rFunctionLexicalNames no longer skips constant-default formals,
so a call through any named formal gets no CALLS edge to an outer function of
that name (the rename planner and the resolver now agree).
The parameter lattice (RParameterKind, kindOfParameter, parameterNamed,
rParameterKind, innermostParameterKind) collapses into the boolean
isRParameterName and a private hasEnclosingParameter. isRConstantValue,
rBoundName and rOwnAssignedNames move to R/assignment.ts (kept, not deleted:
the assignment work needs them); captures.ts no longer imports from rename.ts.
Verdict changes (rename fixtures, helper -> assist unless noted):
- parameter-constant-default-call: success (2 edits) -> error ambiguous_reference
- parameter-constant-default-call-and-read: incomplete_semantics -> ambiguous_reference
- function-unrelated-parameter (compute -> calculate): success -> error ambiguous_reference
- new parameter-no-default-call: error ambiguous_reference
- new collision-new-name-parameter-call: error name_collision
- new parameter-read-only (control): success, 1 edit
- unchanged: parameter-assigned-call, parameter-function-default-call,
collision-unrelated-uses, value-reference-*
CALLS edges: r-formal-shadows `constant_default` no longer reaches `transform`;
`plain` still does.
Tests: r-rename-parameter-shadow (rewritten for isRParameterName and the
collapsed verdicts), r-lexical-names, r-rename-collisions (a call under a
default-less formal named like the new name now collides), r-formal-shadows,
rename-provider-r (58 fixtures). docs/languages/r-provider.md lines on formals,
the rename guard and the new-name collision updated.
* fix(r): refuse exportPattern constructs that TRE reads differently from JavaScript
Fail closed on word boundaries (\< \>), \a \e \Q \E, \x{, \u, letter class
escapes inside brackets, collating and equivalence elements, {,n} and a leading
] in a bracket expression. A refused pattern is dropped, so rename reports
incomplete_semantics instead of guessing.
* fix(r): keep qualified calls and library() inside the package namespace
pkg::name() whose package does not define name no longer falls back to a
same-file or other-package definition: a re-export (export plus importFrom of
a local origin that defines the name once) binds the origin, anything else is
dropped, and so is every qualified site of unknown locality. pkg::name() to a
private name from outside the package tree gets no edge; pkg:::name still
binds. library()/require() attach only the exported names of a package that
has a NAMESPACE (unreadable or cut-short NAMESPACEs are not proven exports),
and the unique-name guess skips a candidate its package's readable, complete
NAMESPACE does not export unless the caller is inside that package's tree
(tests/ and inst/ included; a root-level package covers every file outside
nested packages).
Visibility (public/private/unknown) is decided once per pass in sorted order
with completeness read after the batch, so an exportPattern work-budget
cutoff gives the same verdicts whatever the file or site order.
Reverses the load_all() reading of library() and the "Permanent" re-export
pin. Verdict changes: r-qualified-calls reexport_user (global-name-fallback
0.5 -> import-resolved 0.85 to the origin), truncated-discovery qualifier
sites (kept -> no edge), r.test.ts run_all -> hidden_helper (0.5 -> no edge),
r-dotted-s3-collision use_odd via library (0.85 -> no edge). No rename
verdict changes.
* fix(r): bind R6 self to its enclosing class
`self$m()` inside an R6 method resolved by the shared lexical walk, because `self` had no type
binding. An inherited method got no edge, and a top-level function of the same name was bound
instead (0.49), as was one for a method that no class in the chain defines.
emitRScopeCaptures now types `self` in each R6 method (a function in the public, private or
active list of an R6Class call assigned to a name, bare or R6::) as that class, through a
synthetic @type-binding.self capture that interpretRTypeBinding reads with the shared `self`
source. The shared receiver pass then resolves the call through the class and its MRO at the
receiver-call confidence (0.85). Where self is no R6 instance (a free function, a parameter
named self, an R6Class call that is assigned to nothing, a RefClass method) the module and the
outermost function frames own `self` untyped (scopeOwnsReceivers), so the call is suppressed as
receiver-owned-but-unbound instead of reaching a free function. A file that binds `self` at top
level is exempt, so a global `self <- Foo$new()` still types its free functions' calls. For a
typed self whose class and parents lack the method, resolveReceiverMember answers an empty
ambiguous lookup, which stops the lexical fallback (outcome member-lookup-ambiguous; no shared
code is touched).
A class name containing a dot keeps the generic route: the shared pass reads it as qualified.
Documented in docs/languages/r-provider.md.
Tests: new r-self-binding fixture and test (c1-c13), r-call-shapes pins re-measured, two rename
fixtures (a free function sharing a name with an R6 method called through self).
* fix(r): treat ordinary assignments as lexical bindings and refuse renames they could shadow
`f <- function(x) { helper <- identity; helper(x) }` called the top-level
`helper()`: an ordinary assignment bound nothing in the function's frame. The
function scope now publishes the names its own body assigns a value that may be
a function (an identifier, a call, anything computed, NULL) as lexical names, so
a call of the name stops there (also `=`, `->`, a closure reading the local, and
the base of a complex target such as `names(x) <- v` or `x$a <- v`, never the
called name). A function literal stays a real definition and a constant is
skipped by R at a call, so neither is lexical; `<<-` and `->>` assign outward.
The rule is flow-insensitive: a call before the assignment, or under an `if`,
becomes unresolved.
That alone would let a rename of the outer `helper` succeed and strand
`helper(x)` (the lexical-name claim is a distinct-declaration basis), so the
rename guard refuses with ambiguous_reference when any function body assigns the
renamed name such a value, whether or not a call exists. Both sides read one
walker, `rLexicalAssignedNames` in R/assignment.ts, so they cannot drift.
Verdict changes (rename fixtures, helper -> assist):
- call before the assignment, conditional assignment: incomplete_semantics ->
ambiguous_reference
- new: assign-local-identifier-call, assign-local-no-call (ambiguous_reference),
constant RHS with and without a call (incomplete_semantics, as before),
function literal with and without a call (success, 1 edit), plain call
(success, 2 edits), nested function literal (success, 2 edits)
Known loss until the qualified-call reorder that follows: `pkga::helper(x)`
inside a function that assigns a local `helper` loses its edge.
* refactor(scope-resolution): let a qualified hit outrank a lexical name claim
emitFreeCallFallback applied the lexical name-claim block before it asked the
language's resolveQualifiedFreeCall hook, so a call written with an explicit
path (`pkg::fn()`) lost its edge whenever a parameter, `for` variable or local
binding of the same bare name was in scope, although the path names the module
and a local binding of the tail cannot be what it means. The hook is now
evaluated before the block and a defined hit for a site with rawQualifiedName
bypasses it; the same result is reused at the old call site. An undefined hit,
a site without a written path and a language without the hook keep the block.
This is the declared shared-pass exception of the R review fixes: the edit is
in scope-resolution/passes/free-call-fallback.ts, language-neutral, and names
no language. The resolveQualifiedFreeCall docstring in
scope-resolution/contract/scope-resolver.ts is clarified to say the hook
outranks the name-claim block (the contract left that order open).
Besides R, only PHP and Rust implement the hook; no existing pin in any
language moved. New pins: a unit test with a fake hook for the ordering,
Rust and PHP fixtures for the shape, and the R cells (`pkga::helper(x)` beside
a local `helper`, and beside a same-named parameter or `for` variable) that
the R provider documented as a known loss.
* fix(r): record a replacement call as a call of the setter
* 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(r): add the ingestion gaps guide and a receiver corpus
* 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(r): track the ingestion gaps guide
The file was created under an ignored docs/ path and never committed, although
AGENTS.md and the R provider guide link to it.
* perf(r): find replacement calls in one linear pass
emitRScopeCaptures asked, for every free call, whether it lay in an
assignment target by walking up the tree. tree-sitter's .parent
re-descends from the root and the first-argument check materialised the
whole argument list, so the walk was cubic in first-argument nesting and
quadratic in the number of call-valued arguments: a 1,500-deep nn(...)
or a c() of 10,000 calls stalled the parse worker until the file was
dropped from the index.
rReplacementCallIds now marks the replacement calls top-down, once per
file and only when the file has a free call: from each assignment target
it follows a call's first argument and the base of $, @, [ and [[, the
reverse of the old upward walk, with an explicit stack. The capture
output is identical (equivalence test over every R fixture);
isRReplacementCall stays as the single-call reference.
The trailing-colon trim of an S3method() generic used /:+$/, which is
quadratic in a run of colons; it is now a backwards loop.
The linear-regex cost comment now gives measured figures: a counted
visit costs up to about 70 ns for many short tests, so the package and
load caps are about 2 s and 7 s at worst. No per-test overhead is
charged: doing so moved a budget-exhaustion verdict in the
qualified-visibility determinism test.
* fix(r): type a receiver only when every binding agrees
A constructor binding (`x <- T$new()`) now types `x` only when every
binding of `x` in its frame (the file's top level or a function) is that
constructor; NULL, constants and field writes through `x` are neutral.
Another class, any other value, a formal, a `for` variable, `rm()`,
`assign()` with a literal name or a replacement call on `x` leaves the
receiver untyped, so the call is unresolved instead of reaching another
class's method. `<<-` and `->>` bind in the enclosing frames only, never
in their own.
Every typed receiver now reads the public interface as `self` does: a
private member gets no edge and records `member-lookup-ambiguous`, a
parent's public member wins over a child's private one, and a member the
owner lookup misses is no longer bound to a free function of that name.
Member calls match `$` only, so `u@save()` mints no site. A generator
object (`User$save()`) is never a receiver of an instance method, and a
dotted class name (`My.Class`) gets no receiver lookup (R-13), which also
gives up its own and inherited methods.
New fixtures r-receiver-agreement and r-typed-receiver-members pin the
rule, its kept idioms and its limits (with(), a rebinding in another
file, last-wins); the receiver corpus gains eleven rows.
* fix(r): scope blocks and follow declared package dependencies
Braces that R evaluates in an environment of their own (local(), with(),
within(), test_that(), describe() and it(), bare or pkg::-qualified) are
now block scopes. A definition inside is reached from those braces only:
calls from another block or file are refused rather than guessed, and a
constructor-typed local no longer types receivers in the next test_that
block. withr::with_*() and suppressWarnings() are unchanged.
S3method() registers a method for dispatch; it does not export it. The
NAMESPACE reader records registration-only names, and resolution
(library(), pkg::name, importFrom() and the visibility memo) treats them
as private, while pkg:::name still reaches them. The graph node stays
public and rename keeps refusing a registered method.
The unique-name guess now follows what package code may reach when it
passes R CMD check. From a package's R/ (with a NAMESPACE read in full),
a candidate in another package is refused unless the caller declares a
link (an importFrom() entry for the name, import(), the S4 import forms,
a transitive Depends: or a library() in the caller's file), and a
candidate in a loose script is refused unless an importFrom() entry
exists. A call from tests/ into the package's own data-raw/ or inst/ is
refused unless the file calls source(), system.file() or test_path().
These calls are unsupported for check-clean package code rather than
impossible; an unresolved call is preferred to an unsupported edge.
S4 generator calls are pinned as they are (no generator-specific rule).
* fix(r): refuse renames the graph cannot prove safe
Refuse a rename when the index cannot show it is safe: R6 member
shadowing (portable), a duplicate top-level definition in the load
unit, unindexed R files (via refreshResolutionConfig), a call before a
local or later top-level definition, a new name exported by NAMESPACE,
generated files, call-shaped strings, RefClass inherited members,
roxygen @rawNamespace/@export names, and the pretty and weighted.mean
generics. Adds 36 fixtures and a unit test for the unindexed-source
collector.
* test(r): split the R rename fixtures across two files and run eleven platform shards
The 110 R rename fixtures run as one file that projects to about 1665 s on
Windows at 15 s per test, past the 1200 s shard watchdog. Run them as two files
of 55 fixtures (about 825 s each) so each fits a shard.
The helper keeps defineRenameFixtureTests(language) unchanged for every
language, except that it skips fixtures listed in renameOverflowIds (R only).
defineRenameOverflowFixtureTests(language) registers just those, from the new
rename-provider-r-part2.test.ts. The matrix test is untouched. Each file pins its
partition count, and the first file proves no overflow id names a missing
fixture.
Shard weights, the cross-platform file list and the coverage hints now include
the second file. Charging the second half adds 695 s to the Windows table, which
no longer fits ten shards under the two-minute headroom the shard unit test
requires (busiest shard 1133 s against a 1080 s ceiling). TOTAL in ci-tests.yml
goes from 10 to 11, giving a busiest shard of 1029 s.
* docs(r): close the audit fixes with exact test targets and the final behaviour
Tests: the seven weak assertions in resolvers/r.test.ts now name exact node
ids (the cross-package case pins the pkgB::CleanData call, not the script's
bare call), and r-self-binding gains cell c16 (a parent's public field and a
child's private method share a name: no edge, a suppressed lookup). The
field branch of the self lookup is unreachable for R6 fields, so the
field-branch mutant is equivalent; the cell is red under the mutant that
removes the final ambiguous answer. The chained-receiver marker is not
load-bearing end to end, which the gaps inventory now says.
Docs: the R provider guide and the gaps inventory describe the receiver
agreement rule, block scopes, S3 registration, the dependency rules for the
name guess, the 0.35 qualified tier, the rename guards and their limits; the
inventory gains rows R-26 to R-42 and a corrected audit pin. AGENTS.md header
and changelog row carry the same date; gitnexus/CHANGELOG.md lists the R
language support. Two comment-only edits: the postParse hazard sentence in
language-provider.ts and ARCHITECTURE.md, and a corrected comment on the dotted
call filter in the R scope resolver.
* chore(bench): re-baseline receiver-resolution for the R receiver fixtures
The count arm moves from 138 to 159 call drops and from 168 to 189 across all
kinds. All 21 added drops are .R files (callDropsByExtension..R goes from absent
to 21) and no other extension moves; reads (30) and writes (0) are unchanged.
By shape: chain-field 56 to 63, no-chain 36 to 39, chain-call 32 to 35,
unclassified 13 to 21. By origin: in-program 57 to 64, unknown 49 to 55,
unclassified 2 to 10, external stays 30.
The bench counts only suppressed outcomes with the reason receiver-unresolved
(measure.mjs), so the movement is that reason alone: the R fixtures added since
the last baseline, where the receiver-agreement rule, typed private members,
dotted class names and with() limits end as unresolved receivers. At the
previous head the drift was 138 to 149 (R plus 11); the later receiver and
rename fixtures account for the other 10. No R arm is added to the shape
corpora. BASELINE.md records the movement, and the R gaps inventory notes that
the count arm now attributes drops to .R files.
* fix(r): refuse renames past block-local definitions and $methods() calls
The local-definition guard now also reads the braces of block scopes
(local, test_that, describe, it, with, within; bare or pkg::). A call of
the name before a block-local function literal, or a literal assigned only
under if, refuses the rename: R calls the outer function there, but the
index binds the call to the block-local literal, so the rename left that
call behind. A nested function or block is judged by its own body, so a
stub defined first inside it() under describe() is still accepted.
A x$methods(...) call whose arguments mention the name refuses the rename
too: methods added to a RefClass generator that way are not modelled, so a
bare call inside one was rewritten although R reaches the class method.
Also pin that a function-local rebinding shadows a module-level
constructor type in a file that no <<- rebinds (r-receiver-agreement m10).
Four rename fixtures (57 per test file); gaps rows R-43 and R-44.
* chore(bench): add R to the scope-resolution benchmark
The benchmark from #3711 requires a corpus generator and committed graph
baselines for every supported language, so its inventory check failed
once R was registered. The R arm sources the preceding file and calls
through an R6 instance (`value <- C0$new(); value$make0_0()$make0_1()`):
the first call resolves across files, the second stays unresolved
because R6 method results carry no type, as documented for the provider.
Baselines were recorded with --record; every other language's entry is
unchanged. R: 100 files 99 cross-file calls, 1,000 files 999.
* test(r): drop the Rcpp generator token from the generated-wrapper fixture
gitleaks reads the generator-token UUID that Rcpp writes on line 2 of
RcppExports.R as a generic API key. The rename guard keys only on the
"Generated by" / "do not edit by hand" header on line 1, so the token
line is replaced by a comment and the line numbers stay as they were.
The fixture commit that added the token stays in the branch history,
so its two findings are fingerprinted in .gitleaksignore, following the
existing entry for a synthetic fixture value.
* fix(r): keep the cross-platform command under the Windows length limit
run-cross-platform.ts passes every cross-platform test file to npx on one
command line, run through cmd.exe (shell: true). cmd.exe caps a command
line at 8191 characters, and npx.cmd adds about 131 characters of node
and npx-cli.js paths when it expands its arguments. With the five R
rename files listed, the longest Windows shard command was 8066
characters (about 8197 expanded), and every Windows shard failed with
"The syntax of the command is incorrect." Upstream's own list is 7827
characters without R.
Keep only rename-provider-r.test.ts (part 1, 23 of the 114 fixtures,
dealt round-robin from the sorted ids) on the Windows and macOS list.
Parts 2 to 5 now run on the Linux coverage shards only. The longest
shard command is now 7870 characters (about 8001 expanded). The
five-way split and the partition pins are unchanged; the test comments
and the R docs say which parts run where.
* fix(r): keep names public when NAMESPACE exports cannot be proven complete
refineRExportStatus marked every name absent from NAMESPACE as private
even when the NAMESPACE was unreadable (a conditional export such as
`if (...) export(cond)`) or an exportPattern() was dropped or cut short,
so such names may well be exported. Completeness is now read once per
package after every node has been tested, as rBuildSymbolVisibilityMemo
does.
The rename guard now prefers its incomplete_semantics verdict over the
generic exported refusal when a NAMESPACE was read but not fully applied,
which keeps the namespace-pattern-word-boundary golden unchanged.
Three assertions in r-export-pattern-shared-budget.test.ts encoded the old
behaviour (names of a package with dropped patterns read as unexported) and
now expect them to keep their default export status.
* fix(r): do not read a block-local assignment as a top-level collision
The rename collision scan used !insideFunction to decide whether an
assignment of the new name binds at top level, so `local({ assist <- 1 })`
and `test_that(...)` bodies caused a false name_collision. It now uses
bindsAtTopLevel, which accounts for block scopes and is already used for
the old-name check.
Adds the rename-integration case r/new-name-block-local (a real indexed
run, since the unit helper builds sources without scopes) and raises the
pinned R fixture count to 115 (parts 23/23/23/23/23).
* fix(r): recognise quoted and backticked methods and R6 section formals
The setRefClass extractor compared the raw text of an argument name with
`methods`, and the R6 extractor did the same for `public`, `private` and
`active`, so `` `methods` = `` and `"methods" =` produced the class but no
methods. Both now compare the name with its surrounding quotes or
backticks removed, as Class already is, through a new rArgumentName
wrapper (argumentNameText itself is untouched: 17 upstream dependants).
Partial-name matching (`meth =`) stays a documented limitation.
* docs(r): correct why only R rename part 1 is on the cross-platform list
The comment in cross-platform-tests.ts and the two R docs said parts 2-5
were left off because cmd.exe's 8191-character limit leaves no room. That
was true when run-cross-platform.ts went through a shell, but it now
calls execFileSync(process.execPath, ...) with no shell, so the limit no
longer applies. The wording now says so, and gives the remaining reason:
each part is a real indexing run per fixture and the Windows and macOS
shard time is bounded by keeping them on the Linux shards. The same
claim in a comment of rename-provider-r.test.ts is corrected too.
Comment and documentation only; the list itself is unchanged.
* test(r): make the via_lapply shadowing test non-vacuous
The assertion toEqual(['lapply'].filter(n => targets(...).includes(n)))
passed for any result without extra entries. The suggested
toEqual(['lapply']) would fail against the old fixture, because base
lapply is not defined there and via_lapply resolved to no target at all.
The fixture now defines lapply, so the test asserts both halves
explicitly: via_lapply resolves to exactly ['lapply'] (the call site is
resolved, and the anonymous function's `handler` formal shadows the
top-level handler, so there is no edge to it), and a new
via_lapply_unshadowed, with no shadowing formal, reaches handler as a
positive control. The receiver-resolution baseline check still matches.
* test(r): define the Data class in the same file as the documented function
The r-roxygen-param-prose fixture kept the R6 class Data in model.R and
the two callers in run.R, so Data was not a local class of run.R. The
class now sits in run.R, so a bad inference from the prose
"@param df Data frame of observations" is not stopped by the local-class
guard alone.
Verified by mutation: widening BARE_TYPE_RE to drop its end anchor makes
six type-env-r unit tests fail, but this integration test still passes,
because no graph edge consumes the roxygen type. The anchored-type rule is
therefore pinned by the type-env-r unit tests; this test remains an
end-to-end control. The receiver-resolution baseline check still matches.
* fix(r): refuse a block-local binding of the new name unless it is a constant
Switching the collision scan to bindsAtTopLevel let any binding of the new
name inside a local() or test_that() block through. That is safe only when
the value cannot be a function: R's function lookup skips a non-function,
but a function, or a value not shown to be a constant (a call result),
would capture the renamed calls in the block. The scan now still refuses a
block-local binding of the new name unless its right-hand side is a
literal. Function bodies keep their earlier behaviour.
Adds rename-integration cases r/new-name-block-function (already refused
by an existing path; kept as a regression pin) and r/new-name-block-unknown
(fails without this change), and raises the pinned R fixture count to 117
(parts 24/24/23/23/23). The collision unit test that passed with or without
the fix now says what it covers and points at the integration cases.
* fix(r): recognise quoted and backticked formals in the field extractor
The R6 public/private and setClass/setRefClass representation, slots and
fields formals were compared by raw text, so a class written with
`"public" =` or `` `fields` = `` had methods but no fields. They now use
rArgumentName, like the method extractor. Tests cover fields, slots,
representation, and R6 public and private; the method extractor test also
covers R6 private and active.
* docs(r): tighten comments after review
The refineRExportStatus docstring now states the completeness condition,
the two adjacent rename guard comments are merged, a long comment in
rename-provider-r.test.ts is wrapped, and the r-roxygen-param header says
plainly that the integration test is an end-to-end control that does not
fail when the anchored-type rule is loosened.
* test(r): give the parameterised section-formal cases unique titles
The R6 method cases of r-method-extractor-owner.test.ts hard-coded
'public' in a title shared by rows for public, private and active, so
the completeness audit found the same test identity more than once.
The title now carries both the spelling and the formal; the assertions
are unchanged.
* test(scenario-map): recognise R in the source-shape language tables
Name R in the identifier, file-extension and test-path tables so R tests
that feed inline source, or write .R fixtures, are parsed with the R
grammar when their inputs are shaped instead of being treated as plain
text.
* docs(r): state the grammar install policy and the unset provider hooks
R is a required bundled grammar, so GITNEXUS_SKIP_OPTIONAL_GRAMMARS does
not apply to it. Record also that the provider sets no entry-point
patterns, description extractor or MRO strategy, and which default it
takes.
* test(r): count only real drops in the receiver agreement and corpus tests
The shared receiver pass (DART-11) records an informational
receiver-type-unresolved outcome for an untyped function-local receiver.
It adds no edge and no drop count includes it, so the R tests now count a
suppressed outcome as a drop only when its reason is not informational.
The classification lives in one helper keyed on the reason alone.
The tests also assert the repository has no ACCESSES relationships and
that no informational note sits on the line of a resolving row.
* docs(r): describe the informational receiver note in the ingestion gaps
An untyped function-local receiver adds no edge and no counted drop; since
the shared receiver pass (DART-11) it also records an informational
receiver-type-unresolved note that no drop count and no impact bound
includes. Update the INVISIBLE-GAP definition, R-20 and its next step, and
the README taxonomy line to say so.
* docs(r): scope the informational receiver note claim to drop counts
* test(r): build the import visibility stub through the shared factory
The free-call qualified-over-name-claim test hand-built
ScopeResolutionIndexes.imports as a bare Map. Since the import visibility
interface landed (#3908) the name-claim lookup calls imports.edgesAt, so
the stub threw. Build it with createEagerImportVisibility, as the other
hand-made indexes in test/unit/scope-resolution do.
* fix(r): read unindexed R sources through one file handle
Resolves the CodeQL file-system race alerts (check on a path, then read of
the same path) in collectRUnindexedSources and gitnexusIgnore. Both now go
through readRegularFile: open once, stat the handle, read the handle, close in
finally.
Behaviour, before and after (pinned by r-rename-unindexed-sources.test.ts):
- .gitnexusignore as a symbolic link, directory or FIFO: before, lstat.isFile()
was false so no rules applied; after, no rules apply and a FIFO does not
block. POSIX: the open uses O_NOFOLLOW/O_NONBLOCK, so a final symbolic link
fails with ELOOP (caught, undefined) and the handle stat rejects non-regular
files. Windows has neither flag: the handle stat rejects directories and
oversize files and an lstat after the open rejects a symbolic link, leaving
a narrow open-to-lstat window (same as readNestedGitignore). No dev/ino
comparison is made (Windows stat(path).dev differs from fstat(fd).dev).
- Regular .gitnexusignore: rules applied, unchanged.
- R file over MAX_UNINDEXED_R_SOURCE_BYTES: unreadable entry, unchanged; a file
of exactly the cap is still read.
- R file that is a symbolic link or non-regular: the walk still skips it via
Dirent.isFile(); a file swapped for a link after the walk is now refused
(unreadable) instead of followed.
- Open or read failure: unreadable entry, unchanged.
* fix(scenario-map): anchor the structural node-type pattern
/body|list|specifier$/ read as if all three alternatives were suffixes, but
only specifier$ is anchored: body and list match anywhere in the node type
(class_body_declaration, field_declaration_list). That is the behaviour in
force, so it is kept; the pattern becomes isTypeDeclarationType with explicit
includes/includes/endsWith and no ambiguous regex. Verified identical to the
old expression over 41k generated node-type strings, and pinned by tests.
* fix(r): bound the unindexed-source read to the size cap
* perf(parse-worker): load the R grammar on first R file
* fix(r): give each file its own VIRTUAL placeholder class
The contains = "VIRTUAL" sentinel minted one graph-wide placeholder owned
by an arbitrary declaring file. The incremental writer follows only
file-owned edges, so editing or deleting that file made the next
incremental analyse fail. Mint one placeholder per declaring file, with an
id (Class:<file>:<virtual>) that cannot meet a real class named VIRTUAL, so
every EXTENDS edge stays within one file. Add an incremental regression
test.
* fix(scope-resolution): gate the qualified free-call reorder behind a provider opt-in
The free-call pass ran a provider's resolveQualifiedFreeCall before the lexical
name-claim block for every language. For Rust this added CALLS edges for
let, for, match, if let and file-level const callers of a module-qualified
call beside a same-named binding.
Add the optional ScopeResolver.qualifiedFreeCallOutranksNameClaim, set only
by R. Without it the pass keeps the original order, with the hook after the
block, so Rust and PHP graphs match upstream main again. Pin the Rust shapes
as unchanged and test the opt-out order and the unconditional assignment.
* fix(r): refuse rename when several dirs declare the same Package: name (T9)
A rename preview for a target in a package whose `Package:` name another
directory also declares returned an OK plan: `pk:::fn` was rewritten in one
copy or stranded in the other. The config loader now records the directories
whose name is declared more than once (`duplicatePackageDirs`), and the safety
check refuses with an ambiguity reason. Edge binding for duplicate names is out
of scope.
Impact (index at 44d693958, worktree method): checkSafety UNKNOWN (reached
through the RenameProvider hook, no resolved callers; confirmed by text search
that only the rename engine calls it; the change only adds a refusal),
loadRPackageConfig LOW (8 impacted). detect-changes --scope staged on the
source files: 2 files, 10 symbols, not partial, risk medium.
Refs #114
* fix(r): refuse rename when a call in a parameter default meets a local definition (T10)
A function that defines a local function of the renamed name in its body, and
calls the name in a parameter default, produced an OK plan with one edit and the
default left on the old name. The defaults are lazily evaluated in the function's
own environment, so such a call is as undecidable as a call before the local
definition; rCallsBeforeLocalDefinition now collects calls in `parameters` too,
and the existing ordering test refuses it.
Impact (index at 44d693958, worktree method): rCallsBeforeLocalDefinition LOW
(1 impacted). detect-changes --scope staged on the source file: 1 file,
1 symbol, not partial, risk low.
Refs #114
* fix(r): apply the string-call, unindexed-file and hook-name guards to the new name (T11)
Three rename guards tested only the old name, so `helper` -> `abs` (a string
evaluated as `abs(1)`), `helper` -> a name an unindexed R file uses, and
`helper` -> `.onLoad` all returned OK plans. Each check now also tests newName,
with its own refusal message.
Impact (index at 44d693958, worktree method): checkSafety UNKNOWN (RenameProvider
hook, no resolved callers; only the rename engine calls it; the change only adds
refusals). detect-changes --scope staged on the source file: 1 file, 2 symbols, not partial, risk medium.
Refs #114
* fix(r): refuse rename of a function defined twice at the top level of its own file (T15)
`helper <- function...` twice in one file produced an OK plan that renamed only
one of the definitions. The safety check now counts the top-level bindings of the
name in the target's own file and refuses when there is more than one; the
cross-file duplicate check already existed.
Impact (index at 44d693958, worktree method): definesAtTopLevel LOW (1 impacted,
now a wrapper over topLevelBindingCount); checkSafety UNKNOWN (RenameProvider hook,
only the rename engine calls it; the change only adds a refusal). detect-changes
--scope staged (worktree with the four fixes applied over 44d693958): 2 files,
15 symbols, not partial, risk medium.
Refs #114
* fix(r): refuse library()/importFrom() binding of a name that a closure-local function also carries (T3)
The shared finalize pass indexes the definitions of a file by simple name and
binds an imported name to the first it meets. A closure-local `validate` ahead
of an exported top-level `validate` therefore won the 0.85 edge.
expandRWildcardNames and resolveRNamedImport now refuse a name when another
undotted definition of the file carries it (RFileTopLevel.repeated); the call
falls to the lower tiers. Dotted members stay with namedImportsBindTopLevelOnly.
The r.test.ts "known limitation" test now asserts the refusal.
Impact (index of an earlier commit, storage-version workaround): expandRWildcardNames
LOW, 1 caller; resolveRNamedImport CRITICAL by graph depth (2 direct callers,
resolveRImportTarget and populateRNamespaceImports), the change only drops edges.
detect-changes --scope staged on the source files: low, 0 processes, not partial
(test files excluded: new files are not in the index).
Refs #115
* fix(r): refuse library()/importFrom() binding of a name defined as a function in two files of one package (T6)
Two files of one package that define the same function made library(pkg) and
importFrom(pkg, name) bind the first file at 0.85, against r-provider.md and
the unique-definition rule of the masking pass.
resolveRNamedImport returns null and expandRWildcardNames drops the name when
more than one R/ file of the package binds it to a function (a class of that
name next to one function is not a second callee, so the Bioconductor
generator idiom still binds). Both go through the same helper in
import-target.ts; the call falls to the lower tiers, where the name stays
ambiguous. r-provider.md now says so for importFrom() as well.
Impact (index of an earlier commit): rFileTopLevel LOW, 4 direct callers, 0
processes; resolveRNamedImport and expandRWildcardNames as in the previous
commit (edge-dropping only). detect-changes --scope staged: low, 0 processes,
not partial.
Refs #115
* fix(r): attach nothing for library() calls that spell exclude, include.only or character.only (T7)
The scope emitter took the first argument of every library()/require() as the
package and ignored exclude =, include.only = and character.only =, so a hidden
name, a name outside include.only, or a variable naming another package still
got a 0.85 import-resolved edge.
isRNonNamingScopeMatch now drops the import capture when the call's argument
list spells any of the three (one cached pass per list). Literal filtering is
not attempted. The names fall to the lower tiers (unique-name guess, 0.5).
r-provider.md documents the behaviour. The unit test that expected
library(character.only = TRUE, pkg) to import pkg now expects nothing.
Impact (index of an earlier commit): isRNonNamingScopeMatch CRITICAL by graph
depth (1 direct caller, emitRScopeCaptures; 2 processes at depth 3), the change
only drops import captures. detect-changes --scope staged on source and docs: low,
0 processes, not partial (test files excluded: new files are not indexed).
Refs #115
* test(r): update unit expectations for names defined as a function in two files (T6 follow-up)
The T6 commit made a name that two files of one package define as a function
bind nowhere through importFrom() and library(). Three unit expectations
pinned the old binding to the first file; they now pin the refusal (the
characterisation snapshot changes only for `corelib::shared`).
Refs #115
* fix(r): count exportPattern alternation scan work as build steps (T12)
The literal-alternation check in Nfa.build re-scanned every alternative of a group once
per copy of a repeated group, outside every budget: exportPattern("(" + 16374 x "|" +
"){16384}") fits the 16 KB pattern cap, builds almost no states, and took 10.9 s to
analyse against 3.0 s for a plain NAMESPACE. What the scan visits now counts as build
steps, so such a pattern is refused for the work cap (and charged as a refusal) after a
bounded number of copies. The trie walk of buildWords is no longer than that scan, so it
needs no separate charge. Successfully compiled patterns are not charged to the shared
budget: a successful build is already bounded by the build-step and state caps.
Pinned on the build-step counter in test/unit/r-export-pattern-compile-cost.test.ts, not
on elapsed time. Re-measured: analyse of the crafted NAMESPACE 4.0 s against 5.2 s for a
plain one on the same machine.
Impact (worktree index, approximate; literalWord, literalWords, buildWords,
compileLinearRegexDetailed): LOW, callers only inside languages/r/linear-regex.ts and
export-pattern.ts / package-config.ts. detect-changes staged: low, 4 symbols, 0 processes.
Refs #116
* fix(r): make the exportPattern warnings and the grammar rebuild hint say what happens (L8, L11)
L8: the dropped and cut-short exportPattern warnings said the names "are treated as not
exported", but refineRExportStatus keeps such nodes exported (no name is proven private).
The warnings now say "not proven private and stay exported"; the existing 200-pattern
test asserts both the kept status and the wording.
L11: the "parser not available" skip warning now ends "then analyze --force": after a
grammar is rebuilt, files skipped as unparsed are only picked up by a full re-index. The
text is shared and names no language; the R and Swift expectations are updated.
Impact (worktree index 1de5780b6, approximate): reportRExportPatternProblems and
runChunkedParseAndResolve, string changes only. detect-changes staged: 4 source files,
low risk; test files also mapped.
Refs #116
* docs(r): correct the receiver baseline numbers, the import-target scan reason; list the R NAMESPACE edit test as lbug-db; fix a test comment (L13, L15, L16, L18)
L13: test/integration/r-namespace-edit-incremental.test.ts opens LadybugDB; it is now in
the lbug-db project include list and the default project exclude list in vitest.config.ts
(TESTING.md describes the list generically and needs no edit).
L15: BASELINE.md R section now agrees with baseline.json: 161 call drops and 195 in
total (no-chain 41, unknown 69). The merged Dart awaited-call fix (#3876) removed one
drop after the paragraph was written.
L16: the stated reason for R's import-target ceilings named two O(files) legs; source()
is keyed (normToRaw exact join, suffix index on a miss), only library(localpkg) scans.
Corrected in bench/import-target/measure.mjs and baselines.json (notes only).
L18: the second position of the two-character string is the end context, not the middle.
detect-changes staged is PARTIAL here: vitest.config.ts and measure.mjs map to no
symbols (config/comment-only changes).
Refs #116
* docs(r): state known limits and fix contradictory sentences (T4, T5, T8, T14, T16, L1-L7, L10)
Docs only, plus one source comment (no behaviour change).
- r-provider.md: library() masking caveat beside an S3 method (T5, R-46);
unreadable NAMESPACE file or package beyond the discovery bound is treated
as absent, every name public, silently, and a directive the reader cannot
read is a different case (T8, R-47; package-config.ts:660-700); dotted name
binds the first definition by path, not a unique one (T4, R-45;
scope-resolver.ts:224); URL and ~ source() paths (L10); exotic NAMESPACE
forms (T16, R-48); bare-name export tagging (L7, R-49; post-parse.ts:221);
bounded-work limits L1, L2, L4, L5, L6.
- r-ingestion-gaps.md: rows R-45 to R-49; R-02 gains the 0.85 local() form
(T14; only function nodes mint @scope.lexical-names, captures.ts:101).
- linear-regex.ts: comment corrected; the 350 MB figure counts automata
only, verdict memos are uncounted, reviewer measured 1.2 GB (L3).
Refs #117
* docs(r): state which export flag R-49 refers to and who reads it
Refs #117
* fix(r): keep the import edge of a function whose same-file class def follows it (F1)
repeatedSimpleNames counted every undotted localDef, class defs included, so
`Circle <- function(r)` followed by `setClass("Circle")` in one file was treated
as a repeated name and the 0.85 import edge was dropped, unlike the cross-file
case (cf44fa923). A class def that follows the function of the same name is no
longer a repeat: the shared finalize pass binds the first callable-or-type def,
which is the function. Two functions (T3) and a class def ahead of the function
stay refused, since finalize would bind the class there; that order keeps the
0.5 guess to the right function and is pinned as a limit.
Tests: r-s4-generator same-file-{library,importfrom} fail before, pass after;
classfirst variants pin the limit.
Impact: repeatedSimpleNames LOW, 10 upstream symbols (all R), the change only
adds edges. detect-changes --scope staged on the source file: low, 0 processes
(test and fixture files are new, so not in the index, and were excluded).
Refs #119
Refs #115
* test(r): run r-virtual-placeholder-incremental with the lbug-db tests (F4)
Listed in the lbug-db include and in the default exclude, as e72a4c7c9 did for
r-namespace-edit-incremental.
Refs #119
* test(r): assert the solo rename verdict explicitly and relabel the T10 characterisation (F2)
Refs #119
* test(r): document the dist requirement of the lazy-grammar test and warn when it skips (F3)
Refs #119
* docs(r): qualify the free-call ordering claim, the T3 and T7 limits, the R-47 variants and the duplicate Package: refusal (F5)
Refs #119
* docs(r): soften the claim that the <virtual> id segment cannot meet a real class id (F6)
A class named by a string or in backticks (setClass("<virtual>")) could. Comment
only; no code change. detect-changes --scope staged mapped no symbols (a comment
edit), so it reports PARTIAL and is not a clean check; the diff is one doc comment.
Refs #119
* fix(r): say what the exportPattern warnings mean for library() and pkg:: (F7)
The warnings said unproven names "stay exported". The graph flag does stay true,
but library() and pkg:: resolution do not treat such names as provably public.
The text now says both; the test asserts it.
Impact: reportRExportPatternProblems is a log-text change only. detect-changes
--scope staged: low, 0 processes.
Refs #119
Refs #115
* chore(r): keep the analyze --force rebuild hint for every language (F8, no code change)
Verified in code that a file skipped for a missing grammar binding is picked up
only by a full re-index, for every language: the skip in parse-impl.ts (skippedByLang)
is language-neutral and leaves the file node in the graph; run-analyze.ts hashes
every File node (newFileHashes) and diffs by hash (diffFileHashes), so an unchanged
skipped file is not re-parsed; the already-up-to-date fast path (lastCommit ===
currentCommit) has no grammar-availability input; and ANALYSIS_FEATURES, which
forces a re-index when it changes, holds no grammar-availability entry. Read from the
code, not run end to end. The hint in parse-impl.ts and its test stay as they are.
Refs #119
* test(parse-worker): pin one-time R grammar load and the missing-binding log (Refs #111)
Adds three integration tests to parse-worker-lazy-r-grammar.test.ts: the R grammar is
required once and reused across several sub-batches of one worker; a worker whose R
binding is unloadable logs no missing-binding error when only non-R files are parsed;
and with R files present it logs the failure once, caches it across sub-batches and
skips the R files without crashing. The preload gains a failR switch (workerData) and
an fd 2 write probe; the helper takes a list of sub-batches because availability is
resolved once per language per sub-batch.
Mutation check (dist temporarily edited, restored): disabling both the worker's
lazyLanguageCache and the shared loader's loadCache fails the reuse and the
failure-caching tests; loading R eagerly at module load fails the no-R-file tests.
Disabling only the worker cache does not fail them, because the shared loader cache
also dedups the require.
Impact check: tests only, no source symbol edited. detect-changes not applicable to a
test-only change. git diff --stat: 1 file changed, 88 insertions(+), 15 deletions(-)
* docs(scope-resolution): describe the qualified free-call opt-in without naming a language (Refs #113)
Comment-only rewording of lines this PR added to shared ingestion code so
they describe the mechanism generically: the qualifiedFreeCallOutranksNameClaim
doc, the resolveMemberOwnerNode doc, and two parse-worker comments. No code,
type or behaviour change.
Impact: comment-only, so no symbol's behaviour or callers change; impact
analysis not applicable.
detect-changes (staged): PARTIAL, as expected for a comment-only change
(parse-worker.ts maps no symbols; it holds only comment edits). Mapped:
LanguageProviderConfig, ScopeResolver; 0 affected processes; risk unknown.
* Resolve R callable shadowing in file and block scopes
* Exercise R import index reuse with literal source paths
* Verify exact R import edges and reachable source controls
* Use the shared grammar loader in workers and benchmark literal R sources
* Index R package sources once per import-resolution pass
* Respect refined R visibility when collecting exported types
* Size identity hash buffers to the files being read
* Decline positional R matches consumed by abbreviated arguments
* Preserve R package imports with abbreviated character.only set to FALSE
* perf(r): index package ownership once per discovery pass
* perf(r): classify nested function receivers without repeated parent searches
* perf(index): reuse the synchronous artifact hashing buffer
---------
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
66 KiB
R Language Provider
Status: implemented (experimental)
The provider is covered by unit and integration tests, listed under Tests. It is classified as experimental in the language support table. This status describes what is implemented today; it does not promise R's dynamic dispatch.
Wrong or lost results inside the supported slice, and the work that is deliberately deferred, are tracked with IDs (R-NN), evidence labels and pinning tests in r-ingestion-gaps.md. This guide describes the behaviour; that inventory is the starting point for a plan.
Scope
GitNexus indexes .r and .R files with the @eagleoutice/tree-sitter-r grammar and resolves them through the scope-resolution pipeline (see ARCHITECTURE.md, Scope-Resolution Pipeline). R-specific logic lives in gitnexus/src/core/ingestion/languages/r/, with the per-language extractor files beside those of the other languages (the import resolver is languages/r/import-target.ts). Apart from the registrations every language has (the language enum, the file-extension and classification tables, the grammar loader and parse-worker grammar map, and the query, provider and scope-resolver registries), shared ingestion code does not name R; the provider plugs in through LanguageProvider and ScopeResolver hooks. The grammar is loaded through the shared grammar loader on first use, and the parse worker loads it behind a guard like the vendored grammars: if the native binding cannot load, R files are skipped with one logged warning per run and no other language is affected (the warning names the file count and either "parsing disabled via GITNEXUS_SKIP_OPTIONAL_GRAMMARS" when the grammar was opted out, or "parser not available (native binding may not have built)" with an npm rebuild @eagleoutice/tree-sitter-r hint). R is a required, bundled dependency like tree-sitter-ruby and tree-sitter-rust, not an optional vendored grammar: GITNEXUS_SKIP_OPTIONAL_GRAMMARS does not apply to it, so only the second warning can occur. R's own warnings are the package-configuration ones in package-config.ts.
R has no class syntax: classes are function calls (R6Class(...), setClass(...), setRefClass(...)) and package exports live in a NAMESPACE file rather than in the source. That is why the provider uses three optional hooks: postParse (attach each member to its owner and refine export status once every file is parsed), resolveMemberOwnerNode (find the owner of a member from a call rather than an enclosing node) and resolveDetachedOwnerName (qualify a member's id with its class, so two classes in one file that share a member name stay distinct nodes: Method:R/a.R:Stack.push#0, Property:R/a.R:Stack.items).
Supported constructs
Definitions:
- Functions defined by assignment (
<-,=,<<-). S3 methods appear as ordinary functions with dotted names such asprint.foo. - S4 classes (
setClass), generics (setGeneric), methods (setMethod) and slots (representation,slots). - A
setMethod()is owned by the class its signature names: the string, or the first argument ofsignature(...)orc(...). A method on several classes (multiple dispatch) belongs to its first class, sosignature("A", "B")andsignature("A", "C")give one method ofA(the first written wins) and a signature whose first argument is not a string names no owner. - R6 classes with their methods, fields and active bindings.
- RefClass (
setRefClass) classes with their methods and fields. - Slots and fields given as
list(...),representation(...)orc(...). A named entry (c(a = "numeric")) records its type; an unnamed string inslots = c("a", "b")orfields = c("a", "b")names an untyped member, as in R. An unnamed string inrepresentation(...)orlist(...)is not a member. - The argument that names an S4 or RefClass class, a generic or a method is the argument spelled with the first formal (
Class=,name=,f=) wherever it sits, else the first unnamed argument (so a laterClass=takes the formal from an earlier unnamed argument, as in R). Other strings (contains=,valueClass=, asetMethodsignature) create no node.
Types:
x <- Type$new()(R6, RefClass) andx <- new("Class")(S4) typex. Resolution ofx$method()is asserted by tests for R6 only (r-receiver-corpus). The S4new()binding is made in the per-file type environment, not in the scope, so it types no receiver (u <- new("User"); u$save()has no edge); it is unit-tested only. A constructor types a name only when every binding of that name in its frame agrees with it (receiver-agreement.ts): a second class, an untyped value, a loop variable, a formal,rm(x),assign("x", ...)orclass(x) <- vin the same frame leaves the receiver untyped, andobj$m()then ends asreceiver-unresolvedwith no edge, never as an edge to another class's method.NULL, a constant and a write through the object (x$a <- v,x[[i]] <- v) do not count against it. A frame is the file's top level or onefunction_definition; the braces oflocal({...})and of other calls belong to the enclosing frame;<<-and->>bind in no frame of their own but are recorded in every enclosing frame, up to the top level. A module-levelu <- User$new()also typesuin the file's functions, unless a function bindsuitself or the file<<-s it. Frames are per file: a package namespace spans files, so a rebinding in another file is not seen (R-36).with()andwithin()are not modelled (R-35). A test file that reuses one name for different classes in severaltest_thatblocks leaves that name untyped in all of them, because blocks are not frames. A local from any other call, a parameter and a roxygen type leave it untyped (see r-ingestion-gaps.md, R-20).- roxygen2
@paramtypes in a restricted form: the description is the type alone (#' @param name Type) or starts with it in braces (#' @param name {Type} prose), the type is an R6, S4 or RefClass class defined in the same file, and the name is a formal of the function the block documents. The type is bound inside that function only. Prose that begins with a capitalised word binds nothing. Other roxygen2 tags (@return,@field,@inheritParams,@rdname,@noRd,@export) are not read.
Imports:
library()andrequire()resolve to local packages, andsource()to local files. The argument ispackage=/file=wherever it sits, else the first unnamed argument after any named one; named-first arguments such aslib.loc=andlocal=are not imports.- NAMESPACE
importFrom()names bind to definitions in local packages. A name that can never bind (not exported, not defined at top level, or dotted) creates no import, so its calls keep theglobal-name-fallbackguess, unless the name is provably private to its package: then the guess is vetoed too and the call gets no edge (see Export status).
Calls:
- Free calls,
obj$method()calls (receiver typed as above), R6self$method()calls, and calls inside native pipe (|>) chains. - A chained member call,
a$b$m(),Cls$new()$m()orself$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'struncatedreceiver chain, which the shared fold refuses, and the call ends with areceiver-unresolvedoutcome and no edge, instead of reaching a free function or a method of that name elsewhere (it counts toward theimpactlower bound). The first link must be a plain variable: a chain based on a call (get_user()$save(),pkg::Cls$new()$m()), onx[[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 thetruncatedmarker defence in depth that no producer mints; R relies on it:r-receiver-chain.test.tsfails if R stops minting the marker or if upstream starts folding a truncated chain. End to end the marker is not load-bearing today: with it removed (truncated: false), the outcomes and edges of ther-chained-receiversfixture are unchanged and only that unit test fails (R-09). Renaming a function whose name is the last step of such a call (a freesavebesidea$b$save()) is refused asambiguous_reference. - A replacement-function call,
foo(x) <- value, is recorded as a call of`foo<-`, as R runs it (=,<<-,->and->>too, andpkg::foo(x) <- vas a call ofpkg::`foo<-`, which passes the export check of the setter name: a NAMESPACE entry may be writtenexport(`foo<-`)orexport("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)) <- 1calls`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 offoo(x)[bar(1)] <- v) and the assigned value stay ordinary calls, andx$a <- 1orx[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(...)) andsetReplaceMethod()/setGeneric("foo<-")define no node, so such a call has no edge (not even to the getter). An explicit`foo<-`(x, v)is unchanged.renamerefuses both halves of a replacement pair (see Rename). selfin 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 theR6Classcall is assigned to (Child <- R6::R6Class(...), bare orR6::), and the method is a function in itspublic,privateoractivelist (a private method has a typedselftoo).selfis the public interface, soself$m()reaches only public and active members: a method in aprivatelist, 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'sself. Writing throughself(self$count <- 1,self[["x"]] <- v,self$items[[i]] <- v,names(self$items) <- v) leaves it the instance. Whereselfis no R6 instance (a free function, a parameter calledself, a plainself <- other()in the method or function, anR6Classcall that is assigned to nothing, asetRefClassmethod) aself$m()call gets no edge and the resolution outcome isreceiver-owned-but-unbound, unless that binding is itself typed (self <- Foo$new()makesselfaFoo); a method that neither the class nor a parent defines as a public member (or a parent that is not indexed, as ininherit = pkg::Base) gets no edge and the outcomemember-lookup-ambiguous(the closest label the shared pass offers for "member not found"). A file that bindsselfitself (self <- Foo$new()at top level) is exempt: its free functions read that object. The same lookup rules hold for every typed receiver, not onlyself:u <- User$new(); u$secret()does not reach a private method (a typed miss recordsmember-lookup-ambiguous),u@save()is not a member call and makes no site, and a call through a generator object (g <- setRefClass(...)) is not a receiver. A class whose name contains a dot (My.Class) gets no receiver lookup at all, forself$m()and for typed receivers alike: the call endsreceiver-unresolvedwith no edge, where it used to reach a same-named free function (R-13). The edge of aself$m()call is labelledglobalat 0.85 when the class is in the caller's file andimport-resolvedat 0.85 when it is in another file.- A call through a name that a function's formal or one of its
forvariables 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. Each loop variable belongs to the module, function, or block that contains the loop. - Ordinary assignments bind names in their module, function, or block when the value may be callable (
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 <- vbindx, never the called name). The rule is flow-insensitive, a deliberate trade for a conservative result: a call written before the assignment, or under anifthat may skip it, is left unresolved too. Not modelled, so the call still reaches the outer function:assign(),delayedAssign(),list2env()andwith(list(...), ...)values (R-02; pinned byr-assignment-locals), and a string target ("helper" <- identity). Assignments insidelocal({ ... })belong to that block. Braces that R evaluates in an environment of their own (local({...}),with(data, {...}),within(), testthat'stest_that(desc, {...}),describe()andit(), bare orpkg::-qualified) are block scopes: a function literal defined inside is visible in those braces only, so a call from another block or file does not reach it (fallback-refused, never the 0.5 guess).withr::with_*()andsuppressWarnings({...})evaluate their braces in the caller's frame and get no scope. A block-local definition still counts toward the uniqueness of its name, so a call elsewhere of a name that is also defined at top level in another file gets no edge where R would call the top-level definition: a lost edge, not a wrong one (R-40). A file-level alias blocks a guess at a function from another file. Assigning a literal constant orNULLstill allows R to find an outer callable. A qualified call is decided by its qualifier alone:function(f) mypkg::f()andhelper <- identity; pkga::helper(x)still bindmypkg'sfandpkga'shelper(for a provider that opts in throughqualifiedFreeCallOutranksNameClaim, as R does, the shared free-call pass resolves the qualifier before it applies a lexical name claim; another provider keeps the old order). - 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.
pkg::fn()andpkg:::fn(), decided by the qualifier (see Resolution model).
Heritage:
- R6
inherit=and S4contains=(a single class orc(...)).contains = "VIRTUAL"links to a placeholder class namedVIRTUAL, one per declaring file (a placeholder shared across files would break incremental analysis when its owner file changes).
Exports:
- Read from each local package's NAMESPACE:
export(),exportClasses(),exportMethods(),S3method()andexportPattern().S3method(generic, class, method)registersmethod, the function R registers, elsegeneric.class(a generic of another package,S3method(pkg::generic, class), registersgeneric.class). A registration is not an export:pkg::generic.class,library(pkg)andimportFrom(pkg, generic.class)do not reach a method that onlyS3method()names, though a function also named byexport()orexportPattern()is still exported. The graph node of a registered method stays public (isExported), andrenamerefuses it. Conditional (if/else) exports, raw-string and multi-line arguments and the text after a malformed directive are not read (see Limits and known gaps). ADESCRIPTIONfile with aPackage:line marks a package root.
Resolution model
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()andrequire()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(), a matchingexportPattern();S3method()registers a method and does not export it). A name the NAMESPACE does not export is not attached, and neither is a name it may export but cannot be proven to (a NAMESPACE directive the reader could not read, or anexportPattern()that was dropped or cut short by its work budget): the 0.85 edge alibrary()yields needs proof. An unreadable NAMESPACE leaves its exports unknown. The loader warns, and externalpkg::namecalls need a proven export. The hook has no importer, so alibrary(ownpkg)issued from inside the package (itstests/included) attaches only the exports too. When two attached packages define the same name, the package attached last wins, as R masks it, including whenfmtandprint.fmtshare a file. Of thelibrary()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 letsbmaska). Alibrary()orrequire()call that spellsexclude =,include.only =or a dynamiccharacter.onlyargument yields no attachment. Literalcharacter.only = FALSEpreserves ordinary name lookup. Two files of that one package that both define the name stay ambiguous, with no edge, forlibrary()and forimportFrom()alike. A name that a function nested in another function of the provider file also carries is not attached either, because the shared pass could bind the nested one; so is a name assigned as a function twice at top level of one file (the same refusal, T3), whereas a class of that name after the function (setClass()afterCircle <- function(r)) is not a repeat and the 0.85 edge stays, though a class first is refused. This differs fromdevtools::load_all(), which attaches every top-level name; the earlier behaviour of this provider followedload_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 (an unreadable directive, a cut-shortexportPattern()) keeps the guess. An ambiguous name yields no edge, and a function defined inside another function, or inside a block scope (see Calls), is never a candidate (no other function can reach it by name). In package code the guess is also bounded by the package's declared dependencies. When the caller is inP/R/, P has a NAMESPACE and neither its exports nor its imports were unreadable: Rule A vetoes a candidate in another repository package Q unless P has animportFromentry for the name, imports Q (import(Q),importClassesFrom(Q, ...)orimportMethodsFrom(Q, ...)), lists Q inDepends:(transitively, sincelibrary(A)also attaches A'sDepends:), or the caller file has alibrary(Q)/require(Q); Rule B vetoes a candidate that is in no package'sR/(a loose script, another tree'stests/orinst/) unless animportFromentry exists; Rule D vetoes a call fromP/tests/to a definition underP/data-raw/orP/inst/, which tests reach only by sourcing them, unless the caller file callssource(),system.file()ortest_path(). Rules A and B veto calls that are unsupported for check-clean package code: the package's declared dependencies cannot justify them. That is stricter than the shared hook's wording ("impossible"), since a user can attach Q by hand and the call then runs; the provider prefers an unresolved call to an edge into a package the code does not declare. A vetoed guess recordsfallback-refused. Scripts are not constrained by these rules (R-34). - A bare call never binds to a dotted definition, so
foo(x)cannot reachprint.foo. Dotted (S3-style) names are never import-resolved and skip the 0.5 fallback; a call that spells the full dotted name (read.config(x),print.foo(x)) binds by qualified-name lookup at confidence 0.35 (scope-resolution: call), whether or not alibrary()attached it. When several definitions share a dotted name, a call needs a lexical binding in its file. Other calls with that spelling stay unresolved. That lookup also matches a member whose qualified name isClass.member, sodata.frame(x)can bind the methodframeof an R6 classdata, andStack.push(x)a memberStack.push: a wrong edge when the call means a base-R function or a function from another package (R-32). Dotted names are not bound throughimportFrom(). pkg::name()is decided by its qualifier:pkgis a package of the repository and definesnameexactly once: the call binds to that definition at confidence 0.85 (import-resolved), subject to the export rule below.pkgis certainly not a repository package (discovery completed and found no such package, including a repository with noDESCRIPTION): no edge.pkgdefinesnamemore than once: no edge.pkgis a repository package that defines noname: the call binds only whenpkgre-exports it, i.e. its NAMESPACE hasexport(name)andimportFrom(origin, name)for a repository packageoriginthat definesnameexactly once (one hop; the lastimportFromof the name wins). The edge goes toorigin's definition at 0.85. Anything else (not exported, noimportFrom, an external or multiply-defining origin,:::) gives no edge: a same-file or other-package definition of that name is never reached through a qualifier.- Discovery may have missed a package (its limits were reached): the call gets no edge. No qualified call is left to the lexical or name-guess tiers.
::and:::differ.pkg:::namebinds to the definition whether or not the package exports it.pkg::namebinds 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 reads directories in code-unit order up to depth 3 and 200 directories, then checks for hidden package copies within a separate scan budget. Duplicate names and uncertain package identity suppress package-qualified and attached imports. Discovery skips the directories the indexer itself ignores (dot-directories,
vendor,build,dist,lib64,fixturesand the rest of its built-in list) or those named exactlyrenv,packrat,revdepor<name>.Rcheck. ADESCRIPTIONwith aBuilt:field is an installed library package (lib/,library/) and registers nothing.DESCRIPTIONandNAMESPACEare read only as regular files (a symlink is not followed) and only up to 4 MiB; a largerDESCRIPTIONleaves its package undiscovered (discovery counts as incomplete) and a present but unreadableNAMESPACEleaves exports and imports unknown. The shared file scanner has norenv,packrat,revdepor.Rcheckentries, so.Rfiles 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 outsideR/(tests/,vignettes/,inst/) are not package members and stay public; files inR/subdirectories are treated asR/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@exporttags are not consulted by the index (renamedoes read them, see Rename). The refinement changes the graph nodes'isExportedonly; the definitions scope resolution works from carry no export verdict (isExportedstays undefined there, since afalsewould 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) orunknown(not exported, but a NAMESPACE directive was unreadable or anexportPattern()was dropped or cut short).library()andpkg::nameneedpublic(strict); the global-name fallback vetoesprivate, and, for package code, the dependency rules A, B and D (see Resolution model), but notunknown. 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 aDESCRIPTIONor a NAMESPACE) that is a path prefix of its file is P's:tests/,inst/andvignettes/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 throughpkg::nameand 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, any backslash inside[...](TRE reads it as a literal member, so[a\-z]is a range from\tozand[\n]holdsn; this drops the commonexportPattern("^[^\\.]"), 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, andrenamethen reportsincomplete_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 conditionalexport()below, or a malformed directive that swallowed one), andrenamerefuses on that record (see Rename).
Limits and known gaps
Not edges or nodes:
- A function passed as a value (
lapply(x, f),Map,lapply(x, pkg::f)), dynamic calls (do.call("f", ...),match.fun(),get()) and dispatch through a registry (handlers[["a"]]()) create no CALLS edge, because only the four call shapes above are captured; the cross-language callable-value analysis classifies R as not applicable. - R6
super$method()andprivate$method()calls (nothing bindssuperorprivateto a class), S4 slot access (obj@slot), andUseMethod()/NextMethod()create no edge. - Anonymous functions (
function(x),\(x)) passed as arguments are not indexed as definitions; calls inside are attributed to the enclosing function, or to the File at top level. - Infix operators (
a %op% b) are not linked to their definitions. - Constants and other top-level non-function assignments, and environments (
new.env(),local(),assign()/get()), are not nodes; the only value-like nodes are R6, RefClass and S4 fields and slots.setValidity(),setClassUnion(),setReplaceMethod()andClass$methods(...)create no definition or edge; a bare call inside aClass$methods(...)method resolves as if it were outside the class (R-44). - The provider sets no
entryPointPatterns,astFrameworkPatterns,descriptionExtractor(roxygen#'blocks are not read as descriptions) ormroStrategy. It takes the defaultfirst-winsstrategy, and its scope resolver builds the class linearisation with the shareddefaultLinearize(a breadth-first walk of the recorded parents, first seen wins). Calls and members resolve through the scope-resolution pipeline, so the call, class and variable extractor configs other languages register are not used. - No framework or entry-point detection (Shiny, plumber, targets, testthat). Plumber
#*annotations are not read and no route nodes are created, and no route or fetch edges link R to other languages.
Known gaps in call resolution and class handling. Those that decide which target a call reaches are tracked with IDs, evidence and pinning tests in r-ingestion-gaps.md: the dotted R6 class name (R-13), a global self bound in another file (R-14), RefClass calls by bare name and through .self$ (R-19), and the S4 generic, generator, new() and Class$new() calls that get no edge (R-18). Rows R-26 to R-44 record the boundaries found while fixing the audit. The rest were reproduced and are left as is:
source()paths are matched by suffix: leading directories that do not exist are dropped until a file matches, sosource("secrets/config.R")bindsR/config.R, and the first of several matches wins. Backslash paths and absolute paths resolve to nothing. Only literal.Rand.rpaths are eligible. URLs, home-relative paths such as~/lib/config.R, and computed expressions stay unresolved.library(localpkg)creates oneIMPORTSedge per file of the package from every importing file, so 100 scripts and a package of 200 files give 20,000 edges.- When two repository packages each define a helper of the same name, a bare call to it from another file of either package gets no edge: the name is ambiguous in the repository, although the caller's package decides it in R.
METHOD_OVERRIDEScompares parameter counts, so an R6 or RefClass method that overrides one with a different formals list (speak = function(loud = TRUE)overspeak = function()) gets no edge, although R has no overloading.- Calls inside the function of a
setMethod(),setGeneric()orsetValidity()call are credited to the File, not to theMethodnode the same call creates. Calls insidevalidity =ofsetClass()are credited to the Class. - R6
inherit = pkg::Baseand legacy S4representation("Base")create noEXTENDSedge. - 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, sosetClass("Hello\x41")is a different class fromsetClass("HelloA"), which R treats as one. - A function nested in an R6, RefClass or
setMethod()body has an id such asCounter.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 =orcontains =that is defined more than once in the repository (in two files, or twice in one) gets noEXTENDSedge 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), 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 (...)andelsebodies 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 withname(in column 0. Skipping a body or a malformed directive that names an export-family directive (export,exportClasses,exportMethods,S3method,exportPattern) is recorded, andrenamerefuses a function of such a package; the persistedisExportedis not changed by it. - Quoted and backticked NAMESPACE directive heads are recognized. Unsupported TRE escapes and locale-dependent POSIX class matches leave export status uncertain and prevent a private-function rename.
isExportedon a member is set by bare name: an R6 or RefClass method or field, or a nested function, that shares its name with a NAMESPACE export readsexported=true, and a public R6 method whose name is not exported readsfalse. Nested functions are also still marked exported (R-49).- Known limits of bounded work, none pinned by a test: the walk of unindexed
.Rfiles forrenamehas no bound on file count or total size (12 files of 7.9 MB took 27.6 s and 560 MB); once theexportPattern()budget is spent, packages without a compiled pattern lose their privacy verdicts, and no warning names the package; the roxygen@exportguard ofrenamemisses CRLF line ends,##'comments,@evalNamespaceand@namewith@exportonNULL, which matters only while a roxygen tag leads the NAMESPACE; therenamesafety walk costs time per nesting level (helper(helper(...))125, 250 and 500 deep took 0.4, 3.1 and 26.5 s). The full capture pipeline has no verified worst-case time bound for deeply nested functions.
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).
Not supported:
- The magrittr pipe
%>%has no specific support and none is claimed; the native pipe|>is supported. tidyverse non-standard evaluation (bare column names,.data$x) is not modelled. .Rmdand.qmdfiles are not indexed (the provider handles.rand.Ronly;.Rprofileand.Renvironare not indexed either), andbox::use(),import::from(),loadNamespace(),attachNamespace()andsys.source()imports are not read.- S3 dispatch is not resolved: S3 methods are indexed as functions only. S4 and RefClass dispatch is not resolved either; there are definitions and heritage, not dispatch edges.
- NAMESPACE
import(),importClassesFrom()andimportMethodsFrom()create no import edge and bind no name. They are read only as a declared link to a repository package (the dependency rules A and B in Resolution model), andDESCRIPTIONDepends:likewise. Imports of external (CRAN) packages produce no edges. - NAMESPACE
exportClassPattern()is not read. An S4 class exported only through such a pattern reads as not exported (isExportedfalse), and animportFrom()of it does not bind; classes listed inexport()orexportClasses()are read. - S4
contains=links only to classes defined in the repository or theVIRTUALmarker; basic-type bases such as"numeric"add no edge. - Package discovery is bounded (depth 3, 200 directories), so a package beyond the bound is treated like an unknown one. A package found only under
renv,packrat,revdep,<name>.Rcheck, a dot-directory or another directory the indexer ignores, or whoseDESCRIPTIONhas aBuilt:field, is not a repository package. - A
pkg::namewhose package defines nonameresolves only through a one-hop re-export (exportplusimportFromof a repository package); a re-export through a second hop, throughexportPattern()only, or throughimport()gets no edge.pkg::nameused as a value is not qualifier-resolved. Call sites dropped for certainly-external, unknown-locality, duplicate-definition or not-exported qualifiers leave no recorded outcome, because the drop runs before outcomes exist (R-04, R-11). - When discovery may have missed a package, a
pkg::namecall gets no edge (it used to keep the name-based guess). Alibrary(pkg)attaches no private or not-provably-exported name, and a bare call of a name whose NAMESPACE is unreadable or whoseexportPattern()was cut short (unknown) still gets the 0.5 guess, because it is not proven private. Alibrary(ownpkg)from inside the package loses the private names at the 0.85 tier too (they fall to the 0.5 guess, which is allowed for callers inside the package). Asource()of a private package file does not reach its names through the guess: the guess is vetoed for callers outside the package tree, although R puts sourced names in the global environment. A class reached as a receiver type through alibrary()IMPORTS edge (ResultSet$new()thenrs$count()) is not filtered by this rule (R-03, R-07, R-08, R-12). - Files in
R/subdirectories are treated as package-owned, although R itself does not load them. - NAMESPACE is read from disk during analysis, but neither it nor
DESCRIPTIONis a parsed source file. After an edit to either alone, an incremental analyse (no--force) keeps stale manifest-derived data: the persistedisExportedof symbols in unchangedR/files, aCALLSedge bound through animportFrom()whose target changed, apkg::fnedge after aPackage:rename, and alibrary(),pkg::fnor name-guess edge whose target's export status changed. A full analyse is correct andanalyze --forcerecomputes it. This is a limitation of the shared incremental write path (only changed files are re-processed), not of R resolution; other language manifests that feed resolution can be affected in the same way. A staleisExporteddoes not reachrename: the rename guard does not take the persisted flag as proof that a function is private, and reads the package's NAMESPACE again at plan time (see Rename). - A name written in backticks (
`%+%`,`my fn`) keeps its backticks on the node, and a definition and its call resolve only when both spell the name alike:`helper`(x)againsthelper <- function(...)(or the reverse) gets noCALLSedge. NAMESPACEexport(),exportPattern(),importFrom(),pkg::name()andrenamematch the symbol whichever way it is written.importFrom(pkg,%||%)binds a call spelled like the definition (`%||%`(x, y)), and a call spelled the other way gets the name-based guess instead. - Roxygen
@paramtypes live in the per-file type environment; no graph edge consumes them. - Argument matching follows R for named and reordered arguments but does not model partial argument names:
setClass(Cla = "D"),new(Cla = "E"),setRefClass(Cla = "A")andsetMethod("show", sig = "Foo")are not recognised, so no definition or owner is attached. - Members are read only from the named forms. The positional second argument of
setClass("A", representation(x = "numeric")),R6Class("X", list(...))andsetRefClass("A", list(...))creates no field or slot nodes; useslots=/representation=,public =/private =/active =andfields =. - S4 and RefClass constructors, and the import calls, are recognised only as a bare callee:
setClass(...),setRefClass(...),setGeneric(...),setMethod(...),library(...),require(...)andsource(...). A namespace-qualified call such asmethods::setClass("A", slots = list(x = "numeric"))creates no class, slot, generic or method, andbase::library("pkg")creates no import.R6::R6Class(...)is recognised. - For
S3method(generic, class, method)the positional third argument names the registered method. A named third argument such asS3method(print, foo, method = impl)is not read: R registersimpl, but the registration is recorded forprint.foo, andrenametreats the NAMESPACE as unreadable.
Bounds on NAMESPACE exportPattern matching
- Matching work and NFA states are counted in deterministic work units, never wall-clock time, so the outcome is the same on every machine. A NAMESPACE file is still read in full.
- Caps, in
linear-regex.ts:MAX_TOTAL_WORK(40,000,000 state visits per matcher),MAX_SHARED_WORK(100,000,000 matching visits per load),MAX_PACKAGE_WORK(30,000,000 per package),MAX_SHARED_STATES(500,000 NFA states per load) andMAX_PACKAGE_STATES(100,000 per package); a single pattern is also capped byMAX_PATTERN_LENGTH(16,384 characters) andMAX_STATES(16,384). - A pattern refused after its NFA was partly built is charged for the build (eight visits per state or build step), and once the budget is spent later patterns are refused without being parsed (dropped, with a reason naming the work budget). A NAMESPACE of thousands of oversized patterns therefore spends the same budget as one of hostile matches.
- Groups nested deeper than 256 (
MAX_NESTING) are refused with the reason "groups are nested too deeply". The limit sits well inside the call stack (a quarter of the default stack still compiles 256 levels), so the verdict is the same cold or warm and on every machine. - Once the work budget is spent the matchers are no longer asked. A name an
exportPattern()matched while the budget lasted keeps that answer (a second definition of the same name stays exported; only the first 100,000 distinct matched names per package are remembered, so past that a name reads as not exported once the budget is spent); a name not decided by then reads as not exported (fail closed), and the cut-short patterns are named in a warning. - A verdict answered from a matcher's memo (a name asked about again) costs one visit of the work budget, so many matchers asked about the same names over and over are bounded by the budget too.
- A counted visit costs about 50 to 70 ns of real time on realistic patterns (13 ns for a hostile one, 13 ns for a memo hit; measured), so the package cap is about 2 s and the load cap about 7 s in the worst case: bounded, never a hang. No fixed per-test overhead is charged on top of the visits (it was tried and dropped, because it moved a pinned visit count and a visibility verdict; R-42).
- A file over the shared size cap (512 KB by default,
GITNEXUS_MAX_FILE_SIZE) is skipped for every language. With the cap raised, a 50,000-line (2.4 MB) R file took about 138 s and ended with its definitions dropped, as an equivalent TypeScript file does: shared behaviour, not R-specific, left unchanged (R-41). Separately, the R query returns 1,028 matches for 1,500 nested calls (tree-sitter behaviour), so a match count is not a call count. - A pattern that does not fit is dropped, exports nothing and is warned about: at most 50 patterns are named per package (
MAX_LISTED_DROPPED_PATTERNS), followed by a summary line counting the rest. - The first pattern refused for lack of states closes that package's allowance, so later patterns in the package are refused without being parsed.
- One hostile package cannot exhaust the load budget alone (it is limited to its own share), but several can (three, for matching work); packages processed after that degrade, with warnings. Which package degrades follows graph node order.
- Budget exhaustion while resolving NAMESPACE
importFrom()names is not reported: the scope resolver loads its own configuration, consults the same matchers, and a name a cut-short pattern would have exported then reads as not exported, with no warning. ThepostParsewarnings above are the only report. - Explicit
export()names are unaffected by these bounds.
Control flow
R provides a control-flow-only CFG visitor (cfg/visitors/r.ts), used under analyze --pdg. It gives R BasicBlock nodes, CFG edges and control-dependence (CDG) edges.
Modelled, in statement position inside a function body: if / else if / else, for, while, repeat, break, next, return(...) and bare { } blocks. Every loop, including repeat and while (TRUE), has a structural exit edge so that EXIT stays reachable for control dependence. Each function_definition (function(x) and \(x), assigned or anonymous) gets its own CFG; a nested function is opaque in its parent. An if arm that is missing (no else) or empty ({}) produces no block: it is the header's seq edge to the join, and control dependence labels it as the complement of the other arm's explicit cond-true / cond-false edge (if (c) {} else work() makes work() control-dependent on c with label F).
Not modelled:
- No def/use harvest and no binding table, so reaching definitions report
no-factsand R emits noREACHING_DEFedges; no taint call sites are recorded. This is a coverage gap, not a result of "no flows found". The PDG tools do not say so for R:pdg_querywithmode: "flows"returns{"results": [], "total": 0}with no note,explainreturnsfindings: []with its generic absence note, and theimpactnote formode: "pdg"still reads "over CDG + REACHING_DEF". Read an empty answer for an R function as "not analysed". The shared tools have no per-language capability signal to report this from, so it is documented here rather than patched into them. - Control flow nested inside an expression stays one straight-line block:
y <- if (c) a else b,switch(),&&/||,ifelse(), andreturn()/breakinsidetryCatch({ ... }),local({ ... })or similar wrappers. stop(),on.exit(),tryCatchhandlers and other non-local exits are ordinary calls: no throw edges and no finaliser routing. Abreak/nextwith no enclosing loop falls back to EXIT.- Function join: a CFG is anchored at the
function_definitiontoken, while theFunctionnode starts at the whole assignment. They share a start line forf <- function,f = functionandf <- \(x), but not forf <-followed byfunctionon the next line; there the CFG is still emitted and its blocks lie inside theFunctionnode's span, but the exact start-line join used by taint summaries does not resolve (inert for R today, since reaching definitions have no facts). Anonymous functions have a CFG but noFunctionnode.
Rename
languages/r/rename.ts gives the rename tool a deliberately narrow, fail-closed R provider (fixtures under test/fixtures/rename-integration/r/). R binds names dynamically, so only what the scope graph proves is renamed.
- Succeeds: a plain function (
name <- function(...)) and the calls the graph resolves to it, in one file or across files; a package function thatNAMESPACEleaves private is included. Every parameter is claimed as a binding, whatever its default, so a parameter of the old name that the body never uses is left alone (parameter-read-only); a call of the name under a same-named parameter is refused (see below), and so is a body that reads it (incomplete_semantics, below). - Refused (
unsupported_occurrence, planning statusunsupported):- any target that is not a plain
Function(S4 classes, R6 classes, members); - a function whose old or new name is the whole value of a string literal anywhere in the indexed R sources (
UseMethod("area"),do.call("f", ...),match.fun,get,setGeneric, ...), because string lookup is not resolved. The literal is decoded first, so escapes ("f\x6fo","\u{66}oo", octal) and raw strings (r"(foo)") count. A string that contains a call of the name ("foo(1)", glue or cli interpolation such as"{foo(x)}",parse(text = "foo(1)"), a formula string) is refused too (unsupported_occurrence); a string that only mentions the name as a word,{name}value interpolation, a name built at run time (paste0("fo", "o")), and strings in files that are not indexed R sources (R Markdown,NAMESPACE) are not detected; - a new name
generic.classwhere any dot-separated prefix is a function defined in the indexed R sources or a known base generic, which would register an S3 method (to.json.foofor a definedto.json,print.foo). The known generics are the S3 group generics (Ops,Math,Summary,Complex,matrixOps) with every function each group dispatches (sum.items,abs.diff), theis.*andas.*generics (is.numeric.foo,as.complex.foo), and the common generics of base, stats, graphics and utils (print,format,summary,plot,unlist,pretty,weighted.mean, ...). Generics of other packages (tidy,filter, ...) are not listed; - an infix function or operator, as the old or the new name (
`%+%`,`%||%`,`+`,`[[`):a %+% bis an operator token, not an identifier, so a rename would edit only the definition; - a replacement function and its getter (
unsupported_occurrence): a call of the name anywhere in an assignment target (helper(z) <- 5,helper(z)$a <- 1,names(helper(z)) <- v, the->forms), because R then calls`helper<-`; an old or new name ending in<-; and a string-defined setter ("helper<-" <- function(...)) of either name; - a new name that is already a global (
name_collision): a top-level variable or function of that name in any indexed file (assist <- 3, aforvariable,3 -> assist), a<<-or->>to it anywhere, or a function of that name in another file. Same-file function collisions were already refused by the shared engine; local variables, parameters and members of that name are allowed; - a new name that the sources already read as a value or call (
name_collision):sapply(x, paste),Reduce(max, x),x <- letters, a defaultf = assist, a formula term,assist[1],assist(1). After the rename the function is the global of that name and would capture the read. A parameter of an enclosing function of that name covers a plain read but not a call: a default proves nothing about the argument, so a call of the new name under such a parameter may reach the global the renamed function becomes. Not reads: bound names, argument names (f(assist = 1)), members (x$assist,x@assist) and qualified names (pkg::assist); - a call of the name under a same-named parameter (
ambiguous_reference), whatever its default (none, a constant,NULL, a function or a computed value) and whether or not the body assigns it, because the call may reach the parameter or the function being renamed; - a function while a same-named parameter is read in a body (
function(x, helper) x + helper), or aforvariable of that name is called in a loop (incomplete_semantics; fixturesparameter-body-read,for-variable-call): no edge covers the occurrence, so the planner stops; it never renames and leaves the call behind (R-16); - a function body that assigns the name a value that may be a function (
ambiguous_reference;helper <- identity,helper = f(),identity -> helper,helper$a <- v), whether or not the name is called there and wherever the assignment sits relative to a call, because the local may shadow the function being renamed (the call-resolution side treats the same assignments as lexical names, see Calls). A function literal (helper <- function(y) 2) is a separate definition and does not refuse when it is defined first (see the local-definition guard below); a constant (helper <- 2) is not read as a binding, so the shared engine refuses it as an uncovered occurrence (incomplete_semantics); - a function that is also assigned with
<<-or->>anywhere in the indexed R sources (ambiguous_reference, as the top-level form already was): the global re-assignment is a second definition that a rename would leave behind; - a package function under
R/that is not proven private, becauseNAMESPACEis not an indexed source and its entry would not be renamed. Two checks must both pass. The persistedisExportedflag must be false, which it is only for a function that aNAMESPACEfile beside the package leaves out ofexport(),exportPattern()andS3method()(the third argument ofS3method(generic, class, method)counts): a package with noNAMESPACEfile, or anR/folder that belongs to no package, keeps the default public flag and is refused. That includes projects that keep their functions inR/without aDESCRIPTION(targets, drake and analysis repositories): every rename of a function underR/is refused there, and a function outsideR/is not. The flag is not enough alone, because an edit ofNAMESPACEwith noR/file touched leaves it stale until a full analyse. So every rename plan also reads the package'sNAMESPACEfrom disk again, through the parsing the indexer uses, and refuses (unsupported_occurrence) when it now exports the name byexport(),exportPattern()orS3method(). It fails closed withincomplete_semanticswhen thatNAMESPACEwas deleted or cannot be read, when anexportPattern()of it was dropped or ran out of work budget (a name such a pattern was meant to cover is then not provably private), or when the reader skipped or could not read something that may hide an export: a conditionalif (...) export(x), a raw-string or multi-line argument, an argument that is an expression, anS3method()it cannot read, or a malformed directive that swallowed an export. It also refuses (unsupported_occurrence) a function whose roxygen2 block (the#'lines directly above the definition) carries@export,@exportMethod,@exportS3Methodor another@export*tag, because the nextdocument()would export the new name; the tag is found by text, other roxygen2 tags (@rdname,@inheritParams,@seealso) are not read. A private function in a package whoseNAMESPACEis unchanged is renamed; a script outsideR/is not affected. The check does not need--force; re-runanalyzeto bring the flag itself up to date. The persisted flag stays a second check on purpose, although the plan-time read decides the stale-private case on its own: it costs nothing, it needs no NAMESPACE read to answer, and when it is stale the other way round (the index says exported, NAMESPACE no longer does) it refuses until the next analyse, which is the safe direction. - a bare call of the name inside a method of a portable R6 class that defines a member of that name (
ambiguous_reference): a bare call in a portable method does not see class members, so it reaches the function being renamed but has no proven edge. A class withportable = FALSEis not refused; - a function in a package whose
Package:name anotherDESCRIPTIONalso declares (ambiguous_reference): the walk finds a second copy, for instance undertests/orinst/, as well as a second package directory, and the refusal follows either; - a name defined at top level in more than one file of the same load unit (
ambiguous_reference; the same package, or both files outside every package): load order decides which definition callers reach. Definitions inside functions and inside block scopes (local,test_that,with, ...) do not count; - an R file the index does not cover that uses the name, or that cannot be read in full (
incomplete_semantics). The rename preview walks the repository for.R/.rfiles in directories the indexer skips (bin/,build/,tmp/),.gitignored files, files over the indexer's size cap,.Rprofileand the.S/.q/.scode files underR/, and records their identifier tokens; a file over 8 MB or one that cannot be read fails closed. Not scanned:.git, the index store,node_modules,*.Rcheck,renv/library,packrat/lib*, whatever.gitnexusignoreexcludes, extensionless Rscript files and R Markdown code. Editing a scanned file between preview and apply makes the apply fail asresolution_changed. The tokens of every unindexed file are retained with the plan, so a very large unindexed R tree can push the retained plan past its budget, and the preview then fails closed withplan_too_large(measured as an upper bound, treating every file as unindexed: 511 R files, 59,468 tokens, use 4.06% of the 64 MiB budget; the 6,378 R files of this repository, fixtures included, use 117%; R-38); - a function body, or the braces of a block scope (
local,test_that,describe,it,with,within, bare orpkg::), that defines the name as a function literal, unless the definition is a direct statement of those braces (not underif,switch, a loop,tryCatchor any call) and every call of the name in them, nested functions and blocks included, starts after it (ambiguous_reference: a call may run before the local definition). Sotest_that("x", { expect_equal(helper(), 1); helper <- function() "stub" })andtest_that("x", { if (cond) helper <- function() 2; helper() })refuse: R calls the outerhelperthere, but the index binds every call in the block to the block-local stub, so a rename would leave that call behind (R-43). A definition in a nested function or block is judged by that body alone. A body with no call of the name is not refused, and a call inside the qualifying literal itself (recursion) is ignored (R-39). A top-level call of the name that precedes the top-level definition, in the file or in a script that attaches it, is refused too, because it reaches another function of that name; - a new name that
NAMESPACEalready exports throughexport()orexportPattern(), or registers as an S3 method (unsupported_occurrence): the rename would change the package API; - a generated file (
unsupported_occurrence): the target file, or any indexed R file in which the name occurs as an identifier, has "Generated by" or "do not edit by hand" in its first five lines (RcppExports.R,cpp11.R), because the generator would restore the old name; - a call of the name inside a
setRefClass(..., methods = list(...))method of a class withcontains =when a class of the chain defines a method or field of that name, or when a parent is not indexed (other thanenvRefClassandVIRTUAL) (ambiguous_reference): the call may reach the inherited member; - any
x$methods(...)call (methods added to a RefClass generator aftersetRefClass()) whose arguments mention the name (ambiguous_reference): such methods are not modelled (Limits and known gaps; R-44), so a call inside one is bound to the function being renamed although R reaches a class method of that name first, and a method of the name added there would shadow the function in every method of the class. The receiver is not traced to asetRefClass()call; - a roxygen2
@rawNamespaceline, or an@export <name>line, of the package that names the function (unsupported_occurrence): the nextdocument()would write the old name intoNAMESPACE.
- any target that is not a plain
- Not updated by a successful rename: files that are not indexed R sources. R Markdown and Quarto documents (
.Rmd,.qmd, vignettes,README.Rmd),man/*.Rd(\alias,\usage), roxygen2 tags that name the function (@rdname,@inheritParams,@seealso),_pkgdown.yml,pkg:::nameuses ininst/, and C++ or other code that looks it up by string keep the old name. So does code that reads the name off the call:match.call(),deparse(substitute(f))and snapshot tests of printed calls (R-37). The result does not list them; search for the old name in those files after a rename. - Refused by the shared engine (fail-closed, not provider code): S3 methods and any function name with a dot after its first character (
area.circlereads as an owner-qualified member, sostale_graph). A name whose only dot is the leading one (.helper, the usual internal-function convention) is renamed like any other function, with one exception: R's hook functions.onLoad,.onAttach,.onUnload,.onDetach,.First,.Last,.First.sys,.First.liband.Last.libare refused (unsupported_occurrence), because R calls them by name; S4 class names (unsupported_occurrence, no exact source-name span). - Invalid names (
invalid_name): anything that is not a nonreserved R identifier: the reserved words,...and..1,..2, ..., and any name with a non-ASCII character, because new names are limited to ASCII letters, digits,.and_(conservative by design; the message says so). An old name made only of non-ASCII characters (λ) is refused as not a supported identifier. Backtick-quoting a new name is never offered: a name that needs it is refused rather than quoted at every use. - Refused when any indexed R file does not parse (
parse_error): the rename plan parses every indexed R file, and a syntax error in one of them, related to the target or not, refuses the rename and names that file. Fix the file (or exclude it) and plan again. - Not proven: unqualified calls to a function defined in another file (including the package
R/layout) fail withambiguous_reference, because R's global-name fallback is not a provable binding. Renaming across files works only where the call is qualified or otherwise resolved.
Type annotations
R has no inline type annotations, so the "Type Annotations" column of the language support table is not ticked for R. The roxygen2 @param extraction above is a comment-based fallback, in the same class as the JSDoc, PHPDoc and YARD fallbacks listed in type-resolution-system.md (Ruby's YARD support is likewise not ticked).
Extending the provider
- During scope capture, the R6
selfclassifier visits the outer functions in a file once. Closures in function bodies and parameter defaults inherit the enclosing receiver unless they bindselfthemselves. Classification stops at the outer function and answers later queries by function ID. - Definition captures are in
R_QUERIES(tree-sitter-queries.ts); scope, import, type-binding, heritage and reference captures are inlanguages/r/query.ts. Keep each declaration pattern and its matching@scope.functionpattern in lockstep, as the comments inquery.tsexplain. - The captures for
setClass,setRefClass,setGeneric,setMethodand forlibrary/require/sourceare deliberately loose. The argument that names the definition or the import is chosen afterwards inlanguages/r/naming-argument.ts, because a query-level prefix that skips leading comments and named arguments is quadratic in the argument count. - Resolution wiring is in
languages/r/scope-resolver.ts, registered inSCOPE_RESOLVERS. Import resolution is inimport-target.ts; package discovery and NAMESPACE parsing are inpackage-config.tsandnamespace-imports.ts; qualified calls inqualified-call.ts; owner and export post-processing inpost-parse.tsandowner-hooks.ts. - Changing what the scope query captures changes what cached parsed files contain. There is no counter to raise: the parse-cache identity is derived from the bytes of the owned source roots and the grammar packages, so the change invalidates stale caches by itself. Rebuild
distand verify a cold parse followed by warm reuse, as CONTRIBUTING's "Parser changes and cache compatibility" section describes. - Shared code under
gitnexus/src/core/ingestion/must not name languages; add behaviour through the provider hooks.
Tests
Unit tests are under gitnexus/test/unit/ (r-*.test.ts, type-env-r.test.ts and scope-resolution/r/) and integration tests under gitnexus/test/integration/resolvers/ (r*.test.ts), with r-* fixture projects in gitnexus/test/fixtures/lang-resolution/. They cover:
- definitions, owners and the naming-argument rules (
r-definition-anchors,r-owner-hooks,r-post-parse-owners,r-scope-naming-argument,r-s4-anchors,r-s4-formals,r-scope-args); - NAMESPACE parsing, exports and
exportPattern()safety and scale (r-namespace-parser,r-namespace-exports,r-export-pattern*,r-export-status-*); - package discovery and root-package imports (
r-package-discovery-*,r-import-root-package,r-namespace-imports); - qualified calls, exports and visibility, dotted S3 names and native pipes (
r-qualified-*,r-qualified-exports,r-qualified-visibility,r-dotted-s3-collision,r-native-pipesfixture inr.test.ts); - receivers,
selfand chains (r-self-binding,r-chained-receivers,r-receiver-chain,r-call-shapes,r-receiver-agreement,r-typed-receiver-members) and the receiver corpus (r-receiver-corpus: one table of call shapes with exact expected targets, decoys and recorded outcomes, summarised in r-ingestion-gaps.md); - lexical names, block scopes, assignments and replacement calls (
r-lexical-names,r-formal-shadows,r-assignment-locals,r-rename-assigned-locals,r-replacement-calls,r-block-scopes); - package visibility, S3 registration and S4 generators (
r-package-visibility,r-s3method-registration,r-s4-generator); - work bounds and pathological inputs (
r-replacement-scaling,r-pathological-inputs); - the shared free-call ordering that lets a qualified hit outrank a lexical name claim (
free-call-qualified-over-name-claim,rust-qualified-over-local,php-qualified-over-local); - rename (
rename-provider-randrename-provider-r-part2to-part5, which deal one fixture list into five parts so each shard stays inside the CI time budget; only part 1 runs on the Windows and macOS shards, because the other four run on the Linux shards only (they were first left off for a cmd.exe command-line limit that no longer applies, and are kept off to bound the Windows and macOS shard time);r-rename-*, includingr-rename-unindexed-sources); - roxygen2
@paramtypes (type-env-r,r-roxygen-param); - control flow (
test/unit/cfg/r-visitor.test.ts,test/integration/cfg/r-cfg-join.test.ts).