www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 23299] New: Detect if lambda does not access its delegate

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

          Issue ID: 23299
           Summary: Detect if lambda does not access its delegate context
                    pointer
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: bugzilla digitalmars.com

Consider:

final class RedBlackTree(alias less)
{
    this()
    {
    }
}

auto redBlackTree(alias less)()
{
    return new RedBlackTree!(less)();
}

 save void test()
{
    //static bool compare(double x, double y) { return x < y; }
    //auto rbt2 = redBlackTree!(compare, double)(5.1, 2.3);
    auto rbt2 = redBlackTree!((a, b) => a < b)();
    //auto rbt2 = redBlackTree!((a, b){return a < b;})();
}

This fails to compile with -preview=dip1000 with:

test.d(18): Error: ` safe` function `test.test` cannot call ` system` function
`test.test.redBlackTree!((a, b) => a < b).redBlackTree`
test.d(11):        which was inferred ` system` because of:
test.d(11):        escaping reference to stack allocated value returned by `new
RedBlackTree!(__lambda1)`
test.d(9):        `test.test.redBlackTree!((a, b) => a < b).redBlackTree` is
declared here

The lambda (a,b)=>a<b is resolved as a delegate, but since it never accesses
its delegate pointer, it is not really an escaping reference to something the
delegate may refer to.

The compiler should detect this and not issue the error.

--
Aug 20 2022