@system blocks and safer @trusted (ST) functions
ag0aep6g
anonymous at example.com
Mon Jul 26 00:37:36 UTC 2021
On Monday, 26 July 2021 at 00:08:51 UTC, jfondren wrote:
> On Sunday, 25 July 2021 at 17:47:40 UTC, Paul Backus wrote:
>> ```d
>> module example;
>>
>> size_t favoriteNumber() @safe { return 42; }
>>
>> int favoriteElement(ref int[50] array) @trusted
>> {
>> // This is memory safe because we know favoriteNumber
>> returns 42
>> @system {
>> return array.ptr[favoriteNumber()];
>> }
>> }
>> ```
>
> favoriteElement(), all on its own, has an unchecked type error:
> array is indexed by the int return value of favoriteNumber(),
> but int has a range outside of the 0..49 type of array's
> indices.
>
> In Ada, array's index type would be specified in the code and
> you'd have to either perform a checked type conversion to use
> favoriteNumber() there, or you'd have to change
> favoriteNumber() to return the index type rather than an int.
[...]
> This kind of precision with types isn't so pleasant in D but
> the class of error is the same and it's something a reviewer
> could spot when initially checking this code in.
What if favoriteNumber originally returns a ubyte, and
favoriteElement takes an int[256]?
```d
ubyte favoriteNumber() @safe { return 42; }
int favoriteElement(ref int[256] array) @trusted
{
return array.ptr[favoriteNumber()];
}
```
To your reviewer, there's nothing wrong with favoriteElement,
right?
But later someone might change the return type of favoriteNumber
to size_t and let it return 300. Badaboom: undefined behavior
after touching @safe code. As far as I can tell, there's no way
to truly make it impossible. Maybe disallowing calls to @safe
functions from @trusted and @system code would do the trick, but
that's impractical.
More information about the Digitalmars-d
mailing list