CassetteOverlay.jl icon indicating copy to clipboard operation
CassetteOverlay.jl copied to clipboard

Overloading all functions

Open MilesCranmer opened this issue 11 months ago • 3 comments

@aviatesk

I'm trying to move BorrowChecker.jl to use this over Cassette.jl but am having some difficulties figuring out how to do generic overlay passes where I overlay behavior on all functions that get hit.

Here's my current attempt, from studying the code:

using CassetteOverlay
using CassetteOverlay: CassetteOverlayGenerator
using Test

@MethodTable AllMethods

pass = @overlaypass AllMethods
# ^Just to initialize the object

_sin(x) = sin(x)

# Now, we attempt to do a generic override of it:
@eval function (p::typeof(pass))(f, args...)
    $(Expr(:meta, :generated, CassetteOverlayGenerator(:pass, :fargs)))
    println("Hello from ", f, " with args: ", args)
    return f(args...)
end

pass(() -> _sin(0.5));

This prints:

Hello from #2 with args: ()

So it seems this captures the first function (the closure), but the f(args...) does not hit the same overlay pass again.

Another thing I tried was

@overlay AllMethods (f::Function)(args...) = ...

but faced similar issues.

How can I do this? I basically want to overload all functions matching a specific signature.

MilesCranmer avatar Jan 12 '25 05:01 MilesCranmer

CassetteOverlay rewrites all function calls (via the mechanism implemented in CassetteBase.jl) but the rewriting mechanism relies on method matching against the overlay table. So it's probably not suitable for what you want to achieve.

It might be possible to implement something similar to what Cassette.jl does with CassetteBase.jl.

aviatesk avatar Jan 19 '25 04:01 aviatesk

Thanks, how would I use CassetteBase for that?

MilesCranmer avatar Jan 20 '25 07:01 MilesCranmer

@aviatesk this came up in https://github.com/chalk-lab/Mooncake.jl/issues/648. Do you think you could offer any pointers at how we might use CassetteBase to overdub a function within a context?

MilesCranmer avatar Jul 10 '25 12:07 MilesCranmer