@trusted considered harmful

David Nadlinger see at klickverbot.at
Sat Jul 28 08:05:56 PDT 2012


On Saturday, 28 July 2012 at 11:05:34 UTC, Artur Skawina wrote:
> On 07/28/12 02:08, David Nadlinger wrote:
>> @trusted in its current form needs to go. Its design is badly 
>> broken, as it leaks implementation details and encourages 
>> writing unsafe code.
>
> The problem with @trusted is that it is transitive.
>
> @trusted should allow unsafe operations in the covered scope 
> (right now -
> the function), but disallow calling unsafe (@system) code. IOW 
> a @safe
> function should only be able to call a @safe or @trusted one, 
> and the same
> restriction should apply to @trusted functions. This way you 
> can actually
> audit the code - something which isn't typically possible right 
> now, when
> you have no control over what the "trusted" code might call.

Sorry, while I think I know which problem you are referring to, I 
don't see what your suggestion does to address it. There is no 
such thing as allowing unsafe code »only in the current scope«. 
As soon as you are allowed to do unsafe things, you can e.g. just 
cast a @system function to @safe and call it. Or jump to it using 
inline assembly, etc.

My suggestion might not be perfect, but it addresses the problem 
by allowing you to trust only the specific piece of your code 
which actually need to perform unsafe things. Reviewers can 
concentrate on the smaller sections to make sure that what they 
do is indeed @safe (e.g. that they don't call unsafe external 
code), and if something unsafe is accidentally done outside, the 
compiler will catch it.

I also think implementing your suggestion, i.e. distinguishing 
between »local« and »external« code, would add much value for 
another reason: In my experience, the most frequent use case for 
@trusted is precisely to interface with external code that is 
@system, either for legacy reasons of because it just can't be 
safe in the general case (e.g. grep the Phobos sources for 
@trusted). It seems like the actual low-level pointer/inline asm 
magic is often encapsulated into separate (@system) functions 
anyway.

> The '@attribute {}' syntax is something that is needed, but 
> should probabl
> wait for /proper/ attribute handling, which should also allow 
> for a saner
> 'synchronized' etc.

What is »proper attribute handling« supposed to be? How would 
it influence the implementation of @trusted{}? How is 
synchronized related to @trusted?

David


More information about the Digitalmars-d mailing list