Prototype of Ownership/Borrowing System for D

mipri mipri at minimaltype.com
Wed Nov 20 08:37:37 UTC 2019


On Wednesday, 20 November 2019 at 04:59:37 UTC, Walter Bright 
wrote:
> https://github.com/dlang/dmd/pull/10586
>
> It's entirely opt-in by adding the `@live` attribute on a 
> function, and the implementation is pretty much contained in 
> one module, so it doesn't disrupt the rest of the compiler.

It's doubly-linked lists that are supposed to be impossible
without evading the borrow checker, but a linked list seems
to be useful if you just want to provoke it:

---
import std.stdio: write, writeln;
import core.stdc.stdlib: malloc, free;

struct List {
     bool empty;
     List* next;
     int value;

     @live void popFront() {
         empty = next.empty;
         value = next.value;
         next = next.next;
     }
     @live List* front() {
         return &this;
     }
}

@live void dump(scope List* p) {
     if (!p.empty) {
         write(p.value, ' ');
         return dump(p.next);
     } else {
         writeln;
     }
}

@live void free_list(List* p) {
     if (!p.empty) {
         free_list(p.next);
         free(p);
     } else {
         free(p);
     }
}

// three undefined states
void incr(scope List* p) {
     while (!p.empty) {
         p.value++;
         p = p.next;
     }
}

// both Undefined and Owner
void dump_negated(scope List* p) {
     foreach (node; *p) {
         write(-node.value, ' ');
     }
     writeln;
}

// all kinds of errors
List* listOf(int[] args...) {
     List* result = cast(List*)malloc(List.sizeof);
     List* node = result;
     foreach (arg; args) {
         node.empty = false;
         node.value = arg;
         node.next = cast(List*)malloc(List.sizeof);
         node = node.next;
     }
     node.empty = true;
     return result;
}

@live void main() {
     List* a = listOf(1, 2, 3);
     dump(a);
     incr(a);
     dump(a);
     dump_negated(a);
     free_list(a);
     // free_list(a); // undefined state and can't be read
}



More information about the Digitalmars-d mailing list