JuliaLang / julia

The Julia Programming Language
https://julialang.org/
MIT License
45.56k stars 5.47k forks source link

@code_warntype on functions with keyword arguments #35717

Open cossio opened 4 years ago

cossio commented 4 years ago

@code_warntype applied to a function with keyword arguments only prints a call to an internal function, so it does not provide any useful information. This has been discussed before, but I found no open issue tracking this:

https://github.com/JuliaLang/julia/issues/24985 (closed) https://discourse.julialang.org/t/code-warntype-fails-when-function-has-a-keyword-argument/21907 https://discourse.julialang.org/t/use-of-code-warntype-on-a-function-with-keyword-arguments/5521

MWE:

f(x; y=1) = (rand() < 0.5 ? true : 5)
g(x) = (rand() < 0.5 ? true : 5)

Now compare the output of @code_warntype on f (which takes a keyword argument) and g (which doesn't). On f, the only printed code is a call to an internal function, whereas g immediately shows where the type-instability lies.

julia> @code_warntype f(0.5)
Variables
  #self#::Core.Compiler.Const(f, false)
  x::Float64

Body::Union{Bool, Int64}
1 ─ %1 = Main.:(var"#f#4")(1, #self#, x)::Union{Bool, Int64}
└──      return %1

julia> @code_warntype g(0.5)
Variables
  #self#::Core.Compiler.Const(g, false)
  x::Float64

Body::Union{Bool, Int64}
1 ─ %1 = Main.rand()::Float64
│   %2 = (%1 < 0.5)::Bool
└──      goto #3 if not %2
2 ─      return true
3 ─      return 5
tpapp commented 3 years ago

As a workaround,

using Cthulhu
@descend f(1)

and toggle

[v]erbose printing for warntype code

Generally, since we have Cthulhu.jl, @code_warntype & friends may be considered primitives that one may not want to use directly in practice anyway for complex codebases --- perhaps the docstrings should mention Cthulhu?