DIP1000: Memory Safety in a Modern System Programming Language Pt.1

Steven Schveighoffer schveiguy at gmail.com
Thu Jun 23 14:26:14 UTC 2022


On 6/23/22 8:14 AM, Kagamin wrote:
> On Wednesday, 22 June 2022 at 20:48:13 UTC, Steven Schveighoffer wrote:
>> Sometimes algorithms require manipulation of structure, such as 
>> sorting arrays, or using linked lists, and sometimes it's nice to be 
>> able to point at things on the stack, temporarily. This is one of the 
>> things I was looking forward to with dip1000, since it does allow 
>> pointing at the stack when it can work out the details.
> 
> This works:
> ```
> struct S
> {
>      int[] a;
>      int[] get() return scope @safe { return a; }
>      void set(return int[] b) return scope @safe
>      { a=b; }
> }
> 
> int[] f() @safe
> {
>      int[2] a;
>      scope S t;
>      int[] b=t.get;
>      t.set=a;
>      return b; //no
> }
> ```

This is just saying the same thing -- you must allocate your data on the 
stack in order to have scope elements assignable. This isn't always 
feasible.

```d
     scope a = "first";
     scope b = "second";
     string[2] x = [a, b];
     auto arr = x[]; // ok
     arr = ["first", "second"]; // ok
     arr = [a, b]; // not ok
```

It's established that arr is attributed such that it's able to point at 
stack data. Fine.

It can also point at allocated data. Fine.

But the *allocated data itself* cannot point at scope data. This 
"somewhat" makes sense, because by the time the GC cleans up this array, 
the data is likely invalid (not in this case, but that's because we 
deliberately labeled non-scope data as scope).

However, you may need to mix both non-scope and scope data, which means 
you can't allocate on the stack. But there can be ways to mitigate this:

1. For this simple case, just allocate [a, b] on the stack. It's 
happening in other places (see my other thread), why not here?
2. The compiler could insert a call at the end of the scope to free the 
allocated data. It can't escape anyway, and freeing it early is part of 
the benefit of having scope. Or if it's determined that no destructors 
are involved, just let the GC clean it up.

The more cases where we make this painless for the user, the better.

-Steve


More information about the Digitalmars-d-announce mailing list