Created attachment 2098 [details]
repeated call of overloaded abs operator fails
As already mentioned in 2012 and 2015 in the following SO threads
overloading individual S4 functions in the group functions Math, Ops or Arith does work on the first time but fails for repeated calls with the error message
object '.Generic' not found
. Though this bug occurs in particular in conjunction with the Matrix package, the unexpected behaviour is attributed to R itself.
PS: This seems to be only a problem when overloading methods outside of a package. Overloading an individual function within a package makes R to look at the right place.
The methods package has two implementations of dispatch: internal and standardGeneric(). The combination of setting a method on a "member" generic and caching leads to the internal mechanism. The internal mechanism does not set .Generic, perhaps for performance reasons. Right now callGeneric() and callNextMethod() rely on the heuristic of introspecting the call to get the generic when .Generic is missing. It would help to get John's opinion on this. Should the internal mechanism just set .Generic as PRIMNAME(op)?
There were many problems with primitive functions. Special treatments were often because there is no generic function, e..g, corresponding to the "generic" slot in the method definition object. I don't remember any details of this particular choice.
In principle, yes it would be sensible to set .Generic, but with primitives weird side effects are common.
Went ahead and made internal dispatch set .Generic.