ref is unsafe

Rob T rob at ucora.com
Sun Dec 30 10:59:35 PST 2012


On Sunday, 30 December 2012 at 17:32:41 UTC, Nick Treleaven wrote:
> On 30/12/2012 09:17, Jonathan M Davis wrote:
>> The problem is the wrapper function.
>> You'd also have to disallow functions from returning ref 
>> parameters by ref.
>> Otherwise,
>>
>> ref int foo(ref int i)
>> {
>>     return i;
>> }
>>
>> ref int baz(int i)
>> {
>>     return foo(i);
>> }
>>
>> continues to cause problems. And making it illegal to return 
>> ref parameters by
>> ref would be a serious problem for wrapper ranges, because 
>> they do that sort
>> of thing all the time with front. So, that's not really going 
>> to work.
>
> I think the compiler needs to be able to mark foo as a function 
> that returns its input reference. Then, any arguments to foo 
> that are locals should cause an error at the call site (e.g. in 
> baz). So legal calls to foo can always be @safe.
>
> To extend the above code:
>
> ref int quux(ref int i)
> {
>     return foo(i);
> }
>
> Here the compiler already knows that foo returns its input 
> reference. So it checks whether foo is being passed a local - 
> no; but it also has to check if foo is passed any ref 
> parameters of quux, which it is. The compiler now has to mark 
> quux as a function that returns its input reference.
>
> Works?

That seems like a promising approach. If the compiler can track 
where the local is being passed by ref and returned by ref, then 
it should be able to determine if the ref to the local is leaving 
the scope it was originally conceived in and issue a compiler 
error if it is. The idea of "tagging" the local so that it can be 
tracked may work well. You may still be able to hide it from the 
compiler using pointers, but at that point you're not @safe 
anymore but that should be fine because all we want to do is 
allow returns by ref to be proven @safe or not.

In general terms, no reference to a local should ever leave it's 
scope, so ultimately the compiler *has* to track the scope of any 
local, no matter if it is being passed by ref or not, so really 
this is a solution that has to be implemented one way or the 
other.

--rt


More information about the Digitalmars-d mailing list