static foreach considered

Idan Arye via Digitalmars-d digitalmars-d at puremagic.com
Mon Jun 8 18:14:51 PDT 2015


On Tuesday, 9 June 2015 at 00:48:34 UTC, rsw0x wrote:
> On Tuesday, 9 June 2015 at 00:01:07 UTC, Idan Arye wrote:
>> On Monday, 8 June 2015 at 22:15:32 UTC, rsw0x wrote:
>>> On Monday, 8 June 2015 at 20:02:11 UTC, Andrei Alexandrescu 
>>> wrote:
>>>> I'm trying to collect together motivating examples and to 
>>>> figure out the semantics of the feature.
>>>
>>> maybe not completely related, but I made a blog post on using 
>>> CTFE to unroll foreach at compiletime
>>>
>>> https://rsw0x.github.io/post/switch-unrolling/
>>>
>>> I find myself often writing recursive templates for 
>>> compile-time generation of constructs that could be done 
>>> cleaner with static foreach.
>>
>> I also use this method alot, and sometimes encounter this 
>> "bug": http://dpaste.dzfl.pl/16af3c5dad73
>>
>> The break inside the `foreach` is breaking from the `foreach`, 
>> not from the `switch`, so it continues to execute the 
>> `default` clause.
>>
>> This is not really a bug - `foreach` unrolling is more of a 
>> loop unrolling optimization that we hijack, so it makes sense 
>> `break` inside it will act like it's inside a regular 
>> `foreach`. With `static foreach`, we might want `break`(and 
>> `continue`) to operate on the containing, runtime control 
>> structure.
>
> I knew there was something I was forgetting in that short 
> example, thanks for the reminder.
>
> Interestingly, the assembly generated with `break` and `break 
> label` with a label on the switch is exactly the same. I don't 
> have time right now to go review the spec, so I have no idea if 
> that's correct.

Why wouldn't they? If we neglect RAII(for simplicity), `break` 
jumps to the first instruction after the `foreach`, and `break 
label` with a label on the `switch` jumps to the first 
instruction after the `switch`. Since there is nothing in the 
`switch` after the `foreach`, the first instruction after the 
`foreach` is also the first instruction after the `switch`, so 
the command to jump to that instruction is the same, and the 
assembly is the same.


More information about the Digitalmars-d mailing list