@safe by default

Nick Treleaven nick at geany.org
Fri May 31 09:18:17 UTC 2024


On Thursday, 30 May 2024 at 18:35:36 UTC, Atila Neves wrote:
> https://github.com/atilaneves/DIPs/blob/safe-by-default/safe-by-default.md
>
> Destroy!

> If there is no body, the compiler cannot verify the @safety of 
> the function and in those cases this DIP proposes that there 
> will be no default. All declarations (i.e. functions with no 
> body) must have exactly one of the @safe/@trusted/@system 
> annotations

For extern(D), there will be a linker error if a protoype is 
@safe but the implementation is @system. For other linkage, that 
case would silently link with no error. That breaks the principle 
of being able to grep for @trusted to find an *accidental* safety 
violation. (Deliberate violation with pragma(mangle) is less 
serious as that is intentional and stands out more to a reviewer).

Module 1:
```d
import core.stdc.stdio;
@system extern(C) void ext(int* p) { p++; printf("%d\n", *p); }
```
Module 2:
```d
@safe extern(C) void ext(int* p);

void main() // implicitly @safe
{
     int i;
     ext(&i); // boom
}
```

@safe should mean mechanically checked for accidental 
memory-safety violations - that is a more useful definition. 
Allowing non-extern(D) linkage prototypes to be @safe breaks that 
principle and makes @safe prototypes a minefield.

> This DIP makes no distinction between extern(D), extern(C), and 
> extern(C++) functions. Although the latter two usually apply to 
> functions written in C or C++ respectively, that is not 
> necessarily the case

A non-extern(D) prototype can be @trusted, and its implementation 
in D can be @safe, so the implementation is mechanically checked.


More information about the dip.ideas mailing list