Alternative to Rust's borrow checking and explicit lifetimes?

Timon Gehr timon.gehr at gmx.ch
Thu Apr 16 12:48:56 UTC 2020


On 16.04.20 10:40, Walter Bright wrote:
> On 4/15/2020 7:39 PM, Timon Gehr wrote:
>> On 14.04.20 12:18, Walter Bright wrote:
>>> does do NLL, and uses Data Flow Analysis to achieve it.
>> Do you have an example where that helps?
> 
> int* malloc();
> void free(int*);
> 
> @live void test()
> {
>      auto p = malloc(); // p is owner
>      *p = 1;
>      scope q = p; // q borrows p
>      int x = *q;  // read from borrow
>      *p = 2;      // using p again ends lifetime of q, even though q is 
> in scope
>      x = *q;      // error, q is no longer valid
>      free(p);
> }
> ...

Thanks! (However, this would still be so much better if ownership was 
opt-in at the type level instead of using function annotations.)

> 
>> void ignore(int* p){}
>> void main()@live{
>>      int x=5;
>>      auto p=&x;
>>      x=3; // should fail, but compiles
>>      *p=4;
>>      ignore(p); // not necessary in Rust
>> }
>>
>> void ignore(int* p){}
>> void main()@live{
>>      int x=5;
>>      auto p=&x;
>>      *p=4;
>>      x=3;
>>      ignore(p); // not necessary in Rust
>> }
>>
>> Maybe the problem is that taking a local variable's address results in 
>> an owning pointer instead of a borrowing pointer, but that would not 
>> make any sense. How can a pointer ever own stack memory? Also, it 
>> appears that in a @safe function, it is impossible to ever dispose of 
>> such a pointer as it is both `scope` and has to be freed explicitly.
>>
>> @live also allows the address of the same local variable to be taken 
>> multiple times:
>>
>> void main()@live{
>>      int x=5;
>>      auto p=&x;
>>      auto q=&x;
>>      *p=4;
>>      *q=5;
>>      writeln(*p," ",*q);
>>      ignore(p);
>>      ignore(q);
>> }
> 
> You're right that taking the address of a local currently results in an 
> owning pointer. I'll think about the best way to deal with this.

The owner is the local variable and the pointer should borrow from it.

> Though note that if @safe is also added to the function, taking the address of 
> a local is disallowed.
> 

I assumed -dip1000. Anyway, if you add @safe, @live usually becomes 
essentially useless.


More information about the Digitalmars-d mailing list