Turning Expression into Source Code


#1

Is there a way to turn an expression into valid source code and write it to a file? I’m looking into using ReverseDiffSource, which operates on the AST to produce the expression for reverse mode differentiation, but it uses eval to turn the expression into a function. I want my code to be statically compilable, so I can’t use eval. The traditional way large codes use reverse mode is to generate reverse mode code (using some tool that parses the source code like Tapenade), write it to source files, and then compile the whole thing (regular code + the reverse mode code). I’d like to be able to do this in Julia.


#2

Just calling string on your expression almost works:

ex = quote
    function f(x)
        x^2
    end
    g = x -> x+1
    g(3)
    $(gensym("sda"))
end 
println(string(ex))

There are problems however, e.g. generated symbols. You could clean those up with MacroTools.


#3

Related: