Skip to content

Improvements to WASM binding generator - #247

Open
vijaiaeroastro wants to merge 16 commits into
developfrom
fix/wasm
Open

vijaiaeroastro wants to merge 16 commits into
developfrom
fix/wasm

Conversation

@vijaiaeroastro

Copy link
Copy Markdown
Collaborator

This PR improves the existing Emscripten (embind) binding so that a component such as lib3mf can use it without hand-patched bindings. The notes for users are in the new Documentation/WASM.md. Most of these improvements come from various issues encountered in lib3mf. However, the improvements are very abstract and not specific to any specific library.

What changed

Generator (Source/buildbindingwasm.go)

  • Arrays are exchanged as typed arrays, not embind vectors. Homogeneous numeric structs use one interleaved typed array. Other structs use one typed array per member. 64-bit integers and pointer values are BigInt.
  • Callbacks are supported: a method that takes a callback takes a JS function, and the user data parameter is hidden. This covers class arguments (acquired through the component's acquire method, so the JS object owns a reference), array out parameters (size query, then data), and callback types without user data.
  • ReadMemory and WriteMemory are generated for components with callbacks, for libraries that pass buffer addresses as integers (write and read callbacks).
  • Every class with callback methods gets ClearCallbacks() to release the registered JS functions. The module cannot tell when a library destroys an object, so it does not purge them by itself. Calling it is the user's responsibility.
  • Methods that cannot be expressed are skipped with a reason in the generated file, so the output always compiles. This covers arrays of bool, pointer or enum, returned arrays, enums, structs and classes of imported components, and symbol lookup methods.
  • The generated bindings compile without warnings under -Wall -Wextra.
  • Source/automaticcomponenttoolkit.go: ACT stops with a clear error if a WASM binding has no Cpp binding next to it.
  • The generated buildExample.py builds with em++ and emits TypeScript declarations. The generated example reads the version out-parameter names from the IDL and calls .delete().

Fixes outside WASM, found while testing

  • buildbindingccpp.go: the generated CDynamic example contained invalid C (a stray format argument and a missing );).
  • buildimplementationcpp.go: the base class stub no longer generates ClassTypeId, which made the derived classes ambiguous.
  • ThreadSafety example stubs were missing #include <algorithm>.

New example: Examples/KitchenSink
A component that uses every construct of the IDL, with a hand-completed C++ implementation. Its WASM test (KitchenSink_Test.mjs, 136 checks) runs through Examples/KitchenSink/build.sh, which is added to Examples/build.sh.

Behavior to know about

  • Callbacks are synchronous. A library may call an array-returning callback twice (size query, then data).
  • A stored callback stays valid until the same method is called again on the same library object with the same string arguments, or until the module ends. Several consumers, such as key wrapping callbacks per consumer ID, therefore do not replace each other.
  • If a library owns an object through its own shared_ptr (lib3mf does this for some callback arguments), use that object only inside the callback.
  • Classes of imported components compile but are not bound at runtime, because two bindings in one module collide on the base class and the wrapper.
  • The JS API for struct arrays changes from embind vectors to typed arrays. Existing consumers that rely on the old shape need to adapt.

Testing

Check Result
KitchenSink in node, emsdk 7.0.1 and 4.0.21 (CI image version) 136/136 on both
KitchenSink in headless Chrome run on an earlier 129-check version, not repeated with the final test
Primes, UnitTest, Calculator, ThreadSafety, RTTI build and run in node (7.0.1)
lib3mf, regenerated with this generator (test target only) 14/14 on both emsdk versions, including encrypted write and read with key wrapping callbacks, WriteToCallback, ReadFromCallback and 1,000,000 vertices and triangles in about 30 ms
lib3mf Tests/DisplacementWasm.mjs passes unchanged
Generator builds for all 7 targets of Build/build.sh

Known limitations

  • The callback registry is not purged when an object is deleted (use ClearCallbacks()).
  • If Acquire itself throws while wrapping a callback argument, the acquired instance leaks.
  • Imported enums and structs are not supported.
  • The README feature matrix still says "partial support" for WASM.

Notes for reviewers

  • Review against develop. The branch has 16 commits, and about 26,000 of the added lines are generated KitchenSink output. The review-relevant code is Source/buildbindingwasm.go, the small changes in the three other Go files, Documentation/WASM.md and the KitchenSink IDL, stubs and test.

… arrays

Bugs fixed (each one broke compilation or failed at call time):
- struct return values of out-param methods used a nonexistent type
- struct-array out parameters were passed to embind as raw vectors
- protected _lockInstance/_unlockInstance were bound for thread-safe components
- class parameters of injected components (Numbers:Variable) produced invalid types
- basicarray parameters failed at runtime (vector types were never registered)
- pointer parameters, returns and struct members were not supported
- struct returns of static wrappers were detected by a string prefix

Array API (breaking for users of the old embind vector handles):
- basic arrays are exchanged as typed arrays, inputs accept typed or plain arrays
- structs with members of one numeric type use one interleaved typed array
- other structs use an object with one typed array per member

Also ignore WASM example build output and refresh the committed RTTI bindings.
…ild info

Components that set prereleasemethod or buildinfomethod got a stray format
argument (%!(EXTRA string=...)) and two printf calls without closing
parenthesis in Examples/CDynamic/*_example.c.
A test component for bindings: all scalar types in every direction, pointers,
strings, enums, homogeneous and heterogeneous structs, basic and struct arrays,
class hierarchies, optional classes, callbacks, journal, prerelease and build
info, and the thread safety option. Includes a hand-completed C++
implementation and a WASM test (build and run with buildExample.py).
Point to Examples/KitchenSink from the README and the contributor's guide as a
resource for building and testing bindings and for reproducing binding issues,
and add the WASM binding, which was missing, to the bindings feature matrix.
The Travis CI badge pointed to a service that is no longer used. Show the
status of the two GitHub Actions workflows on develop instead.
JS functions can now be passed wherever the IDL takes a functiontype. The
UserData pointer is hidden from JS, a static trampoline per callback type
forwards to the JS function, and results come from the return value (one
result directly, several as an object keyed by parameter name).

Callbacks with class parameters or out-arrays are still skipped with a
comment in the generated file. KitchenSink gains callback methods and tests
that exercise this, and the README binding matrix marks WASM callbacks as
supported.
The generated WASM file includes the Cpp implicit binding header, so an IDL
listing WASM without Cpp produced a file that did not compile. Stop with an
explanatory error instead.
This builds and tests the WASM binding against every IDL construct.
Every component with a WASM binding now gets Examples/WASM/buildExample.py.
It compiles the implementation and binding with em++, documents the flags the
binding needs, targets web, worker and node by default (RTTI's script was
node only) and runs the .mjs examples. RTTI and KitchenSink use the generated
script instead of their hand-maintained copies.
The generated build script passes --emit-tsd so a .d.ts file is produced next
to the module. The generated example now notes the BigInt, handle lifetime
and error conventions and shows creating an object with the first factory
method, with error handling and cleanup.
Covers the Cpp binding requirement, handle lifetime, errors, BigInt and the
array and callback conventions.
The derived interfaces already implement ClassTypeId, so the extra method in
the base stub made every derived stub fail with 'more than one final
overrider'.
The UnitTest stubs returned placeholder ids from ClassTypeId, which made the
generated factory return null objects. The Primes sieve duplicated the square
root and missed multiples of a prime equal to the limit; the tutorial had the
same code.
…review fixes

Callbacks
- Class arguments arrive as their most derived type; the JS object owns a
  reference taken through the component's acquire method.
- Array out-parameters are returned by the JS function and written with the
  size query / data protocol of the C library. The size announced by a query
  counts as capacity for the data call on the same input (lib3mf passes a
  smaller capacity when it wraps keys).
- ReadMemory and WriteMemory let callbacks that receive a buffer address as an
  integer read and write it without exporting HEAPU8.
- The callback context is replaced only after the library call succeeded, a
  removed function no longer throws through C frames, and a class handle of an
  unexpected type releases its reference.

Generator
- Methods and callback types with an enum or struct of an imported component
  are skipped with a comment instead of generating invalid C++.
- Out-parameter wrappers deduce the type of class and enum return values.
- buildExample.py looks for em++ before creating its temporary folder.

KitchenSink
- Methods for class arguments, array out-parameters, the capacity quirk and
  buffer addresses, with tests (129 checks, no known gaps).

Examples and docs
- ThreadSafety stubs include <algorithm>.
- README and the review checklist describe the final behaviour and results.
…ASM.md

The README keeps a link and the feature matrix row, like the other bindings.
- Callback registry is keyed by library object, method and string arguments, so several
  consumers (for example key wrapping callbacks) no longer replace each other
- Add ClearCallbacks() to every class with callback methods to release the JS functions
- Fix enum return with a class argument, zero-initialise JS structs, accept Number or BigInt
  in ReadMemory/WriteMemory, tolerate callback results without arrays and reject oversize ones
- Skip methods with arrays of bool, pointer or enum, returned arrays, class parameters of
  imported components and duplicate callback parameters instead of generating invalid C++
- Generated bindings compile without warnings under -Wall -Wextra
- Extend KitchenSink (ColorOfShape, AddNamedCallback, CallNamed) and its WASM test (136 checks)
- Correct Documentation/WASM.md for imported components and callback lifetimes
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

Successfully merging this pull request may close these issues.

1 participant