Detecting `using` usage
extremeheat opened this issue · comments
Is it possible to detect that a function was called with the using
keyword? Going by #195 it seems not. Having the ability to detect that a variable was called without using using
could help prevent leaking bugs where the intention of a function was to be called with using.
For example, I'd like a way so this throws an error:
function openFile () {
let fptr = fopen()
return {
read() {
if (!this.managedWithUsing) throw Error('leak: use `using` when calling openFile()')
}
[Symbol.dispose]() { free(fptr) }
}
}
const file = openFile()
file.read() // throws leak error
The closest thing currently I can think of would be to use a FinalizationRegistry
function openFile () {
let disposed = false
let registry = new FinalizationRegistry(() => {
if (!disposed) throw Error('leak')
});
let fptr = fopen()
const ret = {
read() {
}
[Symbol.dispose]() { free(fptr); disposed = true }
}
registry.register(ret, "");
return ret
}
const file = openFile()
file.read() // throws leak error
But I'd imagine the overhead would be much higher and likely be less reliable this way (errors here can be called at arbitrary points of the program) than having a [Symbol.enter] or a maybe something like a decorator.