I have made a minimal working example of a macro that returns a list of handles for the functions it receives as input. Obviously this can be achieved more easily without a macro, but let us assume there is a more complicated task where I need a macro to be able to return working function handles in some data structure. The handles do not have to work inside the macro itself, but they shall point to the respective function in the caller namespace after evaluation.
Macro demo
using MacroTools
macro fun_demo(ex)
return [eval(x) for x in rmlines(ex).args]
end
Example use
f(x)=x
g(x)=x²
@fun_demo begin
f
g
end
Example output
2-element Vector{Function}:
f (generic function with 1 method)
g (generic function with 1 method)
The question
The problem with the implementation is, that (a) you are not supposed to use eval inside a macro and (of more practical importance) (b) it will not work anymore if the macro is inside a module because the functions are not known inside the module.
Thus my question is: How would you achieve the same outcome as above with cleaner code and most importantly in a way that works from within a module?
Some ideas / things i have tried
I have been playing with “esc” without any working results. I could also imagine that instead of returning the vector of function handles directly, you need to return an expression that will generate the vector of function handles once it is returned & evaluated at the call site - but I do not know how to pull it off. A simple “solution” would also be to just return the symbols and then have some external function “instantiate_function_handles” that you have to call on the resulting vector… But this also seems unelegant and requires the user of the macro to call a helper function on top of the macro.