Discussion Thread: DIP 1028--Make @safe the Default--Final Review
Dennis
dkorpel at gmail.com
Sun Apr 12 16:06:16 UTC 2020
On Sunday, 12 April 2020 at 14:25:45 UTC, H. S. Teoh wrote:
> Blindly assuming @safe (and nothrow, etc.) apply to non-D
> declarations by default makes no sense: you can't assume
> D-specific things apply to any other language.
The thing is, like Walter said, extern(language) does not mean
the code was written in another language. It strictly means to
use the ABI and mangling scheme of that language.
I can write my own math library in D:
```
module custommath;
float customSqrt(float x) {
// implementation doing nothing @system
}
float customSin(float x) {
// implementation doing nothing @system
}
```
Then I decide I want to make this a closed-source library
available to C users, so I add extern(C): on top. Back on the D
side, suddenly this code breaks:
```
import std;
void main() {
writeln(customSqrt(16.0)); // error: @safe main can't call
@system customSqrt
}
```
Also, I write this .di file by simply removing the function
bodies:
```
module custommath;
float customSqrt(float x);
float customSin(float x);
```
Again, I suddenly can't call them from my @safe `main` function.
Why did the attributes change?
I think the conflict of this discussion comes from balancing
three expectations:
1. extern(language) merely specifies ABI and mangling
2. a non-auto/template function can be made extern by simply
replacing the {body} into a ;
3. memory corruption can always be traced back to @system or
@trusted code
Now there is actually a way to satisfy all three, and it's with
@system by default :)
But with @safe by default, one of them has to go. Given that the
DIP's rationale hinges on the importance of memory safety, you'd
think point 3 is the most important and either point 1 is
sacrificed (have only extern(D) @safe by default) or point 2
(bodyless functions must be @trusted or @system).
Surprisingly, Walter wants to keep 1. and 2. and justifies it by
saying extern functions are out of scope for @safe, similar to
how @safe cannot save you when bugs in the linker, operating
system or processor cause memory corruption. If your bindings or
the external code are faulty, you're in trouble regardless of
whether you annotate it with @safe / @trusted / @system.
However, at least marking the bindings as @trusted or @system is
in line with D's memory safety goal (point 3 above).
More information about the Digitalmars-d
mailing list