Manu's `shared` vs the @trusted promise

Simen Kjærås simen.kjaras at gmail.com
Mon Oct 22 08:39:27 UTC 2018


On Sunday, 21 October 2018 at 22:03:00 UTC, ag0aep6g wrote:
> (2) What's Wrong with That?
>
> The @trusted contract says that an @trusted function must be 
> safe when called from an @safe function. That calling @safe 
> function might be located in the same module, meaning it might 
> have the same level of access as the @trusted function.
>
> That means, Atomic.incr is invalid. It's invalid whether 
> Atomic.badboy exists or not. It's invalid because we can even 
> possibly write an Atomic.badboy. That's my interpretation of 
> the spec, at least.
>
> But according to Manu, Atomic.incr is fine as long as there's 
> no Atomic.badbody that messes things up. So it looks like we're 
> expected to violate the @trusted contract when dealing with 
> Manu's `shared`. But when we routinely have to break the rules, 
> then that's a sign that the rules are bad.

It's invalid only if Atomic.badboy exists. As the writer of 
Atomic, you should not put badboy in there. If someone else on 
your dev team put it there, you have bigger problems - do more 
code reviews, put stuff in smaller modules, etc.

Essentially, since the module is the unit of encapsulation, it 
also needs to be the unit of programmer responsibility.


> (3) Maybe It Can Be Made to Work?
>
> There might be a way to implement Atomic without breaking the 
> @trusted promise:
>
> ----
> struct Atomic
> {
>     shared/*!*/ int x;
>
>     void incr() shared @trusted { /* ... */ }
>
>     /* Now this gets rejected by the compiler: */
>     void badboy() @safe { ++x; } /* compiler error  */
> }
> ----
>
> With a `shared int x` there's no way that @safe code might 
> access it, so the @trusted promise is kept.

It's clearly better to mark x as shared, yes. However, I fail to 
see how this is significantly different from the above - J. 
Random Newbie can still open that file, remove the 'shared' 
qualifier on x, and rewrite badboy to be thread-unsafe. If we're 
going to assume that bad actors have write-access to all files, 
there's no end to the trouble that can be had.

--
   Simen


More information about the Digitalmars-d mailing list