Skip to content

Instantly share code, notes, and snippets.

@cossio
Last active January 14, 2020 13:53
Show Gist options
  • Save cossio/388106afb8c91be031a59b5d80f931c0 to your computer and use it in GitHub Desktop.
Save cossio/388106afb8c91be031a59b5d80f931c0 to your computer and use it in GitHub Desktop.
Checks for type stability the first time a function is called with a type signature.
macro checked(fdef)
d = splitdef(fdef)
f = d[:name]
args = d[:args]
whereparams = d[:whereparams]
d[:name] = gensym()
shadow_fdef = combinedef(d)
M = __module__
quote
$shadow_fdef
@generated function $f($(args...)) where {$(whereparams...)}
d = $d
T = Tuple{$(args...)}
out_type = Core.Compiler.return_type($(d[:name]), Tuple{$(args...)})
Core.println("statically inferred return type was $out_type")
args = $args
:($(d[:name])($(args...)))
end
end |> esc
end
@cossio
Copy link
Author

cossio commented Oct 9, 2019

Checks for type stability the first time a function is called with a type signature.

Source: https://discourse.julialang.org/t/thoughts-around-ways-of-ensuring-compile-time-evaluation-const-prop-inference/28904/9

Usage:

julia> @checked f(x, y) = x + y
f (generic function with 1 method)

julia> f(1, 2)
statically inferred return type was Int64
3

julia> f(1, 2)
3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment