I want to be able to conitionally trace some of my methods, that is, to log the arguments and return values of each invocation.
For example, given this function definition
function hanoi(from, to, other, count)
if count == 1
println("move 1 from $from to $to")
return
else
hanoi(from, other, to, count - 1)
println("move 1 from $from to $to")
hanoi(other, to, from, count - 1)
return (from, to) # arbitrary result to show
end
end
how would I write a macro that, when applied to that definition, redefines the function as
function hanoi(from, to, other, count)
function var"##bodyfunction#258"()
# This is just the body of the original function:
if count == 1
println("move 1 from $from to $to")
return
else
hanoi(from, other, to, count - 1)
println("move 1 from $from to $to")
hanoi(other, to, from, count - 1)
return (from, to) # arbitrary result to show
end
# end of original function body.
end
# Consitionaly log the function call. The name of the variable
# `trace_hanoi` will be a parameter of the macro:
if trace_hanoi
@info("Trace enter", call = Expr(:call, hanoi, from, to, other, count))
end
var"##result#259" = var"##bodyfunction#258"()
# Conditionally log the function's return value:
if trace_hanoi
@info("Trace exit", result = var"##result#259")
end
var"##result#259"
end
I have a partial inplementation at NahaJuliaLib.jl/src/trace.jl at 1c4f9665d0906121998bcc14b7637c6824464a8b · MarkNahabedian/NahaJuliaLib.jl · GitHub (appologies for the obvious flailing about).
The root of my problem is intercolating the values of the function arguments, rather than their names, in the “Trace enter” call
expression.
I tries asking something similar but didn’t get any response, I suspect because the topic was not descriptive. I hope the lack of response wan’t because there isn’t a way to do this in JUlia.
Thanks.