@trusted attribute should be replaced with @trusted blocks

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Jan 16 18:15:08 UTC 2020


On Thu, Jan 16, 2020 at 10:45:46AM -0500, Steven Schveighoffer via Digitalmars-d wrote:
[...]
> In fact, because of how the system works, @safe code is LESS likely to
> mean what you think.
> 
> If you see a @safe function, it just means "some of this is
> mechanically checked". It doesn't mean that the function is so much
> more solid than a @trusted function that you can skip the review. It
> can have trusted escapes that force the whole function into the realm
> of needing review.
[...]

Yeah, that's the part that makes me uncomfortable every time I see a
@trusted lambda inside a function that *clearly* does not sport a @safe
interface, as in, its safety is dependent on the surrounding code.

I think it would be better to completely outlaw @trusted blocks inside a
@safe function, and to require calling an external @trusted function.
And inside a @trusted function, most of the body will still be subject
to @safe checks, except for explicitly-marked out @system scopes.

This way, the meaning of @safe becomes "this function has been
thoroughly mechanically checked, and it will not corrupt memory provided
all @trusted functions that it calls operate correctly". And @trusted
would mean "this function has been mechanically checked except for those
blocks explicitly marked @safe, which must be reviewed manually together
with the rest of the function body".

The latter is useful as a preventative measure: if you allow
unrestricted use of @system code inside a @trusted function, then every
single code change made to that function requires the manual
re-evaluation of the entire function, because you don't know if you've
inadvertently introduced a safety hole.  Not allowing @system code by
default means if you accidentally slip up outside of the isolated
@system blocks, the compiler will complain and you will fix it. This
way, you minimize the surface area of potential problems to a smaller
scope inside the @trusted function, and leverage the compiler's
automatic checks to catch your mistakes, as opposed to having zero
safeguards as soon as you slap @trusted on your function.


T

-- 
Try to keep an open mind, but not so open your brain falls out. -- theboz


More information about the Digitalmars-d mailing list