@system blocks and safer @trusted (ST) functions

Paul Backus snarwin at gmail.com
Sun Jul 25 13:19:55 UTC 2021


On Sunday, 25 July 2021 at 05:05:44 UTC, Bruce Carneal wrote:
> At beerconf I committed to putting forward a DIP regarding a 
> new syntactic element to be made available within @trusted 
> functions, the @system block.  The presence of one or more 
> @system blocks would enable @safe checking elsewhere in the 
> enclosing @trusted function.

Both before and after this proposal, there are 3 kinds of code:

1. Code that is automatically checked for memory safety.
2. Code that is assumed by the compiler to be safe, and must be 
manually checked for memory safety.
3. Code that is not checked for memory safety, and is assumed to 
be unsafe.

Currently, (1) is marked `@safe`, (2) is marked `@trusted`, and 
(3) is marked `@system`.

Under this proposal, (1) would be marked either `@safe` or 
`@trusted`, (2) would be marked either `@trusted` or `@system`, 
and (3) would be marked `@system`. I do not think this is an 
improvement relative to the status quo.

> The problematic @trusted lambda escapes creeping in to "@safe" 
> code could be replaced going forward by a more honestly named 
> form, @trusted code with @system blocks. Best practices could 
> evolve to the point that @safe actually meant @safe again.

What makes `@trusted` lambdas problematic is that they implicitly 
depend on everything in their enclosing scope, which makes it 
easy for a change in the `@safe` portion of the code to 
accidentally violate an assumption that the `@trusted` portion 
depends on.

If we want to address this issue at the language level, the most 
direct solution is to require that `@trusted` lambdas make their 
dependencies explicit. This can be done by requiring all 
`@trusted` nested functions (of which lambdas are a special case) 
to be `static`.

Of course, this is a breaking change, so it would require a 
deprecation process.


More information about the Digitalmars-d mailing list