Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions src/dmd/mtype.d
Original file line number Diff line number Diff line change
Expand Up @@ -4428,15 +4428,15 @@ extern (C++) final class TypeFunction : TypeNext
}
}

stc |= STC.scope_;

/* Inferring STC.return_ here has false positives
* for pure functions, producing spurious error messages
* about escaping references.
* Give up on it for now.
*/
version (none)
{
stc |= STC.scope_;

Type tret = nextOf().toBasetype();
if (isref || tret.hasPointers())
{
Expand All @@ -4446,6 +4446,17 @@ extern (C++) final class TypeFunction : TypeNext
stc |= STC.return_;
}
}
else
{
// Check escaping through return value
Type tret = nextOf().toBasetype();
if (isref || tret.hasPointers())
{
return stc;
}

stc |= STC.scope_;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just realized there should also be a check that the function is nothrow, or else parameters could escape using Exceptions.

import std.stdio;

void escape(string x) @safe pure {
    throw new Exception(x);
}

void main() @safe {
    static string global;
    immutable(char)[4] local;
    try {
        escape(local[]); 
    } catch(Exception e) {
        global = e.msg;
    }
    assert(&local[0] != &global[0]); // fails
}

Though that might be better to do in a follow-up PR, so we can get the fix for the more common case in quicker.

}

return stc;
}
Expand Down
33 changes: 33 additions & 0 deletions test/fail_compilation/retscope6.d
Original file line number Diff line number Diff line change
Expand Up @@ -198,3 +198,36 @@ void hmac(scope ubyte[] secret)
ubyte[10] buffer;
secret = buffer[];
}

/* TEST_OUTPUT:
---
fail_compilation/retscope6.d(12011): Error: reference to local variable `x` assigned to non-scope parameter `r` calling retscope6.escape_m_20150
fail_compilation/retscope6.d(12022): Error: reference to local variable `x` assigned to non-scope parameter `r` calling retscope6.escape_c_20150
---
*/

#line 12000

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

int* escape_m_20150(int* r) @safe pure
{
return r;
}

int* f_m_20150() @safe
{
int x = 42;
return escape_m_20150(&x);
}

const(int)* escape_c_20150(const int* r) @safe pure
{
return r;
}

const(int)* f_c_20150() @safe
{
int x = 42;
return escape_c_20150(&x);
}