Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ See docs/process.md for more on how version tagging works.

6.0.14 (in development)
-----------------------
- Added `register_expected` and `expected_trait` to Embind for binding
`std::expected<T, E>` and custom expected types as return values that either
unwrap the expected value or throw the unexpected error in JavaScript.
- Remove support for the `EMCC_ONLY_FORCED_STDLIBS` environment variable, which
was deprecated in 2.0.14 (#13448). Use `-nostdlib` instead to avoid linking
standard libraries. (#28151)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1167,14 +1167,16 @@ Out of the box, *embind* provides converters for many standard C++ types:

For convenience, *embind* provides factory functions to register
``std::vector<T, class Allocator=std::allocator<T>>`` (:cpp:func:`register_vector`), ``std::map<K, V, class Compare=std::less<K>, class Allocator=std::allocator<std::pair<const K, V>>>``
(:cpp:func:`register_map`), and ``std::optional<T>`` (:cpp:func:`register_optional`) types:
(:cpp:func:`register_map`), ``std::optional<T>`` (:cpp:func:`register_optional`), and ``std::expected<T, E>`` (:cpp:func:`register_expected`) types:

.. code:: cpp

EMSCRIPTEN_BINDINGS(stl_wrappers) {
register_vector<int>("VectorInt");
register_map<int,int>("MapIntInt");
register_optional<std::string>();
register_expected<int>(); // defaults error type to emscripten::val
register_expected<int, std::string>();
}

A full example is shown below:
Expand All @@ -1185,6 +1187,7 @@ A full example is shown below:
#include <string>
#include <vector>
#include <optional>
#include <expected>

using namespace emscripten;

Expand All @@ -1203,16 +1206,25 @@ A full example is shown below:
return "hello";
}

std::expected<int, val> returnExpectedData(bool ok) {
if (ok) {
return 42;
}
return std::unexpected(val::global("Error").new_(std::string("failed")));
}

EMSCRIPTEN_BINDINGS(module) {
function("returnVectorData", &returnVectorData);
function("returnMapData", &returnMapData);
function("returnOptionalData", &returnOptionalData);
function("returnExpectedData", &returnExpectedData);

// register bindings for std::vector<int>, std::map<int, std::string>, and
// std::optional<std::string>.
// register bindings for std::vector<int>, std::map<int, std::string>,
// std::optional<std::string>, and std::expected<int, val>.
register_vector<int>("vector<int>");
register_map<int, std::string>("map<int, string>");
register_optional<std::string>();
register_expected<int>();
}


Expand Down Expand Up @@ -1268,6 +1280,19 @@ The following JavaScript can be used to interact with the above C++.
console.log(optional);
}

// Expected values return the unwrapped value or throw the error.
console.log(Module['returnExpectedData'](true)); // 42
try {
Module['returnExpectedData'](false);
} catch (e) {
console.error(e); // Error: failed
}

Custom expected or result types (for example, in C++17 or C++20 codebases) can
also be registered with :cpp:func:`register_expected` by specializing
``emscripten::expected_trait`` with ``value_type``, ``error_type``,
``has_value``, ``get_value``, and ``get_error``.


TypeScript Definitions
======================
Expand Down
21 changes: 21 additions & 0 deletions src/lib/libembind.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,23 @@ var LibraryEmbind = {
// emval is passed into JS via an interface
}`,
$EmValOptionalType: '=Object.assign({optional: true}, EmValType);',
$EmValExpectedType: `{
name: 'std::expected',
fromWireType: (handle) => {
// Valid Emval handles are even indices into emval_handles (pairs of
// [value, refcount]), so bit 0 is used to tag an error handle.
var isError = handle & 1;
handle &= ~1;
Comment on lines +37 to +38

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);

var rv = Emval.toValue(handle);
__emval_decref(handle);
if (isError) {
throw rv;
}
return rv;
},
readValueFromPointer: readPointer,
destructorFunction: null,
}`,

$throwUnboundTypeError: (message, types) => {
var unboundTypes = [];
Expand Down Expand Up @@ -555,6 +572,10 @@ var LibraryEmbind = {
registerType(rawOptionalType, EmValOptionalType);
},

_embind_register_expected: (rawExpectedType, rawValueType, rawErrorType) => {
registerType(rawExpectedType, EmValExpectedType);
},

_embind_register_memory_view: (rawType, dataTypeIndex, name) => {
var typeMapping = [
Int8Array,
Expand Down
21 changes: 19 additions & 2 deletions src/lib/libembind_gen.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ var LibraryEmbind = {
this.destructorType = 'none'; // Same as emval.
}
},
$ExpectedType: class {
constructor(type) {
this.type = type;
this.destructorType = 'none'; // Same as emval.
}
},
$FunctionDefinition: class {
hasPublicSymbol = true;
constructor(name, returnType, argumentTypes, functionIndex, thisType = null, isNonnullReturn = false, isAsync = false) {
Expand Down Expand Up @@ -89,11 +95,14 @@ var LibraryEmbind = {

out.push(argOut.join(', '));
let returnType = this.returnType;
if (returnType instanceof ExpectedType) {
returnType = returnType.type;
}
// Constructors can return a pointer, but it will be a non-null pointer.
// Change the return type to the class type so the TS output doesn't
// have `| null`.
if (this.isNonnullReturn && this.returnType instanceof PointerDefinition) {
returnType = this.returnType.classType;
if (this.isNonnullReturn && returnType instanceof PointerDefinition) {
returnType = returnType.classType;
}
returnType = nameMap(returnType, true);
if (this.isAsync) {
Expand Down Expand Up @@ -455,6 +464,9 @@ var LibraryEmbind = {
if (type instanceof OptionalType) {
return `${this.typeToJsName(type.type, isFromWireType)} | undefined`;
}
if (type instanceof ExpectedType) {
return this.typeToJsName(type.type, isFromWireType);
}
return type.name;
}

Expand Down Expand Up @@ -618,6 +630,11 @@ var LibraryEmbind = {
return [new OptionalType(type)];
});
},
_embind_register_expected: (rawExpectedType, rawValueType, rawErrorType) => {
whenDependentTypesAreResolved([rawExpectedType], [rawValueType, rawErrorType], function(types) {
return [new ExpectedType(types[0])];
});
},
_embind_register_memory_view: (rawType, dataTypeIndex, name) => {
// TODO
},
Expand Down
1 change: 1 addition & 0 deletions src/lib/libsigs.js
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,7 @@ sigs = {
_embind_register_emval__sig: 'vp',
_embind_register_enum__sig: 'vpppii',
_embind_register_enum_value__sig: 'vppi',
_embind_register_expected__sig: 'vppp',
_embind_register_float__sig: 'vppp',
_embind_register_function__sig: 'vpippppii',
_embind_register_integer__sig: 'vpppii',
Expand Down
40 changes: 40 additions & 0 deletions system/include/emscripten/bind.h
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,11 @@ void _embind_register_optional(
TYPEID optionalType,
TYPEID type);

void _embind_register_expected(
TYPEID expectedType,
TYPEID valueType,
TYPEID errorType);

void _embind_register_user_type(
TYPEID type,
const char* typeName);
Expand Down Expand Up @@ -1861,6 +1866,41 @@ void register_optional() {
internal::TypeID<typename std::remove_pointer<T>::type>::get());
}

template<typename ExpectedOrValueType>
void register_expected() {
using namespace internal;
#if __cplusplus >= 202302L
if constexpr (!is_expected_v<ExpectedOrValueType>) {
register_expected<std::expected<ExpectedOrValueType, val>>();
} else
#endif
{
static_assert(is_expected_v<ExpectedOrValueType>,
"Type must specialize emscripten::expected_trait (or use C++23 std::expected)");
if constexpr (is_expected_v<ExpectedOrValueType>) {
thread_local bool hasRun;
if (hasRun) {
return;
}
hasRun = true;
using Trait = expected_trait<ExpectedOrValueType>;
using ValueType = typename RawPointerTransformer<typename Trait::value_type, true>::type;
using ErrorType = typename RawPointerTransformer<typename Trait::error_type, true>::type;
_embind_register_expected(
TypeID<ExpectedOrValueType>::get(),
TypeID<ValueType>::get(),
TypeID<ErrorType>::get());
}
}
}

#if __cplusplus >= 202302L
template<typename T, typename E>
void register_expected() {
register_expected<std::expected<T, E>>();
}
#endif

////////////////////////////////////////////////////////////////////////////////
// VECTORS
////////////////////////////////////////////////////////////////////////////////
Expand Down
Loading
Loading