Last active
February 13, 2023 09:17
-
-
Save skyleaworlder/87e3cadf37e76db58aa3ca304eb52d1e to your computer and use it in GitHub Desktop.
One way to hook function elegantly using IRTools.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just a simple example, still need polished more.