Safety, undefined behavior, @safe, @trusted

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Thu Nov 5 13:30:42 PST 2009


Steven Schveighoffer wrote:
> On Thu, 05 Nov 2009 15:20:34 -0500, Andrei Alexandrescu 
> <SeeWebsiteForEmail at erdani.org> wrote:
> 
>> Steven Schveighoffer wrote:
>>> On Thu, 05 Nov 2009 14:57:48 -0500, Michel Fortin 
>>> <michel.fortin at michelf.com> wrote:
>>>
>>>> On 2009-11-05 13:33:09 -0500, Walter Bright 
>>>> <newshound1 at digitalmars.com> said:
>>>>
>>>>> Safety seems more and more to be a characteristic of a function, 
>>>>> rather than a module or command line switch. To that end, I propose 
>>>>> two new attributes:
>>>>>  @safe
>>>>> @trusted
>>>>
>>>> Looks like a good proposal.
>>>>
>>>> That said, since most functions are probably going to be safe, 
>>>> wouldn't it be better to remove @safe and replace it by its 
>>>> counterpart: an @unsafe attribute? This would make things safe by 
>>>> default, which is undoubtedly safer, and avoid the unnecessary 
>>>> clutter of @safe annotations everywhere.
>>>  If unsafe means you cannot pass pointers to local variables, then 
>>> half of tango (and other performance oriented libs which use stack 
>>> allocation as much as possible) will fail to compile.
>>
>> While I agree with your point, quick question: could you use ref 
>> parameters instead? Ref will be usable in SafeD.
> 
> Most of the usages are like this:
> 
> ubyte[1024] buffer;
> functionThatNeedsBufferSpace(buffer);
> 
> where functionThatNeedsBufferSpace takes a ubyte[], thereby taking an 
> address of the local data.
> 
> So it's not explicit address taking, but it's the same thing under the 
> hood.  There always exists the potential for the stack reference to escape.

I see, thank you. I am confident that a trusted reap could be 
implemented in the standard library. (google reap)

> Similar case is scope classes (which are sometimes used to allocate a 
> temporary class for performance in tango).  I can't see scope classes 
> being allowed if you can't take addresses of local variables.

Yah, in fact I think scope classes should just go. But don't hold that 
against me. :o)

> I'm not saying that safed needs to allow these kinds of things somehow 
> (thereby employing escape analysis), but it might be too restrictive for 
> performance-oriented libs/apps.  I think it's acceptable that tango 
> eventually gets marked with @trusted, but by making @safe the default, 
> you will immediately make many D1 projects not compile without 
> significant effort, which might drive away developers from D2, or else 
> make people automatically mark all files as @trusted without thinking 
> about it.  By defaulting to untrusted and unsafe, you allow people to 
> incrementally add @safe and @trusted tags where they are appropriate and 
> correct.

I agree.


Andrei



More information about the Digitalmars-d mailing list