Hi! I’ve opened a bug report (#54344) on github today which was immediately closed and I was sent here. I’ve read that for a good performance @code_warntype
macro should produce an output without lines colored in red. For this purpose I should write code which is “type stable” and there is no “type uncertainty”. Consider the following code:
function foo(array, op, xs)
function cc(:: Any)
op(array)
end
return cc.(xs)
end
After evaluating this in the REPL I get the following:
julia> data = rand(Bool, (100, 100, 100));
julia> @code_warntype foo(data, x -> sum(2x), [2])
MethodInstance for foo(::Array{Bool, 3}, ::var"#2#3", ::Vector{Int64})
from foo(array, op, ps1) @ Main REPL[1]:1
Arguments
#self#::Core.Const(foo)
array::Array{Bool, 3}
op::Core.Const(var"#2#3"())
ps1::Vector{Int64}
Locals
cc::var"#cc#1"{Array{Bool, 3}, var"#2#3"}
Body::Any
1 ─ %1 = Main.:(var"#cc#1")::Core.Const(var"#cc#1")
│ %2 = Core.typeof(array)::Core.Const(Array{Bool, 3})
│ %3 = Core.typeof(op)::Core.Const(var"#2#3")
│ %4 = Core.apply_type(%1, %2, %3)::Core.Const(var"#cc#1"{Array{Bool, 3}, var"#2#3"})
│ (cc = %new(%4, array, op))
│ %6 = Base.broadcasted(cc, ps1)::Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{1}, Nothing, var"#cc#1"{Array{Bool, 3}, var"#2#3"}, Tuple{Vector{Int64}}}
│ %7 = Base.materialize(%6)::Any
└── return %7
Body::Any
is in red. I wonder why @code_warntype
fails to give a narrower type like Vector{Int}
here. What a penalty for this may be? What are the rules for writing a correct code? How does your type inference work?
If the rule is to write functions which return values of the same type for all possible arguments of the same type then this is definitely a bug. This is why I have reported it and I cannot understand why it was closed. If there are more rules, I would like to know an exhaustive list. This is really hard to tell if this is a bug or not because an end user like me has no idea how this inference works or what it proves unlike some well-known algorithms, be it Hindley-Milner like in Haskell or Kaplan-Ullman like in Common Lisp.
Update:* @code_warntype foo(data, sum, [3])
works fine, for example