BorrowScript
BorrowScript copied to clipboard
Unsafe code
Something the spec hasn't touched is the notion of unsafe code with manual memory management.
I think it would also offer a great starting point for the compiler as an unsafe mode would essentially be a statically compiled subset of TypeScript with manual memory management. It would let us try out the viability of the type system where the concepts of the borrow checker could be applied on top of that.
function main() {
unsafe {
const foo: string = "" // allocate a dynamic string on the heap
delete foo // delete allocation
}
}
So as an example, the standard library might include this implementation for an Array
struct ArrayItem<T> {
value: T
next: ArrayItem<T | null>
}
class Array<T> {
private _items: ArrayItem<T> | null
constructor() {
this._items = null
}
destructor() {
// traverse linked list and delete links
}
push(item: T) {
// create or add to linked list
}
pop() {}
shift() {}
unshift() {}
}
const list = new Array<string>() // ref to an array
const a = "a" // ref to a dynamic string
const b = "b" // ref to a dynamic string
list.push(a) // add ref to array
list.push(b) // add ref to array
delete list
delete a
delete b
Deleting the Array
doesn't delete the items contained in the linked list when unsafe
.
When using a borrow checker, the items pushed into the array would have ownership moved to the class. This means the array will be able to clean up all the references it owns - deleting the items and values in the array.
With unsafe
, the array cannot know to delete the values - only the links.