Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detecting using usage #203

Closed
extremeheat opened this issue Sep 13, 2023 · 1 comment
Closed

Detecting using usage #203

extremeheat opened this issue Sep 13, 2023 · 1 comment

Comments

@extremeheat
Copy link

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.

@rbuckton
Copy link
Collaborator

It is possible to detect whether @@dispose was read by making it a getter, which might be "good enough" for some purposes. Anything more complex is better discussed in #195 or #49

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants