DIP 1028---Make @safe the Default---Community Review Round 1

ag0aep6g anonymous at example.com
Thu Jan 2 14:43:50 UTC 2020


On 02.01.20 14:47, Dominikus Dittes Scherkl wrote:
> But at the same time, additionally @trusted as a function attribute 
> should be removed and replaced by @trusted expressions. Because:
[...]
> @trusted should be restricted to as few code as possible, at best only 
> to the line of code where it is really necessary to make a function @safe.

One step at a time. As it is, the DIP may be disruptive but it's simple. 
Improvements to @trusted can go in another DIP.

Applying @trusted to as little code as possible sounds good, but it's 
often done incorrectly with the effect that @safe is weakened.

Here's a quick example from a GitHub search on Phobos [1]:

     auto p = (() @trusted => fakePureMmap(null, bytes,
         PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0))();
     /* ... stuff ... */
     return (() @trusted => p[0 .. bytes])();

Strictly speaking, that second lambda cannot be @trusted. Its safety 
relies on `p` and `bytes` being compatible. But an unlucky contributor 
might accidentally set `p = new byte;` or `bytes = 1024^^3;` in "stuff". 
Those mistakes would pass as @safe, but they would likely lead to memory 
corruption. The corruption would happen after an edit that only touched 
@safe code. That's exactly what D's safety system is supposed to prevent.

But I agree that applying @trusted to the function signature is ugly and 
misleading.

For a caller, there is zero difference between these two functions:

     void f() @trusted { /* ... stuff ... */ }
     void f() @safe { () @trusted { /* ... the same stuff ... */ } (); }

Having @trusted visible in the function signature just gives people 
wrong ideas about what it means.


[1] 
https://github.com/dlang/phobos/blob/5e6fe2f9c8f72f4c3b0497dc363fc61d823ff489/std/experimental/allocator/mmap_allocator.d#L38-L45


More information about the Digitalmars-d mailing list