Thread overview
[Issue 19743] Foreach loops desugar into code that breaks `return scope`
Mar 16, 2019
Meta
[Issue 19743] [dip1000] unclear error message when escaping variable through foreach `ref`
Nov 04, 2022
Dennis
Dec 17, 2022
Iain Buclaw
March 16, 2019
https://issues.dlang.org/show_bug.cgi?id=19743

Meta <monkeyworks12@hotmail.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
            Summary|Foreach loops desugar into  |Foreach loops desugar into
                   |code that does not work     |code that breaks `return
                   |with                        |scope`

--
November 04, 2022
https://issues.dlang.org/show_bug.cgi?id=19743

Dennis <dkorpel@live.nl> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
           Keywords|                            |diagnostic, safe
                 CC|                            |dkorpel@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@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.

--
December 17, 2022
https://issues.dlang.org/show_bug.cgi?id=19743

Iain Buclaw <ibuclaw@gdcproject.org> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
           Priority|P1                          |P4

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

--- Comment #2 from dlangBugzillaToGithub <robert.schadek@posteo.de> ---
THIS ISSUE HAS BEEN MOVED TO GITHUB

https://github.com/dlang/dmd/issues/19542

DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB

--