Say I want to write a macro
@foo f(a,b,c)
that captures and modifies a function call f(a,b,c)
. Is there any way to get the types of the arguments a
,b
, etc. within the macro?
Within the macro they're all just Symbol
s within the captured Expr, so I can't just use typeof
directly...
The only way I can think of is something along the lines of
macro bad_form(expr)
argtypes = ntuple(i->typeof(eval(expr.args[i+1])), length(expr.args)-1)
:($argtypes)
end
julia> a, b, c = 1, 2.0, 3//4
(1, 2.0, 3//4)
julia> @bad_form f(a,b,c)
(Int64, Float64, Rational{Int64})
which works in global scope but is a massive code smell AFAIU
N.b. I can't do something like
macro good_form_but_not_helpful(expr)
:(typeof($(expr.args[2])))
end
because I need access to the types within the body of the macro
Don't the @code_*
macros do exactly this? How do they work? Do they use the generated function suggested above? I'm away from computer, can't easily check myself.
Note that @ccall
shouldn't infer the type of the arguments, you can pass a value with a different type as long as it can be converted to the actual type required by the library
Ok, I browsed a bit the repo on the phone and found it: https://github.com/JuliaLang/julia/blob/bd8dbc388c7b89f68838ca554ed7ba91740cce75/stdlib/InteractiveUtils/src/macros.jl#L34
I don't see any generated function anywhere
Oh woah!
Brenhin Keller has marked this topic as unresolved.
Mosè Giordano said:
Don't the
@code_*
macros do exactly this? How do they work? Do they use the generated function suggested above? I'm away from computer, can't easily check myself.Note that
@ccall
shouldn't infer the type of the arguments, you can pass a value with a different type as long as it can be converted to the actual type required by the library
The @code_*
macros do not do anything with the type in their body.
Last updated: Oct 02 2023 at 04:34 UTC