Skip to content

Commit a8fedfa

Browse files
committed
Add support for std::expected in embind
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
1 parent 83a5309 commit a8fedfa

11 files changed

Lines changed: 707 additions & 15 deletions

File tree

‎ChangeLog.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ See docs/process.md for more on how version tagging works.
2020

2121
6.0.14 (in development)
2222
-----------------------
23+
- Added `register_expected` and `expected_trait` to Embind for binding
24+
`std::expected<T, E>` and custom expected types as return values that either
25+
unwrap the expected value or throw the unexpected error in JavaScript.
2326
- Remove support for the `EMCC_ONLY_FORCED_STDLIBS` environment variable, which
2427
was deprecated in 2.0.14 (#13448). Use `-nostdlib` instead to avoid linking
2528
standard libraries. (#28151)

‎site/source/docs/porting/connecting_cpp_and_javascript/embind.rst‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1167,14 +1167,16 @@ Out of the box, *embind* provides converters for many standard C++ types:
11671167

11681168
For convenience, *embind* provides factory functions to register
11691169
``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>>>``
1170-
(:cpp:func:`register_map`), and ``std::optional<T>`` (:cpp:func:`register_optional`) types:
1170+
(:cpp:func:`register_map`), ``std::optional<T>`` (:cpp:func:`register_optional`), and ``std::expected<T, E>`` (:cpp:func:`register_expected`) types:
11711171

11721172
.. code:: cpp
11731173
11741174
EMSCRIPTEN_BINDINGS(stl_wrappers) {
11751175
register_vector<int>("VectorInt");
11761176
register_map<int,int>("MapIntInt");
11771177
register_optional<std::string>();
1178+
register_expected<int>(); // defaults error type to emscripten::val
1179+
register_expected<int, std::string>();
11781180
}
11791181
11801182
A full example is shown below:
@@ -1185,6 +1187,7 @@ A full example is shown below:
11851187
#include <string>
11861188
#include <vector>
11871189
#include <optional>
1190+
#include <expected>
11881191
11891192
using namespace emscripten;
11901193
@@ -1203,16 +1206,25 @@ A full example is shown below:
12031206
return "hello";
12041207
}
12051208
1209+
std::expected<int, val> returnExpectedData(bool ok) {
1210+
if (ok) {
1211+
return 42;
1212+
}
1213+
return std::unexpected(val::global("Error").new_(std::string("failed")));
1214+
}
1215+
12061216
EMSCRIPTEN_BINDINGS(module) {
12071217
function("returnVectorData", &returnVectorData);
12081218
function("returnMapData", &returnMapData);
12091219
function("returnOptionalData", &returnOptionalData);
1220+
function("returnExpectedData", &returnExpectedData);
12101221
1211-
// register bindings for std::vector<int>, std::map<int, std::string>, and
1212-
// std::optional<std::string>.
1222+
// register bindings for std::vector<int>, std::map<int, std::string>,
1223+
// std::optional<std::string>, and std::expected<int, val>.
12131224
register_vector<int>("vector<int>");
12141225
register_map<int, std::string>("map<int, string>");
12151226
register_optional<std::string>();
1227+
register_expected<int>();
12161228
}
12171229
12181230
@@ -1268,6 +1280,19 @@ The following JavaScript can be used to interact with the above C++.
12681280
console.log(optional);
12691281
}
12701282
1283+
// Expected values return the unwrapped value or throw the error.
1284+
console.log(Module['returnExpectedData'](true)); // 42
1285+
try {
1286+
Module['returnExpectedData'](false);
1287+
} catch (e) {
1288+
console.error(e); // Error: failed
1289+
}
1290+
1291+
Custom expected or result types (for example, in C++17 or C++20 codebases) can
1292+
also be registered with :cpp:func:`register_expected` by specializing
1293+
``emscripten::expected_trait`` with ``value_type``, ``error_type``,
1294+
``has_value``, ``get_value``, and ``get_error``.
1295+
12711296

12721297
TypeScript Definitions
12731298
======================

‎src/lib/libembind.js‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,23 @@ var LibraryEmbind = {
2929
// emval is passed into JS via an interface
3030
}`,
3131
$EmValOptionalType: '=Object.assign({optional: true}, EmValType);',
32+
$EmValExpectedType: `{
33+
name: 'std::expected',
34+
fromWireType: (handle) => {
35+
// Valid Emval handles are even indices into emval_handles (pairs of
36+
// [value, refcount]), so bit 0 is used to tag an error handle.
37+
var isError = handle & 1;
38+
handle &= ~1;
39+
var rv = Emval.toValue(handle);
40+
__emval_decref(handle);
41+
if (isError) {
42+
throw rv;
43+
}
44+
return rv;
45+
},
46+
readValueFromPointer: readPointer,
47+
destructorFunction: null,
48+
}`,
3249

3350
$throwUnboundTypeError: (message, types) => {
3451
var unboundTypes = [];
@@ -555,6 +572,10 @@ var LibraryEmbind = {
555572
registerType(rawOptionalType, EmValOptionalType);
556573
},
557574

575+
_embind_register_expected: (rawExpectedType, rawValueType, rawErrorType) => {
576+
registerType(rawExpectedType, EmValExpectedType);
577+
},
578+
558579
_embind_register_memory_view: (rawType, dataTypeIndex, name) => {
559580
var typeMapping = [
560581
Int8Array,

‎src/lib/libembind_gen.js‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,12 @@ var LibraryEmbind = {
5454
this.destructorType = 'none'; // Same as emval.
5555
}
5656
},
57+
$ExpectedType: class {
58+
constructor(type) {
59+
this.type = type;
60+
this.destructorType = 'none'; // Same as emval.
61+
}
62+
},
5763
$FunctionDefinition: class {
5864
hasPublicSymbol = true;
5965
constructor(name, returnType, argumentTypes, functionIndex, thisType = null, isNonnullReturn = false, isAsync = false) {
@@ -89,11 +95,14 @@ var LibraryEmbind = {
8995

9096
out.push(argOut.join(', '));
9197
let returnType = this.returnType;
98+
if (returnType instanceof ExpectedType) {
99+
returnType = returnType.type;
100+
}
92101
// Constructors can return a pointer, but it will be a non-null pointer.
93102
// Change the return type to the class type so the TS output doesn't
94103
// have `| null`.
95-
if (this.isNonnullReturn && this.returnType instanceof PointerDefinition) {
96-
returnType = this.returnType.classType;
104+
if (this.isNonnullReturn && returnType instanceof PointerDefinition) {
105+
returnType = returnType.classType;
97106
}
98107
returnType = nameMap(returnType, true);
99108
if (this.isAsync) {
@@ -455,6 +464,9 @@ var LibraryEmbind = {
455464
if (type instanceof OptionalType) {
456465
return `${this.typeToJsName(type.type, isFromWireType)} | undefined`;
457466
}
467+
if (type instanceof ExpectedType) {
468+
return this.typeToJsName(type.type, isFromWireType);
469+
}
458470
return type.name;
459471
}
460472

@@ -618,6 +630,11 @@ var LibraryEmbind = {
618630
return [new OptionalType(type)];
619631
});
620632
},
633+
_embind_register_expected: (rawExpectedType, rawValueType, rawErrorType) => {
634+
whenDependentTypesAreResolved([rawExpectedType], [rawValueType, rawErrorType], function(types) {
635+
return [new ExpectedType(types[0])];
636+
});
637+
},
621638
_embind_register_memory_view: (rawType, dataTypeIndex, name) => {
622639
// TODO
623640
},

‎src/lib/libsigs.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,7 @@ sigs = {
310310
_embind_register_emval__sig: 'vp',
311311
_embind_register_enum__sig: 'vpppii',
312312
_embind_register_enum_value__sig: 'vppi',
313+
_embind_register_expected__sig: 'vppp',
313314
_embind_register_float__sig: 'vppp',
314315
_embind_register_function__sig: 'vpippppii',
315316
_embind_register_integer__sig: 'vpppii',

‎system/include/emscripten/bind.h‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,11 @@ void _embind_register_optional(
267267
TYPEID optionalType,
268268
TYPEID type);
269269

270+
void _embind_register_expected(
271+
TYPEID expectedType,
272+
TYPEID valueType,
273+
TYPEID errorType);
274+
270275
void _embind_register_user_type(
271276
TYPEID type,
272277
const char* typeName);
@@ -1861,6 +1866,41 @@ void register_optional() {
18611866
internal::TypeID<typename std::remove_pointer<T>::type>::get());
18621867
}
18631868

1869+
template<typename ExpectedOrValueType>
1870+
void register_expected() {
1871+
using namespace internal;
1872+
#if __cplusplus >= 202302L
1873+
if constexpr (!is_expected_v<ExpectedOrValueType>) {
1874+
register_expected<std::expected<ExpectedOrValueType, val>>();
1875+
} else
1876+
#endif
1877+
{
1878+
static_assert(is_expected_v<ExpectedOrValueType>,
1879+
"Type must specialize emscripten::expected_trait (or use C++23 std::expected)");
1880+
if constexpr (is_expected_v<ExpectedOrValueType>) {
1881+
thread_local bool hasRun;
1882+
if (hasRun) {
1883+
return;
1884+
}
1885+
hasRun = true;
1886+
using Trait = expected_trait<ExpectedOrValueType>;
1887+
using ValueType = typename RawPointerTransformer<typename Trait::value_type, true>::type;
1888+
using ErrorType = typename RawPointerTransformer<typename Trait::error_type, true>::type;
1889+
_embind_register_expected(
1890+
TypeID<ExpectedOrValueType>::get(),
1891+
TypeID<ValueType>::get(),
1892+
TypeID<ErrorType>::get());
1893+
}
1894+
}
1895+
}
1896+
1897+
#if __cplusplus >= 202302L
1898+
template<typename T, typename E>
1899+
void register_expected() {
1900+
register_expected<std::expected<T, E>>();
1901+
}
1902+
#endif
1903+
18641904
////////////////////////////////////////////////////////////////////////////////
18651905
// VECTORS
18661906
////////////////////////////////////////////////////////////////////////////////

0 commit comments

Comments
 (0)