D lang scope guards in Julia

I think julia should incorporate (“steal”) D language type scope guards
ref Scope guards - Dlang Tour
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 Likes

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

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

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