Strings can be made from functions that work with IO
objects by using the sprint
function. For instance, the code_llvm
function accepts an IO
object as the first argument. Typically, it is used like
julia> code_llvm(STDOUT, *, (Int, Int))
define i64 @"jlsys_*_46115"(i64, i64) #0 {
top:
%2 = mul i64 %1, %0
ret i64 %2
}
Suppose we want that output as a string instead. Then we can simply do
julia> sprint(code_llvm, *, (Int, Int))
"\ndefine i64 @\"jlsys_*_46115\"(i64, i64) #0 {\ntop:\n %2 = mul i64 %1, %0\n ret i64 %2\n}\n"
julia> println(ans)
define i64 @"jlsys_*_46115"(i64, i64) #0 {
top:
%2 = mul i64 %1, %0
ret i64 %2
}
Converting the results of "interactive" functions like code_llvm
into strings can be useful for automated analysis, such as testing whether generated code may have regressed.
The sprint
function is a higher-order function which takes the function operating on IO
objects as its first argument. Behind the scenes, it creates an IOBuffer
in RAM, calls the given function, and takes the data from the buffer into a String
object.