Why is 'scope' so weak?

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Wed Nov 24 03:06:26 PST 2010


On Tue, 23 Nov 2010 23:26:54 -0500, Robert Jacques wrote:

> On Tue, 23 Nov 2010 07:59:27 -0500, Lars T. Kyllingstad
> <public at kyllingen.nospamnet> wrote:
> 
>> If I've understood things correctly, by marking a delegate parameter
>> with 'scope' you tell the compiler not to create a true closure for the
>> delegate.  Effectively you're saying "I promise not to escape this
>> delegate, so you don't need to copy its context to the heap".
>>
>> In brief, my question is:  Why doesn't the compiler enforce this
>> promise?  In particular, why is 'scope' not a type constructor?
> 
> For scope to be a type constructor, D requires some form of
> ownership-types & local escape analysis. Just like mutable and immutable
> data needs const, I think stack/thread-local/shared data needs scope.
> (There is an old proposal on the wiki about the technical
> implementation, though it's badly worded) But my understanding is that
> all things ownership related are relegated to D3.

Well, I think something needs to be done about it in D2 as well, because 
right now 'scope' allows memory corruption to happen even in safe mode, 
as demonstrated by this slightly modified example:


// The example I showed earlier, now with @safe annotations.
@safe:

    void delegate() globalDg;
    void call(scope void delegate() @safe dg)
    {
        dg();

        // Don't tell anyone, but I'm saving this for later ;)
        globalDg = dg;
    }


    void foo()
    {
        int i;
        void izero() { i = 0; }
        call(&izero);
        assert (i == 0);
    }


    void bar()
    {
        int x = 123;

        // Simply calling some function cannot possibly
        // do anything to x...
        globalDg();

        // ...or can it?
        assert (x == 0);
    }


    void main()
    {
        foo();
        bar();
    }


More information about the Digitalmars-d mailing list