@system blocks and safer @trusted (ST) functions

Steven Schveighoffer schveiguy at gmail.com
Mon Jul 26 15:54:06 UTC 2021


On Monday, 26 July 2021 at 13:54:33 UTC, Paul Backus wrote:
> On Monday, 26 July 2021 at 11:02:48 UTC, Steven Schveighoffer 
> wrote:
>> However, with a specification of `favoriteNumber`, 
>> `favoriteElement` can be reviewed as correct:
>>
>> ```d
>> /// Returns: a size_t between 0 and 49, inclusive
>> size_t favoriteNumber() @safe;
>>
>> ...
>> ```
>
> If your theory of memory safety leads you to conclude that the 
> presence or absence of a comment can make otherwise-unsafe code 
> memory safe, you have taken a wrong turn somewhere in your 
> reasoning.

It's not a comment, it's a specification. Whereby I can conclude 
that if in review `favoriteNumber` returns something other than 0 
to 49, it is in error. Without specifications, exactly zero 
trusted lines of code can be written.

> I agree with you that the version with the comment is better, 
> more maintainable code, and that we should hold our code to 
> such standards in code review. But bad and hard-to-maintain 
> code can still be memory safe (that is: free from possible UB).

Consider that the posix function `read` has the specification 
that it will read data from a file descriptor, put the data into 
a passed-in buffer, *up to* the amount of bytes indicated in the 
third parameter. Its prototype is:

```d
@system extern(C) int read(int fd, void *ptr, size_t nBytes);
```

Without reading the code of `read`, you must conclude from the 
specification that it does what it says it should do, and not 
say, ignore `nBytes` and just use the pointed-at data for as many 
bytes as it wants. Without the specification, just relying on the 
types, you can conclude nothing, and can never use `read` from 
`@trusted` code, ever.

It's no different from `favoriteNumber`. In order to use it and 
make the assumption that it always will return 42, the author of 
that function must agree that that is what it's going to do. 
Otherwise (as you rightly say), anyone can change it to return 
something else *legitimately* and that might be beyond the bounds 
of the array you are using it for an index.

So without the specification for `favoriteNumber`, I must 
conclude that `favoriteElement` is invalid as written. With a 
specification I can reason about what does and does not 
constitute validity.

-Steve


More information about the Digitalmars-d mailing list