Search code examples
juliaexpr

how can i get Exprs of julia code accoring to function and argtypes?


i am new in Julia. i read a doc about julia static-analysis. it gives a function.

function foo(x,y)
  z = x + y
  return 2 * z
end

and use the julia introspection function code_typed get output:

code_typed(foo,(Int64,Int64))

1-element Array{Any,1}:
:($(Expr(:lambda, {:x,:y}, {{:z},{{:x,Int64,0},{:y,Int64,0},{:z,Int64,18}},{}},
 :(begin  # none, line 2:
        z = (top(box))(Int64,(top(add_int))(x::Int64,y::Int64))::Int64 # line 3:
        return (top(box))(Int64,(top(mul_int))(2,z::Int64))::Int64
    end::Int64))))

it has an Expr . but when i call code_typed, the output is :

code_typed(foo, (Int64,Int64))

1-element Vector{Any}:
 CodeInfo(
1 ─ %1 = Base.add_int(x, y)::Int64
│   %2 = Base.mul_int(2, %1)::Int64
└──      return %2
) => Int64

it has a CodeInfo.it is different with the output in doc.

does julia have some change? and how can i get the Exprs according to my function and argtypes?


Solution

  • That code snippet appears to be taken from https://www.aosabook.org/en/500L/static-analysis.html, which was published in 2016 (about two years before the release of Julia 1.0) and references Julia version 0.3 from 2015.

    Julia 1.0 gives

    julia> code_typed(foo,(Int64,Int64))
    1-element Array{Any,1}:
     CodeInfo(
    2 1 ─ %1 = (Base.add_int)(x, y)::Int64                                   │╻ +
    3 │   %2 = (Base.mul_int)(2, %1)::Int64                                  │╻ *
      └──      return %2                                                     │ 
    ) => Int64
    

    while more current versions such as 1.6 and 1.7 give

    julia> code_typed(foo,(Int64,Int64))
    1-element Vector{Any}:
     CodeInfo(
    1 ─ %1 = Base.add_int(x, y)::Int64
    │   %2 = Base.mul_int(2, %1)::Int64
    └──      return %2
    ) => Int64
    

    (a much more minor change, but nonetheless)

    If for any reason, you want this result in the form of an array or vector of Exprs, you seem to be able to get this using (e.g.)

    julia> t = code_typed(foo,(Int64,Int64));
    
    julia> t[1].first.code
    3-element Vector{Any}:
     :(Base.add_int(_2, _3))
     :(Base.mul_int(2, %1))
     :(return %2)
    

    though this is likely considered an implementation detail and liable to change between minor versions of Julia.