DIP1000 scope inference

Steven Schveighoffer schveiguy at gmail.com
Tue Oct 25 01:35:28 UTC 2022


Deprecation messages due to dip1000's imminent arrival are scheduled to 
happen on the next release of the compiler. I have some concerns about 
scope inference, and wanted to find out the answers here.

Let's say I have a scope array like this in a @trusted function:

```d
int[] mkarr() @trusted {
    scope arr = [1, 2, 3];
    return arr;
}
```

Clearly, this is a bad idea. The compiler might put the array data 
actually on the stack (right?), and therefore return stack data when it 
shouldn't.

But what if you *don't* mark it scope? Let's try something here:

```d
int[] mkarr() @safe {
    int[3] arr = [1, 2, 3];
    int[] other = arr[];

    other = [4, 5, 6];
    return other;
}
```

by the time `other` is returned, it should no longer be pointing at 
stack data. But *because* it was originally assigned to the static 
array, `other` is inferred as scope (as is proven by the code above 
failing to compile with dip1000 enabled with an error about returning 
scope data).

Let's switch that back to `@trusted`, and now it does compile, even with 
dip1000. BUT, let me ask this very crucial question:

Does the inferred `scope` make it so that the compiler is *allowed* to 
allocate the `[4, 5, 6]` literal on the stack? Keep in mind that I never 
put `scope` here, this is something the compiler did on its own.

In a `@trusted` function today, without dip1000, the above is perfectly 
reasonable and not invalid. Will dip1000 make it corrupt memory?

-Steve


More information about the Digitalmars-d mailing list