有什么方法可以在Julia中“扩展”生成的函数?
有没有办法在不评估它的情况下获得 Julia 生成的函数创建的表达式,就像@macroexpand生成的函数一样?
例如,假设我们有
@generated function blah(x)
if x <:Integer
:(x)
else
:(x * 2)
end
end
然后:
julia> blah(1), blah(2.)
(1, 4.0)
我想要的是一个宏,它的工作原理类似于:
julia> @generatedexpand blah(2.)
:(x * 2)
回答
你可以试试@code_lowered:
julia> @code_lowered blah(4)
CodeInfo(
@ REPL[1]:1 within `blah'
? @ REPL[1]:1 within `macro expansion'
1 ?? return x
?
)
julia> @code_lowered blah(4.5)
CodeInfo(
@ REPL[1]:1 within `blah'
? @ REPL[1]:1 within `macro expansion'
1 ?? %1 = x * 2
???? return %1
?
)
或者你可以使用code_lowered函数:
julia> code_lowered(blah,(Int,))[1].code
1-element Vector{Any}:
:(return _2)
julia> code_lowered(blah,(Float64,))[1].code
2-element Vector{Any}:
:(_2 * 2)
:(return %1)