Skip to content

Add support for std::expected in embind - #28156

Open
brendandahl wants to merge 1 commit into
emscripten-core:mainfrom
brendandahl:embind-expected
Open

brendandahl wants to merge 1 commit into
emscripten-core:mainfrom
brendandahl:embind-expected

Conversation

@brendandahl

Copy link
Copy Markdown
Collaborator

Support returning std::expected and custom expected types from embind functions, methods, and constructors.

Functions returning an expected type unwrap the value on success or throw the contained error as a JavaScript exception on failure.

Fixes #28112

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces support for binding std::expected<T, E> and custom expected types in Embind using register_expected and expected_trait. When returned to JavaScript, these types either unwrap the expected value or throw the unexpected error. The changes span Embind's C++ headers, JS library code, TypeScript definition generator, documentation, and tests. Feedback highlights a critical compatibility issue in wasm64 mode, where bitwise operations on EM_VAL handles (represented as BigInt in wasm64) will throw a TypeError, and suggests a type-safe fix.

Comment thread src/lib/libembind.js
Comment on lines +37 to +38
var isError = handle & 1;
handle &= ~1;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

In Emscripten's wasm64 mode, pointers and EM_VAL handles are represented as BigInt values in JavaScript. Performing a bitwise operation between a BigInt and a Number (like handle & 1 or handle &= ~1) will throw a TypeError: Cannot mix BigInt and other types.

To ensure compatibility with both wasm32 and wasm64, we should determine isError by converting handle to a Number first, and then clear the tag bit using a type-safe check that handles both Number and BigInt types.

      var isError = Number(handle) & 1;
      handle = typeof handle === 'bigint' ? (isError ? handle - 1n : handle) : (handle & ~1);

Support returning std::expected and custom expected types from embind
functions, methods, and constructors.

Functions returning an expected type unwrap the value on success or
throw the contained error as a JavaScript exception on failure.

Fixes emscripten-core#28112

This branch has not been deployed

No deployments
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.

Result-or-exception interface for Embind

1 participant