A couple of extensions to `with` that would be worthwhile

Paul Backus snarwin at gmail.com
Wed Oct 13 13:09:06 UTC 2021

On Wednesday, 13 October 2021 at 11:13:32 UTC, Andrei 
Alexandrescu wrote:
> We have an awkward idiom in the dmd source code:
> https://github.com/dlang/dmd/search?q=extendedPathThen
> https://github.com/dlang/dmd/search?q=toWStringzThen
> It's a tail wagging the proverbial dog. Clearly we could do 
> with better ways. We can improve the `with` statement as 
> follows:
> 1. Accept named `with`:
> with (auto xpath = extendPath(name)) {
>     // the only name injected here is xpath
> }
> All destructors for the expression involved in `with` are 
> called AFTER the with is done.

Isn't this the same thing as a normal block scope?

         auto xpath = extendPath(name);
         // the name xpath is available here
         // ...
     } // xpath is destroyed here

As far as I can tell the reason a block scope isn't used in DMD 
is that these methods don't use destructors for cleanup, they use 
manual memory management. So maybe that's the real source of the 

> 3. Accept `with` with colon:
> with (auto xpath = extendPath(name).str):
> The meaning is like a scoped `with` that extends though the end 
> of the scope.

This would also be useful for types like ddash's Expect [1], 
which define static factory methods for each case of a sum type. 
The example in the linked documentation could be rewritten as:

     Expect!int toInt(string str) {
         import std.conv: to;
         try {
             return expected(str.to!int);
         } catch (Exception ex) {
             return unexpected(ex.msg);

...where the `with` statement is used to bring `expected` and 
`unexpected` into scope, and the colon avoids introducing an 
extra level of nesting.

[1] https://aliak00.github.io/ddash/ddash/utils/expect/Expect.html

> 4. Accept `with` at top level.
> All `with` forms that take a type should be accepted at top 
> level. This allows entire modules or fragments thereof to look 
> names up in a flexible manner.

Seems like a natural "turtles all the way down" extension of the 

More information about the Digitalmars-d mailing list