How to print function name and source file/line number

Hello, is it possible to print the current function name and the REPL/Juno/VSCode clickable file name/function name, e.g.

function foo()
    @codeLocation
    ...
end

Resulting in:

Running function foo on /path/to/myfile.jl:123

I am aware of __source__.file and __source__.line, but I coudn’t get them working in the way I described and the function @shown in DebuggingUtilities seems to go a bit too far showing the whole stack.

EDIT:

I did manage to get the file name/ line but not yet the function name. Also I need to call the macro followed with an empty expression, and that’ts ugly:

macro codeLocation(expr)
    return quote
        print("Running function at ",$("$(__source__.file)"),":",$("$(__source__.line)"))
    end
end

function foo()
    @codeLocation " "
end

foo()

Resulting in :

Running function at /home/lobianco/.julia/dev/BetaML/src/temp.jl:14

Just don’t require any argument, no?

macro codeLocation()
2 Likes

ahh… sure… thanks… I am now left with retrieving the function name… I did found __module__ for the modulo name, but not yet the function name…

done it :slight_smile:

macro codeLocation()
    return quote
        st = stacktrace(backtrace())
        myf = ""
        for frm in st
            funcname = frm.func
            if frm.func != :backtrace && frm.func!= Symbol("macro expansion")
                myf = frm.func
                break
            end
        end
        println("Running function ", $("$(__module__)"),".$(myf) at ",$("$(__source__.file)"),":",$("$(__source__.line)"))
    end
end


function foo()
    @codeLocation
end

(taking code from DebuggingUtils)

julia> foo()
Running function Main.foo at /home/lobianco/.julia/dev/BetaML/src/temp.jl:18
6 Likes