Is there a way to convert a function to expressions in Julia?

Viewed 71

I am trying to create a macro which is capable of (probably recursively) turn a function into expressions so as to reach the operations applied within that function.

As a visualization:

function sampleFunc(x)
     println(x)
     y = 2x
     return 2y* x
end

@macroIcannotImplement sampleFunc(x)

Desired Output:

quote
     println(x)
     y = 2x
     return 2y* x    
end

Does Julia support such an extraction or should I start searching for other ways?

1 Answers

Yes, use CodeTracking:

julia> using Revise, CodeTracking

julia> function sampleFunc(x)
            println(x)
            y = 2x
            return 2y* x
       end
sampleFunc (generic function with 1 method)

julia> @code_expr sampleFunc(3)
:(function sampleFunc(x)
      #= REPL[2]:1 =#
      #= REPL[2]:2 =#
      println(x)
      #= REPL[2]:3 =#
      y = 2x
      #= REPL[2]:4 =#
      return (2y) * x
  end)
Related