Comment #0 by bearophile_hugs — 2014-05-26T21:53:34Z
DMD 2.066alpha accepts this code:
// Program#1
void main() @nogc {
int[2] tmp = [1, 2];
foreach (x; tmp) {}
}
While it refuses this code:
// Program#2
void main() @nogc {
foreach (x; [1, 2]) {}
}
With:
test.d(3,17): Error: array literal in @nogc function main may cause GC allocation
I suggest to start introducing a small amount of Escape Analysis in D, to support the @nogc attribute for the Program#2.
Eventually even this program could be supported:
// Program#3
void main() @nogc {
import std.algorithm: filter;
foreach (x; [1, 2].filter!(x => true)) {}
}
Note that with the []s suffix syntax for fixed-size arrays there is no ambiguity:
// Program#4
void main() @nogc {
foreach (x; [1, 2]s) {}
}
And this can generate a clean error message (escape of pointer to stack frame fixed-size array):
// Program#5
int[] foo() @nogc {
return [1, 2]s;
}
void main() {}
See also Issue 10242
Comment #1 by stanislav.blinov — 2021-12-08T16:23:42Z
Rewritten relevant parts into contemprary D. With dmd 2.098:
void program2() @nogc {
foreach (x; [1, 2]) {}
}
import std.array : staticArray;
void program3() @nogc {
import std.algorithm: filter;
foreach (x; [1, 2].filter!(x => true)) {} // fails to infer @nogc
// workaround:
foreach (x; [1, 2].staticArray[].filter!(x => true)) {}
}
int[] program5() @nogc {
return [1, 2].staticArray; // detects the escape correctly
}
void main() {}
So I guess the only outstanding enhancement here is to make this infer @nogc:
foreach (x; [1, 2].filter!(x => true)) {}
...if at all possible. If not, I guess this could be closed?
Comment #2 by robert.schadek — 2024-12-13T18:21:04Z