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.
This commit is contained in:
Mick Cooney 2026-10-18 15:58:12 +01:00
parent fdbb64c920
commit e41f81b36e
18 changed files with 141 additions and 3 deletions

View file

@ -158,7 +158,7 @@ Not modelled:
- 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, because `NAMESPACE` is not an indexed source and its entry would not be renamed. Two checks must both pass. The persisted `isExported` flag must be false, which it is only for a function that a `NAMESPACE` file beside the package leaves out of `export()`, `exportPattern()` and `S3method()` (the third argument of `S3method(generic, class, method)` counts): a package with no `NAMESPACE` file, or an `R/` folder that belongs to no package, keeps the default public flag and is refused. The flag is not enough alone, because an edit of `NAMESPACE` with no `R/` file touched leaves it stale until a full analyse. So every rename plan also reads the package's `NAMESPACE` from disk again, through the parsing the indexer uses, and refuses (`unsupported_occurrence`) when it now exports the name by `export()`, `exportPattern()` or `S3method()`. It fails closed with `incomplete_semantics` when that `NAMESPACE` was deleted or cannot be read, when an `exportPattern()` 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 conditional `if (...) export(x)`, a raw-string or multi-line argument, an argument that is an expression, an `S3method()` 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`, `@exportS3Method` or another `@export*` tag, because the next `document()` 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 whose `NAMESPACE` is unchanged is renamed; a script outside `R/` is not affected. The check does not need `--force`; re-run `analyze` to bring the flag itself up to date.
- **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:::name` uses in `inst/`, and C++ or other code that looks it up by string keep the old name. 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 dotted function name (`area.circle` reads as an owner-qualified member, so `stale_graph`); S4 class names (`unsupported_occurrence`, no exact source-name span).
- **Refused by the shared engine (fail-closed, not provider code):** S3 methods and any function name with a dot after its first character (`area.circle` reads as an owner-qualified member, so `stale_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` and `.Last` are 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.
- **Not proven:** unqualified calls to a function defined in another file (including the package `R/` layout) fail with `ambiguous_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.

View file

@ -353,8 +353,43 @@ const parseNames = createTreeSitterRenameSource({
},
});
/**
* Functions R itself calls by name: package load and unload hooks and the session start and end
* hooks. A rename would leave them defined under a name nothing calls.
*/
const R_HOOK_FUNCTIONS: ReadonlySet<string> = new Set([
'.onLoad',
'.onAttach',
'.onUnload',
'.onDetach',
'.First',
'.Last',
'.First.sys',
'.First.lib',
'.Last.lib',
]);
/**
* The name the engine compares a graph symbol with the scope definition of. The engine reads a
* definition's simple name as the text after the last `.` of its qualified name (the rule that
* splits an owner from a member), which turns the leading-dot name `.helper` into `helper`; for a
* name that is only a leading dot and one word, the simple name is the whole name. Dotted names
* with a dot inside (`print.foo`, `.helper.foo`) are S3-style owner-qualified names and keep the
* engine's reading, so they stay refused.
*/
function rCanonicalName(
name: string,
context?: Parameters<NonNullable<RenameProvider['canonicalName']>>[1],
): string {
const bare = rBareName(name);
const qualified = context?.definition?.qualifiedName;
if (qualified === undefined) return bare;
const full = rBareName(qualified);
return /^\.[^.]+$/.test(full) && bare === full.slice(1) ? full : bare;
}
export const rRenameProvider: RenameProvider = {
canonicalName: rBareName,
canonicalName: rCanonicalName,
validateName(name) {
// `...`, `..1`, `..2`, ... refer to the arguments passed down to a function; R reserves them.
if (name === '...' || /^\.\.[0-9]+$/.test(name))
@ -407,6 +442,10 @@ export const rRenameProvider: RenameProvider = {
const name = rBareName(target.qualifiedName ?? '');
if (target.type !== 'Function')
return unsupported('Only plain R functions can be renamed; classes and members are refused.');
if (R_HOOK_FUNCTIONS.has(name))
return unsupported(
'R calls this function by name (a package or session hook); a renamed one would no longer run.',
);
// `f(x) <- v` calls the replacement function `f<-`, so a name ending in `<-` is half of a pair
// whose other half is written differently.
if (name.endsWith('<-') || newName.endsWith('<-'))

View file

@ -0,0 +1,3 @@
Package: pk
Version: 0.1.0
Title: Fixture

View file

@ -0,0 +1 @@
export(pub)

View file

@ -0,0 +1,3 @@
pub <- function() 1
.onLoad <- function(libname, pkgname) NULL

View file

@ -0,0 +1,3 @@
Package: pk
Version: 0.1.0
Title: Fixture

View file

@ -0,0 +1 @@
export(pub)

View file

@ -0,0 +1,3 @@
pub <- function() 1
.onLoad <- function(libname, pkgname) NULL

View file

@ -0,0 +1,9 @@
{
"language": "r",
"description": "Refuse a package load hook (.onLoad): R calls it by name, so a renamed hook would silently stop running.",
"categories": ["namespace", "negative", "unchanged-on-error"],
"target": { "name": ".onLoad", "kind": "Function", "file": "R/pub.R", "startLine": 2 },
"newName": "on_load",
"expect": { "status": "error", "code": "unsupported_occurrence", "planningStatus": "unsupported" },
"edges": []
}

View file

@ -0,0 +1,3 @@
Package: pk
Version: 0.1.0
Title: Fixture

View file

@ -0,0 +1 @@
export(pub)

View file

@ -0,0 +1,3 @@
secret <- function(x) x * 2
pub <- function() secret(2)

View file

@ -0,0 +1,3 @@
Package: pk
Version: 0.1.0
Title: Fixture

View file

@ -0,0 +1 @@
export(pub)

View file

@ -0,0 +1,3 @@
.helper <- function(x) x * 2
pub <- function() .helper(2)

View file

@ -0,0 +1,15 @@
{
"language": "r",
"description": "Rename a private package function with a leading dot (.helper, the usual internal-function convention); the definition and its call are renamed.",
"categories": ["namespace", "package-export", "positive"],
"target": { "name": ".helper", "kind": "Function", "file": "R/pub.R", "startLine": 0 },
"newName": "secret",
"expect": { "status": "success", "edits": 2 },
"edges": [
{
"type": "CALLS",
"from": { "name": "pub", "kind": "Function", "file": "R/pub.R", "startLine": 2 },
"to": { "name": ".helper", "kind": "Function", "file": "R/pub.R", "startLine": 0 }
}
]
}

View file

@ -5,7 +5,7 @@ import { defineRenameFixtureTests, renameCases } from '../helpers/rename-integra
// would define no test and stay green. Pin the number of R cases: adding one means raising it.
describe('R rename fixtures', () => {
it('are all discovered', () => {
expect(renameCases.filter((fixture) => fixture.language === 'r')).toHaveLength(54);
expect(renameCases.filter((fixture) => fixture.language === 'r')).toHaveLength(56);
});
});

View file

@ -0,0 +1,47 @@
/**
* R rename: leading-dot names. The engine reads a definition's simple name as the text after the
* last `.` of its qualified name, so `.helper` arrived as `helper` and the graph symbol `.helper`
* did not match it (a misleading `stale_graph`). The R provider's `canonicalName` keeps a
* one-word leading-dot name whole and leaves dotted S3-style names as they were; R's own hook
* functions (`.onLoad`, ...) are refused because R calls them by name.
*/
import { describe, expect, it } from 'vitest';
import { rRenameProvider } from '../../src/core/ingestion/languages/r/rename.js';
const canonical = (name: string, qualifiedName: string): string =>
rRenameProvider.canonicalName!(name, { definition: { qualifiedName } } as never);
describe('R rename: canonicalName of leading-dot names', () => {
it('maps the engine simple name of a one-word leading-dot function back to the whole name', () => {
expect(canonical('helper', '.helper')).toBe('.helper');
expect(canonical('.helper', '.helper')).toBe('.helper');
expect(canonical('.helper', '`.helper`')).toBe('.helper');
});
it('leaves dotted S3-style names and plain names as they were', () => {
expect(canonical('circle', 'area.circle')).toBe('circle');
expect(canonical('foo', '.helper.foo')).toBe('foo');
expect(canonical('helper', 'helper')).toBe('helper');
expect(rRenameProvider.canonicalName!('`odd`')).toBe('odd');
});
it('does not rewrite an unrelated simple name', () => {
expect(canonical('other', '.helper')).toBe('other');
});
});
describe('R rename: functions R calls by name', () => {
it.each(['.onLoad', '.onAttach', '.onUnload', '.onDetach', '.First', '.Last'])(
'refuses %s',
(name) => {
const issue = rRenameProvider.checkSafety?.({
target: { type: 'Function', qualifiedName: name, filePath: 'R/zzz.R' },
newName: 'renamed',
files: new Map(),
graph: undefined,
} as never);
expect(issue?.code).toBe('unsupported_occurrence');
expect(issue?.message).toMatch(/hook/);
},
);
});