foreach on aggregate class in some delegate litterals

simon hudon simon_member at pathlink.com
Sun Jul 16 21:23:16 PDT 2006


Hi everyone,

I caught quite a bizarre bug on dmd v0.162 : if I use a foreach to iterate
through an aggreate class instance in a litteral delegate between brackets, like
this :

=====================================================

// some container
class Container {
int opApply (int delegate (inout int) dg) {
int i;
dg(i);
return 0;
}
}

void main () {
// a is assigned a delegate specified by a litteral
auto a = ( {
foreach (i ; new Container)
writefln(i);
});
}

=====================================================

the compiler crashes saying : 
Assertion failure: 'type || init' on line 440 in file 'declaration.c'

abnormal program termination

But if I make one of two possible changes, it compiles and runs without problem.
First, if I want to iterate through a static or a dynamic array (an associative
array won't work, though), it compiles and run perfectly.  Here's an example :

=====================================================

void main () {
int[] b;
// a is assigned a delegate specified by a litteral
auto a = ( {
foreach (i ; b)
writefln(i);
});
}

=====================================================

A perfect work around (in appearance at least, I just spent three hours on that
problem so I don't pretend to have tested everything) is to tell the compiler
explicitly that the expression in the right side of the assignment is a
delegate, like this : 

=====================================================

// some container
class Container {
int opApply (int delegate (inout int) dg) {
int i;
dg(i);
return 0;
}
}

void main () {
// a is assigned a delegate specified by a litteral
auto a = ( delegate int(){
foreach (i ; b)
writefln(i);
} );
}

=====================================================

It seems that this is not a really bad bug since you can get the work done
simply by adding the type of the delegate, but I think the syntax without those
keywords should work whatever is in the delegate.  

Thanks for your attention.

Cheers

Simon Hudon



More information about the Digitalmars-d-bugs mailing list