[Issue 19743] [dip1000] unclear error message when escaping variable through foreach `ref`

d-bugmail at puremagic.com d-bugmail at puremagic.com
Fri Nov 4 21:08:10 UTC 2022


https://issues.dlang.org/show_bug.cgi?id=19743

Dennis <dkorpel at live.nl> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
           Keywords|                            |diagnostic, safe
                 CC|                            |dkorpel at live.nl
            Summary|Foreach loops desugar into  |[dip1000] unclear error
                   |code that breaks `return    |message when escaping
                   |scope`                      |variable through foreach
                   |                            |`ref`
           Severity|normal                      |enhancement

--- Comment #1 from Dennis <dkorpel at live.nl> ---
Haystack in your example is an `int[9]`, a value type without pointers, so
(return) scope doesn't apply to it. When you `return &val;`, you're escaping a
pointer to the expired stack frame containing your `haystack` parameter, so an
error is in place. 

To make `find` valid, your haystack should be passed by `ref`, and then it
compiles:

```
int* find(return ref int[9] haystack, int needle) @safe
{
    foreach (ref val; haystack)
        if (val == needle)
            return &val;

    return null;
}

void main() @safe
{
    int[9] haystack = [0, 10, 5, 6, 2, 3, 9, 4, 5];
    int* foundVal = haystack.find(3);
}
```

However, "scope variable __r2 may not be returned" is not a good diagnostic, so
I'm changing this issue to be about that.

--


More information about the Digitalmars-d-bugs mailing list