dfdx
November 27, 2018, 8:23pm
#1
Digging through the Julia AST docs I’ve got curious how far we can go with the lowered code representation. In particular:
Can we evaluate CodeInfo
object as a whole?
Can we evaluate each its expression (in .code
field) step by step?
Can we run type inference and/or compile CodeInfo
object into a callable object (e.g. a function)?
I did all of these extensively in Espresso.jl for surface AST, but it has its drawbacks, so I’d like to know what I can do with the lowered version.
3 Likes
Per
July 16, 2019, 2:25pm
#2
I have the same question, and Google gave me this thread and no other answer.
An example from the documentation lead me to try this:
julia> g() = 42
g (generic function with 1 method)
julia> ci = code_typed(g, ())[1][1]
CodeInfo(
1 ─ return 42
)
julia> eval(Expr(:thunk, ci))
42
So it seems I’m able to evaluate a CodeInfo object, but I can’t figure out how to turn one into a function.
Any help would be appreciated.
Per
July 18, 2019, 8:13am
#3
It seems an example of how to turn a CodeInfo object into a function can be found here:
using AbstractTrees
# Replace module in Expr tree
function expr_replace_module(expr, pat::Pair{Module, Module})
expr_replace_module!(deepcopy(expr), pat)
end
function expr_replace_module!(expr, pat::Pair{Module, Module})
treemap!(PreOrderDFS(expr)) do node
if node isa GlobalRef && node.mod == pat.first
GlobalRef(pat.second, node.name)
else
node
end
end
end
# Replace Module in CodeInfo
function code_replace_module(code::Core.CodeInfo, pat::Pair{Module, Module})
code2 = copy(code) # I guess this is sufficient...
This file has been truncated. show original
2 Likes
Per
July 19, 2019, 8:07am
#4
Based on the above-mentioned code by @NHDaly , I wrote a small package that can be used to turn CodeInfo
objects back into functions. (Still unregistered, with very little documentation and testing.)
4 Likes
dfdx
July 19, 2019, 8:14am
#5
Wow, looks great! Thanks for your effort!
NHDaly
September 16, 2019, 3:18am
#6
Cool, that looks really handy! I’m glad it was helpful for you.
1 Like