Skip to content

Instantly share code, notes, and snippets.

@skyleaworlder
Last active February 13, 2023 09:17
Show Gist options
  • Save skyleaworlder/87e3cadf37e76db58aa3ca304eb52d1e to your computer and use it in GitHub Desktop.
Save skyleaworlder/87e3cadf37e76db58aa3ca304eb52d1e to your computer and use it in GitHub Desktop.
One way to hook function elegantly using IRTools.
using IRTools
macro hook(method_call_ex, f_name, args...)
ir = gensym()
f = gensym()
return esc(quote
local $ir = IRTools.@code_ir($method_call_ex)
# first: the original function body
IRTools.pushfirst!($ir, :(println("Hello World!")))
local $f = IRTools.func($ir)
function $f_name($(args...))
# second: the body of new defined function
println("f_name: ", $f_name)
return $f(nothing, $(args...))
end
end)
end
""" normal function """
pow(x, n) = x^n
@hook(pow(1,1), pow, x, n)
println(pow(2, 2))
# f_name: pow
# Hello World!
# 4
""" with args... """
pow(a, b, args...) = a^b
@hook(pow(2,2,2), pow, a, b, args...)
println(pow(2, 4, 2))
# f_name: pow
# Hello World!
# 16
@skyleaworlder
Copy link
Author

Just a simple example, still need polished more.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment