# Turning Expression into Source Code

**URL:** <https://discourse.julialang.org/t/turning-expression-into-source-code/1533>\
**Category:** General Usage\
**Created:** [January 17, 2017, 3:34am UTC](https://discourse.julialang.org/t/turning-expression-into-source-code/1533 "2017-01-17T03:34:48Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![JaredCrean2](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jaredcrean2/32/3574_2.png) [@JaredCrean2](https://discourse.julialang.org/u/JaredCrean2)\
**Post date:** [January 17, 2017, 3:34am UTC](https://discourse.julialang.org/t/turning-expression-into-source-code/1533/1 "2017-01-17T03:34:49Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![jw3126](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jw3126/32/3086_2.png) [@jw3126](https://discourse.julialang.org/u/jw3126)\
**Post date:** [January 17, 2017, 8:27am UTC](https://discourse.julialang.org/t/turning-expression-into-source-code/1533/2 "2017-01-17T08:27:15Z")

</div>

Just calling `string` on your expression almost works:

```julia
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](https://github.com/MikeInnes/MacroTools.jl).

---

<div class="post-metadata">

**Author:** ![mauro3](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mauro3/32/292_2.png) [@mauro3](https://discourse.julialang.org/u/mauro3)\
**Post date:** [January 17, 2017, 8:33am UTC](https://discourse.julialang.org/t/turning-expression-into-source-code/1533/3 "2017-01-17T08:33:48Z")

</div>

Related:  
[https://github.com/JuliaLang/JuliaParser.jl/issues/22](https://github.com/JuliaLang/JuliaParser.jl/issues/22)
