Expression Updating

Say I have an expression block like the following:

quote
    x = foo(args...)
    y = otherpackage.bar(args...)
end

I would like to turn that into the following:

quote
    x = Module.foo(args...)
    y = Module.otherpackage.bar(args...)
end

This is a pretty simple example, but I want it to be robust and be able to parse all function calls and stick the Module in front of them.

For reference, I am trying to fix this issue in Handcalcs Function Limitations. You will have to scroll down to the bottom of the section linked. The linked issue I am referring to:

  • If the function has other function calls within it’s body that are not available in Main, then the macro will error.

I would suggest to use MacroTools.jl for this task (see the docs). So your example might look like this:

using MacroTools: @capture, prewalk

ex = quote
    x = foo(args...)
    y = otherpackage.bar(args...)
end


prewalk(ex) do x
    if @capture(x, f_(args__))
        :(Main.($f)($(args...)))
    else
        x
    end
end

which returns:

quote
    x = Main.(foo)(args...)
    y = Main.(otherpackage.bar)(args...)
end

EDIT: it is probably better to use prewalk here to be able to replace nested function calls as well.

1 Like

This is awesome! Thanks!