memory safety checks and trust

Adam D. Ruppe destructionator at gmail.com
Tue Apr 14 22:58:45 UTC 2020


On Tuesday, 14 April 2020 at 20:10:20 UTC, Walter Bright wrote:
> So, Adam, how do you feel about:
>
>   @system int* pumpkin(int i) { return &i);
>
> Timon says that should be an error. What is your opinion?

I could go either way on it. That does catch a real problem in 
real world Phobos use and it is very rarely what you actually 
want:

string s() {
         return hexDigest!MD5("test");
}

So I see the value in that error.

But the array example is different anyway because the above thing 
is almost always wrong while the array is far more ambiguous. Is 
it temporary scratch? Is it being passed to a different thread 
but you then wait until the other thread is done before 
returning? (That's what my crazy code that prompted this did btw.)

If it is an error 99% of the time, the error seems reasonable. 
But even then, what if you are one of the 1% of exceptions?

Or with the array, I'd guess it is an error 60% of the time. 
Maybe still fair to have it an error there... but what if you are 
in the other 40%? What do you do?

How do I tell the compiler "I know this looks wrong at first 
glance, but trust me"?

Again, that's why my subject line for this thread was "and 
trust". I don't mind this error most the time, we can see from 
experience that this kind of mistake can be made often enough to 
take note of it.

I just want some way to tell the compiler to trust me. OK, I 
confess, it'd probably still annoy me, like the annoying integral 
promotion casts kinda drive me nuts. But I can live with it, 
since at least there's a way to cast it away.

But here, @trusted didn't work. cast didn't work. So it just 
stopped me. I changed the code to use a static TLS instance 
instead of a stack item and got it compiling again, but I'm also 
concerned that D is going down an ugly path here. What if my 
workaround hack now gets plugged later? I want something, akin to 
`cast`, that is formally defined to function as an escape hatch.


(Maybe a double cast through void* might work, there seems to be 
potential in tricking the compiler with that, but those can be 
even harder to get right than the original lifetime problem, so 
we do need to make sure the cure isn't worse than the disease in 
allowing the exceptions.)


More information about the Digitalmars-d mailing list