Stream: helpdesk (published)

Topic: Capturing types of variables within a macro


view this post on Zulip Brenhin Keller (Jun 03 2022 at 22:23):

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?

view this post on Zulip Brenhin Keller (Jun 03 2022 at 22:27):

Within the macro they're all just Symbols within the captured Expr, so I can't just use typeof directly...

view this post on Zulip Brenhin Keller (Jun 03 2022 at 22:28):

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

view this post on Zulip Brenhin Keller (Jun 03 2022 at 22:29):

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

view this post on Zulip Brenhin Keller (Jun 03 2022 at 22:33):

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

view this post on Zulip Mosè Giordano (Jun 04 2022 at 01:24):

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

view this post on Zulip Mosè Giordano (Jun 04 2022 at 01:36):

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

view this post on Zulip Mosè Giordano (Jun 04 2022 at 01:39):

I don't see any generated function anywhere

view this post on Zulip Brenhin Keller (Jun 04 2022 at 01:52):

Oh woah!

view this post on Zulip Notification Bot (Jun 04 2022 at 01:52):

Brenhin Keller has marked this topic as unresolved.

view this post on Zulip Mason Protter (Jun 04 2022 at 02:32):

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