Prototype of Ownership/Borrowing System for D
Timon Gehr
timon.gehr at gmx.ch
Sun Nov 24 14:51:31 UTC 2019
On 24.11.19 14:42, Sebastiaan Koppe wrote:
> On Saturday, 23 November 2019 at 23:40:05 UTC, Timon Gehr wrote:
>> struct MP(T){ // owning, malloc-backed pointer
>> private T* payload;
>> @disable this();
>> @disable this(T*); // can't construct
>> @disable this(this); // can't copy (move-only type; therefore track
>> this type like you track
>> pointers in @live now)
>> pragma(inline,true){
>> private @system ~this(){} // only current module can drop
>> // values, in @system or @trusted code
>> ref T borrow()return{ return *payload; }
>> }
>> // can borrow out internal pointer
>> alias borrow this;
>> }
>>
>> @safe MP!T malloc(); // type tracks allocator
>> @trusted void free(MP!T); // @safe because pointer is known to be
>> unique and malloc'd
>
> To be honest I don't fully understand all the points you are making.
> ...
Most points are in support of this kind of strategy.
> But that, that is a thing of beauty, exactly what I want.
>
> The insight I gained from it is that you should not annotate functions,
> but rather, express the semantics you need by annotating a struct. Taken
> to its natural conclusion, that would make raw pointers @system.
This is indeed what Rust does. In D, raw pointers without additional
semantics can actually be fine in @safe code (for example, `new int`
returns an `int*`, and so does `&x` for a module-level (thread-local)
`int x;`), but @trusted and @system code has to be careful what raw
pointers it passes to @safe functions.
> To use
> them in @safe you would need a wrapper struct with the semantics you
> need. This also scales really well, instead of adding yet another
> @annotation to every function every year, you just update your structs
> with the latest semantics you need.
>
> If I have some time I am going to reread your latest posts, as I want to
> have a better understanding of what you are saying.
> ...
Feel free to ask if specific things are unclear. I had a major deadline
yesterday and couldn't spend a lot of my time to make my posts more
detailed. (And often, it is not so clear a priori which points deserve
elaboration.)
> Thank you for fighting this fight.
Sure! I can't help it. :)
More information about the Digitalmars-d
mailing list