@trusted attribute should be replaced with @trusted blocks

Joseph Rushton Wakeling joseph.wakeling at webdrake.net
Wed Jan 15 16:54:58 UTC 2020

On Wednesday, 15 January 2020 at 14:30:02 UTC, Ogi wrote:
> The idea is to remove @trusted as a function attribute and 
> instead introduce @trusted blocks:
> @safe fun() {
>     //safe code here
>     @trusted {
>         //those few lines that require manual checking
>     }
>     //we are safe again
> }
> Generally, only a few lines inside @trusted are actually unsafe.

So here's the problem with this approach (which was mentioned by 
several people in the discussion): the actual safety of a 
function like this is usually down to the combination of the 
lines that (in your example) are both inside and outside the 
@trusted block.

What that means is that it's important that an external user of 
the function doesn't just see it as @safe, but recognizes that 
the function -- as a whole -- is one whose promise of safety is 
conditional on its internals being correct.  And that's 
essentially what @trusted is for.

So, a better approach would be for the function to be marked up 
like this:

@trusted fun ()    // alerts the outside user
     // lines that on their own are provably safe go here
     @system {
         // these lines are allowed to use @system code
     // only provably safe lines here again

... and the compiler's behaviour would be to explicitly verify 
standard @safe rules for all the lines inside the @trusted 
function _except_ the ones inside a @system { ... } block.

Cf. Steven Schveighoffer's remarks here: 

This way the function signature gives a clear indicator to the 
user which functions are provably @safe, and which are safe only 
on the assumption that the developer has done their job properly.

More information about the Digitalmars-d mailing list