Skip to content

[RFC] @external decorator rework to define module exports? #464

@jtenner

Description

@jtenner

Under direction of @dcodeIO I would like to open up discussion for changing the behavior of a decorator. Currently, the only way to define exports is by explicitly exporting something from the entry file.

export function add(a: i32, b: i32): i32 {
  return a + b;
}

It would be useful for some developers when consuming an AssemblyScript library from npm to have some functions automatically exported for convenience using the @external decorator.

Currently, the @external decorator is used to define imported functions like this.

@external("Math", "random")
declare function random(): f64;

Calling this declared random() function will actually call the imported function provided to the WebAssembly module. However, the @external behavior for AssemblyScript defined functions is currently undefined. We can instead use it to define a forced export like this.

@external("imageLoaded")
function imageLoadedInternal(img: Image, width: i32, height: i32): void {
  // do something with the image reference
}

Then it would be usable from the host under the name imageLoaded.

const wasm = instantiateBuffer(buffer, imports);
// obtain an image reference
var imgPointer = wasm.createImage();
// call the internal function
wasm.imageLoaded(imgPointer, 100, 200);

Note, these sorts of exports are best placed inside downstream libraries, because it's not a great user experience for developers to have to manually export downstream glue code functions like this.

// we could avoid ugly exports like this
export { imageLoaded } from "node_modules/myLib/assembly/index";

We could also avoid having to need to define additional entry points for the asc compiler. Currently, this is how https://github.com/as2d/as2d-example/ works.

asc assembly/index.ts node_modules/as2d/assembly/glue.ts -b build/optimized.wasm -t build/optimized.wat --sourceMap --validate --optimize --use Math=JSMath

Any thoughts?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions