Simplification of @trusted

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Jun 16 18:11:18 UTC 2021


On Wed, Jun 16, 2021 at 05:36:46PM +0000, Alexandru Ermicioi via Digitalmars-d wrote:
> On Wednesday, 16 June 2021 at 15:37:22 UTC, H. S. Teoh wrote:
[...]
> > This isn't the first time it was suggested.  Way back when, it was
> > brought up and rejected because Walter thought that @trusted blocks
> > should be discouraged, and therefore should be ugly to write.  It
> > was extensively argued, but Walter preferred the "trusted lambda
> > idiom", precisely because it was ugly, required effort to write, and
> > therefore deters casual (ab)uses of @trusted.
[...]
> Yet, it forces to make entire function trusted if lambdas are not
> used, and safe guarantees are lost to remainder of the code due to
> that.

Yeah, that's a flaw that ought to be fixed.  Marking an entire function
@trusted is generally a bad idea, unless it's a trivial function of 3-4
lines or less, because it turns off ALL safety checks in the function
body.  If the function is large, that's an onerous burden to review
whether or not the code is indeed trustworthy.  What we really want is
to keep those checks on except for the few bits of code that the
compiler cannot automatically verify.

This has also been suggested before, and people are saying it again (and
in principle I agree):

1) Change the meaning of @trusted such that in a @trusted function,
@safe checks are NOT suppressed by default. Instead, a @trusted function
allows @system blocks in its body where @safe checks are temporarily
suspended.

2) @system blocks are NOT allowed inside a @safe function.

Here's the reasoning:

- @trusted marks the *entire* function tainted and needing to be
  reviewed -- this is necessary because the safety of @system blocks
  therein often depends on the surrounding code context, and has to be
  reviewed in that larger context. It is not sufficient to review only
  the blocks containing @system code.

- Leaving @safe checks on outside @system blocks allows the @trusted
  function to be still mechanically checked to minimize human error.
  This allows the unchecked code to be confined to as small of a code
  block as possible.  Basically, limit the surface area of potential
  errors.

- We continue to maintain a difference between a @safe function and a
  @trusted function, because we do not want to allow @system blocks in a
  @safe function -- that would make @safe essentially meaningless
  (anybody can just throw in @system blocks in @safe code to bypass
  safety checks).  Such escapes are only allowed if the entire function
  is marked @trusted, making it clear that it potentially does something
  unsafe and therefore needs careful scrutiny.


T

-- 
One Word to write them all, One Access to find them, One Excel to count them all, And thus to Windows bind them. -- Mike Champion


More information about the Digitalmars-d mailing list