How to know which function calls a given function (without using debugger)?

question

#1

I wonder if there is a way in which I can insert a couple lines of code in a function to know which function calls this one, e.g. by printing out some basic information of the caller, like location etc. I’m trying to understand a large and complicated package for which ASTInterpreter2 fails to track down the work flow of the code due to a few bugs.


#2

You can use stacktrace() for that. The most basic code would look something like this:

function outer(x)
    y = inner(x)
    return y + x
end

function inner(x)
    # paste the following let block wherever
    let trace = stacktrace()
        name = trace[1].func # name of current function
        length(trace) >= 2 ?
            println("function `$(name)` was called by $(trace[2])") :
            println("function `$(name)` was called at the top level")
    end
    1 + x
end

outer(3)

which then prints

function `inner` was called by outer(::Int64) at untitled:74

#3

Christ! This is exactly what I’m looking for. @pfitzseb, you’re absolutely my debugging hero!!