As it stands code_typed returns its output, but code_llvm and code_native return Nothing and instead print their output to an io stream. I would like to propose that all three have no side effects and return some kind of Julia object which displays nicely.
I ran into this when trying to use these functions in a Pluto.jl notebook. code_typed works just fine but the other two don’t display their output in the notebook, which is rather annoying. You can get around this by redirecting stdout or by using sprint and returning a String, but it doesn’t look nice that way.
Would the way to fix this be to have equivalents of the CodeInfo type like a LLVMInfo and NativeInfo types, that just contain a string and get displayed nicely if showed?
code_llvm and code_naive have an optional parameter io to redirect IO:
help?> code_llvm
search: code_llvm @code_llvm
code_llvm([io=stdout,], f, types; raw=false, dump_module=false, optimize=true, debuginfo=:default)
Prints the LLVM bitcodes generated for running the method matching the given generic function and type signature to io.
Yeah, you can also do this with sprint. The problem is, that a Julia String does not get displayed by printing it. Instead, the raw form gets shown in the REPL, which is rather ugly.
julia> my_code_native(args...; kwargs...) = sprint() do io
code_native(io, args...; kwargs...)
end
my_code_native (generic function with 1 method)
julia> my_code_native(abs, (Int,))
"\t.section\t__TEXT,__text,regular,pure_instructions\n; ┌ @ int.jl:170 within `abs'\n; │┌ @ int.jl:130 within `flipsign'\n\tmovq\t%rdi, %rax\n\tnegq\t%rax\n\tcmovlq\t%rdi, %rax\n; │└\n\tretq\n\tnopl\t(%rax,%rax)\n; └\n"
So, I was proposing something more like this
import Base: show
using InteractiveUtils: code_llvm, code_native
struct CodeLLVMInfo{F <: Function, Ts <: Tuple}
f::F
types::Ts
end
function show(io::IO, ::MIME"text/plain", info::CodeLLVMInfo)
code_llvm(io, info.f, info.types)
end
proposed_code_llvm(f, types) = CodeLLVMInfo(f, types)
display(proposed_code_llvm(abs, (Int,)))
I don’t know if Pluto has a way of showing printed strings. I tested the sprint code and it doesn’t display nicely. May be there’s some other way to do it though.
In any case, I think the three inspection functions should be consistent. So, either all should print or all should return their output.
Here’s what I tried.
### A Pluto.jl notebook ###
# v0.15.1
using Markdown
using InteractiveUtils
# ╔═╡ fd998ae0-e480-11eb-2aa1-8317fbbf5333
my_code_native(args...; kwargs...) = sprint() do io
code_native(io, args...; kwargs...)
end
# ╔═╡ 3fa04cfe-ebd5-4a7d-885d-6a6eae4a5a53
my_code_native(abs, (Int,))
# ╔═╡ Cell order:
# ╠═fd998ae0-e480-11eb-2aa1-8317fbbf5333
# ╠═3fa04cfe-ebd5-4a7d-885d-6a6eae4a5a53