How to get the name of macro calling function?

Hey al :slight_smile:

It’s probably easier to ask the question with an example:

module M
macro m()
    get_name_of_calling_function() |> println
    get_name_of_calling_module()   |> println
end

function f()
    @m()
    return
end
end
julia> M.f()
f
M

Is that possible?

Cheers

In general, my advice when writing macros is to forget you’re writing a macro and ask “how do I do X in code?” Then you just generate that code inside your macro.

With that in mind, I think the answers to your question are likely to be something like:

  • StackTraces.stacktrace()[1].func
  • @__MODULE__
module M

macro m()
    quote
        println(StackTraces.stacktrace()[1].func)
        println(@__MODULE__)
    end
end

function f()
    @m()
    return
end

end
julia> M.f()
f
Main.M
2 Likes

Thank you!

Why can I use @__MODULE__ in the macro but not @__FILE__ or @__LINE__. (Instead I have to use __source__.file or __source__.line)