Thread overview
Why foreach is not nothrow even for a simple associative array?
Oct 13, 2011
Cheng Wei
Oct 13, 2011
bearophile
Oct 13, 2011
Cheng Wei
Oct 13, 2011
bearophile
Oct 13, 2011
Cheng Wei
October 13, 2011
import std.c.stdio

int[int] g_map;

void main() {
    test();
}

nothrow void test() {
    foreach(k, v) {
       printf("%d, %d\n", k, v);
    }
}
Cannot compile with the error:

Error: _aaApply2 is not nothrow

It is not so convenient that we have to use try-catch for all iteration even when we know that it will not throw at all.
October 13, 2011
Cheng Wei:

> nothrow void test() {
>     foreach(k, v) {
>        printf("%d, %d\n", k, v);
>     }
> }
> Cannot compile with the error:
> 
> Error: _aaApply2 is not nothrow
> 
> It is not so convenient that we have to use try-catch for all iteration even when we know that it will not throw at all.

_aaApply2 is the function used to iterate on the associative array. It is not yet tagged with "nothrow" so you can't yet use it in an nothrow function. This is a known bug that is already in Bugzilla and will be fixed.

I think it's not hard to add those tags, so if you want you will probably be able to create a little pull request that fixes this even if you don't know much about compilers.

Bye,
bearophile
October 13, 2011
Thanks.

The problem is that if we tag _aaApply2 as nothrow, then can we still put throwable codes in the body of foreach?
October 13, 2011
Cheng Wei:

> The problem is that if we tag _aaApply2 as nothrow, then can we still put throwable codes in the body of foreach?

I see. Now in D there is purity/"throwbility" inference for templates. Is _aaApply2 allowed to become a template?

Bye,
bearophile
October 13, 2011
Yeah, the problem could be solved if _aaApply2 was a template instead of a function.

Alternatively, maybe the compiler can skip the purity/throwbility check for __aaApply2 and directly check the statements inside. That means to treat the compiler generated function __aaApply2 differently than the opApply provided by users.
October 13, 2011
On Thu, 13 Oct 2011 06:16:59 -0400, bearophile <bearophileHUGS@lycos.com> wrote:

> Cheng Wei:
>
>> The problem is that if we tag _aaApply2 as nothrow, then can we still
>> put throwable codes in the body of foreach?
>
> I see. Now in D there is purity/"throwbility" inference for templates. Is _aaApply2 allowed to become a template?

No, but I see no reason why _aaApply2 couldn't be overloaded with nothrow/pure versions.  The underlying code would probably be a template since the actual code is no different.

-Steve