Simplification of @trusted

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Jun 17 17:46:31 UTC 2021


On Thu, Jun 17, 2021 at 05:14:12PM +0000, Paul Backus via Digitalmars-d wrote:
> 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:
[...]
> > > ```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()];
> > > }
> > > ```
[...]
> 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).

Using an out contract is a rather weak guarantee, because the author of
favoriteNumber can easily change the contract and silently break
favoriteElement's assumptions.  Using an assert in favoriteElement is
better, because if favoriteNumber ever changes in an incompatible way,
the assert would trigger.


T

-- 
The best way to destroy a cause is to defend it poorly.


More information about the Digitalmars-d mailing list