JasonBock / WebAssembly.Generators

Source generators for the WebAssembly package.
MIT License
1 stars 1 forks source link

Generate a `Create()` Static Factory Method #4

Closed JasonBock closed 3 years ago

JasonBock commented 3 years ago

Instead of just providing a generated type to call methods on the .wasm module, which forces the developer to do something like this:

var collatz = Compile.FromBinary<CollatzTest>("collatz.wasm");
var result = collatz(new ImportDictionary()).Exports.collatz(3);

The developer could do this:

var collatz = CollatzTest.Create();
var result = collatz.collatz(3);

The source generator would do something like this:

public static CollatzTest Create(string path = "collatz.wasm") =>
  Compile.FromBinary<CollatzTest>(path)(new ImportDictionary()).Exports;

Since the developer has to specify the .wasm source file as an AdditionalFile, the SG should be able to provide the path with a default value. The developer can choose to provide a different one if needed.

If there are imports, consider generating a interface with default implementations that a user can implement to handle callbacks.

public interface ICollatzCallbacks
{
  void collatzCallback(int a0) { }
}

Naming convention would be $"I{ClassName}Callbacks".

Create() would then be gen'd to do this:

public static CollatzTest Create(ICollatzCallbacks callbacks, string path = "collatz.wasm") =>
  Compile.FromBinary<CollatzTest>(path)(new ImportDictionary
  {
    { "imports", "collatzCallback", new FunctionImport(new Action<int>(value => callbacks.collatzCallback(value))) }
  }).Exports;

Note that the developer isn't forced to use Create() - it's just a convenience method that should handle the majority of use cases.