D lang scope guards in Julia

proposal

#1

I think julia should incorporate (“steal”) D language type scope guards
ref https://tour.dlang.org/tour/en/gems/scope-guards
The examples there and in the references make it very clear why such a feature is desirable and useful. I think Julia would benefit from this being baked in at the language level.


#2

This is somewhat similar in spirit to https://github.com/adambrewster/Defer.jl. Note that I have not used that package and can’t endorse that it will suit your use case.

cc @adambrewster


#3

Here are some examples of scope guards to illustrate it’s effect

<statement1>
scope(exit) <statement2>
<statement3>

which lowers to

<statement1>
try
    <statement3>
finally
    <statement2>
end

More examples

<statement1>
scope(exit) <statement2>
<statement3>
scope(exit) <statement4>
<statement5>

which lowers to

<statement1>
try
    <statement3>
        try
            <statement5>
        finally
            <statement4>
        end
finally
    <statement2>
end

Another example

<statement1>
scope(success) <statement2>
<statement3>

lowers to

<statement1>
success = true
try
    <statement3>
catch e
    success = false
    throw(e)
finally
    if success
        <statement2>
    end
end

#4

Defer.jl handles the scope(exit) case. Note that I use the word @scope differently and the @defer macro is more like your scope(exit).

Your example

<statement1>
scope(exit) <statement2>
<statement3>
scope(exit) <statement4>
<statement5>

could be written as

using Defer
@scope begin
  <statement1>
  @defer <statement2>
  <statement3>
  @defer <statement4>
  <statement5>
end