From m|ch@e|ch|r|co4 @end|ng |rom gm@||@com  Tue Jun  7 08:09:29 2022
From: m|ch@e|ch|r|co4 @end|ng |rom gm@||@com (Michael Chirico)
Date: Mon, 6 Jun 2022 23:09:29 -0700
Subject: [Rd] trace() an S3-classed function in .GlobalEnv
Message-ID: <CAPRVBcwOh0zst8mGTCfYXK6OXdGViGHUOiV5A8NhV4Lh6eo2gQ@mail.gmail.com>

Consider:

foo <- function() {
  invisible(1 + 1)
}
trace(foo, quote(message("traced")), print=FALSE)
foo()
# traced

But with a minimal change:

class(foo) <- "bar"
trace(foo, quote(message("traced")), print=FALSE)
# Constructing traceable class ?barWithTrace?
# Error in .classEnv(className) :
#   unable to find an environment containing class ?bar?

I don't see anything like this mentioned in ?trace (nor does a Google
search turn up more than a handful of references to this error),
and from trying to debug what trace() is doing, we arrive to the error line[1]:

.makeTraceClass(traceClass, class(original))  #
methods:::.makeTraceClass("barWithTrace", "bar")

I don't quite follow what's going on here, but it looks like trace()
is trying to determine an S4 class definition for "bar", but isS4(bar)
is FALSE.

I can (apparently -- not sure if there are as yet-unseen downstream
consequences) work around the issue by unsetting the class, tracing,
then re-setting:

class(foo) <- NULL
trace(foo, quote(message("traced")), print=FALSE)
class(foo) <- "bar"

But obviously this is a bit clunky. Is this a bug, or am I missing something?

Mike C

[1] https://github.com/r-devel/r-svn/blob/e2a64a4e14adbc4e9e8635eaa8cbd2835ce1d764/src/library/methods/R/trace.R#L240



[Rd] trace() an S3-classed function in .GlobalEnv
Michael Chirico