Eval from macro

Even though I agree macros should mostly return expressions that get evaluated, it does work for me.

julia> LinearAlgebra
ERROR: UndefVarError: LinearAlgebra not defined

julia> using .mypack; @my_eval LinearAlgebra

julia> LinearAlgebra # not in call scope
ERROR: UndefVarError: LinearAlgebra not defined

julia> mypack.LinearAlgebra # in definition scope
LinearAlgebra

The eval running in the macro body executes in the global scope of my_eval, thus inside mypack. It won’t change even if you put the eval in a returned expression instead, macro hygiene rules look for functions in the macro definition scope. You can use esc on a function expression to make it in the macro call scope:

julia> module mypack # after restart session

       export @my_eval

       macro my_eval(pkg)
           pp = pkg |> string
           :($(esc(:eval))(Meta.parse(string("using ", $pp))))
       end

       end
Main.mypack

julia> LinearAlgebra
ERROR: UndefVarError: LinearAlgebra not defined

julia> using .mypack; @my_eval LinearAlgebra

julia> LinearAlgebra # now in call scope
LinearAlgebra

julia> mypack.LinearAlgebra # not in definition scope
ERROR: UndefVarError: LinearAlgebra not defined

dylanxyz’s version has a keyword using instead of a function, so it shows up in the call scope.

1 Like