[Dlang-internal] foreach + ref bug

Andrea Fontana nospam at example.com
Thu Jun 28 10:27:37 UTC 2018


1- Take a range with a non-ref front() method.
2- Use it with a foreach(ref element; Range) (ex: myrange.each!(x 
=> writeln(x)) since "each" use a ref foreach)

(Bug: https://issues.dlang.org/show_bug.cgi?id=11934)

What happens? This code should be rejected but instead it is 
lowered and each element's ctor is called but not dtor. That 
means, in my case, that my library never frees a lot of resources 
(and relative referenced objects).

I think that (invalid!) code should trigger some kind of 
error/warning.

I tried to put here [1] this code:

if (auto fd = sfront.isFuncDeclaration())
{
   // If front is a function, it must return a ref if used with 
foreach(ref x; ...)
   if ((p.storageClass & STC.ref_) /* && front is ref */)
   {
     fs.error("`%s.front` isn't a ref", oaggr.toChars());
     goto case Terror;
   }
}

But I can't (and nobody can, apparently) tell how to check if 
front is returning a ref.

fd.type.toChars() == "pure nothrow @nogc @property ref @safe 
int() return"

But I still can't understand how this code take "ref" out from 
fd.type :)
Someone suggests to check fd.type.nextOf but it is simply "int" 
(return type of front() function)

Any hint?

Andrea

[1] 
https://github.com/dlang/dmd/blob/master/src/dmd/statementsem.d#L1463
[2] 
https://github.com/dlang/dmd/blob/master/src/dmd/hdrgen.d#L1883


More information about the Dlang-internal mailing list