May I introduce `lazy with`?

Paul Backus snarwin at gmail.com
Thu Nov 24 19:27:00 UTC 2022


On Thursday, 24 November 2022 at 17:41:20 UTC, Quirin Schroll 
wrote:
> The essence of the problem is that `with (TypeOrExpr)` will 
> prefer resolving an identifier `id` as `TypeOrExpr.id` whenever 
> `TypeOrExpr.id` is viable:
> ```d
> with (EnumType)
> switch (enumValue)
> {
>     static foreach (member; EnumMembers!EnumType)
>     {
>         case member: // What if EnumType has a member named 
> `member`?
>             ...;
>     }
> }
> ```
> When `EnumType` happens to have a member named `member`, `with` 
> will greedily take it and the loop will produce nonsense.

I tried it on run.dlang.io and `member` is correctly resolved as 
referring to the loop variable, not the enum member. Here's a 
complete, compilable example:

```d
enum EnumType { foo, member, bar }

void main()
{
     import std.traits;

     EnumType enumValue;

     with (EnumType)
     switch_label: final switch (enumValue)
     {
         static foreach (member; EnumMembers!EnumType)
         {
             case member:
                 pragma(msg, member);
                 break switch_label;
         }
     }
}
```


More information about the Digitalmars-d mailing list