Skip to content

Typescript bindings generation for std::optional types issues #20082

Closed

Description

@mrroohian

Description of the bug report:

I have been trying to generate Typescript types for methods that either receive or return std::optional<T> and using the latest git version, I get BindingError. Building without the --embind-emit-tsd works however fine. I haven't found any direct reference of it in the documentation so was not able to say if it's a bug or missing feature. Thanks in advance for the clarification.

Version of emscripten/emsdk:

emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 3.1.45-git (58e56c4e1409d308ca153d167bd2c6476bd659f3)
Copyright (C) 2014 the Emscripten authors (see AUTHORS.txt)
This is free and open source software under the MIT license.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Failing command line in full:

Given the following short example:

#include <string>
#include <optional>
#include <emscripten/bind.h>

using namespace emscripten;

std::optional<std::string> getOptionalValue(int val) {
  if (val < 0) {
    return std::nullopt;
  }

  return std::to_string(val);
}

EMSCRIPTEN_BINDINGS() {
  function("getOptionalValue", &getOptionalValue);
}

when trying to compile the typescript interfaces using the following command:

em++ -v \
  -O2 \
  --no-entry \
  -sMALLOC=dlmalloc \
  -sEXPORTED_FUNCTIONS="[_malloc,_free]" \
  -lembind \
  --embind-emit-tsd lib.d.ts \
  test.cpp

I get this error: BindingError: Missing type definition for 'NSt3__28optionalINS_12basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEEEE'

I didn't find it anywhere in the repo so I guess maybe it's not yet supported?

Full link command and output with -v appended:

 "/home/reza/emsdk/upstream/bin/clang" --version
 "/home/reza/emsdk/upstream/bin/clang++" -target wasm32-unknown-emscripten -fignore-exceptions -fvisibility=default -mllvm -combiner-global-alias-analysis=false -mllvm -enable-emscripten-sjlj -mllvm -disable-lsr -DEMSCRIPTEN --sysroot=/home/reza/emsdk/upstream/emscripten/cache/sysroot -Xclang -iwithsysroot/include/fakesdl -Xclang -iwithsysroot/include/compat -v -O2 test.cpp -c -o /tmp/emscripten_temp_3_mu__ng/test_0.o
clang version 18.0.0 (https://github.com/llvm/llvm-project 18f5ada24453491f33c0f23eb4eac08e84be72e6)
Target: wasm32-unknown-emscripten
Thread model: posix
InstalledDir: /home/reza/emsdk/upstream/bin
 (in-process)
 "/home/reza/emsdk/upstream/bin/clang-18" -cc1 -triple wasm32-unknown-emscripten -emit-obj -disable-free -clear-ast-before-backend -main-file-name test.cpp -mrelocation-model static -mframe-pointer=none -ffp-contract=on -fno-rounding-math -mconstructor-aliases -target-cpu generic -debugger-tuning=gdb -fdebug-compilation-dir=/tmp/test -v -fcoverage-compilation-dir=/tmp/test -resource-dir /home/reza/emsdk/upstream/lib/clang/18 -D EMSCRIPTEN -isysroot /home/reza/emsdk/upstream/emscripten/cache/sysroot -internal-isystem /home/reza/emsdk/upstream/emscripten/cache/sysroot/include/wasm32-emscripten/c++/v1 -internal-isystem /home/reza/emsdk/upstream/emscripten/cache/sysroot/include/c++/v1 -internal-isystem /home/reza/emsdk/upstream/lib/clang/18/include -internal-isystem /home/reza/emsdk/upstream/emscripten/cache/sysroot/include/wasm32-emscripten -internal-isystem /home/reza/emsdk/upstream/emscripten/cache/sysroot/include -O2 -fdeprecated-macro -ferror-limit 19 -fvisibility=default -fgnuc-version=4.2.1 -fcxx-exceptions -fignore-exceptions -fexceptions -fcolor-diagnostics -vectorize-loops -vectorize-slp -iwithsysroot/include/fakesdl -iwithsysroot/include/compat -mllvm -combiner-global-alias-analysis=false -mllvm -enable-emscripten-sjlj -mllvm -disable-lsr -o /tmp/emscripten_temp_3_mu__ng/test_0.o -x c++ test.cpp
clang -cc1 version 18.0.0 based upon LLVM 18.0.0git default target x86_64-unknown-linux-gnu
ignoring nonexistent directory "/home/reza/emsdk/upstream/emscripten/cache/sysroot/include/wasm32-emscripten/c++/v1"
ignoring nonexistent directory "/home/reza/emsdk/upstream/emscripten/cache/sysroot/include/wasm32-emscripten"
#include "..." search starts here:
#include <...> search starts here:
 /home/reza/emsdk/upstream/emscripten/cache/sysroot/include/fakesdl
 /home/reza/emsdk/upstream/emscripten/cache/sysroot/include/compat
 /home/reza/emsdk/upstream/emscripten/cache/sysroot/include/c++/v1
 /home/reza/emsdk/upstream/lib/clang/18/include
 /home/reza/emsdk/upstream/emscripten/cache/sysroot/include
End of search list.
 "/home/reza/emsdk/upstream/bin/wasm-ld" -o /tmp/emscripten_temp_3_mu__ng/a.out.wasm /tmp/emscripten_temp_3_mu__ng/test_0.o -L/home/reza/emsdk/upstream/emscripten/cache/sysroot/lib/wasm32-emscripten --whole-archive -lembind-rtti --no-whole-archive -lGL -lal -lhtml5 -lstubs -lnoexit -lc -ldlmalloc -lcompiler_rt -lc++-noexcept -lc++abi-noexcept -lsockets -mllvm -combiner-global-alias-analysis=false -mllvm -enable-emscripten-sjlj -mllvm -disable-lsr /tmp/tmp4upd__2plibemscripten_js_symbols.so --strip-debug --export-if-defined=malloc --export-if-defined=free --export-if-defined=__start_em_asm --export-if-defined=__stop_em_asm --export-if-defined=__start_em_lib_deps --export-if-defined=__stop_em_lib_deps --export-if-defined=__start_em_js --export-if-defined=__stop_em_js --export=stackSave --export=stackRestore --export=stackAlloc --export=__errno_location --export=__get_temp_ret --export=__set_temp_ret --export=__wasm_call_ctors --export-table -z stack-size=65536 --initial-memory=16777216 --max-memory=16777216 --no-entry --global-base=1024
 "/home/reza/emsdk/upstream/bin/llvm-objcopy" /tmp/emscripten_temp_3_mu__ng/a.out.wasm /tmp/emscripten_temp_3_mu__ng/a.out.wasm --remove-section=.debug* --remove-section=producers
 "/home/reza/emsdk/upstream/bin/wasm-emscripten-finalize" --dyncalls-i64 --pass-arg=legalize-js-interface-exported-helpers /tmp/emscripten_temp_3_mu__ng/a.out.wasm -o /tmp/emscripten_temp_3_mu__ng/a.out.wasm --detect-features
 "/home/reza/emsdk/node/16.20.0_64bit/bin/node" /home/reza/emsdk/upstream/emscripten/src/compiler.js /tmp/tmp7vazo787.json
 "/home/reza/emsdk/upstream/bin/wasm-opt" --post-emscripten -O2 --low-memory-unused --zero-filled-memory --pass-arg=directize-initial-contents-immutable /tmp/emscripten_temp_3_mu__ng/a.out.wasm -o /tmp/emscripten_temp_3_mu__ng/a.out.wasm --mvp-features --enable-mutable-globals --enable-sign-ext
 "/home/reza/emsdk/node/16.20.0_64bit/bin/node" /home/reza/emsdk/upstream/emscripten/tools/acorn-optimizer.js /tmp/emscripten_temp_3_mu__ng/a.out.js JSDCE minifyWhitespace -o /tmp/emscripten_temp_3_mu__ng/a.out.jso1.js
 "/home/reza/emsdk/node/16.20.0_64bit/bin/node" /tmp/emscripten_temp_3_mu__ng/a.out.js
/tmp/emscripten_temp_3_mu__ng/a.out.js:1
var Module=typeof Module!="undefined"?Module:{};var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof importScripts=="function";var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;if(ENVIRONMENT_IS_NODE){var fs=require("fs");var nodePath=require("path");if(ENVIRONMENT_IS_WORKER){scriptDirectory=nodePath.dirname(scriptDirectory)+"/"}else{scriptDirectory=__dirname+"/"}read_=(filename,binary)=>{filename=isFileURI(filename)?new URL(filename):nodePath.normalize(filename);return fs.readFileSync(filename,binary?undefined:"utf8")};readBinary=filename=>{var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}return ret};readAsync=(filename,onload,onerror,binary=true)=>{filename=isFileURI(filename)?new URL(filename):nodePath.normalize(filename);fs.readFile(filename,binary?undefined:"utf8",(err,data)=>{if(err)onerror(err);else onload(binary?data.buffer:data)})};if(!Module["thisProgram"]&&process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);if(typeof module!="undefined"){module["exports"]=Module}process.on("uncaughtException",ex=>{if(ex!=="unwind"&&!(ex instanceof ExitStatus)&&!(ex.context instanceof ExitStatus)){throw ex}});quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow};Module["inspect"]=()=>"[Emscripten Module object]"}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=(url,onload,onerror)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=title=>document.title=title}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.error.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime=Module["noExitRuntime"]||true;if(typeof WebAssembly!="object"){abort("no native wasm support detected")}var wasmMemory;var ABORT=false;var EXITSTATUS;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b)}var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;var runtimeKeepaliveCounter=0;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){if(Module["onAbort"]){Module["onAbort"](what)}what="Aborted("+what+")";err(what);ABORT=true;EXITSTATUS=1;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return filename.startsWith(dataURIPrefix)}function isFileURI(filename){return filename.startsWith("file://")}var wasmBinaryFile;wasmBinaryFile="a.out.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}function getBinaryPromise(binaryFile){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch=="function"&&!isFileURI(binaryFile)){return fetch(binaryFile,{credentials:"same-origin"}).then(response=>{if(!response["ok"]){throw"failed to load wasm binary file at '"+binaryFile+"'"}return response["arrayBuffer"]()}).catch(()=>getBinarySync(binaryFile))}else if(readAsync){return new Promise((resolve,reject)=>{readAsync(binaryFile,response=>resolve(new Uint8Array(response)),reject)})}}return Promise.resolve().then(()=>getBinarySync(binaryFile))}function instantiateArrayBuffer(binaryFile,imports,receiver){return getBinaryPromise(binaryFile).then(binary=>WebAssembly.instantiate(binary,imports)).then(instance=>instance).then(receiver,reason=>{err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)})}function instantiateAsync(binary,binaryFile,imports,callback){if(!binary&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(binaryFile)&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE&&typeof fetch=="function"){return fetch(binaryFile,{credentials:"same-origin"}).then(response=>{var result=WebAssembly.instantiateStreaming(response,imports);return result.then(callback,function(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(binaryFile,imports,callback)})})}return instantiateArrayBuffer(binaryFile,imports,callback)}function createWasm(){var info={"env":wasmImports,"wasi_snapshot_preview1":wasmImports};function receiveInstance(instance,module){var exports=instance.exports;wasmExports=exports;wasmMemory=wasmExports["memory"];updateMemoryViews();wasmTable=wasmExports["__indirect_function_table"];addOnInit(wasmExports["__wasm_call_ctors"]);removeRunDependency("wasm-instantiate");return exports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}if(Module["instantiateWasm"]){try{return Module["instantiateWasm"](info,receiveInstance)}catch(e){err(`Module.instantiateWasm callback failed with error: ${e}`);return false}}instantiateAsync(wasmBinary,wasmBinaryFile,info,receiveInstantiationResult);return{}}function ExitStatus(status){this.name="ExitStatus";this.message=`Program terminated with exit(${status})`;this.status=status}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var __embind_register_bigint=(primitiveType,name,size,minRange,maxRange)=>{registerPrimitiveType(primitiveType,name)};var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var BindingError=undefined;var throwBindingError=message=>{throw new BindingError(message)};var InternalError=undefined;var throwInternalError=message=>{throw new InternalError(message)};var whenDependentTypesAreResolved=(myTypes,dependentTypes,getTypeConverters)=>{myTypes.forEach(function(type){typeDependencies[type]=dependentTypes});function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i<myTypes.length;++i){registerType(myTypes[i],myTypeConverters[i])}}var typeConverters=new Array(dependentTypes.length);var unregisteredTypes=[];var registered=0;dependentTypes.forEach((dt,i)=>{if(registeredTypes.hasOwnProperty(dt)){typeConverters[i]=registeredTypes[dt]}else{unregisteredTypes.push(dt);if(!awaitingDependencies.hasOwnProperty(dt)){awaitingDependencies[dt]=[]}awaitingDependencies[dt].push(()=>{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length){onComplete(typeConverters)}})}});if(0===unregisteredTypes.length){onComplete(typeConverters)}};function sharedRegisterType(rawType,registeredInstance,options={}){var name=registeredInstance.name;if(!rawType){throwBindingError(`type "${name}" must have a positive integer typeid pointer`)}if(registeredTypes.hasOwnProperty(rawType)){if(options.ignoreDuplicateRegistrations){return}else{throwBindingError(`Cannot register type '${name}' twice`)}}registeredTypes[rawType]=registeredInstance;delete typeDependencies[rawType];if(awaitingDependencies.hasOwnProperty(rawType)){var callbacks=awaitingDependencies[rawType];delete awaitingDependencies[rawType];callbacks.forEach(cb=>cb())}}function registerType(rawType,registeredInstance,options={}){return sharedRegisterType(rawType,registeredInstance,options)}class PrimitiveType{constructor(typeId,name){this.typeId=typeId;this.name=name}}var registerPrimitiveType=(id,name)=>{name=readLatin1String(name);registerType(id,new PrimitiveType(id,name))};var __embind_register_bool=(rawType,name,trueValue,falseValue)=>{registerPrimitiveType(rawType,name)};var __embind_register_emval=(rawType,name)=>{registerPrimitiveType(rawType,name)};var __embind_register_float=(rawType,name,size)=>{registerPrimitiveType(rawType,name)};var moduleDefinitions=[];class FunctionDefinition{constructor(name,returnType,argumentTypes,thisType=null){this.name=name;this.returnType=returnType;this.argumentTypes=argumentTypes;this.thisType=thisType}printSignature(nameMap,out){out.push("(");const argOut=[];for(const arg of this.argumentTypes){argOut.push(`${arg.name}: ${nameMap(arg.type)}`)}out.push(argOut.join(", "));out.push(`): ${nameMap(this.returnType)}`)}printFunction(nameMap,out){out.push(`${this.name}`);this.printSignature(nameMap,out)}printModuleEntry(nameMap,out){out.push("  ");this.printFunction(nameMap,out);out.push(";\n")}}var heap32VectorToArray=(count,firstElement)=>{var array=[];for(var i=0;i<count;i++){array.push(HEAPU32[firstElement+i*4>>2])}return array};var embind_init_charCodes=()=>{var codes=new Array(256);for(var i=0;i<256;++i){codes[i]=String.fromCharCode(i)}embind_charCodes=codes};var embind_charCodes=undefined;var readLatin1String=ptr=>{var ret="";var c=ptr;while(HEAPU8[c]){ret+=embind_charCodes[HEAPU8[c++]]}return ret};class Argument{constructor(name,type){this.name=name;this.type=type}}var createFunctionDefinition=(name,argCount,rawArgTypesAddr,hasThis,cb)=>{const argTypes=heap32VectorToArray(argCount,rawArgTypesAddr);name=readLatin1String(name);whenDependentTypesAreResolved([],argTypes,function(argTypes){const returnType=argTypes[0];let thisType=null;let argStart=1;if(hasThis){thisType=argTypes[1];argStart=2}const args=[];for(let i=argStart;i<argTypes.length;i++){args.push(new Argument(`_${i-argStart}`,argTypes[i]))}const funcDef=new FunctionDefinition(name,returnType,args,thisType);cb(funcDef);return[]})};var __embind_register_function=(name,argCount,rawArgTypesAddr,signature,rawInvoker,fn,isAsync)=>{createFunctionDefinition(name,argCount,rawArgTypesAddr,false,funcDef=>{moduleDefinitions.push(funcDef)})};var __embind_register_integer=(primitiveType,name,size,minRange,maxRange)=>{registerPrimitiveType(primitiveType,name)};var __embind_register_memory_view=(rawType,dataTypeIndex,name)=>{};var __embind_register_std_string=(rawType,name)=>{registerPrimitiveType(rawType,name)};var __embind_register_std_wstring=(rawType,charSize,name)=>{registerPrimitiveType(rawType,name)};var __embind_register_void=(rawType,name)=>{registerPrimitiveType(rawType,name)};var _abort=()=>{abort("")};var _emscripten_memcpy_big=(dest,src,num)=>HEAPU8.copyWithin(dest,src,src+num);var abortOnCannotGrowMemory=requestedSize=>{abort("OOM")};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;abortOnCannotGrowMemory(requestedSize)};var getTypeName=type=>{var ptr=___getTypeName(type);var rv=readLatin1String(ptr);_free(ptr);return rv};class TsPrinter{constructor(definitions){this.definitions=definitions;const jsString="ArrayBuffer|Uint8Array|Uint8ClampedArray|Int8Array|string";this.builtInToJsName=new Map([["bool","boolean"],["char","number"],["unsigned char","number"],["int","number"],["unsigned int","number"],["unsigned long","number"],["float","number"],["double","number"],["void","void"],["std::string",jsString],["std::basic_string<unsigned char>",jsString],["emscripten::val","any"]])}typeToJsName(type){if(type instanceof PrimitiveType){if(!this.builtInToJsName.has(type.name)){throw new Error(`Missing primitive type to TS type for '${type.name}'`)}return this.builtInToJsName.get(type.name)}return type.name}print(){const out=[];for(const def of this.definitions){if(!def.print){continue}def.print(this.typeToJsName.bind(this),out)}out.push("export interface MainModule {\n");for(const def of this.definitions){if(!def.printModuleEntry){continue}def.printModuleEntry(this.typeToJsName.bind(this),out)}out.push("}");console.log(out.join(""))}}var embindEmitTypes=()=>{for(const typeId in awaitingDependencies){throwBindingError(`Missing type definition for '${getTypeName(typeId)}'`)}const printer=new TsPrinter(moduleDefinitions);printer.print()};BindingError=Module["BindingError"]=class BindingError extends Error{constructor(message){super(message);this.name="BindingError"}};InternalError=Module["InternalError"]=class InternalError extends Error{constructor(message){super(message);this.name="InternalError"}};embind_init_charCodes();addOnInit(embindEmitTypes);var wasmImports={_embind_register_bigint:__embind_register_bigint,_embind_register_bool:__embind_register_bool,_embind_register_emval:__embind_register_emval,_embind_register_float:__embind_register_float,_embind_register_function:__embind_register_function,_embind_register_integer:__embind_register_integer,_embind_register_memory_view:__embind_register_memory_view,_embind_register_std_string:__embind_register_std_string,_embind_register_std_wstring:__embind_register_std_wstring,_embind_register_void:__embind_register_void,abort:_abort,emscripten_memcpy_big:_emscripten_memcpy_big,emscripten_resize_heap:_emscripten_resize_heap};var wasmExports=createWasm();var ___wasm_call_ctors=()=>(___wasm_call_ctors=wasmExports["__wasm_call_ctors"])();var ___getTypeName=a0=>(___getTypeName=wasmExports["__getTypeName"])(a0);var __embind_initialize_bindings=Module["__embind_initialize_bindings"]=()=>(__embind_initialize_bindings=Module["__embind_initialize_bindings"]=wasmExports["_embind_initialize_bindings"])();var ___errno_location=()=>(___errno_location=wasmExports["__errno_location"])();var _malloc=Module["_malloc"]=a0=>(_malloc=Module["_malloc"]=wasmExports["malloc"])(a0);var _free=Module["_free"]=a0=>(_free=Module["_free"]=wasmExports["free"])(a0);var stackSave=()=>(stackSave=wasmExports["stackSave"])();var stackRestore=a0=>(stackRestore=wasmExports["stackRestore"])(a0);var stackAlloc=a0=>(stackAlloc=wasmExports["stackAlloc"])(a0);var calledRun;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(){if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run();
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

BindingError: Missing type definition for 'NSt3__28optionalINS_12basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEEEE'
    at throwBindingError (/tmp/emscripten_temp_3_mu__ng/a.out.js:1:8540)
    at embindEmitTypes (/tmp/emscripten_temp_3_mu__ng/a.out.js:1:14541)
    at callRuntimeCallbacks (/tmp/emscripten_temp_3_mu__ng/a.out.js:1:8271)
    at initRuntime (/tmp/emscripten_temp_3_mu__ng/a.out.js:1:4134)
    at doRun (/tmp/emscripten_temp_3_mu__ng/a.out.js:1:16741)
    at run (/tmp/emscripten_temp_3_mu__ng/a.out.js:1:16979)
    at runCaller (/tmp/emscripten_temp_3_mu__ng/a.out.js:1:16513)
    at removeRunDependency (/tmp/emscripten_temp_3_mu__ng/a.out.js:1:5105)
    at receiveInstance (/tmp/emscripten_temp_3_mu__ng/a.out.js:1:7634)
    at receiveInstantiationResult (/tmp/emscripten_temp_3_mu__ng/a.out.js:1:7770)
em++: error: '/home/reza/emsdk/node/16.20.0_64bit/bin/node /tmp/emscripten_temp_3_mu__ng/a.out.js' failed (returned 7)

Activity

  1. brendandahl commented on Aug 21, 2023

    @brendandahl
    Collaborator

    Embind doesn't automatically build bindings for optional types. You'll need to setup bindings for it in EMSCRIPTEN_BINDINGS.

    The reason you see the error with TS generation is because it is more strict and requires all types to be defined. If you take your example and try to run it normally with:

    int main() {
      EM_ASM(
        Module.getOptionalValue(99);
      );
    }

    you'll see the same error without TS generation.

  2. brendandahl commented on Aug 21, 2023

    @brendandahl
    Collaborator

    See also #11139.

  3. mrroohian commented on Aug 21, 2023

    @mrroohian
    ContributorAuthor

    @brendandahl I've managed to put together something to add basic support for std::optional<T>and it kinda works except the value() method, which always gets transpiled to type any. Any idea how to improve it?

    Could we add this, similar to register_vector to bind.h. If yes, we could also implement other methods in the interface.

    #include <optional>
    #include <emscripten/bind.h>
    
    using namespace emscripten;
    
    namespace internal {
    
      template<typename OptType>
      struct OptionalAccess {
        static bool has_value(const OptType& o) {
          return o.has_value();
        }
    
        static val value(const OptType& o) { // FIXME: this is transpile to type any
          if (o.has_value()) {
            return val(o.value());
          } else {
            return val::undefined();
          }
        }
    
        static val value_or(const OptType& o, typename OptType::value_type&& default_value) {
          return val(o.value_or(default_value));
        }
    
        static OptType fromValue(typename OptType::value_type&& value) {
          return OptType(std::move(value));
        }
      };
    
    }
    
    template<typename T>
    class_<std::optional<T>> register_optional(const char* name) {
      typedef std::optional<T> OptType;
    
      return class_<std::optional<T>>(name)
        .template constructor<>()
        .function("hasValue", &internal::OptionalAccess<OptType>::has_value)
        .function("value", &internal::OptionalAccess<OptType>::value)
        .function("valueOr", &internal::OptionalAccess<OptType>::value_or)
        .class_function("fromValue", &internal::OptionalAccess<OptType>::fromValue)
      ;
    }
  4. brendandahl commented on Aug 21, 2023

    @brendandahl
    Collaborator

    To remove val, you could pass in the actual type to the template instead of std::optional. e.g.

      template<typename T>
      struct OptionalAccess {
        static bool has_value(const std::optional<T>& o) {
          return o.has_value();
        }
    
        static T value(const std::optional<T> optional) {
          return optional.value();
        }
    ...
    
    template<typename T>
    class_<std::optional<T>> register_optional(const char* name) {
      return class_<std::optional<T>>(name)
        .template constructor<T>()
        .function("hasValue", &internal::OptionalAccess<T>::has_value)
        .function("value", &internal::OptionalAccess<T>::value)
    ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions