On Wednesday, 26 August 2020 at 15:34:26 UTC, Dennis wrote:
On Wednesday, 26 August 2020 at 14:29:46 UTC, Dukc wrote:
I think there is a workaround to the variable access being always safe. Something like this in a dedicated module:

```
struct SystemVar(T, bool safeVal)
{  private T _var;
   static if (safeVal) @safe pure nothrow @nogc auto val()
   {  return _var;
   }
   else pure nothrow @nogc auto val(){return _var;}
   pure nothrow @nogc ref var(){return _var;}
}
```

This currently does not protect against:
- SystemVar.tupleof[0] (unless you have -preview=dip1000 set)
- __traits(getMember, SystemVar, "_var")
- aliasing (put SystemVar!int in a union with a plain int / cast SystemVar!int[] from int[])
- void initialization

Of course, you could also argue that these are things that shouldn't be allowed in @safe code to begin with--regardless of whether pointers are involved.

I think presenting @system variables as "protection" against memory corruption is the wrong way frame the discussion. The problem is that, currently, it is only possible to provide @safe access to certain kinds of data (discriminated unions, ref-counted pointers, etc.) by having @trusted code make assumptions about @safe code that must be manually verified.

There is, technically, nothing wrong with this. The D language spec does not place any restrictions on what assumptions you are allowed to make in @trusted code; it merely requires that you do the legwork to manually verify those assumptions if you want the compiler's automatic verification of @safe code to give the correct result.

What @system variables do is allow you to document, in machine-readable form, a particular kind of assumption ("this variable is never accessed directly from @safe code"), and have the compiler check it for you. In other words, they make @trusted code more *expressive* and *ergonomic*.

Reply via email to