Get function as expr

My question is the same as Is there a way to get the expression object for a function? , but the old answer does not work in new julia versions.
Lets say you defined method:

function func()
    return 17
end

I know that you ca use @code_lowered func() @code_typed func() @code_llvm func() or @code_native func() to get different represantations of this code. But is there a way to get an Expr? I need a macro/function that takes func() as an argument and returns:

quote
    function func()
        return 17
    end
end

Note: putting an @mymacro in front of function func() is not an option, because it needs to work on existing code.

If the code has no control flow then you can use ModelingToolkit.jl

There is https://github.com/timholy/CodeTracking.jl, but there are many situations where a function simply has no representation as an Expr.

3 Likes

Which functions do not have a representation as an Expr.

Is it possible to use CodeTracking.jl in non interactive scripts?

This:

using InteractiveUtils
using Revise
using CodeTracking

function func()
return 123
end

println(@code_string func())
println(@code_expr func())

outputs:

function func()
    return 123
end
nothing

if I execute it using julia script.jl

In julia, you can generate a function from the IR directly and still have a valid function. Any function generated in that way won’t have an Expr representation. Furthermore, CodeTracking.jl can only be so clever. Most functions generated by macros won’t be recognized or tracked by it.

That seems like a bug, but I don’t know. Perhaps open an issue on the github page.

1 Like