我正在玩 Julia 的宏。我特別好奇的一件事是無需完全編譯代碼即可提取函式的可達呼叫圖的能力。“可達呼叫圖”是指在函式體內找到的所有可能可達的函式,以及這些函式中的函式,等等。
例如:
do_something(x::Int) = println(x*2)
do_something(x::String) = println(x)
function foo(a, b)::Bool
do_something_with(a)
do_something_with(b)
return true
end
# Ideally something like this would be accessible from Base
functions_in_codebase = [:do_something, :foo]
# Not correct, but gets the idea across
macro access_call_graph(f)
tokens = f.text.tokens
graph = [f]
for t in tokens
go_deeper = t in functions_in_codebase
!go_deeper && append!(graph, access_call_graph(get_function_for(t))...)
end
return graph
end
access_call_graph(foo)
# Should get something like the following, nesting notwithstanding:
# foo
# do_something, do_something
這很麻煩,但是能夠在決議時訪問呼叫圖,即使僅就潛在的可訪問函式而言,對于我正在嘗試做的事情也非常有用。如果我必須完全編譯代碼才能使這樣的事情起作用,那將在很大程度上破壞了好處。
這樣的事情可能嗎?
uj5u.com熱心網友回復:
@code_lowered 可能有用:
julia> code = @code_lowered foo(1,"2")
CodeInfo(
1 ─ %1 = Main.Bool
│ Main.do_something_with(a)
│ Main.do_something_with(b)
│ %4 = Base.convert(%1, true)
│ %5 = Core.typeassert(%4, %1)
└── return %5
)
要獲取函式呼叫,您可以執行以下操作:
julia> code.first.code
5-element Vector{Any}:
:(Main.do_something_with)
:((%1)(_2))
:(Main.do_something_with)
:((%3)(_3))
:(return true)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/410071.html
標籤:
