Discussion Thread: DIP 1028--Make @safe the Default--Final Review

Mathias LANG geod24 at gmail.com
Mon Apr 6 03:16:00 UTC 2020


On Monday, 6 April 2020 at 02:23:03 UTC, Walter Bright wrote:
> On 4/5/2020 12:22 PM, Timon Gehr wrote:
>> Right. How can you claim that this is @safe code?
>
> Extern declarations are always going to rely on the user 
> declaring them correctly. It's an inherent property of a 
> language that supports separate compilation.

But correctly is not a black-and-white thing, it's a spectrum.
Take `memcpy` for example. Its prototype in C is:
```
void* memcpy(void *restrict dst, const void *restrict src, size_t 
n);
```

In druntime, it is:
```
extern (C):
@system:
nothrow:
@nogc:
void* memcpy(return void* s1, scope const void* s2, size_t n) 
pure;
```
https://github.com/dlang/druntime/blob/eb6911eeb4f632d42abe4e28f5030158c9e7af52/src/core/stdc/string.d#L42

Now what happens if we omit *any* of those attributes:
- `nothrow`: Can't call it from a `nothrow` function without a 
try/catch. So we *know* it does not throw, but the function 
doesn't guarantee it, so we are restricted in the way we call it.
- `@nogc`: Can't call it from a `@nogc` function. We also *know* 
it is `@nogc`, but the function doesn't expose that.
- `pure`: Same thing. While the function is `pure`, the lack of 
attribute *restricts usage*.
- `scope` on parameter: Same thing, usage is *restricted* to 
passing points which are not scope.
- A lack of `const` is also restrictive, because `const` is the 
loosest modifier (as mutable and immutable both implicitly 
convert to `const`)
- `return` is the *only* one that can cause trouble, because not 
adding it allows escaping a reference to a local variable.

So as long as I don't forget `return` on the first argument, and 
get the arguments type right, I won't violate *any* promise of 
the language even by forgetting to add `nothrow`, `@nogc` or 
`scope`. And even forgetting `const` will not violate any promise 
of the language, it will just restrict my usage.


More information about the Digitalmars-d mailing list