masak / alma

ALgoloid with MAcros -- a language with Algol-family syntax where macros take center stage
Artistic License 2.0
137 stars 15 forks source link

Implement a `with` statement macro #156

Open masak opened 8 years ago

masak commented 8 years ago

Directly from Python.

The idea being that if you do

with getSomeObject() -> o {
    doSomethingWith(o);
}

Then o.enter() runs before the block and e.exit() runs after the block.

o.enter();
doSomethingWith(o);
o.exit();

(The .exit method is called with three arguments. See the Python documentation for details.)

Better yet, the o.exit() call is guaranteed to have finally semantics. So it gets called regardless of how successfully or abruptly the with block itself finishes.

This sounds perfect for a flow-controlish macro. If we can do this, then we have quite a good start.

As usual, let's first implement it in Perl 6 under a feature flag, and then figure out how to do it in 007 as a proper module/macro.

It would probably be extra nice if under a #33 regime, there were an interface that the expression in the with statement was required to type match... the difficulty being not so much doing this type check, but doing it only if/when the feature flag or pragma for type checking is switched on. Ah, the combinations.

masak commented 7 years ago

C# calls this one using, which is also a nice name. Will probably choose with anyway, since Python is one of the languages 007 wishes to copy features from. But using is not bad either.

masak commented 6 years ago

Just passing by to say that we can probably use try { ... } finally { o.exit() } to implement the finally semantics.

Nuh, duh. :smile:

masak commented 5 years ago

C# 8 also gets a declaration form which implicitly goes to the end of the block. Something to consider. :smile:

Edit: On balance, I think I like the using keyword better than the with keyword.