Skip to content

Instantly share code, notes, and snippets.

@c42f
Last active September 23, 2019 07:37
Show Gist options
  • Save c42f/006cb5de1bfbd6ac8c684d97d60d31f6 to your computer and use it in GitHub Desktop.
Save c42f/006cb5de1bfbd6ac8c684d97d60d31f6 to your computer and use it in GitHub Desktop.
Sketch of lowering for improved exception handling
module Asdf
struct ErrorResult{E}
e::E
end
#=
function bar()
throw ErrorException("Blah")
end
function foo(x::Int)
if x > 1
y = bar() throws Exception
else
y = 2
end
y + 2
end
function foo(s::String)
"Hi "*s
end
x = 10
try
z = foo(x) throws Exception
@show z
catch exc::ErrorException
@show exc
end
try
z = foo(x)
@show z
catch exc
@show exc
end
foo("A")
=#
# Turns into:
function bar(_maybe_wrap_error_1)
e = _maybe_wrap_error_1(ErrorException("Blah"))
if e isa ErrorResult
return e
else
throw(e)
end
end
function _foo(_maybe_wrap_error_1, x::Int)
if x > 1
_maybe_wrap_error_2(e) = e isa Exception ? _maybe_wrap_error_1(e) : e
y = bar(_maybe_wrap_error_2)
if y isa ErrorResult
return y
end
else
y = 2
end
y + 2
end
@inline foo(x::Int) = _foo(identity, x)
function foo(s::String)
"Hi "*s
end
# Don't really need the following definition, as cannot throw
# @inline _foo(_maybe_wrap_error_1, s::String) = foo(s)
x = 2
# catch
_maybe_wrap_error_0(e) = e isa ErrorException ? ErrorResult(e) : e
# try body
_maybe_wrap_error_1(e) = e isa Exception ? _maybe_wrap_error_0(e) : e
z_ = _foo(_maybe_wrap_error_1, x)
if !(z_ isa ErrorResult)
z = z_
@show z
else
exc = z_.e
# catch body
@show exc
end
try
z = foo(x)
@show z
catch exc
@show exc
end
@show foo("A")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment