Simplification of @trusted
Paul Backus
snarwin at gmail.com
Thu Jun 17 17:14:12 UTC 2021
On Thursday, 17 June 2021 at 16:50:28 UTC, Paolo Invernizzi wrote:
> On Thursday, 17 June 2021 at 16:21:53 UTC, Paul Backus wrote:
>> On Thursday, 17 June 2021 at 14:30:58 UTC, Steven
>> Schveighoffer wrote:
>>> [...]
>>
>> Consider the following example:
>>
>> ```d
>> size_t favoriteNumber() @safe { return 42; }
>>
>> int favoriteElement(ref int[50] array) @trusted
>> {
>> // This is memory safe because we know favoriteNumber
>> returns 42
>> return array.ptr[favoriteNumber()];
>> }
>> ```
[...]
>>
>> There is no language change you can make (short of removing
>> `@trusted` entirely) that will prevent this situation from
>> arising.
>
> Apart from reviewers asking the author of favoriteElement to
> assert that the index is appropriate ...
Yes, that's exactly my point. This can't be solved by changing
the language, but it *can* be solved by a good code review
process. So we should avoid wasting our time on language-based
solutions (like Steven's proposal for `@system` blocks in
`@trusted` functions), and instead focus on how to improve our
code review process so that this kind of brittle `@trusted` code
doesn't slip through.
For example, a review process that enforced the following rules
would have flagged `favoriteElement` as problematic:
1. Every use of `@trusted` must be accompanied by a comment
containing a proof of memory safety.
2. A memory-safety proof for `@trusted` code may not rely on any
knowledge about other functions beyond what is implied by their
signatures.
Specifically, `favoriteElement` violates rule (2). To bring it
into compliance, we'd have to either add an `assert` to verify
our assumption about `favoriteNumber`, or find a way to encode
that assumption into `favoriteNumber`'s signature (for example,
with an `out` contract).
More information about the Digitalmars-d
mailing list