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

Enhancement: generate Symbol.dispose on exported structs #4117

Closed
H-Plus-Time opened this issue Sep 18, 2024 · 1 comment
Closed

Enhancement: generate Symbol.dispose on exported structs #4117

H-Plus-Time opened this issue Sep 18, 2024 · 1 comment

Comments

@H-Plus-Time
Copy link
Contributor

H-Plus-Time commented Sep 18, 2024

Motivation

The end-goal is drop-in integration with the Explicit Resource Management proposal (at Stage 3), with the nearer term goal of smoothing integration with tools that polyfill that.

The syntax it enables:

const func = () => {
  // declare an instance of our wasm-bindgen'd struct, specifying that it should be cleaned up
  // at the end of the scope it's declared in.
  using foobar = new MyStruct();
  // do a bunch of stuff...
}
func();
// When func() (or any other scope that keyword is used in) finishes, MyStruct::free is called

At the moment, Deno, Bun and Typescript >= 5.2 support the above directly; Usage without the above sugar is a little underwhelming, but probably still useful as a standardized target:

class MyStruct {
  free() {} // the usual wasm-bindgen methods elided for brevity
  [Symbol.dispose]() {
    this.free();
  }
}

const foo = new MyStruct();
foo[Symbol.dispose]();
// or, more usefully, use a disposable stack (supplied by a polyfill) to orchestrate 
// more elaborate resource management
const stack = new DisposableStack();
const bar = stack.use(new MyStruct());
const baz = stack.use(new OtherStruct(bar));
// free the above in reverse order
stack[Symbol.dispose](); 

Proposed Solution

Include the [Symbol.dispose]() { this.free() } pattern on all generated classes, polyfilling via Symbol.dispose ??= Symbol("Symbol.dispose");.

Async dispose is probably irrelevant

Alternatives

It's not terribly difficult for 3rd party authors to run the generated bindings through code transformation of their own.

Additional Context

The ecmascript proposal, for reference: https://github.com/tc39/proposal-explicit-resource-management

@daxpedda
Copy link
Collaborator

daxpedda commented Sep 28, 2024

Implemented in #4118.

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

No branches or pull requests

2 participants