You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Version: 0.2.1
Check: compiled code
Result: NOTE
File ‘S7/libs/S7.so’:
Found non-API call to R: ‘Rf_findVarInFrame’
Compiled code should not call non-API entry points in R.
See ‘Writing portable packages’ in the ‘Writing R Extensions’ manual,
and section ‘Moving into C API compliance’ for issues with the use of
non-API entry points.
We also received an email with a deadline for when these should be addressed:
The NOTEs about calls to Rf_findVar and Rf_findVarInFrame will soon turn
into WARNINGs, and we would like to remove these entry points in the
4.6.0 release, which will be released in late April.
Can you please change to no longer use these entry points as quickly as
possible? They have replacements documented in "Some API replacements
for non-API entry points" of "Writing R Extensions": please change to
use these replacements.
Please correct before 2026-04-09 to safely retain your package on CRAN.
Best wishes,
The CRAN Team
Most of the usage sites in S7 are trivial to update, but there is one for which there is no clear path forward: method dispatch.
With the new C API, some existing S7 behavior is hard to preserve.
Today, S7 dispatch has the following behavior:
dispatch arguments are evaluated once
missing() works as expected in methods
substitute() works as expected in methods, including for dispatch arguments
S7 is able to provide this behavior by forwarding the already-evaluated promise object from the generic call to the method call.
With the new public package C API, this no longer appears to be possible. There are many entry points for binding inspection and creation, but there seems to be no way to forward an existing promise.
I can think of some extremely hacky ways to approach this, but they all introduce tradeoffs or other breakages, and I do not see a clean solution with the current API.
@ltierney, do you have any guidance on how to proceed?
It would be good to address the easy ones soon. The dispatch case needs some brainstorming.
Promises are an internal implementation detail that we need to be able to change or even get rid of. That is why working with them in package C code is not and never was supported. The approach taken in S7 not only uses promises at the C level, it alse exposes them at the R level; for example:
There may still be some places this sort of thing happens in base code as well, but we are trying to get rid of those.
For thinking about how to proceed it might be useful to mock up a dipatcher in R, something like
S7_disp<-function() {
## find the methodgen<- sys.function(-1L)
env<- parent.frame()
obj<- get(gen@dispatch_args, env) ## assumes only onemth<- method(gen, object=obj)
## destructively fix up the call environment if necessary## (not impllemented here)## evaluate the method body in the fixed-up environment
eval(body(mth), env)
}
A tool for rematching the call environment based on the method formals, basically moving some entries from the ... of the generic call to bindings for method arguments, and replacing missing arguments in the generic call by delayed evaluations of default expressions in the method.
Something that does the argument matching and body evaluation in one step.
Some notes:
The call stack will look different with this sort of approach than it does now, but that may not be a bad thing.
This needs figuring out what happens/should happen when isdebugged() is true for the generic and/or the method.
It might make sense to use the Exec/Tailcall mechanism.
Given that lazy argument evaluation is an ingrained feature of the language, despite promises themselves being an implementation detail, could we provide an abstraction that allows for argument forwarding without exposing promise objects to packages? It seems like something any functional OOP framework would want, and there are likely other use cases.
Finding the right abstraction is what I am suggesting we need to think about. I don't believe argument forwarding is a well-defined concept, but if it is concept we can express without resorting to implementation details the we should be able to make it happen.
That said, I'm not sure things are optimal in the current way S7 handles dispatch, so this might be a good tome to re-examine that. Two places where S7 differs from S3 are the call stack seen in a method (one more frame in S7 than S3) and how debugging is handled (in S3 calling debug() on a generic causes the debugger to be entered when evaluating the method body; in S7 that is not the case).
In R calling a closure involves basically these steps:
matching the arguments and creating an environment with delayed bindings
establishing a return/on.exit/debugging context
calling internal eval() on the body with the environment in the context
For method dispatch you have to redo some of the matching and then eval() the method body. There are some choices:
reuse and modify the top environment frame of the generic call, or create a new frame with the same parent
reuse the context you already have from the generic call, or establish a new one
There are arguments to be made for each choice, and probably for other choices . S3 is somewhat constrained by its way of handling NextMethod. I don't know at this point how this works in S7.
I think it will take some time to sort this out, more than we have before R 4.6.0 goes into freeze. I'll try to come up with a bridging solution that allows the current S7 to continue to work, but doesn't kick this can too far down the road.
Thanks so much for these thoughts and accommodating S7, @ltierney! It sounds like it would be worth chatting about this in the near future, either virtually or at useR!.
I may be missing something, but maybe you are making this more complicated than it needs to be. It may not even be necessary of have the S7_dispatch() function.
It seems that for the body of a generic function with dipatch_args = "x" all you need is
For a generic with dispatch_args = c("x", "y") the generic function would look like this:
function(x, y, ...) S7::method(sys.function(), object = list(x, y))(x, y, ...)
With this approach the standard evaluation mechanism takes care of all the things you are doing manually in the implementation of S7_dispatch(), and there is no need for that function.
If you do want to have S7_dispatch(), maybe to support existing saved generics, you could create the body call with some thing like:
This "works" because your check for S7_dispatch in the fun argument doesn't check that it is package-qualified 😊
The call passed to eval() will be the same for every call to the generic. So rather than compute it every time it could be computed the first same and cached, maybe using a weak hash table.
A version of new_generic that uses the first approach without S7_dispatch() might look like:
new_generic <- function(name, dispatch_args, fun = NULL) {
stopifnot(is.character(name) && length(name) == 1)
stopifnot(is.character(dispatch_args) && length(dispatch_args) >= 1)
stopifnot(is.null(fun)) ## not supported yet
## build the source code
args <- paste(dispatch_args, collapse = ", ")
if (length(dispatch_args) == 1)
obform <- dispatch_args
else
obform <- sprintf("list(%s)", args)
template <- "function(%s, ...) S7::method(sys.function(), object = %s)(%s, ...)"
text <- sprintf(template, args, obform, args)
## create the closure
gen <- eval(parse(text = text)[[1]], parent.frame())
## cheat to use S7::new_generic to get the attributes
attributes(gen) <- attributes(S7::new_generic(name, dispatch_args))
gen
}
I forked the S7 repo and modified it to use a pure R implementation of dispatch. The result passes all checks except two on substitute(), and one on class_missing dispatch. Performance isn't horrible as long as the expression S7_dispatch() has to evaluate is cached (I put have new_generic() put it in a property). Since thisis pure R code calling R functions lazy evaluation, no multiple evaluation, and so on all automatically work as expected. I used R 4.5.2; so
it should be possble to replicate any of this in C using the R 4.5.x C API.
For the class_missing issue released S7 throws an error in this setting:
library(S7)
foo <- new_generic("foo", "x")
method(foo, class_missing) <- function(x) missing(x)
(function(x) foo(x))() ## ERROR in released S7
## Error in (function(x) foo(x))() :
## argument "x" is missing, with no default
S3 does as well:
bar <- function(x) UseMethod("bar")
bar.default <- function(x) missing(x)
(function(x) bar(x))() ## ERROR in released S7
## Error in (function(x) bar(x))() :
## argument "x" is missing, with no default
Regular functions do not:
baz <- function(x) missing(x)
(function(x) baz(x))() ## ERROR in released S7
## [1] TRUE
The pure R dispatch version of S7 behaves luke regular funcitons:
On handling substitute(), for regular R functions we have:
g <- function(x, y) substitute(x)
(function(x) g(x))(a + b)
## x
It might be nice if substitute() followed the bindings out to the original expression, but that isn't what happens.
There are two ways I can see to get the call to g() to return the original expression for its argument. The first is through a ... argument:
(function(...) g(...))(a + b)
## a + b
The second option is to evaluate the body of g in the call environment:
(function(x) eval(body(g)))(a + b)
## a + b
To use the first approach we would need to be able to do somehting like this:
f1 <- function(x, ..., z) {
toDots(x, ..., z) ## move x, z bindings from environment() into ...
g(...)
}
toDots is probably not so hard to implement and make available at C (and maybe R) level. This would probably remain closest to the current implementation in term of stack structure and the like.
For the second approach we would need
f2 <- function(x, ..., z) {
rematchArgs(formals(g)) ## fix up environment() for a call to g
eval(body(g))
}
rematchArgs to match arguments in the generic ... to additinal arguments in the method signature is probably messier. This would also represent a bigger change from the way things eork now.
The toDots() function seems the most interesting to me (though it does make me wonder whether we ultimately need a slightly broader API for stateful manipulation of ..., including adding/removing entries and addressing them by position as well as by name).
I'd like to avoid inserting any frames from eval(body(method)) into the call stack.
Perhaps the generic can stay as it is today:
gen<-function(x, y) {
S7_dispatch()
}
and S7_dispatch() would look something like:
S7_dispatch<-function() {
method<- find_method() # evaluates `x` and `y` in parentenvir<- parent.frame()
# insert args at position, preserving promise state,# so `substitute()` and `missing()` work as expected in methods.# (creates `...` if it doesn't already exist)
eval(quote(toDots(x=1, y=2)), envir)
# reuse the generic frame
Exec(quote(method(...)), envir)
}
Unless I'm missing something, Tailcall() doesn't seem like it would help here, since it can only reuse the current frame, not modify or reuse the parent frame.
We'll still want the actual dispatch and method lookup in C for speed. If I recall correctly, we started with a pure R implementation early on and moved to C for speed, and to support substitute() and missing().
The missing() example you posted seems like a bug that we should open as a separate issue.
On Mon, 6 Apr 2026, Tomasz Kalinowski wrote:
...
The missing() example you posted seems like a bug that we should open as a
separate issue.
Another one you might want to consider separately is what `parent.frame()` returns in a method:
```R
library(S7)
foo <- new_generic("foo", "x")
method(foo, class_any) <- function(x) parent.frame()
bar <- function(x) UseMethod("bar")
bar.default <- function(x) parent.frame()
foo(1)
## <environment: 0x55c36a60af28>
bar(1)
## <environment: R_GlobalEnv>
```
@ltierney, the April 9th CRAN deadline is rapidly approaching. It seems we might need an extension, or an interim solution for removing the last Rf_findVarInFrame call in the package, or we release the package with a breaking change. How do you think we should proceed?
As I think about it, rematchArgs() is also very interesting, perhaps the better option.
I have a version of R_UnmatchArgs(SEXP forms, SEXP env) that moves all formals into the .... A version of S7 that uses this to pass arguments via ... to the method passes all tests except the missing arg one I think we agree should fail. Nevertheless, this doesn't feel right as something to add the the API. But maybe I need to think a bit more.
Another option to explore is to factor out and make available the method call part of the S3 implementation. It looks like that is doable, but needs some thinking through to provide the flexibility to handle both S3 and S7 dispatch reasonably cleanly.
@ltierney, the April 9th CRAN deadline is rapidly approaching. It seems we might need an extension, or an interim solution for removing the last Rf_findVarInFrame call in the package, or we release the package with a breaking change. How do you think we should proceed?
S7 no longer signals a warning for using Rf_findVarInFrame so I suspect CRAN will relent. The plan is to remove the declaration for this and other non-API functions for R 4.6.0, with a mechanism to temporarily re-enable them if necessary. If it becomes necessary you as maintainer will be informed how to proceed.
Reading the discussion, this made me think of a syntax I had thought about while working on tidyeval. I think it could be useful here.
One general problem about wrapping NSE functions that use substitute() to provide context on passed expressions, is that there is no easy way to pass a value along its original expression. Take for example plot() which captures expressions to use as default axis labels. If you try to wrap it naively, you'll get an unhelpful label in the plot:
# Passing `x`: the plot label is captured as `x` instead of `1:10`my_plot<-function(x) plot(x)
my_plot(1:10)
There is currently no way to pass both the original expression and make sure it's evaluated in the correct environment. If you try:
The expression is captured correctly, but its evaluation resolves inside my_plot() instead of the caller.
local({
foo<-1
my_plot(foo:10)
})
#> Error in eval(bquote(plot(.(substitute(x))))) : object 'foo' not found
Also note the complicated call you get in the error message, which is unergonomic.
rlang/tidyeval provide solutions for this problem by passing quosures, but there is currently no way to wrap base R NSE functions in such a way that expression capture and argument evaluation both work correctly.
To solve this, we need a similar mechanism to ..., as Luke noted, but for arguments. We could reuse the same ... notation to signal forwarding of arguments in this way:
# Forwarding `x`: the plot label is now correctly captured by `substitue()`my_plot<-function(x) plot(...(x))
my_plot(1:10)
I believe this mechanism would also solve the forwarding issue for the S7 case:
gen<-function(x, y, ...) {
method<- find_method(class_of(x))
method(...(x), ...(y), ...)
}
I have a version of R_UnmatchArgs(SEXP forms, SEXP env) that moves all formals into the .... A version of S7 that uses this to pass arguments via ... to the method passes all tests except the missing arg one I think we agree should fail. Nevertheless, this doesn't feel right as something to add the the API. But maybe I need to think a bit more.
I added an experimental version of R_UnmatchArgs in R-devel (just the code, not in any header). The use-R_UnmatchArgs branch in my fork uses this. Still doesn't feel right but, gives us something to experiment with.
One difference between UseMethod() and S7_dispatch() is that UseMethod() does not return to the generic. It conceptually does a tail call to the method, which then returns to the generic's caller. So code after the 'UseMethod()` call is ignored:
None of the current test code depends on S7_dispatch() returning normally.
If making the call to S7_dispatch() into a tailcall is OK, then a natural resolution would be to modify Tailcall() to forward arguments in the way needed for S7 and to re-use the current context to get
the desired behavior of parent.frame().
IMO we don't want a tail-call here. IMO the S3 behaviour is really confusing and is not a feature we want to replicate.
I'm not buying that. The number of S3 users who are aware of this is likely vanishingly small. Documentation can address any concern those folks have; documenting this is now straightforward as we have the concept of a tail call.
We want non-standard handing of missing arguments, non-standard handling of deferred binding expressions, and non-standard handling of parent.frame(). All of these make sense in the context of a tail call. I'm not sure i can go along with, or get others in R-core to go along with, adding those as S7-specific bells-and-whistles for regular closure calls.
I think expanding Tailcall() to forward arguments is an elegant solution!
to re-use the current context to get the desired behavior of parent.frame().
If I understand correctly, since Tailcall() would be called from inside S7_dispatch(), not directly from the user-written generic body, it would also need some ability to work across frames. Maybe that means it could trigger a tail call in another frame, not just the calling frame. Or maybe Tailcall() could reach up and rebind arguments from a parent.frame() into the frame where it is called.
I also think the S3 behavior is generally confusing to newcomers whenever the body of the generic is not comprised solely of UseMethod(); I still have to look up the details any time I'm tempted to do anything non-trivial in the generic. Similarly, I think the same confusion will exist if users hand-write S7 generics with custom code before or after S7_dispatch().
Either way, I think it is worth being explicit about what this rules out: if we move to reusing the generic frame via Tailcall(), then user code after S7_dispatch() will not run. We already hint that S7_dispatch() is usually the last call in the generics vignette, and we would need to upgrade "usually" to "must":
A custom fun must always include a call to S7_dispatch(), which will usually be the last call.
What are some compelling use cases for a generic author wanting to run code after a method returns? The main ones I can think of are validating, wrapping and/or normalizing the return value, and tracing/instrumentation.
For example, something like this would no longer be possible:
foo<- new_generic("foo", "x", function(x, y, ...) {
stopifnot(
inherits(x, FooInputX),
inherits(y, FooInputY)
)
out<- S7_dispatch()
stopifnot(inherits(out, FooOutput))
out
})
Looking at the snippet above, I wonder whether the tail-call behavior could be an implementation detail contained inside S7_dispatch(). That is, S7_dispatch() could call Tailcall() to reuse the S7_dispatch() frame, with arguments forwarded or bound from the parent.frame(), while the body of the generic would still behaves like a regular function in user code.
With that approach, S7_dispatch() would present as a regular function to generic authors, and without footguns if users started doing things in the generic body such as: bound symbols in the generic being ignored or interfering with method evaluation, or expressions not being run. This approach would unfortunately mean that every generic call introduces two frames on the call stack, but perhaps that is a reasonable tradeoff if we want to support authors writing custom generic functions.
I feel quite strongly about this behaviour; it catches me out frequently and is a personal major frustrations with S3. Maybe there's no other way and I'll just have to accept this, but we did previously have a solution that I liked.
On Mon, 27 Apr 2026, Hadley Wickham wrote:
[4196?s=20&v=4] hadley left a comment (RConsortium/S7#592)
I feel quite strongly about this behaviour; it catches me out frequently and
is a personal major frustrations with S3. Maybe there's no other way and
I'll just have to accept this, but we did previously have a solution that I
liked.
A "solution" that depends on using something that was not and never
has been part of the API was not a solution and never should have
happened. That is why we are here now. More later after teaching.
I've spent some time with this thread, and while I don't have a solution, I now at least understand what the heart of the problem is. What I want from method dispatch is twofold:
It should feel like a real function call, i.e. it should introduce a frame on the call stack.
substitute() should still work (at least on the non-dispatch arguments).
I now realize that these two goals are mutually exclusive with the current C API:
If you make it a real function call, then you have to evaluate the arguments.
If you want to keep them unevaluated, you have to combine the call stack (with Tailcall() or similar).
@ltierney do I interpret your comments correctly that you're willing to consider a way to forward unevaluated arguments, if we can figure out the right API?
@ltierney did you see Lionel’s proposal earlier in the thread? I also missed it but it includes a complete implementation sketch: r-devel/r-svn#250. Obviously anything here could be changed, but it’s convenient to look at a complete proposal.
Activity
t-kalinowski commentedon Mar 20, 2026
Most of the usage sites in S7 are trivial to update, but there is one for which there is no clear path forward: method dispatch.
With the new C API, some existing S7 behavior is hard to preserve.
Today, S7 dispatch has the following behavior:
missing()works as expected in methodssubstitute()works as expected in methods, including for dispatch argumentsS7 is able to provide this behavior by forwarding the already-evaluated promise object from the generic call to the method call.
With the new public package C API, this no longer appears to be possible. There are many entry points for binding inspection and creation, but there seems to be no way to forward an existing promise.
I can think of some extremely hacky ways to approach this, but they all introduce tradeoffs or other breakages, and I do not see a clean solution with the current API.
@ltierney, do you have any guidance on how to proceed?
ltierney commentedon Mar 24, 2026
It would be good to address the easy ones soon. The dispatch case needs some brainstorming.
Promises are an internal implementation detail that we need to be able to change or even get rid of. That is why working with them in package C code is not and never was supported. The approach taken in S7 not only uses promises at the C level, it alse exposes them at the R level; for example:
There may still be some places this sort of thing happens in base code as well, but we are trying to get rid of those.
For thinking about how to proceed it might be useful to mock up a dipatcher in R, something like
A fake generic using this:
This produces:
What is needed to make this work fully is one of:
...of the generic call to bindings for method arguments, and replacing missing arguments in the generic call by delayed evaluations of default expressions in the method.Some notes:
isdebugged()is true for the generic and/or the method.Exec/Tailcallmechanism.lawremi commentedon Mar 24, 2026
Thanks for that idea, Luke.
Given that lazy argument evaluation is an ingrained feature of the language, despite promises themselves being an implementation detail, could we provide an abstraction that allows for argument forwarding without exposing promise objects to packages? It seems like something any functional OOP framework would want, and there are likely other use cases.
ltierney commentedon Mar 24, 2026
Finding the right abstraction is what I am suggesting we need to think about. I don't believe argument forwarding is a well-defined concept, but if it is concept we can express without resorting to implementation details the we should be able to make it happen.
That said, I'm not sure things are optimal in the current way S7 handles dispatch, so this might be a good tome to re-examine that. Two places where S7 differs from S3 are the call stack seen in a method (one more frame in S7 than S3) and how debugging is handled (in S3 calling
debug()on a generic causes the debugger to be entered when evaluating the method body; in S7 that is not the case).In R calling a closure involves basically these steps:
on.exit/debugging contexteval()on the body with the environment in the contextFor method dispatch you have to redo some of the matching and then
eval()the method body. There are some choices:There are arguments to be made for each choice, and probably for other choices . S3 is somewhat constrained by its way of handling
NextMethod. I don't know at this point how this works in S7.I think it will take some time to sort this out, more than we have before R 4.6.0 goes into freeze. I'll try to come up with a bridging solution that allows the current S7 to continue to work, but doesn't kick this can too far down the road.
lawremi commentedon Mar 25, 2026
Thanks so much for these thoughts and accommodating S7, @ltierney! It sounds like it would be worth chatting about this in the near future, either virtually or at useR!.
ltierney commentedon Mar 30, 2026
I may be missing something, but maybe you are making this more complicated than it needs to be. It may not even be necessary of have the
S7_dispatch()function.It seems that for the body of a generic function with
dipatch_args = "x"all you need isSo this seems to work:
[Using
S7::so this works withoutS7attached.]For a generic with
dispatch_args = c("x", "y")the generic function would look like this:With this approach the standard evaluation mechanism takes care of all the things you are doing manually in the implementation of
S7_dispatch(), and there is no need for that function.If you do want to have
S7_dispatch(), maybe to support existing saved generics, you could create the body call with some thing like:Then
S7_dispatchcould be defined asTry it out:
This "works" because your check for
S7_dispatchin thefunargument doesn't check that it is package-qualified 😊The call passed to
eval()will be the same for every call to the generic. So rather than compute it every time it could be computed the first same and cached, maybe using a weak hash table.A version of
new_genericthat uses the first approach withoutS7_dispatch()might look like:A check:
ltierney commentedon Apr 4, 2026
I forked the S7 repo and modified it to use a pure R implementation of dispatch. The result passes all checks except two on
substitute(), and one onclass_missingdispatch. Performance isn't horrible as long as the expressionS7_dispatch()has to evaluate is cached (I put havenew_generic()put it in a property). Since thisis pure R code calling R functions lazy evaluation, no multiple evaluation, and so on all automatically work as expected. I used R 4.5.2; soit should be possble to replicate any of this in C using the R 4.5.x C API.
For the
class_missingissue released S7 throws an error in this setting:S3 does as well:
Regular functions do not:
The pure R dispatch version of S7 behaves luke regular funcitons:
This seems like an improvement to me.
Getting substitute to work the way we want would seem to require a little bit of API support.
ltierney commentedon Apr 4, 2026
On handling
substitute(), for regular R functions we have:It might be nice if
substitute()followed the bindings out to the original expression, but that isn't what happens.There are two ways I can see to get the call to
g()to return the original expression for its argument. The first is through a...argument:The second option is to evaluate the body of
gin the call environment:To use the first approach we would need to be able to do somehting like this:
toDotsis probably not so hard to implement and make available at C (and maybe R) level. This would probably remain closest to the current implementation in term of stack structure and the like.For the second approach we would need
rematchArgsto match arguments in the generic...to additinal arguments in the method signature is probably messier. This would also represent a bigger change from the way things eork now.t-kalinowski commentedon Apr 6, 2026
Thanks Luke.
The
toDots()function seems the most interesting to me (though it does make me wonder whether we ultimately need a slightly broader API for stateful manipulation of..., including adding/removing entries and addressing them by position as well as by name).I'd like to avoid inserting any frames from
eval(body(method))into the call stack.Perhaps the generic can stay as it is today:
and
S7_dispatch()would look something like:Unless I'm missing something,
Tailcall()doesn't seem like it would help here, since it can only reuse the current frame, not modify or reuse the parent frame.We'll still want the actual dispatch and method lookup in C for speed. If I recall correctly, we started with a pure R implementation early on and moved to C for speed, and to support
substitute()andmissing().The
missing()example you posted seems like a bug that we should open as a separate issue.ltierney commentedon Apr 6, 2026
t-kalinowski commentedon Apr 6, 2026
As I think about it,
rematchArgs()is also very interesting, perhaps the better option.t-kalinowski commentedon Apr 7, 2026
@ltierney, the April 9th CRAN deadline is rapidly approaching. It seems we might need an extension, or an interim solution for removing the last
Rf_findVarInFramecall in the package, or we release the package with a breaking change. How do you think we should proceed?ltierney commentedon Apr 7, 2026
I have a version of
R_UnmatchArgs(SEXP forms, SEXP env)that moves all formals into the.... A version of S7 that uses this to pass arguments via...to the method passes all tests except the missing arg one I think we agree should fail. Nevertheless, this doesn't feel right as something to add the the API. But maybe I need to think a bit more.Another option to explore is to factor out and make available the method call part of the S3 implementation. It looks like that is doable, but needs some thinking through to provide the flexibility to handle both S3 and S7 dispatch reasonably cleanly.
ltierney commentedon Apr 7, 2026
S7 no longer signals a warning for using
Rf_findVarInFrameso I suspect CRAN will relent. The plan is to remove the declaration for this and other non-API functions for R 4.6.0, with a mechanism to temporarily re-enable them if necessary. If it becomes necessary you as maintainer will be informed how to proceed.lionel- commentedon Apr 8, 2026
Reading the discussion, this made me think of a syntax I had thought about while working on tidyeval. I think it could be useful here.
One general problem about wrapping NSE functions that use
substitute()to provide context on passed expressions, is that there is no easy way to pass a value along its original expression. Take for exampleplot()which captures expressions to use as default axis labels. If you try to wrap it naively, you'll get an unhelpful label in the plot:There is currently no way to pass both the original expression and make sure it's evaluated in the correct environment. If you try:
The expression is captured correctly, but its evaluation resolves inside
my_plot()instead of the caller.local({ foo <- 1 my_plot(foo:10) }) #> Error in eval(bquote(plot(.(substitute(x))))) : object 'foo' not foundAlso note the complicated call you get in the error message, which is unergonomic.
rlang/tidyeval provide solutions for this problem by passing quosures, but there is currently no way to wrap base R NSE functions in such a way that expression capture and argument evaluation both work correctly.
To solve this, we need a similar mechanism to
..., as Luke noted, but for arguments. We could reuse the same...notation to signal forwarding of arguments in this way:I believe this mechanism would also solve the forwarding issue for the S7 case:
I've put together a proof of concept at r-devel/r-svn#250
You can get the patch from https://github.com/r-devel/r-svn/pull/250.diff
ltierney commentedon Apr 13, 2026
I added an experimental version of
R_UnmatchArgsin R-devel (just the code, not in any header). The use-R_UnmatchArgs branch in my fork uses this. Still doesn't feel right but, gives us something to experiment with.ltierney commentedon Apr 25, 2026
One difference between
UseMethod()andS7_dispatch()is thatUseMethod()does not return to the generic. It conceptually does a tail call to the method, which then returns to the generic's caller. So code after the 'UseMethod()` call is ignored:In contrast, for S7:
None of the current test code depends on
S7_dispatch()returning normally.If making the call to
S7_dispatch()into a tailcall is OK, then a natural resolution would be to modifyTailcall()to forward arguments in the way needed for S7 and to re-use the current context to getthe desired behavior of
parent.frame().Thoughts?
lawremi commentedon Apr 25, 2026
Sounds like the right direction to me.
hadley commentedon Apr 26, 2026
IMO we don't want a tail-call here. IMO the S3 behaviour is really confusing and is not a feature we want to replicate.
ltierney commentedon Apr 26, 2026
I'm not buying that. The number of S3 users who are aware of this is likely vanishingly small. Documentation can address any concern those folks have; documenting this is now straightforward as we have the concept of a tail call.
We want non-standard handing of missing arguments, non-standard handling of deferred binding expressions, and non-standard handling of
parent.frame(). All of these make sense in the context of a tail call. I'm not sure i can go along with, or get others in R-core to go along with, adding those as S7-specific bells-and-whistles for regular closure calls.t-kalinowski commentedon Apr 27, 2026
I think expanding
Tailcall()to forward arguments is an elegant solution!If I understand correctly, since
Tailcall()would be called from insideS7_dispatch(), not directly from the user-written generic body, it would also need some ability to work across frames. Maybe that means it could trigger a tail call in another frame, not just the calling frame. Or maybeTailcall()could reach up and rebind arguments from aparent.frame()into the frame where it is called.I also think the S3 behavior is generally confusing to newcomers whenever the body of the generic is not comprised solely of
UseMethod(); I still have to look up the details any time I'm tempted to do anything non-trivial in the generic. Similarly, I think the same confusion will exist if users hand-write S7 generics with custom code before or afterS7_dispatch().Either way, I think it is worth being explicit about what this rules out: if we move to reusing the generic frame via
Tailcall(), then user code afterS7_dispatch()will not run. We already hint thatS7_dispatch()is usually the last call in the generics vignette, and we would need to upgrade "usually" to "must":What are some compelling use cases for a generic author wanting to run code after a method returns? The main ones I can think of are validating, wrapping and/or normalizing the return value, and tracing/instrumentation.
For example, something like this would no longer be possible:
Looking at the snippet above, I wonder whether the tail-call behavior could be an implementation detail contained inside
S7_dispatch(). That is,S7_dispatch()could callTailcall()to reuse theS7_dispatch()frame, with arguments forwarded or bound from theparent.frame(), while the body of the generic would still behaves like a regular function in user code.With that approach,
S7_dispatch()would present as a regular function to generic authors, and without footguns if users started doing things in the generic body such as: bound symbols in the generic being ignored or interfering with method evaluation, or expressions not being run. This approach would unfortunately mean that every generic call introduces two frames on the call stack, but perhaps that is a reasonable tradeoff if we want to support authors writing custom generic functions.hadley commentedon Apr 27, 2026
I feel quite strongly about this behaviour; it catches me out frequently and is a personal major frustrations with S3. Maybe there's no other way and I'll just have to accept this, but we did previously have a solution that I liked.
ltierney commentedon Apr 27, 2026
hadley commentedon Jun 8, 2026
I've spent some time with this thread, and while I don't have a solution, I now at least understand what the heart of the problem is. What I want from method dispatch is twofold:
substitute()should still work (at least on the non-dispatch arguments).I now realize that these two goals are mutually exclusive with the current C API:
Tailcall()or similar).@ltierney do I interpret your comments correctly that you're willing to consider a way to forward unevaluated arguments, if we can figure out the right API?
hadley commentedon Jun 9, 2026
@ltierney did you see Lionel’s proposal earlier in the thread? I also missed it but it includes a complete implementation sketch: r-devel/r-svn#250. Obviously anything here could be changed, but it’s convenient to look at a complete proposal.