From d3190554b216fef29f49980920b66e88eed2e458 Mon Sep 17 00:00:00 2001 From: Daniel-Genkin Date: Fri, 16 Jul 2021 18:20:31 -0400 Subject: [PATCH 01/19] Converted JS to TS and made build work --- src/mono/wasm/.gitignore | 1 + src/mono/wasm/Makefile | 9 ++++--- ...{binding_support.js => binding_support.ts} | 22 +++++++++-------- .../{dotnet_support.js => dotnet_support.ts} | 22 +++++++++-------- .../{library_mono.js => library_mono.ts} | 24 ++++++++++++++----- src/mono/wasm/runtime/tsconfig.json | 13 ++++++++++ src/mono/wasm/wasm.proj | 11 +++++---- 7 files changed, 69 insertions(+), 33 deletions(-) rename src/mono/wasm/runtime/{binding_support.js => binding_support.ts} (99%) rename src/mono/wasm/runtime/{dotnet_support.js => dotnet_support.ts} (85%) rename src/mono/wasm/runtime/{library_mono.js => library_mono.ts} (98%) create mode 100644 src/mono/wasm/runtime/tsconfig.json diff --git a/src/mono/wasm/.gitignore b/src/mono/wasm/.gitignore index 752927a4aeefb..3c501f29ad1c3 100644 --- a/src/mono/wasm/.gitignore +++ b/src/mono/wasm/.gitignore @@ -1,3 +1,4 @@ !Makefile .stamp-wasm-install-and-select* emsdk +runtime/build \ No newline at end of file diff --git a/src/mono/wasm/Makefile b/src/mono/wasm/Makefile index 52e5de9e30227..b9fec6c433401 100644 --- a/src/mono/wasm/Makefile +++ b/src/mono/wasm/Makefile @@ -101,8 +101,8 @@ $(NATIVE_BIN_DIR)/include/wasm: $(BUILDS_OBJ_DIR): mkdir -p $$@ -$(NATIVE_BIN_DIR)/dotnet.js: $(BUILDS_OBJ_DIR)/driver.o $(BUILDS_OBJ_DIR)/pinvoke.o $(BUILDS_OBJ_DIR)/corebindings.o runtime/library_mono.js runtime/binding_support.js runtime/dotnet_support.js $(SYSTEM_NATIVE_LIBDIR)/pal_random.js $(2) $(EMCC_DEFAULT_RSP) | $(NATIVE_BIN_DIR) - $(EMCC) @$(EMCC_DEFAULT_RSP) $(1) --js-library runtime/library_mono.js --js-library runtime/binding_support.js --js-library runtime/dotnet_support.js --js-library $(SYSTEM_NATIVE_LIBDIR)/pal_random.js $(BUILDS_OBJ_DIR)/driver.o $(BUILDS_OBJ_DIR)/pinvoke.o $(BUILDS_OBJ_DIR)/corebindings.o $(2) -o $(NATIVE_BIN_DIR)/dotnet.js $(3) +$(NATIVE_BIN_DIR)/dotnet.js: $(BUILDS_OBJ_DIR)/driver.o $(BUILDS_OBJ_DIR)/pinvoke.o $(BUILDS_OBJ_DIR)/corebindings.o runtime/build/library_mono.js runtime/build/binding_support.js runtime/build/dotnet_support.js $(SYSTEM_NATIVE_LIBDIR)/pal_random.js $(2) $(EMCC_DEFAULT_RSP) | $(NATIVE_BIN_DIR) + $(EMCC) @$(EMCC_DEFAULT_RSP) $(1) --js-library runtime/build/library_mono.js --js-library runtime/build/binding_support.js --js-library runtime/build/dotnet_support.js --js-library $(SYSTEM_NATIVE_LIBDIR)/pal_random.js $(BUILDS_OBJ_DIR)/driver.o $(BUILDS_OBJ_DIR)/pinvoke.o $(BUILDS_OBJ_DIR)/corebindings.o $(2) -o $(NATIVE_BIN_DIR)/dotnet.js $(3) $(BUILDS_OBJ_DIR)/pinvoke-table.h: $(PINVOKE_TABLE) | $(BUILDS_OBJ_DIR) if cmp -s $(PINVOKE_TABLE) $$@ ; then : ; else cp $(PINVOKE_TABLE) $$@ ; fi @@ -141,7 +141,7 @@ clean: icu-files: $(wildcard $(ICU_LIBDIR)/*.dat) $(ICU_LIBDIR)/libicuuc.a $(ICU_LIBDIR)/libicui18n.a | $(NATIVE_BIN_DIR) cp $^ $(NATIVE_BIN_DIR) -source-files: runtime/driver.c runtime/pinvoke.c runtime/corebindings.c runtime/binding_support.js runtime/dotnet_support.js runtime/library_mono.js $(SYSTEM_NATIVE_LIBDIR)/pal_random.js | $(NATIVE_BIN_DIR)/src +source-files: runtime/driver.c runtime/pinvoke.c runtime/corebindings.c runtime/build/binding_support.js runtime/build/dotnet_support.js runtime/build/library_mono.js $(SYSTEM_NATIVE_LIBDIR)/pal_random.js | $(NATIVE_BIN_DIR)/src cp $^ $(NATIVE_BIN_DIR)/src header-files: runtime/pinvoke.h | $(NATIVE_BIN_DIR)/include/wasm @@ -203,3 +203,6 @@ build-dbg-proxy: $(DOTNET) build $(TOP)/src/mono/wasm/debugger/BrowserDebugHost $(MSBUILD_ARGS) build-dbg-testsuite: $(DOTNET) build $(TOP)/src/mono/wasm/debugger/DebuggerTestSuite $(MSBUILD_ARGS) + +build-js-from-ts: + tsc -p $(TOP)/src/mono/wasm/runtime/ diff --git a/src/mono/wasm/runtime/binding_support.js b/src/mono/wasm/runtime/binding_support.ts similarity index 99% rename from src/mono/wasm/runtime/binding_support.js rename to src/mono/wasm/runtime/binding_support.ts index d96eeed4ff6d8..9078161af9358 100644 --- a/src/mono/wasm/runtime/binding_support.js +++ b/src/mono/wasm/runtime/binding_support.ts @@ -1,6 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// suppress these as they are not defined yet TODO remove once they are +var MONO, DOTNET, setValue, Module, BINDING: any; + var BindingSupportLib = { $BINDING__postset: 'BINDING.export_functions (Module);', $BINDING: { @@ -546,6 +549,7 @@ var BindingSupportLib = { case typeof js_obj === "undefined": return 0; case typeof js_obj === "number": { + let result; if ((js_obj | 0) === js_obj) result = this._box_js_int (js_obj); else if ((js_obj >>> 0) === js_obj) @@ -716,7 +720,7 @@ var BindingSupportLib = { typed_array_from : function (pinned_array, begin, end, bytes_per_element, type) { // typed array - var newTypedArray = 0; + var newTypedArray: ArrayBuffer; switch (type) { @@ -984,7 +988,7 @@ var BindingSupportLib = { var conv = primitiveConverters.get (key); if (!conv) - throw new Error ("Unknown parameter type " + type); + throw new Error ("Unknown parameter type " + key); var localStep = Object.create (conv.steps[0]); localStep.size = conv.size; @@ -1260,7 +1264,6 @@ var BindingSupportLib = { /* args_marshal is a string with one character per parameter that tells how to marshal it, here are the valid values: - i: int32 j: int32 - Enum with underlying type of int32 l: int64 @@ -1271,7 +1274,6 @@ var BindingSupportLib = { S: interned string o: js object will be converted to a C# object (this will box numbers/bool/promises) m: raw mono object. Don't use it unless you know what you're doing - to suppress marshaling of the return value, place '!' at the end of args_marshal, i.e. 'ii!' instead of 'ii' */ call_method: function (method, this_arg, args_marshal, args) { @@ -1323,11 +1325,11 @@ var BindingSupportLib = { ) { this._handle_exception_for_call (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer); + let result = resultRoot.value; + if (is_result_marshaled) result = this._unbox_mono_obj_root (resultRoot); - else - result = resultRoot.value; - + this._teardown_after_call (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer); return result; }, @@ -1465,7 +1467,7 @@ var BindingSupportLib = { "return result;" ); - bodyJs = body.join ("\r\n"); + const bodyJs = body.join ("\r\n"); if (friendly_name) { var escapeRE = /[^A-Za-z0-9_]/g; @@ -2042,9 +2044,9 @@ var BindingSupportLib = { var res = BINDING.typedarray_copy_from(requireObject, pinned_array, begin, end, bytes_per_element); return BINDING.js_to_mono_obj (res) }, - - }; +// @ts-ignore: TS2304 autoAddDeps(BindingSupportLib, '$BINDING') +// @ts-ignore: TS2304 mergeInto(LibraryManager.library, BindingSupportLib) diff --git a/src/mono/wasm/runtime/dotnet_support.js b/src/mono/wasm/runtime/dotnet_support.ts similarity index 85% rename from src/mono/wasm/runtime/dotnet_support.js rename to src/mono/wasm/runtime/dotnet_support.ts index 3272b714eca90..1ad2d057b0089 100644 --- a/src/mono/wasm/runtime/dotnet_support.js +++ b/src/mono/wasm/runtime/dotnet_support.ts @@ -1,13 +1,16 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +// suppress these as they are not defined yet TODO remove once they are +var MONO, DOTNET, setValue, Module: any; + var DotNetSupportLib = { $DOTNET: { conv_string: function (mono_obj) { return MONO.string_decoder.copy (mono_obj); } }, - mono_wasm_invoke_js_blazor: function(exceptionMessage, callInfo, arg0, arg1, arg2) { + mono_wasm_invoke_js_blazor: function (exceptionMessage, callInfo, arg0, arg1, arg2) { var mono_string = globalThis._mono_string_cached || (globalThis._mono_string_cached = Module.cwrap('mono_wasm_string_from_js', 'number', ['string'])); @@ -27,7 +30,7 @@ var DotNetSupportLib = { }, // This is for back-compat only and will eventually be removed - mono_wasm_invoke_js_marshalled: function(exceptionMessage, asyncHandleLongPtr, functionName, argsJson, treatResultAsVoid) { + mono_wasm_invoke_js_marshalled: function (exceptionMessage, asyncHandleLongPtr, functionName, argsJson, treatResultAsVoid) { var mono_string = globalThis._mono_string_cached || (globalThis._mono_string_cached = Module.cwrap('mono_wasm_string_from_js', 'number', ['string'])); @@ -46,7 +49,7 @@ var DotNetSupportLib = { var funcNameJsString = DOTNET.conv_string(functionName); var argsJsonJsString = argsJson && DOTNET.conv_string (argsJson); - var dotNetExports = globaThis.DotNet; + var dotNetExports = globalThis.DotNet; if (!dotNetExports) { throw new Error('The Microsoft.JSInterop.js library is not loaded.'); } @@ -67,7 +70,7 @@ var DotNetSupportLib = { }, // This is for back-compat only and will eventually be removed - mono_wasm_invoke_js_unmarshalled: function(exceptionMessage, funcName, arg0, arg1, arg2) { + mono_wasm_invoke_js_unmarshalled: function (exceptionMessage, funcName, arg0, arg1, arg2) { try { // Get the function you're trying to invoke var funcNameJsString = DOTNET.conv_string(funcName); @@ -86,10 +89,9 @@ var DotNetSupportLib = { return 0; } } +} - -}; - -autoAddDeps(DotNetSupportLib, '$DOTNET') -mergeInto(LibraryManager.library, DotNetSupportLib) - +// @ts-ignore: TS2304 +autoAddDeps(DotNetSupportLib, '$DOTNET'); +// @ts-ignore: TS2304 +mergeInto(LibraryManager.library, DotNetSupportLib); diff --git a/src/mono/wasm/runtime/library_mono.js b/src/mono/wasm/runtime/library_mono.ts similarity index 98% rename from src/mono/wasm/runtime/library_mono.js rename to src/mono/wasm/runtime/library_mono.ts index 8f8d4cbcfe537..fe489b322dae8 100644 --- a/src/mono/wasm/runtime/library_mono.js +++ b/src/mono/wasm/runtime/library_mono.ts @@ -47,6 +47,11 @@ * @property {object} eventArgs - arguments for the event itself */ + +// TODO remove. it is just currently stopping ts failures for undefined objects +let ENVIRONMENT_IS_SHELL, ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_WEB, require, read, locateFile: any; + + var MonoSupportLib = { $MONO__postset: 'MONO.export_functions (Module);', $MONO: { @@ -158,12 +163,17 @@ var MonoSupportLib = { ch2 = reader.read(); ch3 = reader.read(); + // @ts-ignore This condition will always return 'false' since the types 'number' and 'boolean' have no overlap. if (ch1 === false) break; + + // @ts-ignore This condition will always return 'false' since the types 'number' and 'boolean' have no overlap. if (ch2 === false) { ch2 = 0; equalsCount += 1; } + + // @ts-ignore This condition will always return 'false' since the types 'number' and 'boolean' have no overlap. if (ch3 === false) { ch3 = 0; equalsCount += 1; @@ -996,7 +1006,7 @@ var MonoSupportLib = { break; default: - throw new Error ("Unrecognized asset behavior:", asset.behavior, "for asset", asset.name); + throw new Error (`Unrecognized asset behavior: ${asset.behavior} for asset ${asset.name}`); } if (asset.behavior === "assembly") { @@ -1147,9 +1157,9 @@ var MonoSupportLib = { try { load_runtime ("unused", args.debug_level); } catch (ex) { - print ("MONO_WASM: load_runtime () failed: " + ex); - print ("MONO_WASM: Stacktrace: \n"); - print (ex.stack); + Module.print ("MONO_WASM: load_runtime () failed: " + ex); + Module.print ("MONO_WASM: Stacktrace: \n"); + Module.print (ex.stack); var wasm_exit = Module.cwrap ('mono_wasm_exit', null, ['number']); wasm_exit (1); @@ -1375,7 +1385,7 @@ var MonoSupportLib = { var manifest; try { - manifestContent = Module.UTF8ArrayToString(data, 8, manifestSize); + const manifestContent = Module.UTF8ArrayToString(data, 8, manifestSize); manifest = JSON.parse(manifestContent); if (!(manifest instanceof Array)) return false; @@ -1402,7 +1412,7 @@ var MonoSupportLib = { Module['FS_createPath'](prefix, folder, true, true); }); - for (row of manifest) { + for (let row of manifest) { var name = row[0]; var length = row[1]; var bytes = data.slice(0, length); @@ -1512,5 +1522,7 @@ var MonoSupportLib = { } }; +// @ts-ignore: TS2304 autoAddDeps(MonoSupportLib, '$MONO') +// @ts-ignore: TS2304 mergeInto(LibraryManager.library, MonoSupportLib) diff --git a/src/mono/wasm/runtime/tsconfig.json b/src/mono/wasm/runtime/tsconfig.json new file mode 100644 index 0000000000000..0674074591c49 --- /dev/null +++ b/src/mono/wasm/runtime/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "noImplicitAny": false, // todo set to true eventually once types are setup + "noEmitOnError": true, + "removeComments": false, + "sourceMap": false, + "target": "es2019", + "lib": ["es2019", "dom"], + "strict": false, // todo set to true eventually once types are setup + "outDir": "build", + }, + "exclude": [ "build" ] +} \ No newline at end of file diff --git a/src/mono/wasm/wasm.proj b/src/mono/wasm/wasm.proj index 3eacc3e1307c1..c6ab244fb1be7 100644 --- a/src/mono/wasm/wasm.proj +++ b/src/mono/wasm/wasm.proj @@ -221,7 +221,10 @@ EmSdkPath="$(EMSDK_PATH)" IgnoreStandardErrorWarningFormat="true" /> - JS compiler --> + + + @@ -239,9 +242,9 @@ From f53ea70eb027c4ffe71fa06526a651ceb534d550 Mon Sep 17 00:00:00 2001 From: Daniel-Genkin Date: Sat, 17 Jul 2021 11:02:35 -0400 Subject: [PATCH 02/19] cleanup --- src/mono/wasm/runtime/binding_support.ts | 85 +++++++------- src/mono/wasm/runtime/dotnet_support.ts | 9 +- src/mono/wasm/runtime/library_mono.ts | 86 ++++---------- src/mono/wasm/runtime/tsconfig.json | 2 +- src/mono/wasm/runtime/types/Runtime.d.ts | 91 +++++++++++++++ src/mono/wasm/runtime/types/glueForTSC.ts | 132 ++++++++++++++++++++++ 6 files changed, 289 insertions(+), 116 deletions(-) create mode 100644 src/mono/wasm/runtime/types/Runtime.d.ts create mode 100644 src/mono/wasm/runtime/types/glueForTSC.ts diff --git a/src/mono/wasm/runtime/binding_support.ts b/src/mono/wasm/runtime/binding_support.ts index 9078161af9358..f148a97d42d05 100644 --- a/src/mono/wasm/runtime/binding_support.ts +++ b/src/mono/wasm/runtime/binding_support.ts @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// suppress these as they are not defined yet TODO remove once they are -var MONO, DOTNET, setValue, Module, BINDING: any; - var BindingSupportLib = { $BINDING__postset: 'BINDING.export_functions (Module);', $BINDING: { @@ -14,11 +11,11 @@ var BindingSupportLib = { mono_wasm_owned_objects_frames: [], mono_wasm_owned_objects_LMF: [], mono_wasm_marshal_enum_as_int: true, - mono_bindings_init: function (binding_asm) { + mono_bindings_init: function (binding_asm: string): void { this.BINDING_ASM = binding_asm; }, - export_functions: function (module) { + export_functions: function (module: object): void { module ["mono_bindings_init"] = BINDING.mono_bindings_init.bind(BINDING); module ["mono_bind_method"] = BINDING.bind_method.bind(BINDING); module ["mono_method_invoke"] = BINDING.call_method.bind(BINDING); @@ -31,10 +28,10 @@ var BindingSupportLib = { module ["mono_intern_string"] = BINDING.mono_intern_string.bind(BINDING); }, - bindings_lazy_init: function () { + bindings_lazy_init: function (): void { if (this.init) return; - + // avoid infinite recursion this.init = true; @@ -162,7 +159,7 @@ var BindingSupportLib = { // Ensures the string is already interned on both the managed and JavaScript sides, // then returns the interned string value (to provide fast reference comparisons like C#) - mono_intern_string: function (string) { + mono_intern_string: function (string: string): string { if (string.length === 0) return this._empty_string; @@ -171,7 +168,7 @@ var BindingSupportLib = { return result; }, - _store_string_in_intern_table: function (string, ptr, internIt) { + _store_string_in_intern_table: function (string: string, ptr: number, internIt: boolean): number { if (!ptr) throw new Error ("null pointer passed to _store_string_in_intern_table"); else if (typeof (ptr) !== "number") @@ -230,7 +227,7 @@ var BindingSupportLib = { return ptr; }, - js_string_to_mono_string: function (string) { + js_string_to_mono_string: function (string: string): string { if (string === null) return null; else if (typeof (string) === "symbol") @@ -255,7 +252,7 @@ var BindingSupportLib = { return this.js_string_to_mono_string_new (string); }, - js_string_to_mono_string_new: function (string) { + js_string_to_mono_string_new: function (string: string): string { var buffer = Module._malloc ((string.length + 1) * 2); var buffer16 = (buffer / 2) | 0; for (var i = 0; i < string.length; i++) @@ -266,7 +263,7 @@ var BindingSupportLib = { return result; }, - find_method: function (klass, name, n) { + find_method: function (klass: number, name: string, n: number): number { var result = this._find_method(klass, name, n); if (result) { if (!this._method_descriptions) @@ -276,27 +273,27 @@ var BindingSupportLib = { return result; }, - get_js_obj: function (js_handle) { + get_js_obj: function (js_handle: number): object | null { if (js_handle > 0) return this.mono_wasm_require_handle(js_handle); return null; }, - _get_string_from_intern_table: function (mono_obj) { + _get_string_from_intern_table: function (mono_obj: number): string { if (!MONO.interned_string_table) return undefined; return MONO.interned_string_table.get (mono_obj); }, - conv_string: function (mono_obj) { + conv_string: function (mono_obj: number): string { return MONO.string_decoder.copy (mono_obj); }, - is_nested_array: function (ele) { + is_nested_array: function (ele: any): boolean { return this._is_simple_array(ele); }, - mono_array_to_js_array: function (mono_array) { + mono_array_to_js_array: function (mono_array: number): number | null { if (mono_array === 0) return null; @@ -308,7 +305,7 @@ var BindingSupportLib = { } }, - _mono_array_root_to_js_array: function (arrayRoot) { + _mono_array_root_to_js_array: function (arrayRoot){ if (arrayRoot.value === 0) return null; @@ -800,7 +797,7 @@ var BindingSupportLib = { return this.wasm_get_raw_obj (js_obj.__mono_gchandle__, true); }, - mono_method_get_call_signature: function(method, mono_obj) { + mono_method_get_call_signature: function(method, mono_obj): number { let instanceRoot = MONO.mono_wasm_new_root (mono_obj); try { this.bindings_lazy_init (); @@ -1276,7 +1273,7 @@ var BindingSupportLib = { m: raw mono object. Don't use it unless you know what you're doing to suppress marshaling of the return value, place '!' at the end of args_marshal, i.e. 'ii!' instead of 'ii' */ - call_method: function (method, this_arg, args_marshal, args) { + call_method: function (method, this_arg, args_marshal, args): number { this.bindings_lazy_init (); // HACK: Sometimes callers pass null or undefined, coerce it to 0 since that's what wasm expects @@ -1322,7 +1319,7 @@ var BindingSupportLib = { _handle_exception_and_produce_result_for_call: function ( converter, buffer, resultRoot, exceptionRoot, argsRootBuffer, is_result_marshaled - ) { + ): number { this._handle_exception_for_call (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer); let result = resultRoot.value; @@ -1354,7 +1351,7 @@ var BindingSupportLib = { return result; }, - _call_method_with_converted_args: function (method, this_arg, converter, buffer, is_result_marshaled, argsRootBuffer) { + _call_method_with_converted_args: function (method, this_arg, converter, buffer, is_result_marshaled, argsRootBuffer): number { var resultRoot = MONO.mono_wasm_new_root (), exceptionRoot = MONO.mono_wasm_new_root (); resultRoot.value = this.invoke_method (method, this_arg, buffer, exceptionRoot.get_address ()); return this._handle_exception_and_produce_result_for_call (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer, is_result_marshaled); @@ -1551,7 +1548,7 @@ var BindingSupportLib = { return method; }, - call_static_method: function (fqn, args, signature) { + call_static_method: function (fqn: string, args: any[] | null, signature: string | null) { this.bindings_lazy_init (); var method = this.resolve_method_fqn (fqn); @@ -1721,13 +1718,13 @@ var BindingSupportLib = { var obj = BINDING.get_js_obj (js_handle); if (!obj) { - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); return BINDING.js_string_to_mono_string ("Invalid JS object handle '" + js_handle + "'"); } var js_name = BINDING.conv_string (nameRoot.value); if (!js_name || (typeof(js_name) !== "string")) { - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); return BINDING.js_string_to_mono_string ("Invalid method name object '" + nameRoot.value + "'"); } @@ -1744,7 +1741,7 @@ var BindingSupportLib = { // make sure we release object reference counts on errors. BINDING.mono_wasm_unwind_LMF(); var res = e.toString (); - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); if (res === null || res === undefined) res = "unknown exception"; return BINDING.js_string_to_mono_string (res); @@ -1761,13 +1758,13 @@ var BindingSupportLib = { try { var obj = BINDING.mono_wasm_require_handle (js_handle); if (!obj) { - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); return BINDING.js_string_to_mono_string ("Invalid JS object handle '" + js_handle + "'"); } var js_name = BINDING.conv_string (nameRoot.value); if (!js_name) { - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); return BINDING.js_string_to_mono_string ("Invalid property name object '" + nameRoot.value + "'"); } @@ -1780,7 +1777,7 @@ var BindingSupportLib = { return BINDING.js_to_mono_obj (m); } catch (e) { var res = e.toString (); - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); if (res === null || typeof res === "undefined") res = "unknown exception"; return BINDING.js_string_to_mono_string (res); @@ -1795,13 +1792,13 @@ var BindingSupportLib = { BINDING.bindings_lazy_init (); var requireObject = BINDING.mono_wasm_require_handle (js_handle); if (!requireObject) { - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); return BINDING.js_string_to_mono_string ("Invalid JS object handle '" + js_handle + "'"); } var property = BINDING.conv_string (nameRoot.value); if (!property) { - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); return BINDING.js_string_to_mono_string ("Invalid property name object '" + property_name + "'"); } @@ -1845,7 +1842,7 @@ var BindingSupportLib = { var obj = BINDING.mono_wasm_require_handle (js_handle); if (!obj) { - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); return BINDING.js_string_to_mono_string ("Invalid JS object handle '" + js_handle + "'"); } @@ -1854,7 +1851,7 @@ var BindingSupportLib = { return BINDING.js_to_mono_obj (m); } catch (e) { var res = e.toString (); - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); if (res === null || typeof res === "undefined") res = "unknown exception"; return BINDING.js_string_to_mono_string (res); @@ -1867,7 +1864,7 @@ var BindingSupportLib = { var obj = BINDING.mono_wasm_require_handle (js_handle); if (!obj) { - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); return BINDING.js_string_to_mono_string ("Invalid JS object handle '" + js_handle + "'"); } @@ -1880,7 +1877,7 @@ var BindingSupportLib = { return true; } catch (e) { var res = e.toString (); - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); if (res === null || typeof res === "undefined") res = "unknown exception"; return BINDING.js_string_to_mono_string (res); @@ -1906,7 +1903,7 @@ var BindingSupportLib = { } if (globalObj === null || typeof globalObj === undefined) { - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); return BINDING.js_string_to_mono_string ("Global object '" + js_name + "' not found."); } @@ -1930,7 +1927,7 @@ var BindingSupportLib = { var requireObject = BINDING.mono_wasm_require_handle (js_handle); if (!requireObject) { - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); return BINDING.js_string_to_mono_string ("Invalid JS object handle '" + js_handle + "'"); } @@ -1944,7 +1941,7 @@ var BindingSupportLib = { var requireObject = BINDING.mono_wasm_require_handle (js_handle); if (!requireObject) { - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); return BINDING.js_string_to_mono_string ("Invalid JS object handle '" + js_handle + "'"); } @@ -1960,14 +1957,14 @@ var BindingSupportLib = { var js_name = BINDING.conv_string (nameRoot.value); if (!js_name) { - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); return BINDING.js_string_to_mono_string ("Invalid name @" + nameRoot.value); } var coreObj = globalThis[js_name]; if (coreObj === null || typeof coreObj === "undefined") { - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); return BINDING.js_string_to_mono_string ("JavaScript host object '" + js_name + "' not found."); } @@ -1993,7 +1990,7 @@ var BindingSupportLib = { return BINDING.mono_wasm_convert_return_value(gc_handle + 1); } catch (e) { var res = e.toString (); - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); if (res === null || res === undefined) res = "Error allocating object."; return BINDING.js_string_to_mono_string (res); @@ -2009,7 +2006,7 @@ var BindingSupportLib = { var requireObject = BINDING.mono_wasm_require_handle (js_handle); if (!requireObject) { - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); return BINDING.js_string_to_mono_string ("Invalid JS object handle '" + js_handle + "'"); } @@ -2020,7 +2017,7 @@ var BindingSupportLib = { var requireObject = BINDING.mono_wasm_require_handle (js_handle); if (!requireObject) { - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); return BINDING.js_string_to_mono_string ("Invalid JS object handle '" + js_handle + "'"); } @@ -2037,7 +2034,7 @@ var BindingSupportLib = { var requireObject = BINDING.mono_wasm_require_handle (js_handle); if (!requireObject) { - setValue (is_exception, 1, "i32"); + Module.setValue (is_exception, 1, "i32"); return BINDING.js_string_to_mono_string ("Invalid JS object handle '" + js_handle + "'"); } diff --git a/src/mono/wasm/runtime/dotnet_support.ts b/src/mono/wasm/runtime/dotnet_support.ts index 1ad2d057b0089..c7501cc173945 100644 --- a/src/mono/wasm/runtime/dotnet_support.ts +++ b/src/mono/wasm/runtime/dotnet_support.ts @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// suppress these as they are not defined yet TODO remove once they are -var MONO, DOTNET, setValue, Module: any; - var DotNetSupportLib = { $DOTNET: { conv_string: function (mono_obj) { @@ -24,7 +21,7 @@ var DotNetSupportLib = { } catch (ex) { var exceptionJsString = ex.message + '\n' + ex.stack; var exceptionSystemString = mono_string(exceptionJsString); - setValue (exceptionMessage, exceptionSystemString, 'i32'); // *exceptionMessage = exceptionSystemString; + Module.setValue (exceptionMessage, exceptionSystemString, 'i32'); // *exceptionMessage = exceptionSystemString; return 0; } }, @@ -64,7 +61,7 @@ var DotNetSupportLib = { } catch (ex) { var exceptionJsString = ex.message + '\n' + ex.stack; var exceptionSystemString = mono_string(exceptionJsString); - setValue (exceptionMessage, exceptionSystemString, 'i32'); // *exceptionMessage = exceptionSystemString; + Module.setValue (exceptionMessage, exceptionSystemString, 'i32'); // *exceptionMessage = exceptionSystemString; return 0; } }, @@ -85,7 +82,7 @@ var DotNetSupportLib = { var exceptionJsString = ex.message + '\n' + ex.stack; var mono_string = Module.cwrap('mono_wasm_string_from_js', 'number', ['string']); // TODO: Cache var exceptionSystemString = mono_string(exceptionJsString); - setValue (exceptionMessage, exceptionSystemString, 'i32'); // *exceptionMessage = exceptionSystemString; + Module.setValue (exceptionMessage, exceptionSystemString, 'i32'); // *exceptionMessage = exceptionSystemString; return 0; } } diff --git a/src/mono/wasm/runtime/library_mono.ts b/src/mono/wasm/runtime/library_mono.ts index fe489b322dae8..a84bf228141a6 100644 --- a/src/mono/wasm/runtime/library_mono.ts +++ b/src/mono/wasm/runtime/library_mono.ts @@ -1,57 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -/** - * @typedef WasmId - * @type {object} - * @property {string} idStr - full object id string - * @property {string} scheme - eg, object, valuetype, array .. - * @property {string} value - string part after `dotnet:scheme:` of the id string - * @property {object} o - value parsed as JSON - */ - -/** - * @typedef WasmRoot - a single address in the managed heap, visible to the GC - * @type {object} - * @property {ManagedPointer} value - pointer into the managed heap, stored in the root - * @property {function} get_address - retrieves address of the root in wasm memory - * @property {function} get - retrieves pointer value - * @property {function} set - updates the pointer - * @property {function} release - releases the root storage for future use - */ - -/** - * @typedef WasmRootBuffer - a collection of addresses in the managed heap, visible to the GC - * @type {object} - * @property {number} length - number of elements the root buffer can hold - * @property {function} get_address - retrieves address of an element in wasm memory, by index - * @property {function} get - retrieves an element by index - * @property {function} set - sets an element's value by index - * @property {function} release - releases the root storage for future use - */ - -/** - * @typedef ManagedPointer - * @type {number} - address in the managed heap - */ - -/** - * @typedef NativePointer - * @type {number} - address in wasm memory - */ - -/** - * @typedef Event - * @type {object} - * @property {string} eventName - name of the event being raised - * @property {object} eventArgs - arguments for the event itself - */ - - -// TODO remove. it is just currently stopping ts failures for undefined objects -let ENVIRONMENT_IS_SHELL, ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_WEB, require, read, locateFile: any; - - var MonoSupportLib = { $MONO__postset: 'MONO.export_functions (Module);', $MONO: { @@ -60,6 +9,13 @@ var MonoSupportLib = { _vt_stack: [], mono_wasm_runtime_is_ready : false, mono_wasm_ignore_pdb_load_errors: true, + interned_string_table: undefined, + mono_wasm_deregister_root: undefined, // becomes a function later + commands_received: undefined, + var_info: undefined, + loaded_assets: undefined, + loaded_files: undefined, + _c_fn_table: undefined, /** @type {object.} */ _id_table: {}, @@ -151,7 +107,7 @@ var MonoSupportLib = { return result; }, - toBase64StringImpl: function (inArray, offset, length) { + toBase64StringImpl: function (inArray, offset?, length?) { var reader = this._makeByteReader(inArray, offset, length); var result = ""; var ch1 = 0, ch2 = 0, ch3 = 0, bits = 0, equalsCount = 0, sum = 0; @@ -353,7 +309,7 @@ var MonoSupportLib = { * @param {string} [msg] - a description of the root buffer (for debugging) * @returns {WasmRootBuffer} */ - mono_wasm_new_root_buffer: function (capacity, msg) { + mono_wasm_new_root_buffer: function (capacity, msg?) { if (!this.mono_wasm_register_root || !this.mono_wasm_deregister_root) { this.mono_wasm_register_root = Module.cwrap ("mono_wasm_register_root", "number", ["number", "number", "string"]); this.mono_wasm_deregister_root = Module.cwrap ("mono_wasm_deregister_root", null, ["number"]); @@ -390,7 +346,7 @@ var MonoSupportLib = { * @param {string} [msg] - a description of the root buffer (for debugging) * @returns {WasmRootBuffer} */ - mono_wasm_new_root_buffer_from_pointer: function (offset, capacity, msg) { + mono_wasm_new_root_buffer_from_pointer: function (offset, capacity, msg?) { if (!this.mono_wasm_register_root || !this.mono_wasm_deregister_root) { this.mono_wasm_register_root = Module.cwrap ("mono_wasm_register_root", "number", ["number", "number", "string"]); this.mono_wasm_deregister_root = Module.cwrap ("mono_wasm_deregister_root", null, ["number"]); @@ -427,7 +383,7 @@ var MonoSupportLib = { * @param {ManagedPointer} [value] - an address in the managed heap to initialize the root with (or 0) * @returns {WasmRoot} */ - mono_wasm_new_root: function (value) { + mono_wasm_new_root: function (value?): WasmRoot { var result; if (this._scratch_root_free_instances.length > 0) { @@ -486,12 +442,12 @@ var MonoSupportLib = { * even if you are not sure all of your roots have been created yet. * @param {... WasmRoot} roots */ - mono_wasm_release_roots: function () { - for (var i = 0; i < arguments.length; i++) { - if (!arguments[i]) + mono_wasm_release_roots: function (...roots: WasmRoot[]) { + for (var i = 0; i < roots.length; i++) { + if (!roots[i]) continue; - arguments[i].release (); + roots[i].release (); } }, @@ -924,7 +880,7 @@ var MonoSupportLib = { return args.fetch_file_cb; if (ENVIRONMENT_IS_NODE) { - var fs = require('fs'); + var fs: any = require('fs'); return function (asset) { console.debug ("MONO_WASM: Loading... " + asset); var binary = fs.readFileSync (asset); @@ -1401,7 +1357,7 @@ var MonoSupportLib = { // /usr/share/zoneinfo/Asia // .. - var folders = new Set() + var folders = new Set() manifest.filter(m => { var file = m[0]; var last = file.lastIndexOf ("/"); @@ -1425,10 +1381,10 @@ var MonoSupportLib = { /** * Raises an event for the debug proxy * - * @param {Event} event - event to be raised - * @param {object} args - arguments for raising this event, eg. `{trace: true}` + * @param {WasmEvent} event - event to be raised + * @param {object} [args] - arguments for raising this event, eg. `{trace: true}` */ - mono_wasm_raise_debug_event: function(event, args={}) { + mono_wasm_raise_debug_event: function(event: WasmEvent, args?: object): void { if (typeof event !== 'object') throw new Error(`event must be an object, but got ${JSON.stringify(event)}`); @@ -1448,7 +1404,7 @@ var MonoSupportLib = { * @param {string} configFilePath - relative path to the config file * @throws Will throw an error if the config file loading fails */ - mono_wasm_load_config: async function (configFilePath) { + mono_wasm_load_config: async function (configFilePath: string): Promise { Module.addRunDependency(configFilePath); try { let config = null; diff --git a/src/mono/wasm/runtime/tsconfig.json b/src/mono/wasm/runtime/tsconfig.json index 0674074591c49..857b7a4182a1f 100644 --- a/src/mono/wasm/runtime/tsconfig.json +++ b/src/mono/wasm/runtime/tsconfig.json @@ -7,7 +7,7 @@ "target": "es2019", "lib": ["es2019", "dom"], "strict": false, // todo set to true eventually once types are setup - "outDir": "build", + "outDir": "build" }, "exclude": [ "build" ] } \ No newline at end of file diff --git a/src/mono/wasm/runtime/types/Runtime.d.ts b/src/mono/wasm/runtime/types/Runtime.d.ts new file mode 100644 index 0000000000000..3b6fa11734035 --- /dev/null +++ b/src/mono/wasm/runtime/types/Runtime.d.ts @@ -0,0 +1,91 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +/******************************************************************************************* + This file just acts as a set of object definitions to help the TSC compiler understand + the various namespaces and types that we use. Specifically, this file is for the EMSDK API + + THIS FILE IS NOT INCLUDED IN DOTNET.JS. ALL CODE HERE WILL BE IGNORED DURING THE BUILD +********************************************************************************************/ + +// Make sure that this is updated with all the accessible members from dotnet.js such as callbacks +declare namespace Module { + let config: MonoConfig; + let HEAP8: Int8Array; + let HEAP16: Int16Array; + let HEAP32: Int32Array; + let HEAPU8: Uint8Array; + let HEAPU16: Uint16Array; + let HEAPU32: Uint32Array; + let HEAPF32: Float32Array; + let HEAPF64: Float64Array; + + // TODO properly type these anys + + let arguments: string[]; + let loadReadFiles: boolean; + let printWithColors: boolean; + let noExitRuntime: boolean; + let noInitialRun: boolean; + + type preInit = Function | Function[]; + type preRun = Function | Function[]; + + function locateFile (path: string, prefix: string): string; + function onAbort (): void; + function onRuntimeInitialized (): void; + function destroy (obj: any): void; + function getPreloadedPackage (remotePackageName: string, remotePackageSize: number): void; + function _malloc (amnt: number): number; + function _free (amn: number): void; + function addRunDependency(id: string): void; + function removeRunDependency(id: string): void; + function mono_method_get_call_signature (method: any, mono_obj?: any): string; + function print (message: string): void; + + // Make sure that this is updated with all the methods that we manually export from emsdk (i.e. EXPORTED_RUNTIME_METHODS in wasm.proj). The non exported ones I have intentaionally left out + function ccall (ident: string, returnType?: string, argTypes?: any[] , args?: any[] , opts?: any): any; + function FS_createPath (parent: string | any, path: string, canRead?: boolean /* unused */, canWrite?: boolean /* unused */): string; + function FS_createDataFile (parent: string | any, name: string, data: string, canRead: boolean, canWrite: boolean, canOwn?: boolean): string; + function cwrap (ident: string, returnType: string, argTypes?: any[], opts?: any): Function; + function cwrap (ident: string, ...args: any[]): Function; + function setValue (ptr: number, value: number, type: string, noSafe?: number | boolean): void; + function getValue (ptr: number, type: string, noSafe?: number | boolean ): number; + function UTF8ToString (ptr: number, maxBytesToRead?: number): string; + function UTF8ToString (arg: string): string; + function UTF8ArrayToString (str: string, heap: number[] | number, outIdx: number, maxBytesToWrite?: number): string; + function addFunction (func: Function, sig: string): void; +} + +type MonoConfig = { + assembly_root: string, + debug_level: number, + assets: (AssetEntry | AssetEntry | SatelliteAssemblyEntry | VfsEntry | IcuData)[], + remote_sources: string[], + [index: string]: any, // overflow for the "Extra" sections +} | {message: string, error: any}; + +// Types of assets that can be in the mono-config.js/mono-config.json file (taken from /src/tasks/WasmAppBuilder/WasmAppBuilder.cs) +type AssetEntry = { + behavior: string, + name: string +} + +interface AssemblyEntry extends AssetEntry { + name: "assembly" +} + +interface SatelliteAssemblyEntry extends AssetEntry { + name: "resource", + culture: string +} + +interface VfsEntry extends AssetEntry { + name: "vfs", + virtual_path: string +} + +interface IcuData extends AssetEntry { + name: "icu", + load_remote: boolean +} diff --git a/src/mono/wasm/runtime/types/glueForTSC.ts b/src/mono/wasm/runtime/types/glueForTSC.ts new file mode 100644 index 0000000000000..377a1154dfabf --- /dev/null +++ b/src/mono/wasm/runtime/types/glueForTSC.ts @@ -0,0 +1,132 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +/******************************************************************************************* + This file just acts as a set of object definitions to help the TSC compiler understand + the various namespaces that we use. These namespaces are not defined explicitly until + the dotnet.js file is merged, so we pretend they exist by defining them here. + + THIS FILE IS NOT INCLUDED IN DOTNET.JS. ALL CODE HERE WILL BE IGNORED DURING THE BUILD +********************************************************************************************/ + +// VARIOUS C FUNCTIONS THAT WE CALL INTO //////////////////////////////////////////////////// +interface MONO_C_FUNCS { + mono_background_exec (): void; + mono_wasm_register_root (a: number, b: number, c: string): number; + mono_wasm_deregister_root (a: number): void; + mono_wasm_string_get_data (a: number, b: number, c: number, d: number): void; + mono_wasm_set_is_debugger_attached (a: boolean): void; + mono_wasm_send_dbg_command (a: number, b:number, c: number, d: number, e: number): boolean; + mono_wasm_send_dbg_command_with_parms (a: number, b:number, c: number, d: number, e: number, f: number, g: string): boolean; + mono_wasm_setenv (a: string, b: string): void; + mono_wasm_parse_runtime_options (a: number, b:number): void; + mono_wasm_strdup (a: string): number; + mono_wasm_load_icu_data (a: number): number; + mono_wasm_get_icudt_name (a: string): string; + mono_wasm_load_runtime (a: string, b: number): void; + mono_wasm_exit (a: number): void; + mono_wasm_add_assembly (a: string, b: number, c: number): number; + mono_wasm_add_satellite_assembly (a: string, b: string, c: number, d: number): void; + mono_set_timeout_exec (a: number): void; +} + +interface BINDING_C_FUNCS { + mono_wasm_typed_array_new (a: string, b: string, c: number, d: number): number; + assembly_load (a: string): number; + find_corlib_class (a: string, b: string): number; + find_class (a: number, b: string, c: string): number; + _find_method (a: number, b: string, c: number): number; + invoke_method (a: number, b: number, c: number, d: number): number; + mono_string_get_utf8 (a: number): number; + mono_wasm_string_from_utf16 (a: number, b: number): number; + mono_get_obj_type (a: number): number; + mono_array_length (a: number): number; + mono_array_get (a: number, b: number): number; + mono_obj_array_new (a: number): number; + mono_obj_array_set (a: number, b: number, c: number): void; + mono_wasm_register_bundled_satellite_assemblies (): void; + mono_wasm_try_unbox_primitive_and_get_type (a: number, b: number): number; + mono_wasm_box_primitive (a: number, b: number, c: number): number; + mono_wasm_intern_string (a: number): number; + assembly_get_entry_point (a: number): number; + mono_wasm_string_array_new (a: number): number; + mono_wasm_typed_array_new (a: number, b: number, c: number, d: number): number; +} + +interface DOTNET_C_FUNCS { + mono_wasm_string_from_js (a: string): number; +} + +// NAMESPACES /////////////////////////////////////////////////////////////////////////////// +var MONO: typeof MonoSupportLib.$MONO & MONO_C_FUNCS; +var DOTNET: typeof DotNetSupportLib.$DOTNET & DOTNET_C_FUNCS; +var BINDING: typeof BindingSupportLib.$BINDING & BINDING_C_FUNCS; + +// LIBRARY_MONO TYPES /////////////////////////////////////////////////////////////////////// +type ManagedPointer = number; // - address in the managed heap + +type NativePointer = number; // - address in wasm memory + +type WasmEvent = { + eventName: string, // - name of the event being raised + [i: string]: any, // - arguments for the event itself +} + +type WasmId = { + idStr: string, // - full object id string + scheme: string, // - eg, object, valuetype, array .. + value: string, // - string part after `dotnet:scheme:` of the id string + o: string, // - value parsed as JSON +} + +type MonoRuntimeArgs = { + fetch_file_cb: (asset: string) => void, + loaded_cb: () => void, + debug_level: number, + assembly_root: string, + assets: { + name: string, + behavior: string, + }[], +} + +type LoadedFiles = { + url: string, + file: string, +}[]; + +type GlobalizationMode = "icu" | "invarient" | "auto"; + +type WasmRootBuffer = { + length: number, + get_address: (index: number) => number, + get_address_32: (index: number) => NativePointer, + get: (index: number) => ManagedPointer, + set: (index: number, value: number) => void, + release: () => void, +} + +type WasmRoot = { + get_address: () => NativePointer, + get_address_32: () => number, + get: () => ManagedPointer, + set: (value: any) => any, + valueOf: () => ManagedPointer, + clear: () => void, + toString: () => string, + release: () => void, + value: number, +} + +// EMSDK NON MODULE RELATED ///////////////////////////////////////////////////////////////// +var ENVIRONMENT_IS_WEB: boolean; +var ENVIRONMENT_IS_SHELL: boolean; +var ENVIRONMENT_IS_NODE: boolean; +var ENVIRONMENT_IS_WORKER: boolean; + +declare function locateFile(path: string): string; + +// OTHER //////////////////////////////////////////////////////////////////////////////////// +declare function read (path: string): string; +declare function load (path: string): string; +declare function require (path: string): object; From f4515f5fca5a146739aac83a75df48de6785030b Mon Sep 17 00:00:00 2001 From: Daniel-Genkin Date: Sat, 17 Jul 2021 11:35:50 -0400 Subject: [PATCH 03/19] split up glueForTSC --- .../libraries/webassembly-instructions.md | 6 +++ src/mono/wasm/.gitignore | 2 +- src/mono/wasm/runtime/types/Runtime.d.ts | 6 +-- src/mono/wasm/runtime/types/binding_types.ts | 37 ++++++++++++++++ src/mono/wasm/runtime/types/dotnet_types.ts | 18 ++++++++ src/mono/wasm/runtime/types/general_types.ts | 23 ++++++++++ .../types/{glueForTSC.ts => mono_types.ts} | 44 +------------------ 7 files changed, 88 insertions(+), 48 deletions(-) create mode 100644 src/mono/wasm/runtime/types/binding_types.ts create mode 100644 src/mono/wasm/runtime/types/dotnet_types.ts create mode 100644 src/mono/wasm/runtime/types/general_types.ts rename src/mono/wasm/runtime/types/{glueForTSC.ts => mono_types.ts} (62%) diff --git a/docs/workflow/building/libraries/webassembly-instructions.md b/docs/workflow/building/libraries/webassembly-instructions.md index fdc5dc31d2226..04be45534ad5d 100644 --- a/docs/workflow/building/libraries/webassembly-instructions.md +++ b/docs/workflow/building/libraries/webassembly-instructions.md @@ -17,6 +17,12 @@ On Linux and macOS: export EMSDK_PATH=/emsdk ``` +## Installing TypeScript + +To build the repo you will need to have the TypeScript `tsc` compiler installed globally. The easiest way to do this is to run `npm i -g typescript`. Learn more [here](https://www.typescriptlang.org/id/download). + +Also note that `NPM` and `NodeJS` come bundled with `EMSDK` so if you do not want to install these tools you can just add add the ones in `src/mono/wasm/emsdk` to your PATH. + ## Building everything At this time no other build dependencies are necessary to start building for WebAssembly. diff --git a/src/mono/wasm/.gitignore b/src/mono/wasm/.gitignore index 3c501f29ad1c3..5c0206297463c 100644 --- a/src/mono/wasm/.gitignore +++ b/src/mono/wasm/.gitignore @@ -1,4 +1,4 @@ !Makefile .stamp-wasm-install-and-select* emsdk -runtime/build \ No newline at end of file +runtime/build diff --git a/src/mono/wasm/runtime/types/Runtime.d.ts b/src/mono/wasm/runtime/types/Runtime.d.ts index 3b6fa11734035..9678520c9f3bc 100644 --- a/src/mono/wasm/runtime/types/Runtime.d.ts +++ b/src/mono/wasm/runtime/types/Runtime.d.ts @@ -8,7 +8,8 @@ THIS FILE IS NOT INCLUDED IN DOTNET.JS. ALL CODE HERE WILL BE IGNORED DURING THE BUILD ********************************************************************************************/ -// Make sure that this is updated with all the accessible members from dotnet.js such as callbacks +// TODO PROPERLY SET THESE ANYS + declare namespace Module { let config: MonoConfig; let HEAP8: Int8Array; @@ -20,8 +21,6 @@ declare namespace Module { let HEAPF32: Float32Array; let HEAPF64: Float64Array; - // TODO properly type these anys - let arguments: string[]; let loadReadFiles: boolean; let printWithColors: boolean; @@ -43,7 +42,6 @@ declare namespace Module { function mono_method_get_call_signature (method: any, mono_obj?: any): string; function print (message: string): void; - // Make sure that this is updated with all the methods that we manually export from emsdk (i.e. EXPORTED_RUNTIME_METHODS in wasm.proj). The non exported ones I have intentaionally left out function ccall (ident: string, returnType?: string, argTypes?: any[] , args?: any[] , opts?: any): any; function FS_createPath (parent: string | any, path: string, canRead?: boolean /* unused */, canWrite?: boolean /* unused */): string; function FS_createDataFile (parent: string | any, name: string, data: string, canRead: boolean, canWrite: boolean, canOwn?: boolean): string; diff --git a/src/mono/wasm/runtime/types/binding_types.ts b/src/mono/wasm/runtime/types/binding_types.ts new file mode 100644 index 0000000000000..f74986d0a0aca --- /dev/null +++ b/src/mono/wasm/runtime/types/binding_types.ts @@ -0,0 +1,37 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +/******************************************************************************************* + This file just acts as a set of object definitions to help the TSC compiler understand + the various namespaces that we use. These namespaces are not defined explicitly until + the dotnet.js file is merged, so we pretend they exist by defining them here. + + THIS FILE IS NOT INCLUDED IN DOTNET.JS. ALL CODE HERE WILL BE IGNORED DURING THE BUILD +********************************************************************************************/ + +// VARIOUS C FUNCTIONS THAT WE CALL INTO //////////////////////////////////////////////////// +interface BINDING_C_FUNCS { + mono_wasm_typed_array_new (a: string, b: string, c: number, d: number): number; + assembly_load (a: string): number; + find_corlib_class (a: string, b: string): number; + find_class (a: number, b: string, c: string): number; + _find_method (a: number, b: string, c: number): number; + invoke_method (a: number, b: number, c: number, d: number): number; + mono_string_get_utf8 (a: number): number; + mono_wasm_string_from_utf16 (a: number, b: number): number; + mono_get_obj_type (a: number): number; + mono_array_length (a: number): number; + mono_array_get (a: number, b: number): number; + mono_obj_array_new (a: number): number; + mono_obj_array_set (a: number, b: number, c: number): void; + mono_wasm_register_bundled_satellite_assemblies (): void; + mono_wasm_try_unbox_primitive_and_get_type (a: number, b: number): number; + mono_wasm_box_primitive (a: number, b: number, c: number): number; + mono_wasm_intern_string (a: number): number; + assembly_get_entry_point (a: number): number; + mono_wasm_string_array_new (a: number): number; + mono_wasm_typed_array_new (a: number, b: number, c: number, d: number): number; +} + +// NAMESPACES /////////////////////////////////////////////////////////////////////////////// +var BINDING: typeof BindingSupportLib.$BINDING & BINDING_C_FUNCS; diff --git a/src/mono/wasm/runtime/types/dotnet_types.ts b/src/mono/wasm/runtime/types/dotnet_types.ts new file mode 100644 index 0000000000000..7fabe40808f92 --- /dev/null +++ b/src/mono/wasm/runtime/types/dotnet_types.ts @@ -0,0 +1,18 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +/******************************************************************************************* + This file just acts as a set of object definitions to help the TSC compiler understand + the various namespaces that we use. These namespaces are not defined explicitly until + the dotnet.js file is merged, so we pretend they exist by defining them here. + + THIS FILE IS NOT INCLUDED IN DOTNET.JS. ALL CODE HERE WILL BE IGNORED DURING THE BUILD +********************************************************************************************/ + +// VARIOUS C FUNCTIONS THAT WE CALL INTO //////////////////////////////////////////////////// +interface DOTNET_C_FUNCS { + mono_wasm_string_from_js (a: string): number; +} + +// NAMESPACES /////////////////////////////////////////////////////////////////////////////// +var DOTNET: typeof DotNetSupportLib.$DOTNET & DOTNET_C_FUNCS; diff --git a/src/mono/wasm/runtime/types/general_types.ts b/src/mono/wasm/runtime/types/general_types.ts new file mode 100644 index 0000000000000..fc4a8f04e1dd7 --- /dev/null +++ b/src/mono/wasm/runtime/types/general_types.ts @@ -0,0 +1,23 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +/******************************************************************************************* + This file just acts as a set of object definitions to help the TSC compiler understand + the various namespaces that we use. These namespaces are not defined explicitly until + the dotnet.js file is merged, so we pretend they exist by defining them here. + + THIS FILE IS NOT INCLUDED IN DOTNET.JS. ALL CODE HERE WILL BE IGNORED DURING THE BUILD +********************************************************************************************/ + +// EMSDK NON MODULE RELATED ///////////////////////////////////////////////////////////////// +var ENVIRONMENT_IS_WEB: boolean; +var ENVIRONMENT_IS_SHELL: boolean; +var ENVIRONMENT_IS_NODE: boolean; +var ENVIRONMENT_IS_WORKER: boolean; + +declare function locateFile(path: string): string; + +// OTHER //////////////////////////////////////////////////////////////////////////////////// +declare function read (path: string): string; +declare function load (path: string): string; +declare function require (path: string): object; diff --git a/src/mono/wasm/runtime/types/glueForTSC.ts b/src/mono/wasm/runtime/types/mono_types.ts similarity index 62% rename from src/mono/wasm/runtime/types/glueForTSC.ts rename to src/mono/wasm/runtime/types/mono_types.ts index 377a1154dfabf..99c7002f576b0 100644 --- a/src/mono/wasm/runtime/types/glueForTSC.ts +++ b/src/mono/wasm/runtime/types/mono_types.ts @@ -30,39 +30,10 @@ interface MONO_C_FUNCS { mono_set_timeout_exec (a: number): void; } -interface BINDING_C_FUNCS { - mono_wasm_typed_array_new (a: string, b: string, c: number, d: number): number; - assembly_load (a: string): number; - find_corlib_class (a: string, b: string): number; - find_class (a: number, b: string, c: string): number; - _find_method (a: number, b: string, c: number): number; - invoke_method (a: number, b: number, c: number, d: number): number; - mono_string_get_utf8 (a: number): number; - mono_wasm_string_from_utf16 (a: number, b: number): number; - mono_get_obj_type (a: number): number; - mono_array_length (a: number): number; - mono_array_get (a: number, b: number): number; - mono_obj_array_new (a: number): number; - mono_obj_array_set (a: number, b: number, c: number): void; - mono_wasm_register_bundled_satellite_assemblies (): void; - mono_wasm_try_unbox_primitive_and_get_type (a: number, b: number): number; - mono_wasm_box_primitive (a: number, b: number, c: number): number; - mono_wasm_intern_string (a: number): number; - assembly_get_entry_point (a: number): number; - mono_wasm_string_array_new (a: number): number; - mono_wasm_typed_array_new (a: number, b: number, c: number, d: number): number; -} - -interface DOTNET_C_FUNCS { - mono_wasm_string_from_js (a: string): number; -} - // NAMESPACES /////////////////////////////////////////////////////////////////////////////// var MONO: typeof MonoSupportLib.$MONO & MONO_C_FUNCS; -var DOTNET: typeof DotNetSupportLib.$DOTNET & DOTNET_C_FUNCS; -var BINDING: typeof BindingSupportLib.$BINDING & BINDING_C_FUNCS; -// LIBRARY_MONO TYPES /////////////////////////////////////////////////////////////////////// +// OTHER TYPES /////////////////////////////////////////////////////////////////////// type ManagedPointer = number; // - address in the managed heap type NativePointer = number; // - address in wasm memory @@ -117,16 +88,3 @@ type WasmRoot = { release: () => void, value: number, } - -// EMSDK NON MODULE RELATED ///////////////////////////////////////////////////////////////// -var ENVIRONMENT_IS_WEB: boolean; -var ENVIRONMENT_IS_SHELL: boolean; -var ENVIRONMENT_IS_NODE: boolean; -var ENVIRONMENT_IS_WORKER: boolean; - -declare function locateFile(path: string): string; - -// OTHER //////////////////////////////////////////////////////////////////////////////////// -declare function read (path: string): string; -declare function load (path: string): string; -declare function require (path: string): object; From 797ece8fa9dd87b29023d5014a458fdc917c4780 Mon Sep 17 00:00:00 2001 From: Daniel-Genkin Date: Sat, 17 Jul 2021 11:57:07 -0400 Subject: [PATCH 04/19] cleanup of markdown and formatting --- .../libraries/webassembly-instructions.md | 2 +- src/mono/wasm/runtime/binding_support.ts | 2 +- src/mono/wasm/runtime/tsconfig.json | 2 +- src/mono/wasm/runtime/types/binding_types.ts | 20 +++--- src/mono/wasm/runtime/types/mono_types.ts | 72 ++++++++++--------- 5 files changed, 51 insertions(+), 47 deletions(-) diff --git a/docs/workflow/building/libraries/webassembly-instructions.md b/docs/workflow/building/libraries/webassembly-instructions.md index 04be45534ad5d..6d003c8932270 100644 --- a/docs/workflow/building/libraries/webassembly-instructions.md +++ b/docs/workflow/building/libraries/webassembly-instructions.md @@ -19,7 +19,7 @@ export EMSDK_PATH=/emsdk ## Installing TypeScript -To build the repo you will need to have the TypeScript `tsc` compiler installed globally. The easiest way to do this is to run `npm i -g typescript`. Learn more [here](https://www.typescriptlang.org/id/download). +To build the repo you will need to have the TypeScript `tsc` compiler installed globally. The easiest way to do this is to run `npm i -g typescript`. Learn more [here](https://www.typescriptlang.org/id/download). Also note that `NPM` and `NodeJS` come bundled with `EMSDK` so if you do not want to install these tools you can just add add the ones in `src/mono/wasm/emsdk` to your PATH. diff --git a/src/mono/wasm/runtime/binding_support.ts b/src/mono/wasm/runtime/binding_support.ts index f148a97d42d05..f0e3352c64523 100644 --- a/src/mono/wasm/runtime/binding_support.ts +++ b/src/mono/wasm/runtime/binding_support.ts @@ -31,7 +31,7 @@ var BindingSupportLib = { bindings_lazy_init: function (): void { if (this.init) return; - + // avoid infinite recursion this.init = true; diff --git a/src/mono/wasm/runtime/tsconfig.json b/src/mono/wasm/runtime/tsconfig.json index 857b7a4182a1f..da5aa26f34336 100644 --- a/src/mono/wasm/runtime/tsconfig.json +++ b/src/mono/wasm/runtime/tsconfig.json @@ -10,4 +10,4 @@ "outDir": "build" }, "exclude": [ "build" ] -} \ No newline at end of file +} diff --git a/src/mono/wasm/runtime/types/binding_types.ts b/src/mono/wasm/runtime/types/binding_types.ts index f74986d0a0aca..6ed369b83f515 100644 --- a/src/mono/wasm/runtime/types/binding_types.ts +++ b/src/mono/wasm/runtime/types/binding_types.ts @@ -11,26 +11,28 @@ // VARIOUS C FUNCTIONS THAT WE CALL INTO //////////////////////////////////////////////////// interface BINDING_C_FUNCS { - mono_wasm_typed_array_new (a: string, b: string, c: number, d: number): number; + _find_method (a: number, b: string, c: number): number; + assembly_get_entry_point (a: number): number; assembly_load (a: string): number; - find_corlib_class (a: string, b: string): number; find_class (a: number, b: string, c: string): number; - _find_method (a: number, b: string, c: number): number; + find_corlib_class (a: string, b: string): number; invoke_method (a: number, b: number, c: number, d: number): number; - mono_string_get_utf8 (a: number): number; - mono_wasm_string_from_utf16 (a: number, b: number): number; - mono_get_obj_type (a: number): number; + mono_array_length (a: number): number; mono_array_get (a: number, b: number): number; + mono_get_obj_type (a: number): number; mono_obj_array_new (a: number): number; mono_obj_array_set (a: number, b: number, c: number): void; - mono_wasm_register_bundled_satellite_assemblies (): void; - mono_wasm_try_unbox_primitive_and_get_type (a: number, b: number): number; + mono_string_get_utf8 (a: number): number; + mono_wasm_box_primitive (a: number, b: number, c: number): number; mono_wasm_intern_string (a: number): number; - assembly_get_entry_point (a: number): number; + mono_wasm_register_bundled_satellite_assemblies (): void; mono_wasm_string_array_new (a: number): number; + mono_wasm_string_from_utf16 (a: number, b: number): number; + mono_wasm_try_unbox_primitive_and_get_type (a: number, b: number): number; mono_wasm_typed_array_new (a: number, b: number, c: number, d: number): number; + mono_wasm_typed_array_new (a: string, b: string, c: number, d: number): number; } // NAMESPACES /////////////////////////////////////////////////////////////////////////////// diff --git a/src/mono/wasm/runtime/types/mono_types.ts b/src/mono/wasm/runtime/types/mono_types.ts index 99c7002f576b0..424ae0aa855d7 100644 --- a/src/mono/wasm/runtime/types/mono_types.ts +++ b/src/mono/wasm/runtime/types/mono_types.ts @@ -12,43 +12,38 @@ // VARIOUS C FUNCTIONS THAT WE CALL INTO //////////////////////////////////////////////////// interface MONO_C_FUNCS { mono_background_exec (): void; - mono_wasm_register_root (a: number, b: number, c: string): number; + mono_set_timeout_exec (a: number): void; + + mono_wasm_add_assembly (a: string, b: number, c: number): number; + mono_wasm_add_satellite_assembly (a: string, b: string, c: number, d: number): void; mono_wasm_deregister_root (a: number): void; - mono_wasm_string_get_data (a: number, b: number, c: number, d: number): void; - mono_wasm_set_is_debugger_attached (a: boolean): void; + mono_wasm_exit (a: number): void; + mono_wasm_get_icudt_name (a: string): string; + mono_wasm_load_icu_data (a: number): number; + mono_wasm_load_runtime (a: string, b: number): void; + mono_wasm_parse_runtime_options (a: number, b:number): void; + mono_wasm_register_root (a: number, b: number, c: string): number; mono_wasm_send_dbg_command (a: number, b:number, c: number, d: number, e: number): boolean; mono_wasm_send_dbg_command_with_parms (a: number, b:number, c: number, d: number, e: number, f: number, g: string): boolean; + mono_wasm_set_is_debugger_attached (a: boolean): void; mono_wasm_setenv (a: string, b: string): void; - mono_wasm_parse_runtime_options (a: number, b:number): void; mono_wasm_strdup (a: string): number; - mono_wasm_load_icu_data (a: number): number; - mono_wasm_get_icudt_name (a: string): string; - mono_wasm_load_runtime (a: string, b: number): void; - mono_wasm_exit (a: number): void; - mono_wasm_add_assembly (a: string, b: number, c: number): number; - mono_wasm_add_satellite_assembly (a: string, b: string, c: number, d: number): void; - mono_set_timeout_exec (a: number): void; + mono_wasm_string_get_data (a: number, b: number, c: number, d: number): void; } // NAMESPACES /////////////////////////////////////////////////////////////////////////////// var MONO: typeof MonoSupportLib.$MONO & MONO_C_FUNCS; // OTHER TYPES /////////////////////////////////////////////////////////////////////// -type ManagedPointer = number; // - address in the managed heap -type NativePointer = number; // - address in wasm memory +type GlobalizationMode = "icu" | "invarient" | "auto"; -type WasmEvent = { - eventName: string, // - name of the event being raised - [i: string]: any, // - arguments for the event itself -} +type LoadedFiles = { + url: string, + file: string, +}[]; -type WasmId = { - idStr: string, // - full object id string - scheme: string, // - eg, object, valuetype, array .. - value: string, // - string part after `dotnet:scheme:` of the id string - o: string, // - value parsed as JSON -} +type ManagedPointer = number; // - address in the managed heap type MonoRuntimeArgs = { fetch_file_cb: (asset: string) => void, @@ -61,20 +56,18 @@ type MonoRuntimeArgs = { }[], } -type LoadedFiles = { - url: string, - file: string, -}[]; +type NativePointer = number; // - address in wasm memory -type GlobalizationMode = "icu" | "invarient" | "auto"; +type WasmEvent = { + eventName: string, // - name of the event being raised + [i: string]: any, // - arguments for the event itself +} -type WasmRootBuffer = { - length: number, - get_address: (index: number) => number, - get_address_32: (index: number) => NativePointer, - get: (index: number) => ManagedPointer, - set: (index: number, value: number) => void, - release: () => void, +type WasmId = { + idStr: string, // - full object id string + scheme: string, // - eg, object, valuetype, array .. + value: string, // - string part after `dotnet:scheme:` of the id string + o: string, // - value parsed as JSON } type WasmRoot = { @@ -88,3 +81,12 @@ type WasmRoot = { release: () => void, value: number, } + +type WasmRootBuffer = { + length: number, + get_address: (index: number) => number, + get_address_32: (index: number) => NativePointer, + get: (index: number) => ManagedPointer, + set: (index: number, value: number) => void, + release: () => void, +} From 7ea904d7a83ab2276b5e8a154c59646ec86bd1fb Mon Sep 17 00:00:00 2001 From: Daniel Genkin <85504900+Daniel-Genkin-MS@users.noreply.github.com> Date: Sat, 17 Jul 2021 20:47:01 +0000 Subject: [PATCH 05/19] added tsc step to linux build --- src/mono/wasm/wasm.proj | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/mono/wasm/wasm.proj b/src/mono/wasm/wasm.proj index c6ab244fb1be7..47a75282b43a4 100644 --- a/src/mono/wasm/wasm.proj +++ b/src/mono/wasm/wasm.proj @@ -140,6 +140,9 @@ AfterTargets="Build" DependsOnTargets="GenerateEmccPropsAndRspFiles;BuildPInvokeTable;BundleTimeZones"> + + + From 536962ed8bf204a941ce9564990fb7b8c7a7b521 Mon Sep 17 00:00:00 2001 From: Daniel-Genkin Date: Mon, 19 Jul 2021 13:43:31 -0400 Subject: [PATCH 06/19] + renamed build folder to bin + made extra type files declaration files --- src/mono/wasm/Makefile | 6 +++--- src/mono/wasm/runtime/tsconfig.json | 4 ++-- src/mono/wasm/runtime/types/{Runtime.d.ts => Module.d.ts} | 0 .../types/{binding_types.ts => binding_types.d.ts} | 2 +- .../runtime/types/{dotnet_types.ts => dotnet_types.d.ts} | 2 +- .../types/{general_types.ts => general_types.d.ts} | 8 ++++---- .../wasm/runtime/types/{mono_types.ts => mono_types.d.ts} | 2 +- src/mono/wasm/wasm.proj | 8 ++++---- 8 files changed, 16 insertions(+), 16 deletions(-) rename src/mono/wasm/runtime/types/{Runtime.d.ts => Module.d.ts} (100%) rename src/mono/wasm/runtime/types/{binding_types.ts => binding_types.d.ts} (96%) rename src/mono/wasm/runtime/types/{dotnet_types.ts => dotnet_types.d.ts} (93%) rename src/mono/wasm/runtime/types/{general_types.ts => general_types.d.ts} (86%) rename src/mono/wasm/runtime/types/{mono_types.ts => mono_types.d.ts} (98%) diff --git a/src/mono/wasm/Makefile b/src/mono/wasm/Makefile index b9fec6c433401..2242fb8d79885 100644 --- a/src/mono/wasm/Makefile +++ b/src/mono/wasm/Makefile @@ -101,8 +101,8 @@ $(NATIVE_BIN_DIR)/include/wasm: $(BUILDS_OBJ_DIR): mkdir -p $$@ -$(NATIVE_BIN_DIR)/dotnet.js: $(BUILDS_OBJ_DIR)/driver.o $(BUILDS_OBJ_DIR)/pinvoke.o $(BUILDS_OBJ_DIR)/corebindings.o runtime/build/library_mono.js runtime/build/binding_support.js runtime/build/dotnet_support.js $(SYSTEM_NATIVE_LIBDIR)/pal_random.js $(2) $(EMCC_DEFAULT_RSP) | $(NATIVE_BIN_DIR) - $(EMCC) @$(EMCC_DEFAULT_RSP) $(1) --js-library runtime/build/library_mono.js --js-library runtime/build/binding_support.js --js-library runtime/build/dotnet_support.js --js-library $(SYSTEM_NATIVE_LIBDIR)/pal_random.js $(BUILDS_OBJ_DIR)/driver.o $(BUILDS_OBJ_DIR)/pinvoke.o $(BUILDS_OBJ_DIR)/corebindings.o $(2) -o $(NATIVE_BIN_DIR)/dotnet.js $(3) +$(NATIVE_BIN_DIR)/dotnet.js: $(BUILDS_OBJ_DIR)/driver.o $(BUILDS_OBJ_DIR)/pinvoke.o $(BUILDS_OBJ_DIR)/corebindings.o runtime/bin/library_mono.js runtime/bin/binding_support.js runtime/bin/dotnet_support.js $(SYSTEM_NATIVE_LIBDIR)/pal_random.js $(2) $(EMCC_DEFAULT_RSP) | $(NATIVE_BIN_DIR) + $(EMCC) @$(EMCC_DEFAULT_RSP) $(1) --js-library runtime/bin/library_mono.js --js-library runtime/bin/binding_support.js --js-library runtime/bin/dotnet_support.js --js-library $(SYSTEM_NATIVE_LIBDIR)/pal_random.js $(BUILDS_OBJ_DIR)/driver.o $(BUILDS_OBJ_DIR)/pinvoke.o $(BUILDS_OBJ_DIR)/corebindings.o $(2) -o $(NATIVE_BIN_DIR)/dotnet.js $(3) $(BUILDS_OBJ_DIR)/pinvoke-table.h: $(PINVOKE_TABLE) | $(BUILDS_OBJ_DIR) if cmp -s $(PINVOKE_TABLE) $$@ ; then : ; else cp $(PINVOKE_TABLE) $$@ ; fi @@ -141,7 +141,7 @@ clean: icu-files: $(wildcard $(ICU_LIBDIR)/*.dat) $(ICU_LIBDIR)/libicuuc.a $(ICU_LIBDIR)/libicui18n.a | $(NATIVE_BIN_DIR) cp $^ $(NATIVE_BIN_DIR) -source-files: runtime/driver.c runtime/pinvoke.c runtime/corebindings.c runtime/build/binding_support.js runtime/build/dotnet_support.js runtime/build/library_mono.js $(SYSTEM_NATIVE_LIBDIR)/pal_random.js | $(NATIVE_BIN_DIR)/src +source-files: runtime/driver.c runtime/pinvoke.c runtime/corebindings.c runtime/bin/binding_support.js runtime/bin/dotnet_support.js runtime/bin/library_mono.js $(SYSTEM_NATIVE_LIBDIR)/pal_random.js | $(NATIVE_BIN_DIR)/src cp $^ $(NATIVE_BIN_DIR)/src header-files: runtime/pinvoke.h | $(NATIVE_BIN_DIR)/include/wasm diff --git a/src/mono/wasm/runtime/tsconfig.json b/src/mono/wasm/runtime/tsconfig.json index da5aa26f34336..fc3d9890b8a15 100644 --- a/src/mono/wasm/runtime/tsconfig.json +++ b/src/mono/wasm/runtime/tsconfig.json @@ -7,7 +7,7 @@ "target": "es2019", "lib": ["es2019", "dom"], "strict": false, // todo set to true eventually once types are setup - "outDir": "build" + "outDir": "bin" }, - "exclude": [ "build" ] + "exclude": [ "bin" ] } diff --git a/src/mono/wasm/runtime/types/Runtime.d.ts b/src/mono/wasm/runtime/types/Module.d.ts similarity index 100% rename from src/mono/wasm/runtime/types/Runtime.d.ts rename to src/mono/wasm/runtime/types/Module.d.ts diff --git a/src/mono/wasm/runtime/types/binding_types.ts b/src/mono/wasm/runtime/types/binding_types.d.ts similarity index 96% rename from src/mono/wasm/runtime/types/binding_types.ts rename to src/mono/wasm/runtime/types/binding_types.d.ts index 6ed369b83f515..e799533aa4fea 100644 --- a/src/mono/wasm/runtime/types/binding_types.ts +++ b/src/mono/wasm/runtime/types/binding_types.d.ts @@ -36,4 +36,4 @@ interface BINDING_C_FUNCS { } // NAMESPACES /////////////////////////////////////////////////////////////////////////////// -var BINDING: typeof BindingSupportLib.$BINDING & BINDING_C_FUNCS; +declare var BINDING: typeof BindingSupportLib.$BINDING & BINDING_C_FUNCS; diff --git a/src/mono/wasm/runtime/types/dotnet_types.ts b/src/mono/wasm/runtime/types/dotnet_types.d.ts similarity index 93% rename from src/mono/wasm/runtime/types/dotnet_types.ts rename to src/mono/wasm/runtime/types/dotnet_types.d.ts index 7fabe40808f92..f950bc51a9140 100644 --- a/src/mono/wasm/runtime/types/dotnet_types.ts +++ b/src/mono/wasm/runtime/types/dotnet_types.d.ts @@ -15,4 +15,4 @@ interface DOTNET_C_FUNCS { } // NAMESPACES /////////////////////////////////////////////////////////////////////////////// -var DOTNET: typeof DotNetSupportLib.$DOTNET & DOTNET_C_FUNCS; +declare var DOTNET: typeof DotNetSupportLib.$DOTNET & DOTNET_C_FUNCS; diff --git a/src/mono/wasm/runtime/types/general_types.ts b/src/mono/wasm/runtime/types/general_types.d.ts similarity index 86% rename from src/mono/wasm/runtime/types/general_types.ts rename to src/mono/wasm/runtime/types/general_types.d.ts index fc4a8f04e1dd7..512adf7640555 100644 --- a/src/mono/wasm/runtime/types/general_types.ts +++ b/src/mono/wasm/runtime/types/general_types.d.ts @@ -10,10 +10,10 @@ ********************************************************************************************/ // EMSDK NON MODULE RELATED ///////////////////////////////////////////////////////////////// -var ENVIRONMENT_IS_WEB: boolean; -var ENVIRONMENT_IS_SHELL: boolean; -var ENVIRONMENT_IS_NODE: boolean; -var ENVIRONMENT_IS_WORKER: boolean; +declare var ENVIRONMENT_IS_WEB: boolean; +declare var ENVIRONMENT_IS_SHELL: boolean; +declare var ENVIRONMENT_IS_NODE: boolean; +declare var ENVIRONMENT_IS_WORKER: boolean; declare function locateFile(path: string): string; diff --git a/src/mono/wasm/runtime/types/mono_types.ts b/src/mono/wasm/runtime/types/mono_types.d.ts similarity index 98% rename from src/mono/wasm/runtime/types/mono_types.ts rename to src/mono/wasm/runtime/types/mono_types.d.ts index 424ae0aa855d7..66dbe402f7143 100644 --- a/src/mono/wasm/runtime/types/mono_types.ts +++ b/src/mono/wasm/runtime/types/mono_types.d.ts @@ -32,7 +32,7 @@ interface MONO_C_FUNCS { } // NAMESPACES /////////////////////////////////////////////////////////////////////////////// -var MONO: typeof MonoSupportLib.$MONO & MONO_C_FUNCS; +declare var MONO: typeof MonoSupportLib.$MONO & MONO_C_FUNCS; // OTHER TYPES /////////////////////////////////////////////////////////////////////// diff --git a/src/mono/wasm/wasm.proj b/src/mono/wasm/wasm.proj index c6ab244fb1be7..2122d05494bf7 100644 --- a/src/mono/wasm/wasm.proj +++ b/src/mono/wasm/wasm.proj @@ -224,7 +224,7 @@ - @@ -242,9 +242,9 @@ From d9ef3b429994995d5f3279ca0da51c7070ad6fe4 Mon Sep 17 00:00:00 2001 From: Daniel-Genkin Date: Mon, 19 Jul 2021 14:30:03 -0400 Subject: [PATCH 07/19] Updated ci ubuntu image version --- eng/pipelines/common/platform-matrix.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eng/pipelines/common/platform-matrix.yml b/eng/pipelines/common/platform-matrix.yml index defd34be84ae2..61fecd83e764c 100644 --- a/eng/pipelines/common/platform-matrix.yml +++ b/eng/pipelines/common/platform-matrix.yml @@ -219,7 +219,7 @@ jobs: targetRid: browser-wasm platform: Browser_wasm container: - image: ubuntu-18.04-webassembly-20210531091624-f5c7a43 + image: ubuntu-18.04-webassembly-20210719180238-880fd01 registry: mcr jobParameters: runtimeFlavor: ${{ parameters.runtimeFlavor }} From 63631d11986f8c8162381b2db41181e447d44da1 Mon Sep 17 00:00:00 2001 From: Daniel-Genkin Date: Mon, 19 Jul 2021 17:09:52 -0400 Subject: [PATCH 08/19] replaced most `this` with the corresponding namespace to help tsc track types + tried to fix the build error --- src/mono/wasm/runtime/binding_support.ts | 545 +++++++++--------- src/mono/wasm/runtime/library_mono.ts | 217 ++++--- src/mono/wasm/runtime/types/Module.d.ts | 7 +- .../wasm/runtime/types/binding_types.d.ts | 67 ++- .../wasm/runtime/types/general_types.d.ts | 3 + src/mono/wasm/runtime/types/mono_types.d.ts | 17 +- src/mono/wasm/wasm.proj | 4 +- 7 files changed, 463 insertions(+), 397 deletions(-) diff --git a/src/mono/wasm/runtime/binding_support.ts b/src/mono/wasm/runtime/binding_support.ts index f0e3352c64523..dee3da25b86c3 100644 --- a/src/mono/wasm/runtime/binding_support.ts +++ b/src/mono/wasm/runtime/binding_support.ts @@ -12,7 +12,7 @@ var BindingSupportLib = { mono_wasm_owned_objects_LMF: [], mono_wasm_marshal_enum_as_int: true, mono_bindings_init: function (binding_asm: string): void { - this.BINDING_ASM = binding_asm; + BINDING.BINDING_ASM = binding_asm; }, export_functions: function (module: object): void { @@ -29,11 +29,11 @@ var BindingSupportLib = { }, bindings_lazy_init: function (): void { - if (this.init) + if (BINDING.init) return; // avoid infinite recursion - this.init = true; + BINDING.init = true; Array.prototype[Symbol.for("wasm type")] = 1; ArrayBuffer.prototype[Symbol.for("wasm type")] = 2; @@ -52,41 +52,41 @@ var BindingSupportLib = { Float32Array.prototype[Symbol.for("wasm type")] = 17; Float64Array.prototype[Symbol.for("wasm type")] = 18; - this.assembly_load = Module.cwrap ('mono_wasm_assembly_load', 'number', ['string']); - this.find_corlib_class = Module.cwrap ('mono_wasm_find_corlib_class', 'number', ['string', 'string']); - this.find_class = Module.cwrap ('mono_wasm_assembly_find_class', 'number', ['number', 'string', 'string']); - this._find_method = Module.cwrap ('mono_wasm_assembly_find_method', 'number', ['number', 'string', 'number']); - this.invoke_method = Module.cwrap ('mono_wasm_invoke_method', 'number', ['number', 'number', 'number', 'number']); - this.mono_string_get_utf8 = Module.cwrap ('mono_wasm_string_get_utf8', 'number', ['number']); - this.mono_wasm_string_from_utf16 = Module.cwrap ('mono_wasm_string_from_utf16', 'number', ['number', 'number']); - this.mono_get_obj_type = Module.cwrap ('mono_wasm_get_obj_type', 'number', ['number']); - this.mono_array_length = Module.cwrap ('mono_wasm_array_length', 'number', ['number']); - this.mono_array_get = Module.cwrap ('mono_wasm_array_get', 'number', ['number', 'number']); - this.mono_obj_array_new = Module.cwrap ('mono_wasm_obj_array_new', 'number', ['number']); - this.mono_obj_array_set = Module.cwrap ('mono_wasm_obj_array_set', 'void', ['number', 'number', 'number']); - this.mono_wasm_register_bundled_satellite_assemblies = Module.cwrap ('mono_wasm_register_bundled_satellite_assemblies', 'void', [ ]); - this.mono_wasm_try_unbox_primitive_and_get_type = Module.cwrap ('mono_wasm_try_unbox_primitive_and_get_type', 'number', ['number', 'number']); - this.mono_wasm_box_primitive = Module.cwrap ('mono_wasm_box_primitive', 'number', ['number', 'number', 'number']); - this.mono_wasm_intern_string = Module.cwrap ('mono_wasm_intern_string', 'number', ['number']); - this.assembly_get_entry_point = Module.cwrap ('mono_wasm_assembly_get_entry_point', 'number', ['number']); - this.mono_wasm_get_delegate_invoke = Module.cwrap ('mono_wasm_get_delegate_invoke', 'number', ['number']); - this.mono_wasm_string_array_new = Module.cwrap ('mono_wasm_string_array_new', 'number', ['number']); - - this._box_buffer = Module._malloc(16); - this._unbox_buffer = Module._malloc(16); - this._class_int32 = this.find_corlib_class ("System", "Int32"); - this._class_uint32 = this.find_corlib_class ("System", "UInt32"); - this._class_double = this.find_corlib_class ("System", "Double"); - this._class_boolean = this.find_corlib_class ("System", "Boolean"); + BINDING.assembly_load = Module.cwrap ('mono_wasm_assembly_load', 'number', ['string']); + BINDING.find_corlib_class = Module.cwrap ('mono_wasm_find_corlib_class', 'number', ['string', 'string']); + BINDING.find_class = Module.cwrap ('mono_wasm_assembly_find_class', 'number', ['number', 'string', 'string']); + BINDING._find_method = Module.cwrap ('mono_wasm_assembly_find_method', 'number', ['number', 'string', 'number']); + BINDING.invoke_method = Module.cwrap ('mono_wasm_invoke_method', 'number', ['number', 'number', 'number', 'number']); + BINDING.mono_string_get_utf8 = Module.cwrap ('mono_wasm_string_get_utf8', 'number', ['number']); + BINDING.mono_wasm_string_from_utf16 = Module.cwrap ('mono_wasm_string_from_utf16', 'number', ['number', 'number']); + BINDING.mono_get_obj_type = Module.cwrap ('mono_wasm_get_obj_type', 'number', ['number']); + BINDING.mono_array_length = Module.cwrap ('mono_wasm_array_length', 'number', ['number']); + BINDING.mono_array_get = Module.cwrap ('mono_wasm_array_get', 'number', ['number', 'number']); + BINDING.mono_obj_array_new = Module.cwrap ('mono_wasm_obj_array_new', 'number', ['number']); + BINDING.mono_obj_array_set = Module.cwrap ('mono_wasm_obj_array_set', 'void', ['number', 'number', 'number']); + BINDING.mono_wasm_register_bundled_satellite_assemblies = Module.cwrap ('mono_wasm_register_bundled_satellite_assemblies', 'void', [ ]); + BINDING.mono_wasm_try_unbox_primitive_and_get_type = Module.cwrap ('mono_wasm_try_unbox_primitive_and_get_type', 'number', ['number', 'number']); + BINDING.mono_wasm_box_primitive = Module.cwrap ('mono_wasm_box_primitive', 'number', ['number', 'number', 'number']); + BINDING.mono_wasm_intern_string = Module.cwrap ('mono_wasm_intern_string', 'number', ['number']); + BINDING.assembly_get_entry_point = Module.cwrap ('mono_wasm_assembly_get_entry_point', 'number', ['number']); + BINDING.mono_wasm_get_delegate_invoke = Module.cwrap ('mono_wasm_get_delegate_invoke', 'number', ['number']); + BINDING.mono_wasm_string_array_new = Module.cwrap ('mono_wasm_string_array_new', 'number', ['number']); + + BINDING._box_buffer = Module._malloc(16); + BINDING._unbox_buffer = Module._malloc(16); + BINDING._class_int32 = BINDING.find_corlib_class ("System", "Int32"); + BINDING._class_uint32 = BINDING.find_corlib_class ("System", "UInt32"); + BINDING._class_double = BINDING.find_corlib_class ("System", "Double"); + BINDING._class_boolean = BINDING.find_corlib_class ("System", "Boolean"); // receives a byteoffset into allocated Heap with a size. - this.mono_typed_array_new = Module.cwrap ('mono_wasm_typed_array_new', 'number', ['number','number','number','number']); + BINDING.mono_typed_array_new = Module.cwrap ('mono_wasm_typed_array_new', 'number', ['number','number','number','number']); - var binding_fqn_asm = this.BINDING_ASM.substring(this.BINDING_ASM.indexOf ("[") + 1, this.BINDING_ASM.indexOf ("]")).trim(); - var binding_fqn_class = this.BINDING_ASM.substring (this.BINDING_ASM.indexOf ("]") + 1).trim(); + var binding_fqn_asm = BINDING.BINDING_ASM.substring(BINDING.BINDING_ASM.indexOf ("[") + 1, BINDING.BINDING_ASM.indexOf ("]")).trim(); + var binding_fqn_class = BINDING.BINDING_ASM.substring (BINDING.BINDING_ASM.indexOf ("]") + 1).trim(); - this.binding_module = this.assembly_load (binding_fqn_asm); - if (!this.binding_module) + BINDING.binding_module = BINDING.assembly_load (binding_fqn_asm); + if (!BINDING.binding_module) throw "Can't find bindings module assembly: " + binding_fqn_asm; var namespace = null, classname = null; @@ -101,7 +101,7 @@ var BindingSupportLib = { } } - var wasm_runtime_class = this.find_class (this.binding_module, namespace, classname); + var wasm_runtime_class = BINDING.find_class (BINDING.binding_module, namespace, classname); if (!wasm_runtime_class) throw "Can't find " + binding_fqn_class + " class"; @@ -112,7 +112,7 @@ var BindingSupportLib = { return res; }; - var bind_runtime_method = function (method_name, signature) { + var bind_runtime_method = function (method_name: string, signature: string): Function { var method = get_method (method_name); return BINDING.bind_method (method, 0, signature, "BINDINGS_" + method_name); }; @@ -121,49 +121,49 @@ var BindingSupportLib = { // that any code relying on the old get_method/call_method pattern will // break in a more understandable way. - this._bind_js_obj = bind_runtime_method ("BindJSObject", "iii"); - this._bind_core_clr_obj = bind_runtime_method ("BindCoreCLRObject", "ii"); - this._bind_existing_obj = bind_runtime_method ("BindExistingObject", "mi"); - this._unbind_raw_obj_and_free = bind_runtime_method ("UnBindRawJSObjectAndFree", "ii"); - this._get_js_id = bind_runtime_method ("GetJSObjectId", "m"); - this._get_raw_mono_obj = bind_runtime_method ("GetDotNetObject", "ii!"); + BINDING._bind_js_obj = bind_runtime_method ("BindJSObject", "iii"); + BINDING._bind_core_clr_obj = bind_runtime_method ("BindCoreCLRObject", "ii"); + BINDING._bind_existing_obj = bind_runtime_method ("BindExistingObject", "mi"); + BINDING._unbind_raw_obj_and_free = bind_runtime_method ("UnBindRawJSObjectAndFree", "ii"); + BINDING._get_js_id = bind_runtime_method ("GetJSObjectId", "m"); + BINDING._get_raw_mono_obj = bind_runtime_method ("GetDotNetObject", "ii!"); - this._is_simple_array = bind_runtime_method ("IsSimpleArray", "m"); - this.setup_js_cont = get_method ("SetupJSContinuation"); + BINDING._is_simple_array = bind_runtime_method ("IsSimpleArray", "m"); + BINDING.setup_js_cont = get_method ("SetupJSContinuation"); - this.create_tcs = get_method ("CreateTaskSource"); - this.set_tcs_result = get_method ("SetTaskSourceResult"); - this.set_tcs_failure = get_method ("SetTaskSourceFailure"); - this.tcs_get_task_and_bind = get_method ("GetTaskAndBind"); - this.get_call_sig = get_method ("GetCallSignature"); + BINDING.create_tcs = get_method ("CreateTaskSource"); + BINDING.set_tcs_result = get_method ("SetTaskSourceResult"); + BINDING.set_tcs_failure = get_method ("SetTaskSourceFailure"); + BINDING.tcs_get_task_and_bind = get_method ("GetTaskAndBind"); + BINDING.get_call_sig = get_method ("GetCallSignature"); - this._object_to_string = bind_runtime_method ("ObjectToString", "m"); - this.get_date_value = get_method ("GetDateValue"); - this.create_date_time = get_method ("CreateDateTime"); - this.create_uri = get_method ("CreateUri"); + BINDING._object_to_string = bind_runtime_method ("ObjectToString", "m"); + BINDING.get_date_value = get_method ("GetDateValue"); + BINDING.create_date_time = get_method ("CreateDateTime"); + BINDING.create_uri = get_method ("CreateUri"); - this.safehandle_addref = get_method ("SafeHandleAddRef"); - this.safehandle_release = get_method ("SafeHandleRelease"); - this.safehandle_get_handle = get_method ("SafeHandleGetHandle"); - this.safehandle_release_by_handle = get_method ("SafeHandleReleaseByHandle"); + BINDING.safehandle_addref = get_method ("SafeHandleAddRef"); + BINDING.safehandle_release = get_method ("SafeHandleRelease"); + BINDING.safehandle_get_handle = get_method ("SafeHandleGetHandle"); + BINDING.safehandle_release_by_handle = get_method ("SafeHandleReleaseByHandle"); - this._are_promises_supported = ((typeof Promise === "object") || (typeof Promise === "function")) && (typeof Promise.resolve === "function"); + BINDING._are_promises_supported = ((typeof Promise === "object") || (typeof Promise === "function")) && (typeof Promise.resolve === "function"); - this._empty_string = ""; - this._empty_string_ptr = 0; - this._interned_string_full_root_buffers = []; - this._interned_string_current_root_buffer = null; - this._interned_string_current_root_buffer_count = 0; - this._interned_js_string_table = new Map (); + BINDING._empty_string = ""; + BINDING._empty_string_ptr = 0; + BINDING._interned_string_full_root_buffers = []; + BINDING._interned_string_current_root_buffer = null; + BINDING._interned_string_current_root_buffer_count = 0; + BINDING._interned_js_string_table = new Map (); }, // Ensures the string is already interned on both the managed and JavaScript sides, // then returns the interned string value (to provide fast reference comparisons like C#) mono_intern_string: function (string: string): string { if (string.length === 0) - return this._empty_string; + return BINDING._empty_string; - var ptr = this.js_string_to_mono_string_interned (string); + var ptr = BINDING.js_string_to_mono_string_interned (string); var result = MONO.interned_string_table.get (ptr); return result; }, @@ -176,35 +176,35 @@ var BindingSupportLib = { const internBufferSize = 8192; - if (this._interned_string_current_root_buffer_count >= internBufferSize) { - this._interned_string_full_root_buffers.push (this._interned_string_current_root_buffer); - this._interned_string_current_root_buffer = null; + if (BINDING._interned_string_current_root_buffer_count >= internBufferSize) { + BINDING._interned_string_full_root_buffers.push (BINDING._interned_string_current_root_buffer); + BINDING._interned_string_current_root_buffer = null; } - if (!this._interned_string_current_root_buffer) { - this._interned_string_current_root_buffer = MONO.mono_wasm_new_root_buffer (internBufferSize, "interned strings"); - this._interned_string_current_root_buffer_count = 0; + if (!BINDING._interned_string_current_root_buffer) { + BINDING._interned_string_current_root_buffer = MONO.mono_wasm_new_root_buffer (internBufferSize, "interned strings"); + BINDING._interned_string_current_root_buffer_count = 0; } - var rootBuffer = this._interned_string_current_root_buffer; - var index = this._interned_string_current_root_buffer_count++; + var rootBuffer = BINDING._interned_string_current_root_buffer; + var index = BINDING._interned_string_current_root_buffer_count++; rootBuffer.set (index, ptr); // Store the managed string into the managed intern table. This can theoretically // provide a different managed object than the one we passed in, so update our // pointer (stored in the root) with the result. if (internIt) - rootBuffer.set (index, ptr = this.mono_wasm_intern_string (ptr)); + rootBuffer.set (index, ptr = BINDING.mono_wasm_intern_string (ptr)); if (!ptr) throw new Error ("mono_wasm_intern_string produced a null pointer"); - this._interned_js_string_table.set (string, ptr); + BINDING._interned_js_string_table.set (string, ptr); if (!MONO.interned_string_table) MONO.interned_string_table = new Map(); MONO.interned_string_table.set (ptr, string); - if ((string.length === 0) && !this._empty_string_ptr) - this._empty_string_ptr = ptr; + if ((string.length === 0) && !BINDING._empty_string_ptr) + BINDING._empty_string_ptr = ptr; return ptr; }, @@ -214,68 +214,68 @@ var BindingSupportLib = { ? (string.description || Symbol.keyFor(string) || "") : string; - if ((text.length === 0) && this._empty_string_ptr) - return this._empty_string_ptr; + if ((text.length === 0) && BINDING._empty_string_ptr) + return BINDING._empty_string_ptr; - var ptr = this._interned_js_string_table.get (string); + var ptr = BINDING._interned_js_string_table.get (string); if (ptr) return ptr; - ptr = this.js_string_to_mono_string_new (text); - ptr = this._store_string_in_intern_table (string, ptr, true); + ptr = BINDING.js_string_to_mono_string_new (text); + ptr = BINDING._store_string_in_intern_table (string, ptr, true); return ptr; }, - js_string_to_mono_string: function (string: string): string { + js_string_to_mono_string: function (string: string): number { if (string === null) return null; else if (typeof (string) === "symbol") - return this.js_string_to_mono_string_interned (string); + return BINDING.js_string_to_mono_string_interned (string); else if (typeof (string) !== "string") throw new Error ("Expected string argument"); // Always use an interned pointer for empty strings if (string.length === 0) - return this.js_string_to_mono_string_interned (string); + return BINDING.js_string_to_mono_string_interned (string); // Looking up large strings in the intern table will require the JS runtime to // potentially hash them and then do full byte-by-byte comparisons, which is // very expensive. Because we can not guarantee it won't happen, try to minimize // the cost of this and prevent performance issues for large strings if (string.length <= 256) { - var interned = this._interned_js_string_table.get (string); + var interned = BINDING._interned_js_string_table.get (string); if (interned) return interned; } - return this.js_string_to_mono_string_new (string); + return BINDING.js_string_to_mono_string_new (string); }, - js_string_to_mono_string_new: function (string: string): string { + js_string_to_mono_string_new: function (string: string): number { var buffer = Module._malloc ((string.length + 1) * 2); var buffer16 = (buffer / 2) | 0; for (var i = 0; i < string.length; i++) Module.HEAP16[buffer16 + i] = string.charCodeAt (i); Module.HEAP16[buffer16 + string.length] = 0; - var result = this.mono_wasm_string_from_utf16 (buffer, string.length); + var result = BINDING.mono_wasm_string_from_utf16 (buffer, string.length); Module._free (buffer); return result; }, find_method: function (klass: number, name: string, n: number): number { - var result = this._find_method(klass, name, n); + var result = BINDING._find_method(klass, name, n); if (result) { - if (!this._method_descriptions) - this._method_descriptions = new Map(); - this._method_descriptions.set(result, name); + if (!BINDING._method_descriptions) + BINDING._method_descriptions = new Map(); + BINDING._method_descriptions.set(result, name); } return result; }, get_js_obj: function (js_handle: number): object | null { if (js_handle > 0) - return this.mono_wasm_require_handle(js_handle); + return BINDING.mono_wasm_require_handle(js_handle); return null; }, @@ -290,16 +290,16 @@ var BindingSupportLib = { }, is_nested_array: function (ele: any): boolean { - return this._is_simple_array(ele); + return BINDING._is_simple_array(ele); }, - mono_array_to_js_array: function (mono_array: number): number | null { + mono_array_to_js_array: function (mono_array: number): any { if (mono_array === 0) return null; var arrayRoot = MONO.mono_wasm_new_root (mono_array); try { - return this._mono_array_root_to_js_array (arrayRoot); + return BINDING._mono_array_root_to_js_array (arrayRoot); } finally { arrayRoot.release(); } @@ -312,16 +312,16 @@ var BindingSupportLib = { let elemRoot = MONO.mono_wasm_new_root (); try { - var len = this.mono_array_length (arrayRoot.value); + var len = BINDING.mono_array_length (arrayRoot.value); var res = new Array (len); for (var i = 0; i < len; ++i) { - elemRoot.value = this.mono_array_get (arrayRoot.value, i); + elemRoot.value = BINDING.mono_array_get (arrayRoot.value, i); - if (this.is_nested_array (elemRoot.value)) - res[i] = this._mono_array_root_to_js_array (elemRoot); + if (BINDING.is_nested_array (elemRoot.value)) + res[i] = BINDING._mono_array_root_to_js_array (elemRoot); else - res[i] = this._unbox_mono_obj_root (elemRoot); + res[i] = BINDING._unbox_mono_obj_root (elemRoot); } } finally { elemRoot.release (); @@ -331,7 +331,7 @@ var BindingSupportLib = { }, js_array_to_mono_array: function (js_array, asString = false) { - var mono_array = asString ? this.mono_wasm_string_array_new (js_array.length) : this.mono_obj_array_new (js_array.length); + var mono_array = asString ? BINDING.mono_wasm_string_array_new (js_array.length) : BINDING.mono_obj_array_new (js_array.length); let [arrayRoot, elemRoot] = MONO.mono_wasm_new_roots ([mono_array, 0]); try { @@ -340,8 +340,8 @@ var BindingSupportLib = { if (asString) obj = obj.toString (); - elemRoot.value = this.js_to_mono_obj (obj); - this.mono_obj_array_set (arrayRoot.value, i, elemRoot.value); + elemRoot.value = BINDING.js_to_mono_obj (obj); + BINDING.mono_obj_array_set (arrayRoot.value, i, elemRoot.value); } return mono_array; @@ -356,14 +356,14 @@ var BindingSupportLib = { var root = MONO.mono_wasm_new_root (mono_obj); try { - return this._unbox_mono_obj_root (root); + return BINDING._unbox_mono_obj_root (root); } finally { root.release(); } }, _unbox_delegate_root: function (root) { - var obj = this.extract_js_obj_root (root); + var obj = BINDING.extract_js_obj_root (root); obj.__mono_delegate_alive__ = true; // FIXME: Should we root the object as long as this function has not been GCd? return function () { @@ -373,10 +373,10 @@ var BindingSupportLib = { }, _unbox_task_root: function (root) { - if (!this._are_promises_supported) + if (!BINDING._are_promises_supported) throw new Error ("Promises are not supported thus 'System.Threading.Tasks.Task' can not work in this context."); - var obj = this.extract_js_obj_root (root); + var obj = BINDING.extract_js_obj_root (root); var cont_obj = null; var promise = new Promise (function (resolve, reject) { cont_obj = { @@ -386,7 +386,7 @@ var BindingSupportLib = { }); // FIXME: Lifetime management/pinning? - this.call_method (this.setup_js_cont, null, "mo", [ root.value, cont_obj ]); + BINDING.call_method (BINDING.setup_js_cont, null, "mo", [ root.value, cont_obj ]); obj.__mono_js_cont__ = cont_obj.__mono_gchandle__; cont_obj.__mono_js_task__ = obj.__mono_gchandle__; return promise; @@ -394,14 +394,14 @@ var BindingSupportLib = { _unbox_safehandle_root: function (root) { var addRef = true; - var js_handle = this.call_method(this.safehandle_get_handle, null, "mi", [ root.value, addRef ]); + var js_handle = BINDING.call_method(BINDING.safehandle_get_handle, null, "mi", [ root.value, addRef ]); var requiredObject = BINDING.mono_wasm_require_handle (js_handle); if (addRef) { - if (typeof this.mono_wasm_owned_objects_LMF === "undefined") - this.mono_wasm_owned_objects_LMF = []; + if (typeof BINDING.mono_wasm_owned_objects_LMF === "undefined") + BINDING.mono_wasm_owned_objects_LMF = []; - this.mono_wasm_owned_objects_LMF.push(js_handle); + BINDING.mono_wasm_owned_objects_LMF.push(js_handle); } return requiredObject; }, @@ -418,15 +418,15 @@ var BindingSupportLib = { throw new Error ("int64 not available"); case 3: // string case 29: // interned string - return this.conv_string (root.value); + return BINDING.conv_string (root.value); case 4: //vts throw new Error ("no idea on how to unbox value types"); case 5: // delegate - return this._unbox_delegate_root (root); + return BINDING._unbox_delegate_root (root); case 6: // Task - return this._unbox_task_root (root); + return BINDING._unbox_task_root (root); case 7: // ref type - return this.extract_js_obj_root (root); + return BINDING.extract_js_obj_root (root); case 10: // arrays case 11: case 12: @@ -438,16 +438,16 @@ var BindingSupportLib = { case 18: throw new Error ("Marshalling of primitive arrays are not supported. Use the corresponding TypedArray instead."); case 20: // clr .NET DateTime - var dateValue = this.call_method(this.get_date_value, null, "m", [ root.value ]); + var dateValue = BINDING.call_method(BINDING.get_date_value, null, "m", [ root.value ]); return new Date(dateValue); case 21: // clr .NET DateTimeOffset - var dateoffsetValue = this._object_to_string (root.value); + var dateoffsetValue = BINDING._object_to_string (root.value); return dateoffsetValue; case 22: // clr .NET Uri - var uriValue = this._object_to_string (root.value); + var uriValue = BINDING._object_to_string (root.value); return uriValue; case 23: // clr .NET SafeHandle - return this._unbox_safehandle_root (root); + return BINDING._unbox_safehandle_root (root); case 30: return undefined; default: @@ -459,41 +459,41 @@ var BindingSupportLib = { if (root.value === 0) return undefined; - var type = this.mono_wasm_try_unbox_primitive_and_get_type (root.value, this._unbox_buffer); + var type = BINDING.mono_wasm_try_unbox_primitive_and_get_type (root.value, BINDING._unbox_buffer); switch (type) { case 1: // int - return Module.HEAP32[this._unbox_buffer / 4]; + return Module.HEAP32[BINDING._unbox_buffer / 4]; case 25: // uint32 - return Module.HEAPU32[this._unbox_buffer / 4]; + return Module.HEAPU32[BINDING._unbox_buffer / 4]; case 24: // float32 - return Module.HEAPF32[this._unbox_buffer / 4]; + return Module.HEAPF32[BINDING._unbox_buffer / 4]; case 2: // float64 - return Module.HEAPF64[this._unbox_buffer / 8]; + return Module.HEAPF64[BINDING._unbox_buffer / 8]; case 8: // boolean - return (Module.HEAP32[this._unbox_buffer / 4]) !== 0; + return (Module.HEAP32[BINDING._unbox_buffer / 4]) !== 0; case 28: // char - return String.fromCharCode(Module.HEAP32[this._unbox_buffer / 4]); + return String.fromCharCode(Module.HEAP32[BINDING._unbox_buffer / 4]); default: - return this._unbox_mono_obj_root_with_known_nonprimitive_type (root, type); + return BINDING._unbox_mono_obj_root_with_known_nonprimitive_type (root, type); } }, create_task_completion_source: function () { - return this.call_method (this.create_tcs, null, "i", [ -1 ]); + return BINDING.call_method (BINDING.create_tcs, null, "i", [ -1 ]); }, set_task_result: function (tcs, result) { tcs.is_mono_tcs_result_set = true; - this.call_method (this.set_tcs_result, null, "oo", [ tcs, result ]); + BINDING.call_method (BINDING.set_tcs_result, null, "oo", [ tcs, result ]); if (tcs.is_mono_tcs_task_bound) - this.free_task_completion_source(tcs); + BINDING.free_task_completion_source(tcs); }, set_task_failure: function (tcs, reason) { tcs.is_mono_tcs_result_set = true; - this.call_method (this.set_tcs_failure, null, "os", [ tcs, reason.toString () ]); + BINDING.call_method (BINDING.set_tcs_failure, null, "os", [ tcs, reason.toString () ]); if (tcs.is_mono_tcs_task_bound) - this.free_task_completion_source(tcs); + BINDING.free_task_completion_source(tcs); }, // https://github.com/Planeshifter/emscripten-examples/blob/master/01_PassingArrays/sum_post.js @@ -506,27 +506,27 @@ var BindingSupportLib = { }, _box_js_int: function (js_obj) { - Module.HEAP32[this._box_buffer / 4] = js_obj; - return this.mono_wasm_box_primitive (this._class_int32, this._box_buffer, 4); + Module.HEAP32[BINDING._box_buffer / 4] = js_obj; + return BINDING.mono_wasm_box_primitive (BINDING._class_int32, BINDING._box_buffer, 4); }, _box_js_uint: function (js_obj) { - Module.HEAPU32[this._box_buffer / 4] = js_obj; - return this.mono_wasm_box_primitive (this._class_uint32, this._box_buffer, 4); + Module.HEAPU32[BINDING._box_buffer / 4] = js_obj; + return BINDING.mono_wasm_box_primitive (BINDING._class_uint32, BINDING._box_buffer, 4); }, _box_js_double: function (js_obj) { - Module.HEAPF64[this._box_buffer / 8] = js_obj; - return this.mono_wasm_box_primitive (this._class_double, this._box_buffer, 8); + Module.HEAPF64[BINDING._box_buffer / 8] = js_obj; + return BINDING.mono_wasm_box_primitive (BINDING._class_double, BINDING._box_buffer, 8); }, _box_js_bool: function (js_obj) { - Module.HEAP32[this._box_buffer / 4] = js_obj ? 1 : 0; - return this.mono_wasm_box_primitive (this._class_boolean, this._box_buffer, 4); + Module.HEAP32[BINDING._box_buffer / 4] = js_obj ? 1 : 0; + return BINDING.mono_wasm_box_primitive (BINDING._class_boolean, BINDING._box_buffer, 4); }, js_to_mono_obj: function (js_obj) { - this.bindings_lazy_init (); + BINDING.bindings_lazy_init (); // determines if the javascript object is a Promise or Promise like which can happen // when using an external Promise library. The javascript object should be marshalled @@ -548,44 +548,44 @@ var BindingSupportLib = { case typeof js_obj === "number": { let result; if ((js_obj | 0) === js_obj) - result = this._box_js_int (js_obj); + result = BINDING._box_js_int (js_obj); else if ((js_obj >>> 0) === js_obj) - result = this._box_js_uint (js_obj); + result = BINDING._box_js_uint (js_obj); else - result = this._box_js_double (js_obj); + result = BINDING._box_js_double (js_obj); if (!result) throw new Error (`Boxing failed for ${js_obj}`); return result; } case typeof js_obj === "string": - return this.js_string_to_mono_string (js_obj); + return BINDING.js_string_to_mono_string (js_obj); case typeof js_obj === "symbol": - return this.js_string_to_mono_string_interned (js_obj); + return BINDING.js_string_to_mono_string_interned (js_obj); case typeof js_obj === "boolean": - return this._box_js_bool (js_obj); + return BINDING._box_js_bool (js_obj); case isThenable() === true: - var the_task = this.try_extract_mono_obj (js_obj); + var the_task = BINDING.try_extract_mono_obj (js_obj); if (the_task) return the_task; // FIXME: We need to root tcs for an appropriate timespan, at least until the Task // is resolved - var tcs = this.create_task_completion_source (); + var tcs = BINDING.create_task_completion_source (); js_obj.then (function (result) { BINDING.set_task_result (tcs, result); }, function (reason) { BINDING.set_task_failure (tcs, reason); }) - return this.get_task_and_bind (tcs, js_obj); + return BINDING.get_task_and_bind (tcs, js_obj); case js_obj.constructor.name === "Date": // We may need to take into account the TimeZone Offset - return this.call_method(this.create_date_time, null, "d!", [ js_obj.getTime() ]); + return BINDING.call_method(BINDING.create_date_time, null, "d!", [ js_obj.getTime() ]); default: - return this.extract_mono_obj (js_obj); + return BINDING.extract_mono_obj (js_obj); } }, js_to_mono_uri: function (js_obj) { - this.bindings_lazy_init (); + BINDING.bindings_lazy_init (); switch (true) { case js_obj === null: @@ -593,9 +593,9 @@ var BindingSupportLib = { return 0; case typeof js_obj === "symbol": case typeof js_obj === "string": - return this.call_method(this.create_uri, null, "s!", [ js_obj ]) + return BINDING.call_method(BINDING.create_uri, null, "s!", [ js_obj ]) default: - return this.extract_mono_obj (js_obj); + return BINDING.extract_mono_obj (js_obj); } }, has_backing_array_buffer: function (js_obj) { @@ -614,11 +614,11 @@ var BindingSupportLib = { // you need to use a view. A view provides a context — that is, a data type, starting offset, // and number of elements — that turns the data into an actual typed array. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays - if (!!(this.has_backing_array_buffer(js_obj) && js_obj.BYTES_PER_ELEMENT)) + if (!!(BINDING.has_backing_array_buffer(js_obj) && js_obj.BYTES_PER_ELEMENT)) { var arrayType = js_obj[Symbol.for("wasm type")]; - var heapBytes = this.js_typedarray_to_heap(js_obj); - var bufferArray = this.mono_typed_array_new(heapBytes.byteOffset, js_obj.length, js_obj.BYTES_PER_ELEMENT, arrayType); + var heapBytes = BINDING.js_typedarray_to_heap(js_obj); + var bufferArray = BINDING.mono_typed_array_new(heapBytes.byteOffset, js_obj.length, js_obj.BYTES_PER_ELEMENT, arrayType); Module._free(heapBytes.byteOffset); return bufferArray; } @@ -640,7 +640,7 @@ var BindingSupportLib = { // you need to use a view. A view provides a context — that is, a data type, starting offset, // and number of elements — that turns the data into an actual typed array. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays - if (!!(this.has_backing_array_buffer(typed_array) && typed_array.BYTES_PER_ELEMENT)) + if (!!(BINDING.has_backing_array_buffer(typed_array) && typed_array.BYTES_PER_ELEMENT)) { // Some sanity checks of what is being asked of us // lets play it safe and throw an error here instead of assuming to much. @@ -683,7 +683,7 @@ var BindingSupportLib = { // you need to use a view. A view provides a context — that is, a data type, starting offset, // and number of elements — that turns the data into an actual typed array. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays - if (!!(this.has_backing_array_buffer(typed_array) && typed_array.BYTES_PER_ELEMENT)) + if (!!(BINDING.has_backing_array_buffer(typed_array) && typed_array.BYTES_PER_ELEMENT)) { // Some sanity checks of what is being asked of us // lets play it safe and throw an error here instead of assuming to much. @@ -750,11 +750,11 @@ var BindingSupportLib = { break; } - this.typedarray_copy_from(newTypedArray, pinned_array, begin, end, bytes_per_element); + BINDING.typedarray_copy_from(newTypedArray, pinned_array, begin, end, bytes_per_element); return newTypedArray; }, js_to_mono_enum: function (js_obj, method, parmIdx) { - this.bindings_lazy_init (); + BINDING.bindings_lazy_init (); if (typeof (js_obj) !== "number") throw new Error (`Expected numeric value for enum argument, got '${js_obj}'`); @@ -763,21 +763,21 @@ var BindingSupportLib = { }, wasm_binding_obj_new: function (js_obj_id, ownsHandle, type) { - return this._bind_js_obj (js_obj_id, ownsHandle, type); + return BINDING._bind_js_obj (js_obj_id, ownsHandle, type); }, wasm_bind_existing: function (mono_obj, js_id) { - return this._bind_existing_obj (mono_obj, js_id); + return BINDING._bind_existing_obj (mono_obj, js_id); }, wasm_bind_core_clr_obj: function (js_id, gc_handle) { - return this._bind_core_clr_obj (js_id, gc_handle); + return BINDING._bind_core_clr_obj (js_id, gc_handle); }, wasm_get_js_id: function (mono_obj) { - return this._get_js_id (mono_obj); + return BINDING._get_js_id (mono_obj); }, // when should_add_in_flight === true, the JSObject would be temporarily hold by Normal GCHandle, so that it would not get collected during transition to the managed stack. @@ -788,46 +788,46 @@ var BindingSupportLib = { return 0; } - return this._get_raw_mono_obj (gchandle, should_add_in_flight ? 1 : 0); + return BINDING._get_raw_mono_obj (gchandle, should_add_in_flight ? 1 : 0); }, try_extract_mono_obj:function (js_obj) { if (js_obj === null || typeof js_obj === "undefined" || typeof js_obj.__mono_gchandle__ === "undefined") return 0; - return this.wasm_get_raw_obj (js_obj.__mono_gchandle__, true); + return BINDING.wasm_get_raw_obj (js_obj.__mono_gchandle__, true); }, mono_method_get_call_signature: function(method, mono_obj): number { let instanceRoot = MONO.mono_wasm_new_root (mono_obj); try { - this.bindings_lazy_init (); + BINDING.bindings_lazy_init (); - return this.call_method (this.get_call_sig, null, "im", [ method, instanceRoot.value ]); + return BINDING.call_method (BINDING.get_call_sig, null, "im", [ method, instanceRoot.value ]); } finally { instanceRoot.release(); } }, get_task_and_bind: function (tcs, js_obj) { - var gc_handle = this.mono_wasm_free_list.length ? this.mono_wasm_free_list.pop() : this.mono_wasm_ref_counter++; - var task_gchandle = this.call_method (this.tcs_get_task_and_bind, null, "oi", [ tcs, gc_handle + 1 ]); + var gc_handle = BINDING.mono_wasm_free_list.length ? BINDING.mono_wasm_free_list.pop() : BINDING.mono_wasm_ref_counter++; + var task_gchandle = BINDING.call_method (BINDING.tcs_get_task_and_bind, null, "oi", [ tcs, gc_handle + 1 ]); js_obj.__mono_gchandle__ = task_gchandle; - this.mono_wasm_object_registry[gc_handle] = js_obj; - this.free_task_completion_source(tcs); + BINDING.mono_wasm_object_registry[gc_handle] = js_obj; + BINDING.free_task_completion_source(tcs); tcs.is_mono_tcs_task_bound = true; js_obj.__mono_bound_tcs__ = tcs.__mono_gchandle__; tcs.__mono_bound_task__ = js_obj.__mono_gchandle__; - return this.wasm_get_raw_obj (js_obj.__mono_gchandle__, true); + return BINDING.wasm_get_raw_obj (js_obj.__mono_gchandle__, true); }, free_task_completion_source: function (tcs) { if (tcs.is_mono_tcs_result_set) { - this._unbind_raw_obj_and_free (tcs.__mono_gchandle__); + BINDING._unbind_raw_obj_and_free (tcs.__mono_gchandle__); } if (tcs.__mono_bound_task__) { - this._unbind_raw_obj_and_free (tcs.__mono_bound_task__); + BINDING._unbind_raw_obj_and_free (tcs.__mono_bound_task__); } }, @@ -838,7 +838,7 @@ var BindingSupportLib = { var result = null; var gc_handle = js_obj.__mono_gchandle__; if (gc_handle) { - result = this.wasm_get_raw_obj (gc_handle, true); + result = BINDING.wasm_get_raw_obj (gc_handle, true); // It's possible the managed object corresponding to this JS object was collected, // in which case we need to make a new one. @@ -849,8 +849,8 @@ var BindingSupportLib = { } if (!result) { - var { gc_handle: new_gc_handle, should_add_in_flight } = this.mono_wasm_register_obj(js_obj); - result = this.wasm_get_raw_obj (new_gc_handle, should_add_in_flight); + var { gc_handle: new_gc_handle, should_add_in_flight } = BINDING.mono_wasm_register_obj(js_obj); + result = BINDING.wasm_get_raw_obj (new_gc_handle, should_add_in_flight); } return result; @@ -861,7 +861,7 @@ var BindingSupportLib = { return null; var root = MONO.mono_wasm_new_root (mono_obj); try { - return this.extract_js_obj_root (root); + return BINDING.extract_js_obj_root (root); } finally { root.release(); } @@ -871,21 +871,21 @@ var BindingSupportLib = { if (root.value === 0) return null; - var js_id = this.wasm_get_js_id (root.value); + var js_id = BINDING.wasm_get_js_id (root.value); if (js_id > 0) - return this.mono_wasm_require_handle(js_id); + return BINDING.mono_wasm_require_handle(js_id); - var gcHandle = this.mono_wasm_free_list.length ? this.mono_wasm_free_list.pop() : this.mono_wasm_ref_counter++; + var gcHandle = BINDING.mono_wasm_free_list.length ? BINDING.mono_wasm_free_list.pop() : BINDING.mono_wasm_ref_counter++; var js_obj = { - __mono_gchandle__: this.wasm_bind_existing(root.value, gcHandle + 1), + __mono_gchandle__: BINDING.wasm_bind_existing(root.value, gcHandle + 1), is_mono_bridged_obj: true }; - this.mono_wasm_object_registry[gcHandle] = js_obj; + BINDING.mono_wasm_object_registry[gcHandle] = js_obj; return js_obj; }, - _create_named_function: function (name, argumentNames, body, closure) { + _create_named_function: function (name, argumentNames, body, closure): any { var result = null, keys = null, closureArgumentList = null, closureArgumentNames = null; if (closure) { @@ -895,13 +895,13 @@ var BindingSupportLib = { closureArgumentList[i] = closure[closureArgumentNames[i]]; } - var constructor = this._create_rebindable_named_function (name, argumentNames, body, closureArgumentNames); + var constructor = BINDING._create_rebindable_named_function (name, argumentNames, body, closureArgumentNames); result = constructor.apply (null, closureArgumentList); return result; }, - _create_rebindable_named_function: function (name, argumentNames, body, closureArgNames) { + _create_rebindable_named_function: function (name, argumentNames, body, closureArgNames): any { var strictPrefix = "\"use strict\";\r\n"; var uriPrefix = "", escapedFunctionIdentifier = ""; @@ -940,27 +940,27 @@ var BindingSupportLib = { _create_primitive_converters: function () { var result = new Map (); result.set ('m', { steps: [{ }], size: 0}); - result.set ('s', { steps: [{ convert: this.js_string_to_mono_string.bind (this) }], size: 0, needs_root: true }); - result.set ('S', { steps: [{ convert: this.js_string_to_mono_string_interned.bind (this) }], size: 0, needs_root: true }); - result.set ('o', { steps: [{ convert: this.js_to_mono_obj.bind (this) }], size: 0, needs_root: true }); - result.set ('u', { steps: [{ convert: this.js_to_mono_uri.bind (this) }], size: 0, needs_root: true }); + result.set ('s', { steps: [{ convert: BINDING.js_string_to_mono_string.bind (this) }], size: 0, needs_root: true }); + result.set ('S', { steps: [{ convert: BINDING.js_string_to_mono_string_interned.bind (this) }], size: 0, needs_root: true }); + result.set ('o', { steps: [{ convert: BINDING.js_to_mono_obj.bind (this) }], size: 0, needs_root: true }); + result.set ('u', { steps: [{ convert: BINDING.js_to_mono_uri.bind (this) }], size: 0, needs_root: true }); - // result.set ('k', { steps: [{ convert: this.js_to_mono_enum.bind (this), indirect: 'i64'}], size: 8}); - result.set ('j', { steps: [{ convert: this.js_to_mono_enum.bind (this), indirect: 'i32'}], size: 8}); + // result.set ('k', { steps: [{ convert: BINDING.js_to_mono_enum.bind (this), indirect: 'i64'}], size: 8}); + result.set ('j', { steps: [{ convert: BINDING.js_to_mono_enum.bind (this), indirect: 'i32'}], size: 8}); result.set ('i', { steps: [{ indirect: 'i32'}], size: 8}); result.set ('l', { steps: [{ indirect: 'i64'}], size: 8}); result.set ('f', { steps: [{ indirect: 'float'}], size: 8}); result.set ('d', { steps: [{ indirect: 'double'}], size: 8}); - this._primitive_converters = result; + BINDING._primitive_converters = result; return result; }, _create_converter_for_marshal_string: function (args_marshal) { - var primitiveConverters = this._primitive_converters; + var primitiveConverters = BINDING._primitive_converters; if (!primitiveConverters) - primitiveConverters = this._create_primitive_converters (); + primitiveConverters = BINDING._create_primitive_converters (); var steps = []; var size = 0; @@ -1007,20 +1007,20 @@ var BindingSupportLib = { }, _get_converter_for_marshal_string: function (args_marshal) { - if (!this._signature_converters) - this._signature_converters = new Map(); + if (!BINDING._signature_converters) + BINDING._signature_converters = new Map(); - var converter = this._signature_converters.get (args_marshal); + var converter = BINDING._signature_converters.get (args_marshal); if (!converter) { - converter = this._create_converter_for_marshal_string (args_marshal); - this._signature_converters.set (args_marshal, converter); + converter = BINDING._create_converter_for_marshal_string (args_marshal); + BINDING._signature_converters.set (args_marshal, converter); } return converter; }, _compile_converter_for_marshal_string: function (args_marshal) { - var converter = this._get_converter_for_marshal_string (args_marshal); + var converter = BINDING._get_converter_for_marshal_string (args_marshal); if (typeof (converter.args_marshal) !== "string") throw new Error ("Corrupt converter for '" + args_marshal + "'"); @@ -1035,7 +1035,7 @@ var BindingSupportLib = { // worst-case allocation size instead of allocating dynamically, plus padding var bufferSizeBytes = converter.size + (args_marshal.length * 4) + 16; - var rootBufferSize = args_marshal.length; + // ensure the indirect values are 8-byte aligned so that aligned loads and stores will work var indirectBaseOffset = ((((args_marshal.length * 4) + 7) / 8) | 0) * 8; @@ -1106,7 +1106,7 @@ var BindingSupportLib = { var bodyJs = body.join ("\r\n"), compiledFunction = null, compiledVariadicFunction = null; try { - compiledFunction = this._create_named_function("converter_" + converterName, argumentNames, bodyJs, closure); + compiledFunction = BINDING._create_named_function("converter_" + converterName, argumentNames, bodyJs, closure); converter.compiled_function = compiledFunction; } catch (exc) { converter.compiled_function = null; @@ -1138,7 +1138,7 @@ var BindingSupportLib = { bodyJs = body.join ("\r\n"); try { - compiledVariadicFunction = this._create_named_function("variadic_converter_" + converterName, argumentNames, bodyJs, closure); + compiledVariadicFunction = BINDING._create_named_function("variadic_converter_" + converterName, argumentNames, bodyJs, closure); converter.compiled_variadic_function = compiledVariadicFunction; } catch (exc) { converter.compiled_variadic_function = null; @@ -1224,7 +1224,7 @@ var BindingSupportLib = { if (exception === 0) return null; - var msg = this.conv_string (result); + var msg = BINDING.conv_string (result); var err = new Error (msg); //the convention is that invoke_method ToString () any outgoing exception // console.warn ("error", msg, "at location", err.stack); return err; @@ -1249,7 +1249,7 @@ var BindingSupportLib = { if (argc < converter.result_unmarshaled_if_argc) throw new Error(["Expected >= ", converter.result_unmarshaled_if_argc, "argument(s) but got", argc, "for signature " + converter.args_marshal].join(" ")); - this._maybe_produce_signature_warning (converter); + BINDING._maybe_produce_signature_warning (converter); return false; } else { if (argc < converter.steps.length) @@ -1274,7 +1274,7 @@ var BindingSupportLib = { to suppress marshaling of the return value, place '!' at the end of args_marshal, i.e. 'ii!' instead of 'ii' */ call_method: function (method, this_arg, args_marshal, args): number { - this.bindings_lazy_init (); + BINDING.bindings_lazy_init (); // HACK: Sometimes callers pass null or undefined, coerce it to 0 since that's what wasm expects this_arg = this_arg | 0; @@ -1285,55 +1285,55 @@ var BindingSupportLib = { if (!method) throw new Error ("no method specified"); - var needs_converter = this._verify_args_for_method_call (args_marshal, args); + var needs_converter = BINDING._verify_args_for_method_call (args_marshal, args); var buffer = 0, converter = null, argsRootBuffer = null; var is_result_marshaled = true; // check if the method signature needs argument mashalling if (needs_converter) { - converter = this._compile_converter_for_marshal_string (args_marshal); + converter = BINDING._compile_converter_for_marshal_string (args_marshal); - is_result_marshaled = this._decide_if_result_is_marshaled (converter, args.length); + is_result_marshaled = BINDING._decide_if_result_is_marshaled (converter, args.length); - argsRootBuffer = this._get_args_root_buffer_for_method_call (converter); + argsRootBuffer = BINDING._get_args_root_buffer_for_method_call (converter); - var scratchBuffer = this._get_buffer_for_method_call (converter); + var scratchBuffer = BINDING._get_buffer_for_method_call (converter); buffer = converter.compiled_variadic_function (scratchBuffer, argsRootBuffer, method, args); } - return this._call_method_with_converted_args (method, this_arg, converter, buffer, is_result_marshaled, argsRootBuffer); + return BINDING._call_method_with_converted_args (method, this_arg, converter, buffer, is_result_marshaled, argsRootBuffer); }, _handle_exception_for_call: function ( converter, buffer, resultRoot, exceptionRoot, argsRootBuffer ) { - var exc = this._convert_exception_for_method_call (resultRoot.value, exceptionRoot.value); + var exc = BINDING._convert_exception_for_method_call (resultRoot.value, exceptionRoot.value); if (!exc) return; - this._teardown_after_call (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer); + BINDING._teardown_after_call (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer); throw exc; }, _handle_exception_and_produce_result_for_call: function ( converter, buffer, resultRoot, exceptionRoot, argsRootBuffer, is_result_marshaled ): number { - this._handle_exception_for_call (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer); + BINDING._handle_exception_for_call (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer); let result = resultRoot.value; if (is_result_marshaled) - result = this._unbox_mono_obj_root (resultRoot); + result = BINDING._unbox_mono_obj_root (resultRoot); - this._teardown_after_call (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer); + BINDING._teardown_after_call (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer); return result; }, _teardown_after_call: function (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer) { - this._release_args_root_buffer_from_method_call (converter, argsRootBuffer); - this._release_buffer_from_method_call (converter, buffer | 0); + BINDING._release_args_root_buffer_from_method_call (converter, argsRootBuffer); + BINDING._release_buffer_from_method_call (converter, buffer | 0); if (resultRoot) resultRoot.release (); @@ -1342,10 +1342,10 @@ var BindingSupportLib = { }, _get_method_description: function (method) { - if (!this._method_descriptions) - this._method_descriptions = new Map(); + if (!BINDING._method_descriptions) + BINDING._method_descriptions = new Map(); - var result = this._method_descriptions.get (method); + var result = BINDING._method_descriptions.get (method); if (!result) result = "method#" + method; return result; @@ -1353,18 +1353,18 @@ var BindingSupportLib = { _call_method_with_converted_args: function (method, this_arg, converter, buffer, is_result_marshaled, argsRootBuffer): number { var resultRoot = MONO.mono_wasm_new_root (), exceptionRoot = MONO.mono_wasm_new_root (); - resultRoot.value = this.invoke_method (method, this_arg, buffer, exceptionRoot.get_address ()); - return this._handle_exception_and_produce_result_for_call (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer, is_result_marshaled); + resultRoot.value = BINDING.invoke_method (method, this_arg, buffer, exceptionRoot.get_address ()); + return BINDING._handle_exception_and_produce_result_for_call (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer, is_result_marshaled); }, bind_method: function (method, this_arg, args_marshal, friendly_name) { - this.bindings_lazy_init (); + BINDING.bindings_lazy_init (); this_arg = this_arg | 0; var converter = null; if (typeof (args_marshal) === "string") - converter = this._compile_converter_for_marshal_string (args_marshal); + converter = BINDING._compile_converter_for_marshal_string (args_marshal); var closure = { library_mono: MONO, @@ -1476,11 +1476,11 @@ var BindingSupportLib = { if (this_arg) displayName += "_with_this_" + this_arg; - return this._create_named_function(displayName, argumentNames, bodyJs, closure); + return BINDING._create_named_function(displayName, argumentNames, bodyJs, closure); }, invoke_delegate: function (delegate_obj, js_args) { - this.bindings_lazy_init (); + BINDING.bindings_lazy_init (); // Check to make sure the delegate is still alive on the CLR side of things. if (typeof delegate_obj.__mono_delegate_alive__ !== "undefined") { @@ -1494,24 +1494,24 @@ var BindingSupportLib = { } } - var delegateRoot = MONO.mono_wasm_new_root (this.extract_mono_obj (delegate_obj)); + var delegateRoot = MONO.mono_wasm_new_root (BINDING.extract_mono_obj (delegate_obj)); try { if (typeof delegate_obj.__mono_delegate_invoke__ === "undefined") - delegate_obj.__mono_delegate_invoke__ = this.mono_wasm_get_delegate_invoke(delegateRoot.value); + delegate_obj.__mono_delegate_invoke__ = BINDING.mono_wasm_get_delegate_invoke(delegateRoot.value); if (!delegate_obj.__mono_delegate_invoke__) throw new Error("System.Delegate Invoke method can not be resolved."); if (typeof delegate_obj.__mono_delegate_invoke_sig__ === "undefined") delegate_obj.__mono_delegate_invoke_sig__ = Module.mono_method_get_call_signature (delegate_obj.__mono_delegate_invoke__, delegateRoot.value); - return this.call_method (delegate_obj.__mono_delegate_invoke__, delegateRoot.value, delegate_obj.__mono_delegate_invoke_sig__, js_args); + return BINDING.call_method (delegate_obj.__mono_delegate_invoke__, delegateRoot.value, delegate_obj.__mono_delegate_invoke_sig__, js_args); } finally { delegateRoot.release(); } }, resolve_method_fqn: function (fqn) { - this.bindings_lazy_init (); + BINDING.bindings_lazy_init (); var assembly = fqn.substring(fqn.indexOf ("[") + 1, fqn.indexOf ("]")).trim(); fqn = fqn.substring (fqn.indexOf ("]") + 1).trim(); @@ -1534,35 +1534,35 @@ var BindingSupportLib = { if (!methodname.trim()) throw new Error("No method name specified"); - var asm = this.assembly_load (assembly); + var asm = BINDING.assembly_load (assembly); if (!asm) throw new Error ("Could not find assembly: " + assembly); - var klass = this.find_class(asm, namespace, classname); + var klass = BINDING.find_class(asm, namespace, classname); if (!klass) throw new Error ("Could not find class: " + namespace + ":" + classname + " in assembly " + assembly); - var method = this.find_method (klass, methodname, -1); + var method = BINDING.find_method (klass, methodname, -1); if (!method) throw new Error ("Could not find method: " + methodname); return method; }, call_static_method: function (fqn: string, args: any[] | null, signature: string | null) { - this.bindings_lazy_init (); + BINDING.bindings_lazy_init (); - var method = this.resolve_method_fqn (fqn); + var method = BINDING.resolve_method_fqn (fqn); if (typeof signature === "undefined") signature = Module.mono_method_get_call_signature (method); - return this.call_method (method, null, signature, args); + return BINDING.call_method (method, null, signature, args); }, bind_static_method: function (fqn, signature) { - this.bindings_lazy_init (); + BINDING.bindings_lazy_init (); - var method = this.resolve_method_fqn (fqn); + var method = BINDING.resolve_method_fqn (fqn); if (typeof signature === "undefined") signature = Module.mono_method_get_call_signature (method); @@ -1570,23 +1570,22 @@ var BindingSupportLib = { return BINDING.bind_method (method, null, signature, fqn); }, - bind_assembly_entry_point: function (assembly, signature) { - this.bindings_lazy_init (); + bind_assembly_entry_point: function (assembly, signature): (...args: any) => Promise { + BINDING.bindings_lazy_init (); - var asm = this.assembly_load (assembly); + var asm = BINDING.assembly_load (assembly); if (!asm) throw new Error ("Could not find assembly: " + assembly); - var method = this.assembly_get_entry_point(asm); + var method = BINDING.assembly_get_entry_point(asm); if (!method) throw new Error ("Could not find entry point for assembly: " + assembly); if (typeof signature === "undefined") signature = Module.mono_method_get_call_signature (method); - return function() { + return function(...args: any) { try { - var args = [...arguments]; if (args.length > 0 && Array.isArray (args[0])) args[0] = BINDING.js_array_to_mono_array (args[0], true); @@ -1598,7 +1597,7 @@ var BindingSupportLib = { }; }, call_assembly_entry_point: function (assembly, args, signature) { - return this.bind_assembly_entry_point (assembly, signature) (...args) + return BINDING.bind_assembly_entry_point (assembly, signature) (...args); }, // Object wrapping helper functions to handle reference handles that will // be used in managed code. @@ -1610,14 +1609,14 @@ var BindingSupportLib = { gc_handle = js_obj.__mono_gchandle__; if (typeof gc_handle === "undefined") { - var handle = this.mono_wasm_free_list.length ? - this.mono_wasm_free_list.pop() : this.mono_wasm_ref_counter++; + var handle = BINDING.mono_wasm_free_list.length ? + BINDING.mono_wasm_free_list.pop() : BINDING.mono_wasm_ref_counter++; js_obj.__mono_jshandle__ = handle; // Obtain the JS -> C# type mapping. var wasm_type = js_obj[Symbol.for("wasm type")]; js_obj.__owns_handle__ = true; - gc_handle = js_obj.__mono_gchandle__ = this.wasm_binding_obj_new(handle + 1, js_obj.__owns_handle__, typeof wasm_type === "undefined" ? -1 : wasm_type); - this.mono_wasm_object_registry[handle] = js_obj; + gc_handle = js_obj.__mono_gchandle__ = BINDING.wasm_binding_obj_new(handle + 1, js_obj.__owns_handle__, typeof wasm_type === "undefined" ? -1 : wasm_type); + BINDING.mono_wasm_object_registry[handle] = js_obj; // as this instance was just created, it was already created with Inflight strong GCHandle, so we do not have to do it again return { gc_handle, should_add_in_flight: false }; } @@ -1627,11 +1626,11 @@ var BindingSupportLib = { }, mono_wasm_require_handle: function(handle) { if (handle > 0) - return this.mono_wasm_object_registry[handle - 1]; + return BINDING.mono_wasm_object_registry[handle - 1]; return null; }, mono_wasm_unregister_obj: function(js_id) { - var obj = this.mono_wasm_object_registry[js_id - 1]; + var obj = BINDING.mono_wasm_object_registry[js_id - 1]; if (typeof obj !== "undefined" && obj !== null) { // if this is the global object then do not // unregister it. @@ -1650,17 +1649,17 @@ var BindingSupportLib = { if (typeof obj.__mono_delegate_alive__ !== "undefined") obj.__mono_delegate_alive__ = false; - this.mono_wasm_object_registry[js_id - 1] = undefined; - this.mono_wasm_free_list.push(js_id - 1); + BINDING.mono_wasm_object_registry[js_id - 1] = undefined; + BINDING.mono_wasm_free_list.push(js_id - 1); } } return obj; }, mono_wasm_free_handle: function(handle) { - this.mono_wasm_unregister_obj(handle); + BINDING.mono_wasm_unregister_obj(handle); }, mono_wasm_free_raw_object: function(js_id) { - var obj = this.mono_wasm_object_registry[js_id - 1]; + var obj = BINDING.mono_wasm_object_registry[js_id - 1]; if (typeof obj !== "undefined" && obj !== null) { // if this is the global object then do not // unregister it. @@ -1673,15 +1672,15 @@ var BindingSupportLib = { obj.__mono_gchandle__ = undefined; obj.__mono_jshandle__ = undefined; - this.mono_wasm_object_registry[js_id - 1] = undefined; - this.mono_wasm_free_list.push(js_id - 1); + BINDING.mono_wasm_object_registry[js_id - 1] = undefined; + BINDING.mono_wasm_free_list.push(js_id - 1); } } return obj; }, mono_wasm_parse_args_root : function (argsRoot) { - var js_args = this._mono_array_root_to_js_array(argsRoot); - this.mono_wasm_save_LMF(); + var js_args = BINDING._mono_array_root_to_js_array(argsRoot); + BINDING.mono_wasm_save_LMF(); return js_args; }, mono_wasm_save_LMF : function () { @@ -1690,7 +1689,7 @@ var BindingSupportLib = { BINDING.mono_wasm_owned_objects_LMF = undefined; }, mono_wasm_unwind_LMF : function () { - var __owned_objects__ = this.mono_wasm_owned_objects_frames.pop(); + var __owned_objects__ = BINDING.mono_wasm_owned_objects_frames.pop(); // Release all managed objects that are loaded into the LMF if (typeof __owned_objects__ !== "undefined") { @@ -1699,15 +1698,15 @@ var BindingSupportLib = { for (refidx = 0; refidx < __owned_objects__.length; refidx++) { var ownerRelease = __owned_objects__[refidx]; - this.call_method(this.safehandle_release_by_handle, null, "i", [ ownerRelease ]); + BINDING.call_method(BINDING.safehandle_release_by_handle, null, "i", [ ownerRelease ]); } } //console.log("restore LMF: " + BINDING.mono_wasm_owned_objects_frames.length) }, mono_wasm_convert_return_value: function (ret) { - this.mono_wasm_unwind_LMF(); - return this.js_to_mono_obj (ret); + BINDING.mono_wasm_unwind_LMF(); + return BINDING.js_to_mono_obj (ret); }, }, diff --git a/src/mono/wasm/runtime/library_mono.ts b/src/mono/wasm/runtime/library_mono.ts index a84bf228141a6..bd72a716f7c8a 100644 --- a/src/mono/wasm/runtime/library_mono.ts +++ b/src/mono/wasm/runtime/library_mono.ts @@ -21,15 +21,15 @@ var MonoSupportLib = { _id_table: {}, pump_message: function () { - if (!this.mono_background_exec) - this.mono_background_exec = Module.cwrap ("mono_background_exec", null); + if (!MONO.mono_background_exec) + MONO.mono_background_exec = Module.cwrap ("mono_background_exec", null); while (MONO.timeout_queue.length > 0) { --MONO.pump_count; MONO.timeout_queue.shift()(); } while (MONO.pump_count > 0) { --MONO.pump_count; - this.mono_background_exec (); + MONO.mono_background_exec (); } }, @@ -170,18 +170,15 @@ var MonoSupportLib = { if ((index >= this.__count) || (index < 0)) this._throw_index_out_of_range(); }, - /** @returns {NativePointer} */ - get_address: function (index) { + get_address: function (index: number): NativePointer { this._check_in_range (index); return this.__offset + (index * 4); }, - /** @returns {number} */ - get_address_32: function (index) { + get_address_32: function (index: number): number { this._check_in_range (index); return this.__offset32 + index; }, - /** @returns {ManagedPointer} */ - get: function (index) { + get: function (index: number): ManagedPointer { this._check_in_range (index); return Module.HEAP32[this.get_address_32 (index)]; }, @@ -219,16 +216,13 @@ var MonoSupportLib = { _scratch_root_free_instances: [], _mono_wasm_root_prototype: { - /** @returns {NativePointer} */ - get_address: function () { + get_address: function (): NativePointer { return this.__buffer.get_address (this.__index); }, - /** @returns {number} */ - get_address_32: function () { + get_address_32: function (): number { return this.__buffer.get_address_32 (this.__index); }, - /** @returns {ManagedPointer} */ - get: function () { + get: function (): ManagedPointer { var result = this.__buffer._unsafe_get (this.__index); return result; }, @@ -236,8 +230,7 @@ var MonoSupportLib = { this.__buffer._unsafe_set (this.__index, value); return value; }, - /** @returns {ManagedPointer} */ - valueOf: function () { + valueOf: function (): ManagedPointer { return this.get (); }, clear: function () { @@ -263,33 +256,33 @@ var MonoSupportLib = { if (index === undefined) return; - this._scratch_root_buffer.set (index, 0); - this._scratch_root_free_indices[this._scratch_root_free_indices_count] = index; - this._scratch_root_free_indices_count++; + MONO._scratch_root_buffer.set (index, 0); + MONO._scratch_root_free_indices[MONO._scratch_root_free_indices_count] = index; + MONO._scratch_root_free_indices_count++; }, _mono_wasm_claim_scratch_index: function () { - if (!this._scratch_root_buffer) { + if (!MONO._scratch_root_buffer) { const maxScratchRoots = 8192; - this._scratch_root_buffer = this.mono_wasm_new_root_buffer (maxScratchRoots, "js roots"); + MONO._scratch_root_buffer = MONO.mono_wasm_new_root_buffer (maxScratchRoots, "js roots"); - this._scratch_root_free_indices = new Int32Array (maxScratchRoots); - this._scratch_root_free_indices_count = maxScratchRoots; + MONO._scratch_root_free_indices = new Int32Array (maxScratchRoots); + MONO._scratch_root_free_indices_count = maxScratchRoots; for (var i = 0; i < maxScratchRoots; i++) - this._scratch_root_free_indices[i] = maxScratchRoots - i - 1; + MONO._scratch_root_free_indices[i] = maxScratchRoots - i - 1; - Object.defineProperty (this._mono_wasm_root_prototype, "value", { - get: this._mono_wasm_root_prototype.get, - set: this._mono_wasm_root_prototype.set, + Object.defineProperty (MONO._mono_wasm_root_prototype, "value", { + get: MONO._mono_wasm_root_prototype.get, + set: MONO._mono_wasm_root_prototype.set, configurable: false }); } - if (this._scratch_root_free_indices_count < 1) + if (MONO._scratch_root_free_indices_count < 1) throw new Error ("Out of scratch root space"); - var result = this._scratch_root_free_indices[this._scratch_root_free_indices_count - 1]; - this._scratch_root_free_indices_count--; + var result = MONO._scratch_root_free_indices[MONO._scratch_root_free_indices_count - 1]; + MONO._scratch_root_free_indices_count--; return result; }, @@ -309,10 +302,10 @@ var MonoSupportLib = { * @param {string} [msg] - a description of the root buffer (for debugging) * @returns {WasmRootBuffer} */ - mono_wasm_new_root_buffer: function (capacity, msg?) { - if (!this.mono_wasm_register_root || !this.mono_wasm_deregister_root) { - this.mono_wasm_register_root = Module.cwrap ("mono_wasm_register_root", "number", ["number", "number", "string"]); - this.mono_wasm_deregister_root = Module.cwrap ("mono_wasm_deregister_root", null, ["number"]); + mono_wasm_new_root_buffer: function (capacity: number, msg?: string): WasmRootBuffer { + if (!MONO.mono_wasm_register_root || !MONO.mono_wasm_deregister_root) { + MONO.mono_wasm_register_root = Module.cwrap ("mono_wasm_register_root", "number", ["number", "number", "string"]); + MONO.mono_wasm_deregister_root = Module.cwrap ("mono_wasm_deregister_root", null, ["number"]); } if (capacity <= 0) @@ -325,14 +318,14 @@ var MonoSupportLib = { if ((offset % 4) !== 0) throw new Error ("Malloc returned an unaligned offset"); - this._zero_region (offset, capacityBytes); + MONO._zero_region (offset, capacityBytes); - var result = Object.create (this._mono_wasm_root_buffer_prototype); + var result = Object.create (MONO._mono_wasm_root_buffer_prototype); result.__offset = offset; result.__offset32 = (offset / 4) | 0; result.__count = capacity; result.length = capacity; - result.__handle = this.mono_wasm_register_root (offset, capacityBytes, msg || 0); + result.__handle = MONO.mono_wasm_register_root (offset, capacityBytes, msg || 0); result.__ownsAllocation = true; return result; @@ -346,10 +339,10 @@ var MonoSupportLib = { * @param {string} [msg] - a description of the root buffer (for debugging) * @returns {WasmRootBuffer} */ - mono_wasm_new_root_buffer_from_pointer: function (offset, capacity, msg?) { - if (!this.mono_wasm_register_root || !this.mono_wasm_deregister_root) { - this.mono_wasm_register_root = Module.cwrap ("mono_wasm_register_root", "number", ["number", "number", "string"]); - this.mono_wasm_deregister_root = Module.cwrap ("mono_wasm_deregister_root", null, ["number"]); + mono_wasm_new_root_buffer_from_pointer: function (offset: NativePointer, capacity: number, msg?: string): WasmRootBuffer { + if (!MONO.mono_wasm_register_root || !MONO.mono_wasm_deregister_root) { + MONO.mono_wasm_register_root = Module.cwrap ("mono_wasm_register_root", "number", ["number", "number", "string"]); + MONO.mono_wasm_deregister_root = Module.cwrap ("mono_wasm_deregister_root", null, ["number"]); } if (capacity <= 0) @@ -361,14 +354,14 @@ var MonoSupportLib = { if ((offset % 4) !== 0) throw new Error ("Unaligned offset"); - this._zero_region (offset, capacityBytes); + MONO._zero_region (offset, capacityBytes); - var result = Object.create (this._mono_wasm_root_buffer_prototype); + var result = Object.create (MONO._mono_wasm_root_buffer_prototype); result.__offset = offset; result.__offset32 = (offset / 4) | 0; result.__count = capacity; result.length = capacity; - result.__handle = this.mono_wasm_register_root (offset, capacityBytes, msg || 0); + result.__handle = MONO.mono_wasm_register_root (offset, capacityBytes, msg || 0); result.__ownsAllocation = false; return result; @@ -383,16 +376,16 @@ var MonoSupportLib = { * @param {ManagedPointer} [value] - an address in the managed heap to initialize the root with (or 0) * @returns {WasmRoot} */ - mono_wasm_new_root: function (value?): WasmRoot { + mono_wasm_new_root: function (value?: ManagedPointer): WasmRoot { var result; - if (this._scratch_root_free_instances.length > 0) { - result = this._scratch_root_free_instances.pop (); + if (MONO._scratch_root_free_instances.length > 0) { + result = MONO._scratch_root_free_instances.pop (); } else { - var index = this._mono_wasm_claim_scratch_index (); - var buffer = this._scratch_root_buffer; + var index = MONO._mono_wasm_claim_scratch_index (); + var buffer = MONO._scratch_root_buffer; - result = Object.create (this._mono_wasm_root_prototype); + result = Object.create (MONO._mono_wasm_root_prototype); result.__buffer = buffer; result.__index = index; } @@ -417,17 +410,17 @@ var MonoSupportLib = { * @param {(number | ManagedPointer[])} count_or_values - either a number of roots or an array of pointers * @returns {WasmRoot[]} */ - mono_wasm_new_roots: function (count_or_values) { + mono_wasm_new_roots: function (count_or_values: number | ManagedPointer[]): WasmRoot[] { var result; if (Array.isArray (count_or_values)) { result = new Array (count_or_values.length); for (var i = 0; i < result.length; i++) - result[i] = this.mono_wasm_new_root (count_or_values[i]); + result[i] = MONO.mono_wasm_new_root (count_or_values[i]); } else if ((count_or_values | 0) > 0) { result = new Array (count_or_values); for (var i = 0; i < result.length; i++) - result[i] = this.mono_wasm_new_root (); + result[i] = MONO.mono_wasm_new_root (); } else { throw new Error ("count_or_values must be either an array or a number greater than 0"); } @@ -442,7 +435,7 @@ var MonoSupportLib = { * even if you are not sure all of your roots have been created yet. * @param {... WasmRoot} roots */ - mono_wasm_release_roots: function (...roots: WasmRoot[]) { + mono_wasm_release_roots: function (...roots: WasmRoot[]): void { for (var i = 0; i < roots.length; i++) { if (!roots[i]) continue; @@ -547,8 +540,8 @@ var MonoSupportLib = { mono_wasm_send_dbg_command_with_parms: function (id, command_set, command, command_parameters, length, valtype, newvalue) { const dataHeap = new Uint8Array (Module.HEAPU8.buffer, command_parameters, command_parameters.length); - dataHeap.set (new Uint8Array (this._base64_to_uint8 (command_parameters))); - this._c_fn_table.mono_wasm_send_dbg_command_with_parms_wrapper (id, command_set, command, dataHeap.byteOffset, length, valtype, newvalue.toString()); + dataHeap.set (new Uint8Array (MONO._base64_to_uint8 (command_parameters))); + MONO._c_fn_table.mono_wasm_send_dbg_command_with_parms_wrapper (id, command_set, command, dataHeap.byteOffset, length, valtype, newvalue.toString()); let { res_ok, res } = MONO.commands_received; if (!res_ok) throw new Error (`Failed on mono_wasm_invoke_method_debugger_agent_with_parms`); @@ -558,9 +551,9 @@ var MonoSupportLib = { mono_wasm_send_dbg_command: function (id, command_set, command, command_parameters) { const dataHeap = new Uint8Array (Module.HEAPU8.buffer, command_parameters, command_parameters.length); - dataHeap.set (new Uint8Array (this._base64_to_uint8 (command_parameters))); + dataHeap.set (new Uint8Array (MONO._base64_to_uint8 (command_parameters))); - this._c_fn_table.mono_wasm_send_dbg_command_wrapper (id, command_set, command, dataHeap.byteOffset, command_parameters.length); + MONO._c_fn_table.mono_wasm_send_dbg_command_wrapper (id, command_set, command, dataHeap.byteOffset, command_parameters.length); let { res_ok, res } = MONO.commands_received; if (!res_ok) @@ -578,10 +571,10 @@ var MonoSupportLib = { }, _get_cfo_res_details: function (objectId, args) { - if (!(objectId in this._call_function_res_cache)) + if (!(objectId in MONO._call_function_res_cache)) throw new Error(`Could not find any object with id ${objectId}`); - const real_obj = this._call_function_res_cache [objectId]; + const real_obj = MONO._call_function_res_cache [objectId]; const descriptors = Object.getOwnPropertyDescriptors (real_obj); if (args.accessorPropertiesOnly) { @@ -636,18 +629,18 @@ var MonoSupportLib = { }, mono_wasm_get_details: function (objectId, args={}) { - return this._get_cfo_res_details (`dotnet:cfo_res:${objectId}`, args); + return MONO._get_cfo_res_details (`dotnet:cfo_res:${objectId}`, args); }, _cache_call_function_res: function (obj) { - const id = `dotnet:cfo_res:${this._next_call_function_res_id++}`; - this._call_function_res_cache[id] = obj; + const id = `dotnet:cfo_res:${MONO._next_call_function_res_id++}`; + MONO._call_function_res_cache[id] = obj; return id; }, mono_wasm_release_object: function (objectId) { - if (objectId in this._cache_call_function_res) - delete this._cache_call_function_res[objectId]; + if (objectId in MONO._cache_call_function_res) + delete MONO._cache_call_function_res[objectId]; }, _create_proxy_from_object_id: function (objectId, details) { @@ -688,12 +681,12 @@ var MonoSupportLib = { let proxy; if (objId.startsWith ('dotnet:cfo_res:')) { - if (objId in this._call_function_res_cache) - proxy = this._call_function_res_cache [objId]; + if (objId in MONO._call_function_res_cache) + proxy = MONO._call_function_res_cache [objId]; else throw new Error (`Unknown object id ${objId}`); } else { - proxy = this._create_proxy_from_object_id (objId, details); + proxy = MONO._create_proxy_from_object_id (objId, details); } const fn_args = request.arguments != undefined ? request.arguments.map(a => JSON.stringify(a.value)) : []; @@ -714,7 +707,7 @@ var MonoSupportLib = { return {type: "object", value: fn_res}; if (Object.getPrototypeOf (fn_res) == Array.prototype) { - const fn_res_id = this._cache_call_function_res (fn_res); + const fn_res_id = MONO._cache_call_function_res (fn_res); return { type: "object", @@ -730,27 +723,27 @@ var MonoSupportLib = { if (fn_res == proxy) return { type: "object", className: "Object", description: "Object", objectId: objId }; - const fn_res_id = this._cache_call_function_res (fn_res); + const fn_res_id = MONO._cache_call_function_res (fn_res); return { type: "object", className: "Object", description: "Object", objectId: fn_res_id }; }, _clear_per_step_state: function () { - this._next_id_var = 0; - this._id_table = {}; + MONO._next_id_var = 0; + MONO._id_table = {}; }, mono_wasm_debugger_resume: function () { - this._clear_per_step_state (); + MONO._clear_per_step_state (); }, mono_wasm_detach_debugger: function () { - if (!this.mono_wasm_set_is_debugger_attached) - this.mono_wasm_set_is_debugger_attached = Module.cwrap ('mono_wasm_set_is_debugger_attached', 'void', ['bool']); - this.mono_wasm_set_is_debugger_attached(false); + if (!MONO.mono_wasm_set_is_debugger_attached) + MONO.mono_wasm_set_is_debugger_attached = Module.cwrap ('mono_wasm_set_is_debugger_attached', 'void', ['bool']); + MONO.mono_wasm_set_is_debugger_attached(false); }, _register_c_fn: function (name, ...args) { - Object.defineProperty (this._c_fn_table, name + '_wrapper', { value: Module.cwrap (name, ...args) }); + Object.defineProperty (MONO._c_fn_table, name + '_wrapper', { value: Module.cwrap (name, ...args) }); }, /** @@ -764,11 +757,11 @@ var MonoSupportLib = { * * @returns {void} */ - _register_c_var_fn: function (name, ret_type, params) { + _register_c_var_fn: function (name: string, ret_type: string, params: string[]): void { if (ret_type !== 'bool') throw new Error (`Bug: Expected a C function signature that returns bool`); - this._register_c_fn (name, ret_type, params); + MONO._register_c_fn (name, ret_type, params); Object.defineProperty (this, name + '_info', { value: function (...args) { MONO.var_info = []; @@ -786,16 +779,16 @@ var MonoSupportLib = { }, mono_wasm_runtime_ready: function () { - this.mono_wasm_runtime_is_ready = true; - this._clear_per_step_state (); + MONO.mono_wasm_runtime_is_ready = true; + MONO._clear_per_step_state (); // FIXME: where should this go? - this._next_call_function_res_id = 0; - this._call_function_res_cache = {}; + MONO._next_call_function_res_id = 0; + MONO._call_function_res_cache = {}; - this._c_fn_table = {}; - this._register_c_fn ('mono_wasm_send_dbg_command', 'bool', [ 'number', 'number', 'number', 'number', 'number' ]); - this._register_c_fn ('mono_wasm_send_dbg_command_with_parms', 'bool', [ 'number', 'number', 'number', 'number', 'number', 'number', 'string' ]); + MONO._c_fn_table = {}; + MONO._register_c_fn ('mono_wasm_send_dbg_command', 'bool', [ 'number', 'number', 'number', 'number', 'number' ]); + MONO._register_c_fn ('mono_wasm_send_dbg_command_with_parms', 'bool', [ 'number', 'number', 'number', 'number', 'number', 'number', 'string' ]); // DO NOT REMOVE - magic debugger init function if (globalThis.dotnetDebugger) @@ -807,14 +800,14 @@ var MonoSupportLib = { // Set environment variable NAME to VALUE // Should be called before mono_load_runtime_and_bcl () in most cases mono_wasm_setenv: function (name, value) { - if (!this.wasm_setenv) - this.wasm_setenv = Module.cwrap ('mono_wasm_setenv', null, ['string', 'string']); - this.wasm_setenv (name, value); + if (!MONO.wasm_setenv) + MONO.wasm_setenv = Module.cwrap ('mono_wasm_setenv', null, ['string', 'string']); + MONO.wasm_setenv (name, value); }, mono_wasm_set_runtime_options: function (options) { - if (!this.wasm_parse_runtime_options) - this.wasm_parse_runtime_options = Module.cwrap ('mono_wasm_parse_runtime_options', null, ['number', 'number']); + if (!MONO.wasm_parse_runtime_options) + MONO.wasm_parse_runtime_options = Module.cwrap ('mono_wasm_parse_runtime_options', null, ['number', 'number']); var argv = Module._malloc (options.length * 4); var wasm_strdup = Module.cwrap ('mono_wasm_strdup', 'number', ['string']); let aindex = 0; @@ -822,7 +815,7 @@ var MonoSupportLib = { Module.setValue (argv + (aindex * 4), wasm_strdup (options [i]), "i32"); aindex += 1; } - this.wasm_parse_runtime_options (options.length, argv); + MONO.wasm_parse_runtime_options (options.length, argv); }, // @@ -924,7 +917,7 @@ var MonoSupportLib = { ctx.loaded_files.push ({ url: url, file: virtualName}); case "heap": case "icu": - offset = this.mono_wasm_load_bytes_into_heap (bytes); + offset = MONO.mono_wasm_load_bytes_into_heap (bytes); ctx.loaded_assets[virtualName] = [offset, bytes.length]; break; @@ -953,7 +946,7 @@ var MonoSupportLib = { if (ctx.tracing) console.log ("MONO_WASM: Creating file '" + fileName + "' in directory '" + parentDirectory + "'"); - if (!this.mono_wasm_load_data_archive (bytes, parentDirectory)) { + if (!MONO.mono_wasm_load_data_archive (bytes, parentDirectory)) { var fileRet = ctx.createDataFile ( parentDirectory, fileName, bytes, true /* canRead */, true /* canWrite */, true /* canOwn */ @@ -974,7 +967,7 @@ var MonoSupportLib = { } } else if (asset.behavior === "icu") { - if (this.mono_wasm_load_icu_data (offset)) + if (MONO.mono_wasm_load_icu_data (offset)) ctx.num_icu_assets_loaded_successfully += 1; else console.error ("Error loading ICU asset", asset.name); @@ -1012,7 +1005,7 @@ var MonoSupportLib = { }); } - return this.mono_load_runtime_and_bcl_args (args); + return MONO.mono_load_runtime_and_bcl_args (args); }, // Initializes the runtime and loads assemblies, debug information, and other files. @@ -1056,7 +1049,7 @@ var MonoSupportLib = { // diagnostic_tracing: (optional) enables diagnostic log messages during startup mono_load_runtime_and_bcl_args: function (args) { try { - return this._load_assets_and_runtime (args); + return MONO._load_assets_and_runtime (args); } catch (exc) { console.error ("error in mono_load_runtime_and_bcl_args:", exc); throw exc; @@ -1080,7 +1073,7 @@ var MonoSupportLib = { var fn = Module.cwrap ('mono_wasm_load_icu_data', 'number', ['number']); var ok = (fn (offset)) === 1; if (ok) - this.num_icu_assets_loaded_successfully++; + MONO.num_icu_assets_loaded_successfully++; return ok; }, @@ -1107,7 +1100,7 @@ var MonoSupportLib = { console.debug ("MONO_WASM: Initializing mono runtime"); - this.mono_wasm_globalization_init (args.globalization_mode); + MONO.mono_wasm_globalization_init (args.globalization_mode); if (ENVIRONMENT_IS_SHELL || ENVIRONMENT_IS_NODE) { try { @@ -1160,9 +1153,9 @@ var MonoSupportLib = { if (ctx.tracing) console.log ("mono_wasm_load_runtime_with_args", JSON.stringify(args)); - this._apply_configuration_from_args (args); + MONO._apply_configuration_from_args (args); - var fetch_file_cb = this._get_fetch_file_cb_from_args (args); + var fetch_file_cb = MONO._get_fetch_file_cb_from_args (args); var onPendingRequestComplete = function () { --ctx.pending_count; @@ -1283,7 +1276,7 @@ var MonoSupportLib = { invariantMode = true; if (!invariantMode) { - if (this.num_icu_assets_loaded_successfully > 0) { + if (MONO.num_icu_assets_loaded_successfully > 0) { console.debug ("MONO_WASM: ICU data archive(s) loaded, disabling invariant mode"); } else if (globalization_mode !== "icu") { console.debug ("MONO_WASM: ICU data archive(s) not loaded, using invariant globalization mode"); @@ -1296,17 +1289,17 @@ var MonoSupportLib = { } if (invariantMode) - this.mono_wasm_setenv ("DOTNET_SYSTEM_GLOBALIZATION_INVARIANT", "1"); + MONO.mono_wasm_setenv ("DOTNET_SYSTEM_GLOBALIZATION_INVARIANT", "1"); // Set globalization mode to PredefinedCulturesOnly - this.mono_wasm_setenv ("DOTNET_SYSTEM_GLOBALIZATION_PREDEFINED_CULTURES_ONLY", "1"); + MONO.mono_wasm_setenv ("DOTNET_SYSTEM_GLOBALIZATION_PREDEFINED_CULTURES_ONLY", "1"); }, // Used by the debugger to enumerate loaded dlls and pdbs mono_wasm_get_loaded_files: function() { - if (!this.mono_wasm_set_is_debugger_attached) - this.mono_wasm_set_is_debugger_attached = Module.cwrap ('mono_wasm_set_is_debugger_attached', 'void', ['bool']); - this.mono_wasm_set_is_debugger_attached (true); + if (!MONO.mono_wasm_set_is_debugger_attached) + MONO.mono_wasm_set_is_debugger_attached = Module.cwrap ('mono_wasm_set_is_debugger_attached', 'void', ['bool']); + MONO.mono_wasm_set_is_debugger_attached (true); return MONO.loaded_files; }, @@ -1433,17 +1426,17 @@ var MonoSupportLib = { }, mono_set_timeout: function (timeout, id) { - if (!this.mono_set_timeout_exec) - this.mono_set_timeout_exec = Module.cwrap ("mono_set_timeout_exec", null, [ 'number' ]); + if (!MONO.mono_set_timeout_exec) + MONO.mono_set_timeout_exec = Module.cwrap ("mono_set_timeout_exec", null, [ 'number' ]); if (typeof globalThis.setTimeout === 'function') { globalThis.setTimeout (function () { - this.mono_set_timeout_exec (id); + MONO.mono_set_timeout_exec (id); }, timeout); } else { ++MONO.pump_count; MONO.timeout_queue.push(function() { - this.mono_set_timeout_exec (id); + MONO.mono_set_timeout_exec (id); }) } }, diff --git a/src/mono/wasm/runtime/types/Module.d.ts b/src/mono/wasm/runtime/types/Module.d.ts index 9678520c9f3bc..f50efae7b3152 100644 --- a/src/mono/wasm/runtime/types/Module.d.ts +++ b/src/mono/wasm/runtime/types/Module.d.ts @@ -42,11 +42,12 @@ declare namespace Module { function mono_method_get_call_signature (method: any, mono_obj?: any): string; function print (message: string): void; - function ccall (ident: string, returnType?: string, argTypes?: any[] , args?: any[] , opts?: any): any; + function ccall (ident: string, returnType?: string, argTypes?: string[], args?: any[] , opts?: any): T; + function cwrap (ident: string, returnType: string, argTypes?: string[], opts?: any): T; + function cwrap (ident: string, ...args: any[]): T; + function FS_createPath (parent: string | any, path: string, canRead?: boolean /* unused */, canWrite?: boolean /* unused */): string; function FS_createDataFile (parent: string | any, name: string, data: string, canRead: boolean, canWrite: boolean, canOwn?: boolean): string; - function cwrap (ident: string, returnType: string, argTypes?: any[], opts?: any): Function; - function cwrap (ident: string, ...args: any[]): Function; function setValue (ptr: number, value: number, type: string, noSafe?: number | boolean): void; function getValue (ptr: number, type: string, noSafe?: number | boolean ): number; function UTF8ToString (ptr: number, maxBytesToRead?: number): string; diff --git a/src/mono/wasm/runtime/types/binding_types.d.ts b/src/mono/wasm/runtime/types/binding_types.d.ts index e799533aa4fea..3dbc5da3afc0b 100644 --- a/src/mono/wasm/runtime/types/binding_types.d.ts +++ b/src/mono/wasm/runtime/types/binding_types.d.ts @@ -26,14 +26,75 @@ interface BINDING_C_FUNCS { mono_string_get_utf8 (a: number): number; mono_wasm_box_primitive (a: number, b: number, c: number): number; + mono_wasm_get_delegate_invoke (a: number): number; mono_wasm_intern_string (a: number): number; mono_wasm_register_bundled_satellite_assemblies (): void; mono_wasm_string_array_new (a: number): number; mono_wasm_string_from_utf16 (a: number, b: number): number; mono_wasm_try_unbox_primitive_and_get_type (a: number, b: number): number; - mono_wasm_typed_array_new (a: number, b: number, c: number, d: number): number; - mono_wasm_typed_array_new (a: string, b: string, c: number, d: number): number; + mono_typed_array_new (a: number, b: number, c: number, d: number): number; +} + +interface BINDING_VARS { + init: boolean; + _box_buffer: number; + _unbox_buffer: number; + _class_int32: number; + _class_uint32: number; + _class_double: number; + _class_boolean: number; + binding_module: number; + safehandle_addref: number; + safehandle_release: number; + safehandle_get_handle: number; + safehandle_release_by_handle: number; + _are_promises_supported: boolean; + _empty_string: string; + _empty_string_ptr: number; + _interned_string_full_root_buffers: WasmRootBuffer[]; + _interned_string_current_root_buffer: WasmRootBuffer; + _interned_string_current_root_buffer_count: number; + _interned_js_string_table: Map; + _method_descriptions: Map; + _signature_converters: Map; + _primitive_converters: Map; + scratchBuffer: number; + + _bind_js_obj: Function; + _bind_core_clr_obj: Function; + _bind_existing_obj: Function; + _unbind_raw_obj_and_free: Function; + _get_js_id: Function; + _get_raw_mono_obj: Function; + _is_simple_array: Function; + _object_to_string: Function; + setup_js_cont: number; + create_tcs: number; + set_tcs_result: number; + set_tcs_failure: number; + tcs_get_task_and_bind: number; + get_call_sig: number; + get_date_value: number; + create_date_time: number; + create_uri: number; } // NAMESPACES /////////////////////////////////////////////////////////////////////////////// -declare var BINDING: typeof BindingSupportLib.$BINDING & BINDING_C_FUNCS; +declare var BINDING: typeof BindingSupportLib.$BINDING & BINDING_C_FUNCS & BINDING_VARS; + +// OTHER TYPES /////////////////////////////////////////////////////////////////////// +type Converter = { + steps: any[]; + size: number; + args_marshal?: any; + is_result_definitely_unmarshaled?: boolean; + is_result_possibly_unmarshaled?: boolean; + result_unmarshaled_if_argc?: number; + needs_root_buffer?: boolean; + name?: string; + needs_root?: boolean; + compiled_variadic_function?: any; + compiled_function?: any; + scratchRootBuffer?: any; + scratchBuffer?: any; +} diff --git a/src/mono/wasm/runtime/types/general_types.d.ts b/src/mono/wasm/runtime/types/general_types.d.ts index 512adf7640555..936e6fd782918 100644 --- a/src/mono/wasm/runtime/types/general_types.d.ts +++ b/src/mono/wasm/runtime/types/general_types.d.ts @@ -21,3 +21,6 @@ declare function locateFile(path: string): string; declare function read (path: string): string; declare function load (path: string): string; declare function require (path: string): object; + +// Joins the various file specific C functions into 1 interface for easier access +interface C_FUNCS extends BINDING_C_FUNCS, DOTNET_C_FUNCS, MONO_C_FUNCS {} diff --git a/src/mono/wasm/runtime/types/mono_types.d.ts b/src/mono/wasm/runtime/types/mono_types.d.ts index 66dbe402f7143..ed0bc3cec1ceb 100644 --- a/src/mono/wasm/runtime/types/mono_types.d.ts +++ b/src/mono/wasm/runtime/types/mono_types.d.ts @@ -21,18 +21,27 @@ interface MONO_C_FUNCS { mono_wasm_get_icudt_name (a: string): string; mono_wasm_load_icu_data (a: number): number; mono_wasm_load_runtime (a: string, b: number): void; - mono_wasm_parse_runtime_options (a: number, b:number): void; - mono_wasm_register_root (a: number, b: number, c: string): number; + wasm_parse_runtime_options (a: number, b:number): void; + mono_wasm_register_root (a: number, b: number, c: string | 0): number; mono_wasm_send_dbg_command (a: number, b:number, c: number, d: number, e: number): boolean; mono_wasm_send_dbg_command_with_parms (a: number, b:number, c: number, d: number, e: number, f: number, g: string): boolean; mono_wasm_set_is_debugger_attached (a: boolean): void; - mono_wasm_setenv (a: string, b: string): void; + wasm_setenv (a: string, b: string): void; mono_wasm_strdup (a: string): number; mono_wasm_string_get_data (a: number, b: number, c: number, d: number): void; } +interface MONO_VARS { + _base64Table: string[]; + mono_wasm_string_decoder_buffer: number; + mono_wasm_empty_string: string; + _next_call_function_res_id: number; + _next_id_var: number; + _call_function_res_cache: any; +} + // NAMESPACES /////////////////////////////////////////////////////////////////////////////// -declare var MONO: typeof MonoSupportLib.$MONO & MONO_C_FUNCS; +declare var MONO: typeof MonoSupportLib.$MONO & MONO_C_FUNCS & MONO_VARS; // OTHER TYPES /////////////////////////////////////////////////////////////////////// diff --git a/src/mono/wasm/wasm.proj b/src/mono/wasm/wasm.proj index 1703b86398131..ec50e483a4120 100644 --- a/src/mono/wasm/wasm.proj +++ b/src/mono/wasm/wasm.proj @@ -141,7 +141,7 @@ DependsOnTargets="GenerateEmccPropsAndRspFiles;BuildPInvokeTable;BundleTimeZones"> - + @@ -225,7 +225,7 @@ IgnoreStandardErrorWarningFormat="true" /> - + Date: Tue, 20 Jul 2021 09:50:04 -0400 Subject: [PATCH 09/19] addressed PR comments --- .../sfx/Microsoft.NETCore.App/Directory.Build.props | 6 +++--- src/mono/wasm/Makefile | 6 +++--- src/mono/wasm/debugger/DebuggerTestSuite/ArrayTests.cs | 2 +- .../debugger/DebuggerTestSuite/DebuggerTestBase.cs | 2 +- .../runtime/{binding_support.ts => binding-support.ts} | 0 .../runtime/{dotnet_support.ts => dotnet-support.ts} | 0 src/mono/wasm/runtime/driver.c | 4 ++-- .../wasm/runtime/{library_mono.ts => library-mono.ts} | 10 +++++----- .../types/{binding_types.d.ts => binding-types.d.ts} | 0 .../types/{dotnet_types.d.ts => dotnet-types.d.ts} | 0 .../types/{general_types.d.ts => general-types.d.ts} | 0 .../runtime/types/{mono_types.d.ts => mono-types.d.ts} | 0 src/mono/wasm/wasm.proj | 10 +++++----- 13 files changed, 20 insertions(+), 20 deletions(-) rename src/mono/wasm/runtime/{binding_support.ts => binding-support.ts} (100%) rename src/mono/wasm/runtime/{dotnet_support.ts => dotnet-support.ts} (100%) rename src/mono/wasm/runtime/{library_mono.ts => library-mono.ts} (99%) rename src/mono/wasm/runtime/types/{binding_types.d.ts => binding-types.d.ts} (100%) rename src/mono/wasm/runtime/types/{dotnet_types.d.ts => dotnet-types.d.ts} (100%) rename src/mono/wasm/runtime/types/{general_types.d.ts => general-types.d.ts} (100%) rename src/mono/wasm/runtime/types/{mono_types.d.ts => mono-types.d.ts} (100%) diff --git a/src/installer/pkg/sfx/Microsoft.NETCore.App/Directory.Build.props b/src/installer/pkg/sfx/Microsoft.NETCore.App/Directory.Build.props index 19c48f2ec850c..2f349b5c667ba 100644 --- a/src/installer/pkg/sfx/Microsoft.NETCore.App/Directory.Build.props +++ b/src/installer/pkg/sfx/Microsoft.NETCore.App/Directory.Build.props @@ -216,9 +216,9 @@ - - - + + + diff --git a/src/mono/wasm/Makefile b/src/mono/wasm/Makefile index 2242fb8d79885..e162dc44400f5 100644 --- a/src/mono/wasm/Makefile +++ b/src/mono/wasm/Makefile @@ -101,8 +101,8 @@ $(NATIVE_BIN_DIR)/include/wasm: $(BUILDS_OBJ_DIR): mkdir -p $$@ -$(NATIVE_BIN_DIR)/dotnet.js: $(BUILDS_OBJ_DIR)/driver.o $(BUILDS_OBJ_DIR)/pinvoke.o $(BUILDS_OBJ_DIR)/corebindings.o runtime/bin/library_mono.js runtime/bin/binding_support.js runtime/bin/dotnet_support.js $(SYSTEM_NATIVE_LIBDIR)/pal_random.js $(2) $(EMCC_DEFAULT_RSP) | $(NATIVE_BIN_DIR) - $(EMCC) @$(EMCC_DEFAULT_RSP) $(1) --js-library runtime/bin/library_mono.js --js-library runtime/bin/binding_support.js --js-library runtime/bin/dotnet_support.js --js-library $(SYSTEM_NATIVE_LIBDIR)/pal_random.js $(BUILDS_OBJ_DIR)/driver.o $(BUILDS_OBJ_DIR)/pinvoke.o $(BUILDS_OBJ_DIR)/corebindings.o $(2) -o $(NATIVE_BIN_DIR)/dotnet.js $(3) +$(NATIVE_BIN_DIR)/dotnet.js: $(BUILDS_OBJ_DIR)/driver.o $(BUILDS_OBJ_DIR)/pinvoke.o $(BUILDS_OBJ_DIR)/corebindings.o runtime/bin/library-mono.js runtime/bin/binding-support.js runtime/bin/dotnet-support.js $(SYSTEM_NATIVE_LIBDIR)/pal_random.js $(2) $(EMCC_DEFAULT_RSP) | $(NATIVE_BIN_DIR) + $(EMCC) @$(EMCC_DEFAULT_RSP) $(1) --js-library runtime/bin/library-mono.js --js-library runtime/bin/binding-support.js --js-library runtime/bin/dotnet-support.js --js-library $(SYSTEM_NATIVE_LIBDIR)/pal_random.js $(BUILDS_OBJ_DIR)/driver.o $(BUILDS_OBJ_DIR)/pinvoke.o $(BUILDS_OBJ_DIR)/corebindings.o $(2) -o $(NATIVE_BIN_DIR)/dotnet.js $(3) $(BUILDS_OBJ_DIR)/pinvoke-table.h: $(PINVOKE_TABLE) | $(BUILDS_OBJ_DIR) if cmp -s $(PINVOKE_TABLE) $$@ ; then : ; else cp $(PINVOKE_TABLE) $$@ ; fi @@ -141,7 +141,7 @@ clean: icu-files: $(wildcard $(ICU_LIBDIR)/*.dat) $(ICU_LIBDIR)/libicuuc.a $(ICU_LIBDIR)/libicui18n.a | $(NATIVE_BIN_DIR) cp $^ $(NATIVE_BIN_DIR) -source-files: runtime/driver.c runtime/pinvoke.c runtime/corebindings.c runtime/bin/binding_support.js runtime/bin/dotnet_support.js runtime/bin/library_mono.js $(SYSTEM_NATIVE_LIBDIR)/pal_random.js | $(NATIVE_BIN_DIR)/src +source-files: runtime/driver.c runtime/pinvoke.c runtime/corebindings.c runtime/bin/binding-support.js runtime/bin/dotnet-support.js runtime/bin/library-mono.js $(SYSTEM_NATIVE_LIBDIR)/pal_random.js | $(NATIVE_BIN_DIR)/src cp $^ $(NATIVE_BIN_DIR)/src header-files: runtime/pinvoke.h | $(NATIVE_BIN_DIR)/include/wasm diff --git a/src/mono/wasm/debugger/DebuggerTestSuite/ArrayTests.cs b/src/mono/wasm/debugger/DebuggerTestSuite/ArrayTests.cs index dfe99aed5a769..f457ce857f873 100644 --- a/src/mono/wasm/debugger/DebuggerTestSuite/ArrayTests.cs +++ b/src/mono/wasm/debugger/DebuggerTestSuite/ArrayTests.cs @@ -574,7 +574,7 @@ public async Task InvalidArrayId() => await CheckInspectLocalsAtBreakpointSite( // Trying to access object as an array if (!DotnetObjectId.TryParse(c_obj_id, out var id) || id.Scheme != "object") - Assert.True(false, "Unexpected object id format. Maybe this test is out of sync with the object id format in library_mono.js?"); + Assert.True(false, "Unexpected object id format. Maybe this test is out of sync with the object id format in library-mono.ts?"); if (!int.TryParse(id.Value, out var idNum)) Assert.True(false, "Expected a numeric value part of the object id: {c_obj_id}"); diff --git a/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestBase.cs b/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestBase.cs index b26624807150f..fe7b5df4998a0 100644 --- a/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestBase.cs +++ b/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestBase.cs @@ -803,7 +803,7 @@ internal async Task GetProperties(string id, JToken fn_args = null, bool return null; var locals = frame_props.Value["result"]; - // FIXME: Should be done when generating the list in library_mono.js, but not sure yet + // FIXME: Should be done when generating the list in library-mono.ts, but not sure yet // whether to remove it, and how to do it correctly. if (locals is JArray) { diff --git a/src/mono/wasm/runtime/binding_support.ts b/src/mono/wasm/runtime/binding-support.ts similarity index 100% rename from src/mono/wasm/runtime/binding_support.ts rename to src/mono/wasm/runtime/binding-support.ts diff --git a/src/mono/wasm/runtime/dotnet_support.ts b/src/mono/wasm/runtime/dotnet-support.ts similarity index 100% rename from src/mono/wasm/runtime/dotnet_support.ts rename to src/mono/wasm/runtime/dotnet-support.ts diff --git a/src/mono/wasm/runtime/driver.c b/src/mono/wasm/runtime/driver.c index ca98e347dd120..c893e17e6eb15 100644 --- a/src/mono/wasm/runtime/driver.c +++ b/src/mono/wasm/runtime/driver.c @@ -29,7 +29,7 @@ void core_initialize_internals (); #endif -// Blazor specific custom routines - see dotnet_support.js for backing code +// Blazor specific custom routines - see dotnet-support.ts for backing code extern void* mono_wasm_invoke_js_blazor (MonoString **exceptionMessage, void *callInfo, void* arg0, void* arg1, void* arg2); // The following two are for back-compat and will eventually be removed extern void* mono_wasm_invoke_js_marshalled (MonoString **exceptionMessage, void *asyncHandleLongPtr, MonoString *funcName, MonoString *argsJson); @@ -445,7 +445,7 @@ void mono_initialize_internals () mono_add_internal_call ("Interop/Runtime::InvokeJS", mono_wasm_invoke_js); // TODO: what happens when two types in different assemblies have the same FQN? - // Blazor specific custom routines - see dotnet_support.js for backing code + // Blazor specific custom routines - see dotnet-support.js for backing code mono_add_internal_call ("WebAssembly.JSInterop.InternalCalls::InvokeJS", mono_wasm_invoke_js_blazor); // The following two are for back-compat and will eventually be removed mono_add_internal_call ("WebAssembly.JSInterop.InternalCalls::InvokeJSMarshalled", mono_wasm_invoke_js_marshalled); diff --git a/src/mono/wasm/runtime/library_mono.ts b/src/mono/wasm/runtime/library-mono.ts similarity index 99% rename from src/mono/wasm/runtime/library_mono.ts rename to src/mono/wasm/runtime/library-mono.ts index bd72a716f7c8a..55244b0e4238f 100644 --- a/src/mono/wasm/runtime/library_mono.ts +++ b/src/mono/wasm/runtime/library-mono.ts @@ -537,9 +537,9 @@ var MonoSupportLib = { MONO.commands_received = buffer_obj; }, - mono_wasm_send_dbg_command_with_parms: function (id, command_set, command, command_parameters, length, valtype, newvalue) + mono_wasm_send_dbg_command_with_parms: function (id: number, command_set: number, command: number, command_parameters: string, length: number, valtype: number, newvalue: string) { - const dataHeap = new Uint8Array (Module.HEAPU8.buffer, command_parameters, command_parameters.length); + const dataHeap = new Uint8Array (Module.HEAPU8.buffer, command_parameters.length); dataHeap.set (new Uint8Array (MONO._base64_to_uint8 (command_parameters))); MONO._c_fn_table.mono_wasm_send_dbg_command_with_parms_wrapper (id, command_set, command, dataHeap.byteOffset, length, valtype, newvalue.toString()); let { res_ok, res } = MONO.commands_received; @@ -548,9 +548,9 @@ var MonoSupportLib = { return res; }, - mono_wasm_send_dbg_command: function (id, command_set, command, command_parameters) + mono_wasm_send_dbg_command: function (id: number, command_set: number, command: number, command_parameters: string) { - const dataHeap = new Uint8Array (Module.HEAPU8.buffer, command_parameters, command_parameters.length); + const dataHeap = new Uint8Array (Module.HEAPU8.buffer, command_parameters.length); dataHeap.set (new Uint8Array (MONO._base64_to_uint8 (command_parameters))); MONO._c_fn_table.mono_wasm_send_dbg_command_wrapper (id, command_set, command, dataHeap.byteOffset, command_parameters.length); @@ -742,7 +742,7 @@ var MonoSupportLib = { MONO.mono_wasm_set_is_debugger_attached(false); }, - _register_c_fn: function (name, ...args) { + _register_c_fn: function (name: string, ...args: any[]) { Object.defineProperty (MONO._c_fn_table, name + '_wrapper', { value: Module.cwrap (name, ...args) }); }, diff --git a/src/mono/wasm/runtime/types/binding_types.d.ts b/src/mono/wasm/runtime/types/binding-types.d.ts similarity index 100% rename from src/mono/wasm/runtime/types/binding_types.d.ts rename to src/mono/wasm/runtime/types/binding-types.d.ts diff --git a/src/mono/wasm/runtime/types/dotnet_types.d.ts b/src/mono/wasm/runtime/types/dotnet-types.d.ts similarity index 100% rename from src/mono/wasm/runtime/types/dotnet_types.d.ts rename to src/mono/wasm/runtime/types/dotnet-types.d.ts diff --git a/src/mono/wasm/runtime/types/general_types.d.ts b/src/mono/wasm/runtime/types/general-types.d.ts similarity index 100% rename from src/mono/wasm/runtime/types/general_types.d.ts rename to src/mono/wasm/runtime/types/general-types.d.ts diff --git a/src/mono/wasm/runtime/types/mono_types.d.ts b/src/mono/wasm/runtime/types/mono-types.d.ts similarity index 100% rename from src/mono/wasm/runtime/types/mono_types.d.ts rename to src/mono/wasm/runtime/types/mono-types.d.ts diff --git a/src/mono/wasm/wasm.proj b/src/mono/wasm/wasm.proj index ec50e483a4120..351b4a11aec35 100644 --- a/src/mono/wasm/wasm.proj +++ b/src/mono/wasm/wasm.proj @@ -141,7 +141,7 @@ DependsOnTargets="GenerateEmccPropsAndRspFiles;BuildPInvokeTable;BundleTimeZones"> - + @@ -227,7 +227,7 @@ - @@ -245,9 +245,9 @@ From b9c909f2eb82ed0c2347cfaf99d3f226d54d9456 Mon Sep 17 00:00:00 2001 From: Daniel-Genkin Date: Tue, 20 Jul 2021 12:41:46 -0400 Subject: [PATCH 10/19] replaced hardcoded numbers with enums + fixed tsc exit code 1 error --- src/mono/wasm/runtime/binding-support.ts | 123 +++++++++--------- src/mono/wasm/runtime/library-mono.ts | 16 +-- src/mono/wasm/runtime/types/Module.d.ts | 11 +- .../wasm/runtime/types/binding-types.d.ts | 55 +++++++- src/mono/wasm/wasm.proj | 2 +- 5 files changed, 136 insertions(+), 71 deletions(-) diff --git a/src/mono/wasm/runtime/binding-support.ts b/src/mono/wasm/runtime/binding-support.ts index dee3da25b86c3..6e13c09d24efa 100644 --- a/src/mono/wasm/runtime/binding-support.ts +++ b/src/mono/wasm/runtime/binding-support.ts @@ -168,7 +168,7 @@ var BindingSupportLib = { return result; }, - _store_string_in_intern_table: function (string: string, ptr: number, internIt: boolean): number { + _store_string_in_intern_table: function (string: string | Symbol, ptr: number, internIt: boolean): number { if (!ptr) throw new Error ("null pointer passed to _store_string_in_intern_table"); else if (typeof (ptr) !== "number") @@ -203,16 +203,20 @@ var BindingSupportLib = { MONO.interned_string_table = new Map(); MONO.interned_string_table.set (ptr, string); - if ((string.length === 0) && !BINDING._empty_string_ptr) + var text = ((typeof (string) === "symbol") + ? (string.description || Symbol.keyFor(string) || "") + : string) as string; + + if ((text.length === 0) && !BINDING._empty_string_ptr) BINDING._empty_string_ptr = ptr; return ptr; }, - js_string_to_mono_string_interned: function (string) { - var text = (typeof (string) === "symbol") + js_string_to_mono_string_interned: function (string: string | Symbol): number { + var text = ((typeof (string) === "symbol") ? (string.description || Symbol.keyFor(string) || "") - : string; + : string) as string; if ((text.length === 0) && BINDING._empty_string_ptr) return BINDING._empty_string_ptr; @@ -227,7 +231,7 @@ var BindingSupportLib = { return ptr; }, - js_string_to_mono_string: function (string: string): number { + js_string_to_mono_string: function (string: string | Symbol): number { if (string === null) return null; else if (typeof (string) === "symbol") @@ -293,7 +297,7 @@ var BindingSupportLib = { return BINDING._is_simple_array(ele); }, - mono_array_to_js_array: function (mono_array: number): any { + mono_array_to_js_array: function (mono_array: number): any[] | null { if (mono_array === 0) return null; @@ -305,7 +309,7 @@ var BindingSupportLib = { } }, - _mono_array_root_to_js_array: function (arrayRoot){ + _mono_array_root_to_js_array: function (arrayRoot): any[] | null { if (arrayRoot.value === 0) return null; @@ -330,7 +334,7 @@ var BindingSupportLib = { return res; }, - js_array_to_mono_array: function (js_array, asString = false) { + js_array_to_mono_array: function (js_array: any[], asString: boolean = false): number { var mono_array = asString ? BINDING.mono_wasm_string_array_new (js_array.length) : BINDING.mono_obj_array_new (js_array.length); let [arrayRoot, elemRoot] = MONO.mono_wasm_new_roots ([mono_array, 0]); @@ -350,7 +354,7 @@ var BindingSupportLib = { } }, - unbox_mono_obj: function (mono_obj) { + unbox_mono_obj: function (mono_obj: number): number { if (mono_obj === 0) return undefined; @@ -392,7 +396,7 @@ var BindingSupportLib = { return promise; }, - _unbox_safehandle_root: function (root) { + _unbox_safehandle_root: function (root: WasmRoot) { var addRef = true; var js_handle = BINDING.call_method(BINDING.safehandle_get_handle, null, "mi", [ root.value, addRef ]); var requiredObject = BINDING.mono_wasm_require_handle (js_handle); @@ -406,26 +410,27 @@ var BindingSupportLib = { return requiredObject; }, - _unbox_mono_obj_root_with_known_nonprimitive_type: function (root, type) { + /** @returns return type is determined by the type parameter */ + _unbox_mono_obj_root_with_known_nonprimitive_type: function (root: WasmRoot, type: number): any { if (root.value === undefined) throw new Error(`Expected a root but got ${root}`); //See MARSHAL_TYPE_ defines in driver.c switch (type) { - case 26: // int64 - case 27: // uint64 + case CNonPrimativeTypes.Int64: + case CNonPrimativeTypes.UInt64: // TODO: Fix this once emscripten offers HEAPI64/HEAPU64 or can return them throw new Error ("int64 not available"); - case 3: // string - case 29: // interned string + case CNonPrimativeTypes.String: + case CNonPrimativeTypes.Char: // interned string return BINDING.conv_string (root.value); - case 4: //vts + case CNonPrimativeTypes.VTS: throw new Error ("no idea on how to unbox value types"); - case 5: // delegate + case CNonPrimativeTypes.Delegate: return BINDING._unbox_delegate_root (root); - case 6: // Task + case CNonPrimativeTypes.Task: return BINDING._unbox_task_root (root); - case 7: // ref type + case CNonPrimativeTypes.Ref: return BINDING.extract_js_obj_root (root); case 10: // arrays case 11: @@ -437,59 +442,59 @@ var BindingSupportLib = { case 17: case 18: throw new Error ("Marshalling of primitive arrays are not supported. Use the corresponding TypedArray instead."); - case 20: // clr .NET DateTime + case CNonPrimativeTypes.DateTime: // clr .NET DateTime var dateValue = BINDING.call_method(BINDING.get_date_value, null, "m", [ root.value ]); return new Date(dateValue); - case 21: // clr .NET DateTimeOffset + case CNonPrimativeTypes.DateTimeOffset: // clr .NET DateTimeOffset var dateoffsetValue = BINDING._object_to_string (root.value); return dateoffsetValue; - case 22: // clr .NET Uri + case CNonPrimativeTypes.Uri: // clr .NET Uri var uriValue = BINDING._object_to_string (root.value); return uriValue; - case 23: // clr .NET SafeHandle + case CNonPrimativeTypes.SafeHandle: // clr .NET SafeHandle return BINDING._unbox_safehandle_root (root); - case 30: + case CNonPrimativeTypes.Undefined: return undefined; default: throw new Error (`no idea on how to unbox object kind ${type} at offset ${root.value} (root address is ${root.get_address()})`); } }, - _unbox_mono_obj_root: function (root) { + _unbox_mono_obj_root: function (root: WasmRoot): any { if (root.value === 0) return undefined; var type = BINDING.mono_wasm_try_unbox_primitive_and_get_type (root.value, BINDING._unbox_buffer); switch (type) { - case 1: // int + case CPrimativeTypes.Int: return Module.HEAP32[BINDING._unbox_buffer / 4]; - case 25: // uint32 + case CPrimativeTypes.UInt32: return Module.HEAPU32[BINDING._unbox_buffer / 4]; - case 24: // float32 + case CPrimativeTypes.Float32: return Module.HEAPF32[BINDING._unbox_buffer / 4]; - case 2: // float64 + case CPrimativeTypes.Float64: return Module.HEAPF64[BINDING._unbox_buffer / 8]; - case 8: // boolean + case CPrimativeTypes.Bool: return (Module.HEAP32[BINDING._unbox_buffer / 4]) !== 0; - case 28: // char + case CPrimativeTypes.Char: return String.fromCharCode(Module.HEAP32[BINDING._unbox_buffer / 4]); default: return BINDING._unbox_mono_obj_root_with_known_nonprimitive_type (root, type); } }, - create_task_completion_source: function () { + create_task_completion_source: function (): number { return BINDING.call_method (BINDING.create_tcs, null, "i", [ -1 ]); }, - set_task_result: function (tcs, result) { + set_task_result: function (tcs, result: string): void { tcs.is_mono_tcs_result_set = true; BINDING.call_method (BINDING.set_tcs_result, null, "oo", [ tcs, result ]); if (tcs.is_mono_tcs_task_bound) BINDING.free_task_completion_source(tcs); }, - set_task_failure: function (tcs, reason) { + set_task_failure: function (tcs, reason): void { tcs.is_mono_tcs_result_set = true; BINDING.call_method (BINDING.set_tcs_failure, null, "os", [ tcs, reason.toString () ]); if (tcs.is_mono_tcs_task_bound) @@ -497,7 +502,7 @@ var BindingSupportLib = { }, // https://github.com/Planeshifter/emscripten-examples/blob/master/01_PassingArrays/sum_post.js - js_typedarray_to_heap: function(typedArray){ + js_typedarray_to_heap: function(typedArray): Uint8Array { var numBytes = typedArray.length * typedArray.BYTES_PER_ELEMENT; var ptr = Module._malloc(numBytes); var heapBytes = new Uint8Array(Module.HEAPU8.buffer, ptr, numBytes); @@ -505,27 +510,27 @@ var BindingSupportLib = { return heapBytes; }, - _box_js_int: function (js_obj) { + _box_js_int: function (js_obj: number): number { Module.HEAP32[BINDING._box_buffer / 4] = js_obj; return BINDING.mono_wasm_box_primitive (BINDING._class_int32, BINDING._box_buffer, 4); }, - _box_js_uint: function (js_obj) { + _box_js_uint: function (js_obj: number): number { Module.HEAPU32[BINDING._box_buffer / 4] = js_obj; return BINDING.mono_wasm_box_primitive (BINDING._class_uint32, BINDING._box_buffer, 4); }, - _box_js_double: function (js_obj) { + _box_js_double: function (js_obj: number): number { Module.HEAPF64[BINDING._box_buffer / 8] = js_obj; return BINDING.mono_wasm_box_primitive (BINDING._class_double, BINDING._box_buffer, 8); }, - _box_js_bool: function (js_obj) { + _box_js_bool: function (js_obj: boolean): number { Module.HEAP32[BINDING._box_buffer / 4] = js_obj ? 1 : 0; return BINDING.mono_wasm_box_primitive (BINDING._class_boolean, BINDING._box_buffer, 4); }, - js_to_mono_obj: function (js_obj) { + js_to_mono_obj: function (js_obj: any): any { BINDING.bindings_lazy_init (); // determines if the javascript object is a Promise or Promise like which can happen @@ -584,7 +589,7 @@ var BindingSupportLib = { return BINDING.extract_mono_obj (js_obj); } }, - js_to_mono_uri: function (js_obj) { + js_to_mono_uri: function (js_obj: any): any { BINDING.bindings_lazy_init (); switch (true) { @@ -630,7 +635,7 @@ var BindingSupportLib = { }, // Copy the existing typed array to the heap pointed to by the pinned array address // typed array memory -> copy to heap -> address of managed pinned array - typedarray_copy_to : function (typed_array, pinned_array, begin, end, bytes_per_element) { + typedarray_copy_to : function (typed_array, pinned_array, begin, end, bytes_per_element): number { // JavaScript typed arrays are array-like objects and provide a mechanism for accessing // raw binary data. (...) To achieve maximum flexibility and efficiency, JavaScript typed arrays @@ -673,7 +678,7 @@ var BindingSupportLib = { }, // Copy the pinned array address from pinned_array allocated on the heap to the typed array. // adress of managed pinned array -> copy from heap -> typed array memory - typedarray_copy_from : function (typed_array, pinned_array, begin, end, bytes_per_element) { + typedarray_copy_from : function (typed_array, pinned_array, begin, end, bytes_per_element): number { // JavaScript typed arrays are array-like objects and provide a mechanism for accessing // raw binary data. (...) To achieve maximum flexibility and efficiency, JavaScript typed arrays @@ -714,38 +719,38 @@ var BindingSupportLib = { }, // Creates a new typed array from pinned array address from pinned_array allocated on the heap to the typed array. // adress of managed pinned array -> copy from heap -> typed array memory - typed_array_from : function (pinned_array, begin, end, bytes_per_element, type) { + typed_array_from : function (pinned_array, begin: number, end: number, bytes_per_element: number, type: number): ArrayBuffer { // typed array var newTypedArray: ArrayBuffer; switch (type) { - case 5: + case JSTypedArrays.Int8Array: newTypedArray = new Int8Array(end - begin); break; - case 6: + case JSTypedArrays.Uint8Array: newTypedArray = new Uint8Array(end - begin); break; - case 7: + case JSTypedArrays.Int16Array: newTypedArray = new Int16Array(end - begin); break; - case 8: + case JSTypedArrays.Uint16Array: newTypedArray = new Uint16Array(end - begin); break; - case 9: + case JSTypedArrays.Int32Array: newTypedArray = new Int32Array(end - begin); break; - case 10: + case JSTypedArrays.Uint32Array: newTypedArray = new Uint32Array(end - begin); break; - case 13: + case JSTypedArrays.Float32Array: newTypedArray = new Float32Array(end - begin); break; - case 14: + case JSTypedArrays.Float64Array: newTypedArray = new Float64Array(end - begin); break; - case 15: // This is a special case because the typed array is also byte[] + case JSTypedArrays.Uint8ClampedArray: // This is a special case because the typed array is also byte[] newTypedArray = new Uint8ClampedArray(end - begin); break; } @@ -1072,19 +1077,19 @@ var BindingSupportLib = { var heapArrayName = null; switch (step.indirect) { - case "u32": + case ConverterStepIndirects.UInt32: heapArrayName = "HEAPU32"; break; - case "i32": + case ConverterStepIndirects.Int32: heapArrayName = "HEAP32"; break; - case "float": + case ConverterStepIndirects.Float: heapArrayName = "HEAPF32"; break; - case "double": + case ConverterStepIndirects.Float64: body.push (`Module.HEAPF64[indirect64 + ${(indirectLocalOffset / 8)}] = ${valueKey};`); break; - case "i64": + case ConverterStepIndirects.Int64: body.push (`Module.setValue (indirectStart + ${indirectLocalOffset}, ${valueKey}, 'i64');`); break; default: diff --git a/src/mono/wasm/runtime/library-mono.ts b/src/mono/wasm/runtime/library-mono.ts index 55244b0e4238f..c15e68f8d1bd6 100644 --- a/src/mono/wasm/runtime/library-mono.ts +++ b/src/mono/wasm/runtime/library-mono.ts @@ -912,16 +912,16 @@ var MonoSupportLib = { var offset = null; switch (asset.behavior) { - case "resource": - case "assembly": + case AssetBehaviours.Resource: + case AssetBehaviours.Assembly: ctx.loaded_files.push ({ url: url, file: virtualName}); - case "heap": - case "icu": + case AssetBehaviours.Heap: + case AssetBehaviours.ICU: offset = MONO.mono_wasm_load_bytes_into_heap (bytes); ctx.loaded_assets[virtualName] = [offset, bytes.length]; break; - case "vfs": + case AssetBehaviours.VFS: // FIXME var lastSlash = virtualName.lastIndexOf("/"); var parentDirectory = (lastSlash > 0) @@ -958,7 +958,7 @@ var MonoSupportLib = { throw new Error (`Unrecognized asset behavior: ${asset.behavior} for asset ${asset.name}`); } - if (asset.behavior === "assembly") { + if (asset.behavior === AssetBehaviours.Assembly) { var hasPpdb = ctx.mono_wasm_add_assembly (virtualName, offset, bytes.length); if (!hasPpdb) { @@ -966,13 +966,13 @@ var MonoSupportLib = { ctx.loaded_files.splice(index, 1); } } - else if (asset.behavior === "icu") { + else if (asset.behavior === AssetBehaviours.ICU) { if (MONO.mono_wasm_load_icu_data (offset)) ctx.num_icu_assets_loaded_successfully += 1; else console.error ("Error loading ICU asset", asset.name); } - else if (asset.behavior === "resource") { + else if (asset.behavior === AssetBehaviours.Resource) { ctx.mono_wasm_add_satellite_assembly (virtualName, asset.culture, offset, bytes.length); } }, diff --git a/src/mono/wasm/runtime/types/Module.d.ts b/src/mono/wasm/runtime/types/Module.d.ts index f50efae7b3152..029270f63fb5e 100644 --- a/src/mono/wasm/runtime/types/Module.d.ts +++ b/src/mono/wasm/runtime/types/Module.d.ts @@ -66,7 +66,7 @@ type MonoConfig = { // Types of assets that can be in the mono-config.js/mono-config.json file (taken from /src/tasks/WasmAppBuilder/WasmAppBuilder.cs) type AssetEntry = { - behavior: string, + behavior: AssetBehaviours, name: string } @@ -88,3 +88,12 @@ interface IcuData extends AssetEntry { name: "icu", load_remote: boolean } + +// Note that since these are annoated as `declare const enum` they are replaces by tsc with their raw value during compilation +declare const enum AssetBehaviours { + Resource = "resource", + Assembly = "assembly", + Heap = "heap", + ICU = "icu", + VFS = "vfs", +} diff --git a/src/mono/wasm/runtime/types/binding-types.d.ts b/src/mono/wasm/runtime/types/binding-types.d.ts index 3dbc5da3afc0b..6819901d6f84a 100644 --- a/src/mono/wasm/runtime/types/binding-types.d.ts +++ b/src/mono/wasm/runtime/types/binding-types.d.ts @@ -54,7 +54,7 @@ interface BINDING_VARS { _interned_string_full_root_buffers: WasmRootBuffer[]; _interned_string_current_root_buffer: WasmRootBuffer; _interned_string_current_root_buffer_count: number; - _interned_js_string_table: Map; + _interned_js_string_table: Map; _method_descriptions: Map; _signature_converters: Map; _primitive_converters: Map; @@ -84,7 +84,12 @@ declare var BINDING: typeof BindingSupportLib.$BINDING & BINDING_C_FUNCS & BINDI // OTHER TYPES /////////////////////////////////////////////////////////////////////// type Converter = { - steps: any[]; + steps: { + convert: boolean; + needs_root: boolean; + indirect: ConverterStepIndirects; + size: number; + }[]; size: number; args_marshal?: any; is_result_definitely_unmarshaled?: boolean; @@ -98,3 +103,49 @@ type Converter = { scratchRootBuffer?: any; scratchBuffer?: any; } + +// Note that since these are annoated as `declare const enum` they are replaces by tsc with their raw value during compilation +declare const enum ConverterStepIndirects { + UInt32 = "u32", + Int32 = "i32", + Float = "float", + Float64 = "double", + Int64 = "i64", +} + +declare const enum CNonPrimativeTypes { + String = 3, + VTS = 4, // throws errors due to "no idea on how to unbox value types" + Delegate = 5, + Task = 6, + Ref = 7, + DateTime = 20, + DateTimeOffset = 21, + Uri = 22, + SafeHandle = 23, + Int64 = 26, // TODO: Fix this once emscripten offers HEAPI64/HEAPU64 or can return them, currently throws an error + UInt64 = 27, // TODO: Fix this once emscripten offers HEAPI64/HEAPU64 or can return them, currently throws an error + Char = 29, + Undefined = 30 +} + +declare const enum CPrimativeTypes { + Int = 1, + Float64 = 2, + Bool = 8, + Float32 = 24, + UInt32 = 25, + Char = 28 +} + +declare const enum JSTypedArrays { + Int8Array = 5, + Uint8Array = 6, + Int16Array = 7, + Uint16Array = 8, + Int32Array = 9, + Uint32Array = 10, + Float32Array = 13, + Float64Array = 14, + Uint8ClampedArray = 15, +} diff --git a/src/mono/wasm/wasm.proj b/src/mono/wasm/wasm.proj index 351b4a11aec35..30f5ad6f04762 100644 --- a/src/mono/wasm/wasm.proj +++ b/src/mono/wasm/wasm.proj @@ -141,7 +141,7 @@ DependsOnTargets="GenerateEmccPropsAndRspFiles;BuildPInvokeTable;BundleTimeZones"> - + From 6bdfd80fd5599cf9f83d2748810cf2acb2d80106 Mon Sep 17 00:00:00 2001 From: Daniel-Genkin Date: Tue, 20 Jul 2021 16:15:27 -0400 Subject: [PATCH 11/19] Added a TON of types to binding-suppoprt.ts + Fixed windows build on CI --- src/mono/wasm/runtime/binding-support.ts | 184 ++++++++---------- src/mono/wasm/runtime/dotnet-support.ts | 6 +- src/mono/wasm/runtime/library-mono.ts | 32 +-- src/mono/wasm/runtime/types/Module.d.ts | 2 +- .../wasm/runtime/types/binding-types.d.ts | 46 ++++- src/mono/wasm/runtime/types/mono-types.d.ts | 7 + src/mono/wasm/wasm.proj | 2 +- 7 files changed, 154 insertions(+), 125 deletions(-) diff --git a/src/mono/wasm/runtime/binding-support.ts b/src/mono/wasm/runtime/binding-support.ts index 6e13c09d24efa..8351cd7ad4a5a 100644 --- a/src/mono/wasm/runtime/binding-support.ts +++ b/src/mono/wasm/runtime/binding-support.ts @@ -15,7 +15,7 @@ var BindingSupportLib = { BINDING.BINDING_ASM = binding_asm; }, - export_functions: function (module: object): void { + export_functions: function (module: typeof Module): void { module ["mono_bindings_init"] = BINDING.mono_bindings_init.bind(BINDING); module ["mono_bind_method"] = BINDING.bind_method.bind(BINDING); module ["mono_method_invoke"] = BINDING.call_method.bind(BINDING); @@ -112,7 +112,7 @@ var BindingSupportLib = { return res; }; - var bind_runtime_method = function (method_name: string, signature: string): Function { + var bind_runtime_method = function (method_name: string, signature: ArgsMarshalString): Function { var method = get_method (method_name); return BINDING.bind_method (method, 0, signature, "BINDINGS_" + method_name); }; @@ -366,7 +366,7 @@ var BindingSupportLib = { } }, - _unbox_delegate_root: function (root) { + _unbox_delegate_root: function (root: WasmRoot): () => number { var obj = BINDING.extract_js_obj_root (root); obj.__mono_delegate_alive__ = true; // FIXME: Should we root the object as long as this function has not been GCd? @@ -376,7 +376,7 @@ var BindingSupportLib = { }; }, - _unbox_task_root: function (root) { + _unbox_task_root: function (root: WasmRoot): Promise { if (!BINDING._are_promises_supported) throw new Error ("Promises are not supported thus 'System.Threading.Tasks.Task' can not work in this context."); @@ -411,7 +411,7 @@ var BindingSupportLib = { }, /** @returns return type is determined by the type parameter */ - _unbox_mono_obj_root_with_known_nonprimitive_type: function (root: WasmRoot, type: number): any { + _unbox_mono_obj_root_with_known_nonprimitive_type: function (root: WasmRoot, type: CNonPrimativeTypes): any { if (root.value === undefined) throw new Error(`Expected a root but got ${root}`); @@ -432,15 +432,15 @@ var BindingSupportLib = { return BINDING._unbox_task_root (root); case CNonPrimativeTypes.Ref: return BINDING.extract_js_obj_root (root); - case 10: // arrays - case 11: - case 12: - case 13: - case 14: - case 15: - case 16: - case 17: - case 18: + case CNonPrimativeTypes.Int8Array: + case CNonPrimativeTypes.Uint8Array: + case CNonPrimativeTypes.Uint8ClampedArray: + case CNonPrimativeTypes.Int16Array: + case CNonPrimativeTypes.UInt16Array: + case CNonPrimativeTypes.Int32Array: + case CNonPrimativeTypes.UInt32Array: + case CNonPrimativeTypes.Float32Array: + case CNonPrimativeTypes.Float64Array: throw new Error ("Marshalling of primitive arrays are not supported. Use the corresponding TypedArray instead."); case CNonPrimativeTypes.DateTime: // clr .NET DateTime var dateValue = BINDING.call_method(BINDING.get_date_value, null, "m", [ root.value ]); @@ -530,7 +530,7 @@ var BindingSupportLib = { return BINDING.mono_wasm_box_primitive (BINDING._class_boolean, BINDING._box_buffer, 4); }, - js_to_mono_obj: function (js_obj: any): any { + js_to_mono_obj: function (js_obj: any): number { BINDING.bindings_lazy_init (); // determines if the javascript object is a Promise or Promise like which can happen @@ -589,7 +589,7 @@ var BindingSupportLib = { return BINDING.extract_mono_obj (js_obj); } }, - js_to_mono_uri: function (js_obj: any): any { + js_to_mono_uri: function (js_obj: any): number { BINDING.bindings_lazy_init (); switch (true) { @@ -603,13 +603,13 @@ var BindingSupportLib = { return BINDING.extract_mono_obj (js_obj); } }, - has_backing_array_buffer: function (js_obj) { + has_backing_array_buffer: function (js_obj): boolean { return typeof SharedArrayBuffer !== 'undefined' ? js_obj.buffer instanceof ArrayBuffer || js_obj.buffer instanceof SharedArrayBuffer : js_obj.buffer instanceof ArrayBuffer; }, - js_typed_array_to_array : function (js_obj) { + js_typed_array_to_array : function (js_obj): number { // JavaScript typed arrays are array-like objects and provide a mechanism for accessing // raw binary data. (...) To achieve maximum flexibility and efficiency, JavaScript typed arrays @@ -635,7 +635,7 @@ var BindingSupportLib = { }, // Copy the existing typed array to the heap pointed to by the pinned array address // typed array memory -> copy to heap -> address of managed pinned array - typedarray_copy_to : function (typed_array, pinned_array, begin, end, bytes_per_element): number { + typedarray_copy_to : function (typed_array, pinned_array: number, begin: number, end: number, bytes_per_element: number): number { // JavaScript typed arrays are array-like objects and provide a mechanism for accessing // raw binary data. (...) To achieve maximum flexibility and efficiency, JavaScript typed arrays @@ -678,7 +678,7 @@ var BindingSupportLib = { }, // Copy the pinned array address from pinned_array allocated on the heap to the typed array. // adress of managed pinned array -> copy from heap -> typed array memory - typedarray_copy_from : function (typed_array, pinned_array, begin, end, bytes_per_element): number { + typedarray_copy_from : function (typed_array, pinned_array: number, begin: number, end: number, bytes_per_element: number): number { // JavaScript typed arrays are array-like objects and provide a mechanism for accessing // raw binary data. (...) To achieve maximum flexibility and efficiency, JavaScript typed arrays @@ -719,7 +719,7 @@ var BindingSupportLib = { }, // Creates a new typed array from pinned array address from pinned_array allocated on the heap to the typed array. // adress of managed pinned array -> copy from heap -> typed array memory - typed_array_from : function (pinned_array, begin: number, end: number, bytes_per_element: number, type: number): ArrayBuffer { + typed_array_from: function (pinned_array, begin: number, end: number, bytes_per_element: number, type: JSTypedArrays): ArrayBuffer { // typed array var newTypedArray: ArrayBuffer; @@ -758,7 +758,7 @@ var BindingSupportLib = { BINDING.typedarray_copy_from(newTypedArray, pinned_array, begin, end, bytes_per_element); return newTypedArray; }, - js_to_mono_enum: function (js_obj, method, parmIdx) { + js_to_mono_enum: function (js_obj, method?: any/* todo unused var */, parmIdx?: any /* todo unused var */): number { BINDING.bindings_lazy_init (); if (typeof (js_obj) !== "number") @@ -766,16 +766,16 @@ var BindingSupportLib = { return js_obj | 0; }, - wasm_binding_obj_new: function (js_obj_id, ownsHandle, type) + wasm_binding_obj_new: function (js_obj_id, ownsHandle, type): Function { return BINDING._bind_js_obj (js_obj_id, ownsHandle, type); }, - wasm_bind_existing: function (mono_obj, js_id) + wasm_bind_existing: function (mono_obj, js_id): Function { return BINDING._bind_existing_obj (mono_obj, js_id); }, - wasm_bind_core_clr_obj: function (js_id, gc_handle) + wasm_bind_core_clr_obj: function (js_id, gc_handle): Function { return BINDING._bind_core_clr_obj (js_id, gc_handle); }, @@ -796,13 +796,13 @@ var BindingSupportLib = { return BINDING._get_raw_mono_obj (gchandle, should_add_in_flight ? 1 : 0); }, - try_extract_mono_obj:function (js_obj) { + try_extract_mono_obj: function (js_obj) { if (js_obj === null || typeof js_obj === "undefined" || typeof js_obj.__mono_gchandle__ === "undefined") return 0; return BINDING.wasm_get_raw_obj (js_obj.__mono_gchandle__, true); }, - mono_method_get_call_signature: function(method, mono_obj): number { + mono_method_get_call_signature: function(method: number, mono_obj): number { let instanceRoot = MONO.mono_wasm_new_root (mono_obj); try { BINDING.bindings_lazy_init (); @@ -872,7 +872,7 @@ var BindingSupportLib = { } }, - extract_js_obj_root: function (root) { + extract_js_obj_root: function (root: WasmRoot) { if (root.value === 0) return null; @@ -890,7 +890,7 @@ var BindingSupportLib = { return js_obj; }, - _create_named_function: function (name, argumentNames, body, closure): any { + _create_named_function: function (name: string, argumentNames, body: string, closure): any { var result = null, keys = null, closureArgumentList = null, closureArgumentNames = null; if (closure) { @@ -906,7 +906,7 @@ var BindingSupportLib = { return result; }, - _create_rebindable_named_function: function (name, argumentNames, body, closureArgNames): any { + _create_rebindable_named_function: function (name: string, argumentNames, body: string, closureArgNames): any { var strictPrefix = "\"use strict\";\r\n"; var uriPrefix = "", escapedFunctionIdentifier = ""; @@ -942,7 +942,7 @@ var BindingSupportLib = { return result; }, - _create_primitive_converters: function () { + _create_primitive_converters: function (): Map { var result = new Map (); result.set ('m', { steps: [{ }], size: 0}); result.set ('s', { steps: [{ convert: BINDING.js_string_to_mono_string.bind (this) }], size: 0, needs_root: true }); @@ -951,18 +951,18 @@ var BindingSupportLib = { result.set ('u', { steps: [{ convert: BINDING.js_to_mono_uri.bind (this) }], size: 0, needs_root: true }); // result.set ('k', { steps: [{ convert: BINDING.js_to_mono_enum.bind (this), indirect: 'i64'}], size: 8}); - result.set ('j', { steps: [{ convert: BINDING.js_to_mono_enum.bind (this), indirect: 'i32'}], size: 8}); + result.set ('j', { steps: [{ convert: BINDING.js_to_mono_enum.bind (this), indirect: ConverterStepIndirects.Int32}], size: 8}); - result.set ('i', { steps: [{ indirect: 'i32'}], size: 8}); - result.set ('l', { steps: [{ indirect: 'i64'}], size: 8}); - result.set ('f', { steps: [{ indirect: 'float'}], size: 8}); - result.set ('d', { steps: [{ indirect: 'double'}], size: 8}); + result.set ('i', { steps: [{ indirect: ConverterStepIndirects.Int32}], size: 8}); + result.set ('l', { steps: [{ indirect: ConverterStepIndirects.Int64}], size: 8}); + result.set ('f', { steps: [{ indirect: ConverterStepIndirects.Float}], size: 8}); + result.set ('d', { steps: [{ indirect: ConverterStepIndirects.Float64}], size: 8}); BINDING._primitive_converters = result; return result; }, - _create_converter_for_marshal_string: function (args_marshal) { + _create_converter_for_marshal_string: function (args_marshal: ArgsMarshalString): Converter { var primitiveConverters = BINDING._primitive_converters; if (!primitiveConverters) primitiveConverters = BINDING._create_primitive_converters (); @@ -1011,7 +1011,7 @@ var BindingSupportLib = { }; }, - _get_converter_for_marshal_string: function (args_marshal) { + _get_converter_for_marshal_string: function (args_marshal: ArgsMarshalString): Converter { if (!BINDING._signature_converters) BINDING._signature_converters = new Map(); @@ -1024,7 +1024,7 @@ var BindingSupportLib = { return converter; }, - _compile_converter_for_marshal_string: function (args_marshal) { + _compile_converter_for_marshal_string: function (args_marshal: ArgsMarshalString): Converter { var converter = BINDING._get_converter_for_marshal_string (args_marshal); if (typeof (converter.args_marshal) !== "string") throw new Error ("Corrupt converter for '" + args_marshal + "'"); @@ -1157,7 +1157,7 @@ var BindingSupportLib = { return converter; }, - _verify_args_for_method_call: function (args_marshal, args) { + _verify_args_for_method_call: function (args_marshal: ArgsMarshalString, args: any[]): boolean { var has_args = args && (typeof args === "object") && args.length > 0; var has_args_marshal = typeof args_marshal === "string"; @@ -1171,7 +1171,7 @@ var BindingSupportLib = { return has_args_marshal && has_args; }, - _get_buffer_for_method_call: function (converter) { + _get_buffer_for_method_call: function (converter: Converter): number { if (!converter) return 0; @@ -1180,7 +1180,7 @@ var BindingSupportLib = { return result; }, - _get_args_root_buffer_for_method_call: function (converter) { + _get_args_root_buffer_for_method_call: function (converter: Converter): WasmRootBuffer | null { if (!converter) return null; @@ -1202,7 +1202,7 @@ var BindingSupportLib = { return result; }, - _release_args_root_buffer_from_method_call: function (converter, argsRootBuffer) { + _release_args_root_buffer_from_method_call: function (converter: Converter, argsRootBuffer): void { if (!argsRootBuffer || !converter) return; @@ -1215,7 +1215,7 @@ var BindingSupportLib = { } }, - _release_buffer_from_method_call: function (converter, buffer) { + _release_buffer_from_method_call: function (converter: Converter, buffer: number): void { if (!converter || !buffer) return; @@ -1225,7 +1225,7 @@ var BindingSupportLib = { Module._free (buffer | 0); }, - _convert_exception_for_method_call: function (result, exception) { + _convert_exception_for_method_call: function (result: number, exception: number): Error | null { if (exception === 0) return null; @@ -1235,7 +1235,7 @@ var BindingSupportLib = { return err; }, - _maybe_produce_signature_warning: function (converter) { + _maybe_produce_signature_warning: function (converter: Converter): void { if (converter.has_warned_about_signature) return; @@ -1243,7 +1243,7 @@ var BindingSupportLib = { converter.has_warned_about_signature = true; }, - _decide_if_result_is_marshaled: function (converter, argc) { + _decide_if_result_is_marshaled: function (converter: Converter, argc: number): boolean { if (!converter) return true; @@ -1264,21 +1264,7 @@ var BindingSupportLib = { } }, - /* - args_marshal is a string with one character per parameter that tells how to marshal it, here are the valid values: - i: int32 - j: int32 - Enum with underlying type of int32 - l: int64 - k: int64 - Enum with underlying type of int64 - f: float - d: double - s: string - S: interned string - o: js object will be converted to a C# object (this will box numbers/bool/promises) - m: raw mono object. Don't use it unless you know what you're doing - to suppress marshaling of the return value, place '!' at the end of args_marshal, i.e. 'ii!' instead of 'ii' - */ - call_method: function (method, this_arg, args_marshal, args): number { + call_method: function (method: number, this_arg, args_marshal: ArgsMarshalString, args: any[]): number { BINDING.bindings_lazy_init (); // HACK: Sometimes callers pass null or undefined, coerce it to 0 since that's what wasm expects @@ -1312,8 +1298,8 @@ var BindingSupportLib = { }, _handle_exception_for_call: function ( - converter, buffer, resultRoot, exceptionRoot, argsRootBuffer - ) { + converter: Converter, buffer, resultRoot, exceptionRoot, argsRootBuffer + ): void { var exc = BINDING._convert_exception_for_method_call (resultRoot.value, exceptionRoot.value); if (!exc) return; @@ -1323,7 +1309,7 @@ var BindingSupportLib = { }, _handle_exception_and_produce_result_for_call: function ( - converter, buffer, resultRoot, exceptionRoot, argsRootBuffer, is_result_marshaled + converter: Converter, buffer, resultRoot, exceptionRoot, argsRootBuffer, is_result_marshaled: boolean ): number { BINDING._handle_exception_for_call (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer); @@ -1336,7 +1322,7 @@ var BindingSupportLib = { return result; }, - _teardown_after_call: function (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer) { + _teardown_after_call: function (converter: Converter, buffer, resultRoot, exceptionRoot, argsRootBuffer): void { BINDING._release_args_root_buffer_from_method_call (converter, argsRootBuffer); BINDING._release_buffer_from_method_call (converter, buffer | 0); @@ -1346,7 +1332,7 @@ var BindingSupportLib = { exceptionRoot.release (); }, - _get_method_description: function (method) { + _get_method_description: function (method: number): string { if (!BINDING._method_descriptions) BINDING._method_descriptions = new Map(); @@ -1356,13 +1342,13 @@ var BindingSupportLib = { return result; }, - _call_method_with_converted_args: function (method, this_arg, converter, buffer, is_result_marshaled, argsRootBuffer): number { + _call_method_with_converted_args: function (method: number, this_arg, converter, buffer, is_result_marshaled: boolean, argsRootBuffer): number { var resultRoot = MONO.mono_wasm_new_root (), exceptionRoot = MONO.mono_wasm_new_root (); resultRoot.value = BINDING.invoke_method (method, this_arg, buffer, exceptionRoot.get_address ()); return BINDING._handle_exception_and_produce_result_for_call (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer, is_result_marshaled); }, - bind_method: function (method, this_arg, args_marshal, friendly_name) { + bind_method: function (method: number, this_arg, args_marshal: ArgsMarshalString, friendly_name: string): Function { BINDING.bindings_lazy_init (); this_arg = this_arg | 0; @@ -1484,7 +1470,7 @@ var BindingSupportLib = { return BINDING._create_named_function(displayName, argumentNames, bodyJs, closure); }, - invoke_delegate: function (delegate_obj, js_args) { + invoke_delegate: function (delegate_obj, js_args): number { BINDING.bindings_lazy_init (); // Check to make sure the delegate is still alive on the CLR side of things. @@ -1495,7 +1481,7 @@ var BindingSupportLib = { // at a point where we've already disposed of the object the event handler is attached to. // As such, we log here instead of throwing an error. We may want to not log at all... console.log("The delegate target that is being invoked is no longer available. Please check if it has been prematurely GC'd."); - return; + return; // TODO make this some number output } } @@ -1515,7 +1501,7 @@ var BindingSupportLib = { } }, - resolve_method_fqn: function (fqn) { + resolve_method_fqn: function (fqn: string): number { BINDING.bindings_lazy_init (); var assembly = fqn.substring(fqn.indexOf ("[") + 1, fqn.indexOf ("]")).trim(); @@ -1553,7 +1539,7 @@ var BindingSupportLib = { return method; }, - call_static_method: function (fqn: string, args: any[] | null, signature: string | null) { + call_static_method: function (fqn: string, args: any[] | null, signature: ArgsMarshalString | null): number { BINDING.bindings_lazy_init (); var method = BINDING.resolve_method_fqn (fqn); @@ -1564,7 +1550,7 @@ var BindingSupportLib = { return BINDING.call_method (method, null, signature, args); }, - bind_static_method: function (fqn, signature) { + bind_static_method: function (fqn: string, signature: ArgsMarshalString): Function { BINDING.bindings_lazy_init (); var method = BINDING.resolve_method_fqn (fqn); @@ -1575,7 +1561,7 @@ var BindingSupportLib = { return BINDING.bind_method (method, null, signature, fqn); }, - bind_assembly_entry_point: function (assembly, signature): (...args: any) => Promise { + bind_assembly_entry_point: function (assembly: string, signature: ArgsMarshalString): (...args: any) => Promise { BINDING.bindings_lazy_init (); var asm = BINDING.assembly_load (assembly); @@ -1601,7 +1587,7 @@ var BindingSupportLib = { } }; }, - call_assembly_entry_point: function (assembly, args, signature) { + call_assembly_entry_point: function (assembly: string, args: any[], signature: ArgsMarshalString) { return BINDING.bind_assembly_entry_point (assembly, signature) (...args); }, // Object wrapping helper functions to handle reference handles that will @@ -1629,12 +1615,12 @@ var BindingSupportLib = { // this is pre-existing instance, we need to add Inflight strong GCHandle before passing it to managed return { gc_handle, should_add_in_flight: true }; }, - mono_wasm_require_handle: function(handle) { + mono_wasm_require_handle: function(handle: number) { if (handle > 0) return BINDING.mono_wasm_object_registry[handle - 1]; return null; }, - mono_wasm_unregister_obj: function(js_id) { + mono_wasm_unregister_obj: function(js_id: number) { var obj = BINDING.mono_wasm_object_registry[js_id - 1]; if (typeof obj !== "undefined" && obj !== null) { // if this is the global object then do not @@ -1663,7 +1649,7 @@ var BindingSupportLib = { mono_wasm_free_handle: function(handle) { BINDING.mono_wasm_unregister_obj(handle); }, - mono_wasm_free_raw_object: function(js_id) { + mono_wasm_free_raw_object: function(js_id: number) { var obj = BINDING.mono_wasm_object_registry[js_id - 1]; if (typeof obj !== "undefined" && obj !== null) { // if this is the global object then do not @@ -1683,17 +1669,17 @@ var BindingSupportLib = { } return obj; }, - mono_wasm_parse_args_root : function (argsRoot) { + mono_wasm_parse_args_root: function (argsRoot) { var js_args = BINDING._mono_array_root_to_js_array(argsRoot); BINDING.mono_wasm_save_LMF(); return js_args; }, - mono_wasm_save_LMF : function () { + mono_wasm_save_LMF: function (): void { //console.log("save LMF: " + BINDING.mono_wasm_owned_objects_frames.length) BINDING.mono_wasm_owned_objects_frames.push(BINDING.mono_wasm_owned_objects_LMF); BINDING.mono_wasm_owned_objects_LMF = undefined; }, - mono_wasm_unwind_LMF : function () { + mono_wasm_unwind_LMF: function (): void { var __owned_objects__ = BINDING.mono_wasm_owned_objects_frames.pop(); // Release all managed objects that are loaded into the LMF if (typeof __owned_objects__ !== "undefined") @@ -1709,13 +1695,13 @@ var BindingSupportLib = { //console.log("restore LMF: " + BINDING.mono_wasm_owned_objects_frames.length) }, - mono_wasm_convert_return_value: function (ret) { + mono_wasm_convert_return_value: function (ret): number { BINDING.mono_wasm_unwind_LMF(); return BINDING.js_to_mono_obj (ret); }, }, - mono_wasm_invoke_js_with_args: function(js_handle, method_name, args, is_exception) { + mono_wasm_invoke_js_with_args: function(js_handle, method_name, args, is_exception): number { let argsRoot = MONO.mono_wasm_new_root (args), nameRoot = MONO.mono_wasm_new_root (method_name); try { BINDING.bindings_lazy_init (); @@ -1755,7 +1741,7 @@ var BindingSupportLib = { nameRoot.release(); } }, - mono_wasm_get_object_property: function(js_handle, property_name, is_exception) { + mono_wasm_get_object_property: function(js_handle, property_name, is_exception): number { BINDING.bindings_lazy_init (); var nameRoot = MONO.mono_wasm_new_root (property_name); @@ -1790,7 +1776,7 @@ var BindingSupportLib = { nameRoot.release(); } }, - mono_wasm_set_object_property: function (js_handle, property_name, value, createIfNotExist, hasOwnProperty, is_exception) { + mono_wasm_set_object_property: function (js_handle, property_name, value, createIfNotExist, hasOwnProperty, is_exception): number | boolean { var valueRoot = MONO.mono_wasm_new_root (value), nameRoot = MONO.mono_wasm_new_root (property_name); try { BINDING.bindings_lazy_init (); @@ -1841,7 +1827,7 @@ var BindingSupportLib = { valueRoot.release(); } }, - mono_wasm_get_by_index: function(js_handle, property_index, is_exception) { + mono_wasm_get_by_index: function(js_handle, property_index, is_exception): number { BINDING.bindings_lazy_init (); var obj = BINDING.mono_wasm_require_handle (js_handle); @@ -1861,7 +1847,7 @@ var BindingSupportLib = { return BINDING.js_string_to_mono_string (res); } }, - mono_wasm_set_by_index: function(js_handle, property_index, value, is_exception) { + mono_wasm_set_by_index: function(js_handle, property_index, value, is_exception): number | boolean { var valueRoot = MONO.mono_wasm_new_root (value); try { BINDING.bindings_lazy_init (); @@ -1890,7 +1876,7 @@ var BindingSupportLib = { valueRoot.release(); } }, - mono_wasm_get_global_object: function(global_name, is_exception) { + mono_wasm_get_global_object: function(global_name, is_exception): number { var nameRoot = MONO.mono_wasm_new_root (global_name); try { BINDING.bindings_lazy_init (); @@ -1916,17 +1902,17 @@ var BindingSupportLib = { nameRoot.release(); } }, - mono_wasm_release_handle: function(js_handle, is_exception) { + mono_wasm_release_handle: function(js_handle: number, is_exception?: any /* unused var */): void { BINDING.bindings_lazy_init (); BINDING.mono_wasm_free_handle(js_handle); }, - mono_wasm_release_object: function(js_handle, is_exception) { + mono_wasm_release_object: function(js_handle: number, is_exception?: any /* unused var */): void { BINDING.bindings_lazy_init (); BINDING.mono_wasm_free_raw_object(js_handle); }, - mono_wasm_bind_core_object: function(js_handle, gc_handle, is_exception) { + mono_wasm_bind_core_object: function(js_handle: number, gc_handle: number, is_exception): number { BINDING.bindings_lazy_init (); var requireObject = BINDING.mono_wasm_require_handle (js_handle); @@ -1935,12 +1921,12 @@ var BindingSupportLib = { return BINDING.js_string_to_mono_string ("Invalid JS object handle '" + js_handle + "'"); } - BINDING.wasm_bind_core_clr_obj(js_handle, gc_handle ); + BINDING.wasm_bind_core_clr_obj(js_handle, gc_handle); requireObject.__mono_gchandle__ = gc_handle; requireObject.__js_handle__ = js_handle; return gc_handle; }, - mono_wasm_bind_host_object: function(js_handle, gc_handle, is_exception) { + mono_wasm_bind_host_object: function(js_handle: number, gc_handle: number, is_exception): number { BINDING.bindings_lazy_init (); var requireObject = BINDING.mono_wasm_require_handle (js_handle); @@ -1953,7 +1939,7 @@ var BindingSupportLib = { requireObject.__mono_gchandle__ = gc_handle; return gc_handle; }, - mono_wasm_new: function (core_name, args, is_exception) { + mono_wasm_new: function (core_name, args, is_exception): number { var argsRoot = MONO.mono_wasm_new_root (args), nameRoot = MONO.mono_wasm_new_root (core_name); try { BINDING.bindings_lazy_init (); @@ -2005,7 +1991,7 @@ var BindingSupportLib = { } }, - mono_wasm_typed_array_to_array: function(js_handle, is_exception) { + mono_wasm_typed_array_to_array: function(js_handle: number, is_exception) { BINDING.bindings_lazy_init (); var requireObject = BINDING.mono_wasm_require_handle (js_handle); @@ -2016,7 +2002,7 @@ var BindingSupportLib = { return BINDING.js_typed_array_to_array(requireObject); }, - mono_wasm_typed_array_copy_to: function(js_handle, pinned_array, begin, end, bytes_per_element, is_exception) { + mono_wasm_typed_array_copy_to: function(js_handle: number, pinned_array: number, begin: number, end: number, bytes_per_element: number, is_exception): number { BINDING.bindings_lazy_init (); var requireObject = BINDING.mono_wasm_require_handle (js_handle); @@ -2028,12 +2014,12 @@ var BindingSupportLib = { var res = BINDING.typedarray_copy_to(requireObject, pinned_array, begin, end, bytes_per_element); return BINDING.js_to_mono_obj (res) }, - mono_wasm_typed_array_from: function(pinned_array, begin, end, bytes_per_element, type, is_exception) { + mono_wasm_typed_array_from: function(pinned_array: number, begin: number, end: number, bytes_per_element: number, type, is_exception): number { BINDING.bindings_lazy_init (); var res = BINDING.typed_array_from(pinned_array, begin, end, bytes_per_element, type); return BINDING.js_to_mono_obj (res) }, - mono_wasm_typed_array_copy_from: function(js_handle, pinned_array, begin, end, bytes_per_element, is_exception) { + mono_wasm_typed_array_copy_from: function(js_handle: number, pinned_array: number, begin: number, end: number, bytes_per_element: number, is_exception): number { BINDING.bindings_lazy_init (); var requireObject = BINDING.mono_wasm_require_handle (js_handle); diff --git a/src/mono/wasm/runtime/dotnet-support.ts b/src/mono/wasm/runtime/dotnet-support.ts index c7501cc173945..24967568d4b32 100644 --- a/src/mono/wasm/runtime/dotnet-support.ts +++ b/src/mono/wasm/runtime/dotnet-support.ts @@ -7,7 +7,7 @@ var DotNetSupportLib = { return MONO.string_decoder.copy (mono_obj); } }, - mono_wasm_invoke_js_blazor: function (exceptionMessage, callInfo, arg0, arg1, arg2) { + mono_wasm_invoke_js_blazor: function (exceptionMessage: number, callInfo, arg0, arg1, arg2) { var mono_string = globalThis._mono_string_cached || (globalThis._mono_string_cached = Module.cwrap('mono_wasm_string_from_js', 'number', ['string'])); @@ -27,7 +27,7 @@ var DotNetSupportLib = { }, // This is for back-compat only and will eventually be removed - mono_wasm_invoke_js_marshalled: function (exceptionMessage, asyncHandleLongPtr, functionName, argsJson, treatResultAsVoid) { + mono_wasm_invoke_js_marshalled: function (exceptionMessage: number, asyncHandleLongPtr, functionName, argsJson, treatResultAsVoid) { var mono_string = globalThis._mono_string_cached || (globalThis._mono_string_cached = Module.cwrap('mono_wasm_string_from_js', 'number', ['string'])); @@ -67,7 +67,7 @@ var DotNetSupportLib = { }, // This is for back-compat only and will eventually be removed - mono_wasm_invoke_js_unmarshalled: function (exceptionMessage, funcName, arg0, arg1, arg2) { + mono_wasm_invoke_js_unmarshalled: function (exceptionMessage: number, funcName, arg0, arg1, arg2) { try { // Get the function you're trying to invoke var funcNameJsString = DOTNET.conv_string(funcName); diff --git a/src/mono/wasm/runtime/library-mono.ts b/src/mono/wasm/runtime/library-mono.ts index c15e68f8d1bd6..5323527b17327 100644 --- a/src/mono/wasm/runtime/library-mono.ts +++ b/src/mono/wasm/runtime/library-mono.ts @@ -33,7 +33,7 @@ var MonoSupportLib = { } }, - export_functions: function (module) { + export_functions: function (module: typeof Module) { module ["pump_message"] = MONO.pump_message.bind(MONO); module ["mono_load_runtime_and_bcl"] = MONO.mono_load_runtime_and_bcl.bind(MONO); module ["mono_load_runtime_and_bcl_args"] = MONO.mono_load_runtime_and_bcl_args.bind(MONO); @@ -76,7 +76,7 @@ var MonoSupportLib = { '+', '/' ], - _makeByteReader: function (bytes, index, count) { + _makeByteReader: function (bytes: Uint8Array, index?: number, count?: number): ByteReader { var position = (typeof (index) === "number") ? index : 0; var endpoint; @@ -107,7 +107,7 @@ var MonoSupportLib = { return result; }, - toBase64StringImpl: function (inArray, offset?, length?) { + toBase64StringImpl: function (inArray: Uint8Array, offset?: number, length?: number): string { var reader = this._makeByteReader(inArray, offset, length); var result = ""; var ch1 = 0, ch2 = 0, ch3 = 0, bits = 0, equalsCount = 0, sum = 0; @@ -163,10 +163,10 @@ var MonoSupportLib = { }, _mono_wasm_root_buffer_prototype: { - _throw_index_out_of_range: function () { + _throw_index_out_of_range: function (): void { throw new Error ("index out of range"); }, - _check_in_range: function (index) { + _check_in_range: function (index: number): void { if ((index >= this.__count) || (index < 0)) this._throw_index_out_of_range(); }, @@ -182,21 +182,21 @@ var MonoSupportLib = { this._check_in_range (index); return Module.HEAP32[this.get_address_32 (index)]; }, - set: function (index, value) { + set: function (index: number, value: number): number { Module.HEAP32[this.get_address_32 (index)] = value; return value; }, - _unsafe_get: function (index) { + _unsafe_get: function (index: number): number { return Module.HEAP32[this.__offset32 + index]; }, - _unsafe_set: function (index, value) { + _unsafe_set: function (index: number, value: number): void { Module.HEAP32[this.__offset32 + index] = value; }, - clear: function () { + clear: function (): void { if (this.__offset) MONO._zero_region (this.__offset, this.__count * 4); }, - release: function () { + release: function (): void { if (this.__offset && this.__ownsAllocation) { MONO.mono_wasm_deregister_root (this.__offset); MONO._zero_region (this.__offset, this.__count * 4); @@ -205,7 +205,7 @@ var MonoSupportLib = { this.__handle = this.__offset = this.__count = this.__offset32 = 0; }, - toString: function () { + toString: function (): string { return "[root buffer @" + this.get_address (0) + ", size " + this.__count + "]"; } }, @@ -226,17 +226,17 @@ var MonoSupportLib = { var result = this.__buffer._unsafe_get (this.__index); return result; }, - set: function (value) { + set: function (value: number): number { this.__buffer._unsafe_set (this.__index, value); return value; }, valueOf: function (): ManagedPointer { return this.get (); }, - clear: function () { + clear: function (): void { this.set (0); }, - release: function () { + release: function (): void { const maxPooledInstances = 128; if (MONO._scratch_root_free_instances.length > maxPooledInstances) { MONO._mono_wasm_release_scratch_index (this.__index); @@ -247,12 +247,12 @@ var MonoSupportLib = { MONO._scratch_root_free_instances.push (this); } }, - toString: function () { + toString: function (): string { return "[root @" + this.get_address () + "]"; } }, - _mono_wasm_release_scratch_index: function (index) { + _mono_wasm_release_scratch_index: function (index: number): void { if (index === undefined) return; diff --git a/src/mono/wasm/runtime/types/Module.d.ts b/src/mono/wasm/runtime/types/Module.d.ts index 029270f63fb5e..ecf253c80fedd 100644 --- a/src/mono/wasm/runtime/types/Module.d.ts +++ b/src/mono/wasm/runtime/types/Module.d.ts @@ -39,7 +39,7 @@ declare namespace Module { function _free (amn: number): void; function addRunDependency(id: string): void; function removeRunDependency(id: string): void; - function mono_method_get_call_signature (method: any, mono_obj?: any): string; + function mono_method_get_call_signature (method: any, mono_obj?: any): ArgsMarshalString; function print (message: string): void; function ccall (ident: string, returnType?: string, argTypes?: string[], args?: any[] , opts?: any): T; diff --git a/src/mono/wasm/runtime/types/binding-types.d.ts b/src/mono/wasm/runtime/types/binding-types.d.ts index 6819901d6f84a..6d6d1f0a140e7 100644 --- a/src/mono/wasm/runtime/types/binding-types.d.ts +++ b/src/mono/wasm/runtime/types/binding-types.d.ts @@ -31,7 +31,7 @@ interface BINDING_C_FUNCS { mono_wasm_register_bundled_satellite_assemblies (): void; mono_wasm_string_array_new (a: number): number; mono_wasm_string_from_utf16 (a: number, b: number): number; - mono_wasm_try_unbox_primitive_and_get_type (a: number, b: number): number; + mono_wasm_try_unbox_primitive_and_get_type (a: number, b: number): CPrimativeTypes; mono_typed_array_new (a: number, b: number, c: number, d: number): number; } @@ -91,7 +91,7 @@ type Converter = { size: number; }[]; size: number; - args_marshal?: any; + args_marshal?: ArgsMarshalString; is_result_definitely_unmarshaled?: boolean; is_result_possibly_unmarshaled?: boolean; result_unmarshaled_if_argc?: number; @@ -100,8 +100,9 @@ type Converter = { needs_root?: boolean; compiled_variadic_function?: any; compiled_function?: any; - scratchRootBuffer?: any; - scratchBuffer?: any; + scratchRootBuffer?: WasmRootBuffer; + scratchBuffer?: number; + has_warned_about_signature?: boolean; } // Note that since these are annoated as `declare const enum` they are replaces by tsc with their raw value during compilation @@ -111,7 +112,33 @@ declare const enum ConverterStepIndirects { Float = "float", Float64 = "double", Int64 = "i64", -} +} + +declare const enum ArgsMarshal { + Int32 = "i", // int32 + Int32Enum = "j", // int32 - Enum with underlying type of int32 + Int64 = "l", // int64 + Int64Enum = "k", // int64 - Enum with underlying type of int64 + Float32 = "f", // float + Float64 = "d", // double + String = "s", // string + Char = "s", // interned string + JSObj = "o", // js object will be converted to a C# object (this will box numbers/bool/promises) + MONOObj = "m", // raw mono object. Don't use it unless you know what you're doing +} + +// to suppress marshaling of the return value, place '!' at the end of args_marshal, i.e. 'ii!' instead of 'ii' +type _ExtraArgsMarshalOperators = "!" | ""; + +// TODO make this more efficient so we can add more parameters (currently it only checks up to 4). One option is to add a +// blank to the ArgsMarshal enum but that doesn't solve the TS limit of number of options in 1 type +// Take the 2 marshaling enums and convert to all the valid strings for type checking. +type ArgsMarshalString = + `${ArgsMarshal}${_ExtraArgsMarshalOperators}` + | `${ArgsMarshal}${ArgsMarshal}${_ExtraArgsMarshalOperators}` + | `${ArgsMarshal}${ArgsMarshal}${ArgsMarshal}${_ExtraArgsMarshalOperators}` + | `${ArgsMarshal}${ArgsMarshal}${ArgsMarshal}${ArgsMarshal}${_ExtraArgsMarshalOperators}`; + declare const enum CNonPrimativeTypes { String = 3, @@ -119,6 +146,15 @@ declare const enum CNonPrimativeTypes { Delegate = 5, Task = 6, Ref = 7, + Int8Array = 10, // unimplemented + Uint8Array = 11, // unimplemented + Uint8ClampedArray = 12, // unimplemented + Int16Array = 13, // unimplemented + UInt16Array = 14, // unimplemented + Int32Array = 15, // unimplemented + UInt32Array = 16, // unimplemented + Float32Array = 17, // unimplemented + Float64Array = 18, // unimplemented DateTime = 20, DateTimeOffset = 21, Uri = 22, diff --git a/src/mono/wasm/runtime/types/mono-types.d.ts b/src/mono/wasm/runtime/types/mono-types.d.ts index ed0bc3cec1ceb..73f84c7179014 100644 --- a/src/mono/wasm/runtime/types/mono-types.d.ts +++ b/src/mono/wasm/runtime/types/mono-types.d.ts @@ -99,3 +99,10 @@ type WasmRootBuffer = { set: (index: number, value: number) => void, release: () => void, } + +type ByteReader = { + read: () => number | false, + get?: () => boolean, + configurable?: boolean, + enumerable?: boolean +} diff --git a/src/mono/wasm/wasm.proj b/src/mono/wasm/wasm.proj index 30f5ad6f04762..1cc973127509e 100644 --- a/src/mono/wasm/wasm.proj +++ b/src/mono/wasm/wasm.proj @@ -225,7 +225,7 @@ IgnoreStandardErrorWarningFormat="true" /> - + Date: Wed, 21 Jul 2021 11:15:38 -0400 Subject: [PATCH 12/19] Added a TON of types to library-mono.ts --- src/mono/wasm/runtime/binding-support.ts | 4 +- src/mono/wasm/runtime/library-mono.ts | 97 +++++++++---------- src/mono/wasm/runtime/types/Module.d.ts | 30 +++++- .../wasm/runtime/types/debugger-types.d.ts | 80 +++++++++++++++ src/mono/wasm/runtime/types/mono-types.d.ts | 46 ++++++--- 5 files changed, 184 insertions(+), 73 deletions(-) create mode 100644 src/mono/wasm/runtime/types/debugger-types.d.ts diff --git a/src/mono/wasm/runtime/binding-support.ts b/src/mono/wasm/runtime/binding-support.ts index 8351cd7ad4a5a..44c2436589987 100644 --- a/src/mono/wasm/runtime/binding-support.ts +++ b/src/mono/wasm/runtime/binding-support.ts @@ -159,7 +159,7 @@ var BindingSupportLib = { // Ensures the string is already interned on both the managed and JavaScript sides, // then returns the interned string value (to provide fast reference comparisons like C#) - mono_intern_string: function (string: string): string { + mono_intern_string: function (string: string): string | Symbol { if (string.length === 0) return BINDING._empty_string; @@ -283,7 +283,7 @@ var BindingSupportLib = { return null; }, - _get_string_from_intern_table: function (mono_obj: number): string { + _get_string_from_intern_table: function (mono_obj: number): string | Symbol { if (!MONO.interned_string_table) return undefined; return MONO.interned_string_table.get (mono_obj); diff --git a/src/mono/wasm/runtime/library-mono.ts b/src/mono/wasm/runtime/library-mono.ts index 5323527b17327..57053285628b9 100644 --- a/src/mono/wasm/runtime/library-mono.ts +++ b/src/mono/wasm/runtime/library-mono.ts @@ -9,13 +9,6 @@ var MonoSupportLib = { _vt_stack: [], mono_wasm_runtime_is_ready : false, mono_wasm_ignore_pdb_load_errors: true, - interned_string_table: undefined, - mono_wasm_deregister_root: undefined, // becomes a function later - commands_received: undefined, - var_info: undefined, - loaded_assets: undefined, - loaded_files: undefined, - _c_fn_table: undefined, /** @type {object.} */ _id_table: {}, @@ -286,7 +279,7 @@ var MonoSupportLib = { return result; }, - _zero_region: function (byteOffset, sizeBytes) { + _zero_region: function (byteOffset: number, sizeBytes: number): void { if (((byteOffset % 4) === 0) && ((sizeBytes % 4) === 0)) Module.HEAP32.fill(0, byteOffset / 4, sizeBytes / 4); else @@ -446,7 +439,7 @@ var MonoSupportLib = { mono_text_decoder: undefined, string_decoder: { - copy: function (mono_string) { + copy: function (mono_string: number): string { if (mono_string === 0) return null; @@ -497,7 +490,7 @@ var MonoSupportLib = { this.mono_wasm_string_root.value = 0; return result; }, - decode: function (start, end, save) { + decode: function (start: number, end: number, save: boolean): string { if (!MONO.mono_text_decoder) { MONO.mono_text_decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-16le') : undefined; } @@ -524,7 +517,7 @@ var MonoSupportLib = { }, }, - mono_wasm_add_dbg_command_received: function(res_ok, id, buffer, buffer_len) { + mono_wasm_add_dbg_command_received: function(res_ok: number, id: number, buffer: number, buffer_len: number): void { const assembly_data = new Uint8Array(Module.HEAPU8.buffer, buffer, buffer_len); const base64String = MONO._base64Converter.toBase64StringImpl(assembly_data); const buffer_obj = { @@ -537,7 +530,7 @@ var MonoSupportLib = { MONO.commands_received = buffer_obj; }, - mono_wasm_send_dbg_command_with_parms: function (id: number, command_set: number, command: number, command_parameters: string, length: number, valtype: number, newvalue: string) + mono_wasm_send_dbg_command_with_parms: function (id: number, command_set: number, command: number, command_parameters: string, length: number, valtype: number, newvalue: string): CommandResult { const dataHeap = new Uint8Array (Module.HEAPU8.buffer, command_parameters.length); dataHeap.set (new Uint8Array (MONO._base64_to_uint8 (command_parameters))); @@ -548,7 +541,7 @@ var MonoSupportLib = { return res; }, - mono_wasm_send_dbg_command: function (id: number, command_set: number, command: number, command_parameters: string) + mono_wasm_send_dbg_command: function (id: number, command_set: number, command: number, command_parameters: string): CommandResult { const dataHeap = new Uint8Array (Module.HEAPU8.buffer, command_parameters.length); dataHeap.set (new Uint8Array (MONO._base64_to_uint8 (command_parameters))); @@ -562,7 +555,7 @@ var MonoSupportLib = { }, - mono_wasm_get_dbg_command_info: function () + mono_wasm_get_dbg_command_info: function (): CommandResult { let { res_ok, res } = MONO.commands_received; if (!res_ok) @@ -570,7 +563,7 @@ var MonoSupportLib = { return res; }, - _get_cfo_res_details: function (objectId, args) { + _get_cfo_res_details: function (objectId: string, args: ChromeDevToolsArgs): { __value_as_json_string__: string } { if (!(objectId in MONO._call_function_res_cache)) throw new Error(`Could not find any object with id ${objectId}`); @@ -628,22 +621,22 @@ var MonoSupportLib = { return { __value_as_json_string__: JSON.stringify (res_details) }; }, - mono_wasm_get_details: function (objectId, args={}) { + mono_wasm_get_details: function (objectId: string, args: ChromeDevToolsArgs ={}) { return MONO._get_cfo_res_details (`dotnet:cfo_res:${objectId}`, args); }, - _cache_call_function_res: function (obj) { + _cache_call_function_res: function (obj): string { const id = `dotnet:cfo_res:${MONO._next_call_function_res_id++}`; MONO._call_function_res_cache[id] = obj; return id; }, - mono_wasm_release_object: function (objectId) { + mono_wasm_release_object: function (objectId: string): void { if (objectId in MONO._cache_call_function_res) delete MONO._cache_call_function_res[objectId]; }, - _create_proxy_from_object_id: function (objectId, details) { + _create_proxy_from_object_id: function (objectId: string, details: CallDetails[]): Proxy | string[] | {} { if (objectId.startsWith ('dotnet:array:')) { let ret = details.map (p => p.value); @@ -672,7 +665,7 @@ var MonoSupportLib = { return proxy; }, - mono_wasm_call_function_on: function (request) { + mono_wasm_call_function_on: function (request: CallRequest): CallResult { if (request.arguments != undefined && !Array.isArray (request.arguments)) throw new Error (`"arguments" should be an array, but was ${request.arguments}`); @@ -727,22 +720,22 @@ var MonoSupportLib = { return { type: "object", className: "Object", description: "Object", objectId: fn_res_id }; }, - _clear_per_step_state: function () { + _clear_per_step_state: function (): void { MONO._next_id_var = 0; MONO._id_table = {}; }, - mono_wasm_debugger_resume: function () { + mono_wasm_debugger_resume: function (): void { MONO._clear_per_step_state (); }, - mono_wasm_detach_debugger: function () { + mono_wasm_detach_debugger: function (): void { if (!MONO.mono_wasm_set_is_debugger_attached) MONO.mono_wasm_set_is_debugger_attached = Module.cwrap ('mono_wasm_set_is_debugger_attached', 'void', ['bool']); MONO.mono_wasm_set_is_debugger_attached(false); }, - _register_c_fn: function (name: string, ...args: any[]) { + _register_c_fn: function (name: string, ...args: any[]): void { Object.defineProperty (MONO._c_fn_table, name + '_wrapper', { value: Module.cwrap (name, ...args) }); }, @@ -778,7 +771,7 @@ var MonoSupportLib = { }); }, - mono_wasm_runtime_ready: function () { + mono_wasm_runtime_ready: function (): void { MONO.mono_wasm_runtime_is_ready = true; MONO._clear_per_step_state (); @@ -799,13 +792,13 @@ var MonoSupportLib = { // Set environment variable NAME to VALUE // Should be called before mono_load_runtime_and_bcl () in most cases - mono_wasm_setenv: function (name, value) { + mono_wasm_setenv: function (name: string, value: string): void { if (!MONO.wasm_setenv) MONO.wasm_setenv = Module.cwrap ('mono_wasm_setenv', null, ['string', 'string']); MONO.wasm_setenv (name, value); }, - mono_wasm_set_runtime_options: function (options) { + mono_wasm_set_runtime_options: function (options): void { if (!MONO.wasm_parse_runtime_options) MONO.wasm_parse_runtime_options = Module.cwrap ('mono_wasm_parse_runtime_options', null, ['number', 'number']); var argv = Module._malloc (options.length * 4); @@ -827,7 +820,7 @@ var MonoSupportLib = { // send_to defaults to 'WebAssembly.Runtime::DumpAotProfileData'. // DumpAotProfileData stores the data into Module.aot_profile_data. // - mono_wasm_init_aot_profiler: function (options) { + mono_wasm_init_aot_profiler: function (options): void { if (options == null) options = {} if (!('write_at' in options)) @@ -843,7 +836,7 @@ var MonoSupportLib = { // write_at defaults to 'WebAssembly.Runtime::StopProfile'. // send_to defaults to 'WebAssembly.Runtime::DumpCoverageProfileData'. // DumpCoverageProfileData stores the data into Module.coverage_profile_data. - mono_wasm_init_coverage_profiler: function (options) { + mono_wasm_init_coverage_profiler: function (options): void { if (options == null) options = {} if (!('write_at' in options)) @@ -854,7 +847,7 @@ var MonoSupportLib = { Module.ccall ('mono_wasm_load_profiler_coverage', null, ['string'], [arg]); }, - _apply_configuration_from_args: function (args) { + _apply_configuration_from_args: function (args): void { for (var k in (args.environment_variables || {})) MONO.mono_wasm_setenv (k, args.environment_variables[k]); @@ -868,7 +861,7 @@ var MonoSupportLib = { MONO.mono_wasm_init_coverage_profiler (args.coverage_profiler_options); }, - _get_fetch_file_cb_from_args: function (args) { + _get_fetch_file_cb_from_args: function (args?: {fetch_file_cb: FetchRequest}): FetchRequest { if (typeof (args.fetch_file_cb) === "function") return args.fetch_file_cb; @@ -896,14 +889,14 @@ var MonoSupportLib = { }; } else if (typeof (fetch) === "function") { return function (asset) { - return fetch (asset, { credentials: 'same-origin' }); - }; + return fetch (asset, { credentials: 'same-origin' }) as any; // this any forces TS to abide by our rules + } as FetchRequest; } else { throw new Error ("No fetch_file_cb was provided and this environment does not expose 'fetch'."); } }, - _handle_loaded_asset: function (ctx, asset, url, blob) { + _handle_loaded_asset: function (ctx, asset: AssetEntry, url: string, blob: Iterable): void { var bytes = new Uint8Array (blob); if (ctx.tracing) console.log ("MONO_WASM: Loaded:", asset.name, "size", bytes.length, "from", url); @@ -979,9 +972,9 @@ var MonoSupportLib = { // deprecated mono_load_runtime_and_bcl: function ( - unused_vfs_prefix, deploy_prefix, debug_level, file_list, loaded_cb, fetch_file_cb + unused_vfs_prefix: any /* unused var */, deploy_prefix: string, debug_level: number, file_list: string[], loaded_cb: () => void, fetch_file_cb: FetchRequest ) { - var args = { + var args: MonoRuntimeArgs = { fetch_file_cb: fetch_file_cb, loaded_cb: loaded_cb, debug_level: debug_level, @@ -1058,7 +1051,7 @@ var MonoSupportLib = { // @bytes must be a typed array. space is allocated for it in the native heap // and it is copied to that location. returns the address of the allocation. - mono_wasm_load_bytes_into_heap: function (bytes) { + mono_wasm_load_bytes_into_heap: function (bytes: Uint8Array): number { var memoryOffset = Module._malloc (bytes.length); var heapBytes = new Uint8Array (Module.HEAPU8.buffer, memoryOffset, bytes.length); heapBytes.set (bytes); @@ -1069,7 +1062,7 @@ var MonoSupportLib = { // @offset must be the address of an ICU data archive in the native heap. // returns true on success. - mono_wasm_load_icu_data: function (offset) { + mono_wasm_load_icu_data: function (offset: number): boolean { var fn = Module.cwrap ('mono_wasm_load_icu_data', 'number', ['number']); var ok = (fn (offset)) === 1; if (ok) @@ -1081,11 +1074,11 @@ var MonoSupportLib = { // "ja" -> "icudt_CJK.dat" // "en_US" (or "en-US" or just "en") -> "icudt_EFIGS.dat" // etc, see "mono_wasm_get_icudt_name" implementation in pal_icushim_static.c - mono_wasm_get_icudt_name: function (culture) { + mono_wasm_get_icudt_name: function (culture: Culture): string { return Module.ccall ('mono_wasm_get_icudt_name', 'string', ['string'], [culture]); }, - _finalize_startup: function (args, ctx) { + _finalize_startup: function (args: MonoRuntimeArgs, ctx): void { var loaded_files_with_debug_info = []; MONO.loaded_assets = ctx.loaded_assets; @@ -1126,7 +1119,7 @@ var MonoSupportLib = { args.loaded_cb (); }, - _load_assets_and_runtime: function (args) { + _load_assets_and_runtime: function (args: MonoRuntimeArgs): void { if (args.enable_debugging) args.debug_level = args.enable_debugging; if (args.assembly_list) @@ -1236,7 +1229,7 @@ var MonoSupportLib = { if (asset.behavior === "assembly") attemptUrl = locateFile (args.assembly_root + "/" + asset.name); else if (asset.behavior === "resource") { - var path = asset.culture !== '' ? `${asset.culture}/${asset.name}` : asset.name; + var path = asset.culture.length > 0 ? `${asset.culture}/${asset.name}` : asset.name; attemptUrl = locateFile (args.assembly_root + "/" + path); } else @@ -1269,10 +1262,10 @@ var MonoSupportLib = { // @globalization_mode is one of "icu", "invariant", or "auto". // "auto" will use "icu" if any ICU data archives have been loaded, // otherwise "invariant". - mono_wasm_globalization_init: function (globalization_mode) { + mono_wasm_globalization_init: function (globalization_mode: GlobalizationMode): void { var invariantMode = false; - if (globalization_mode === "invariant") + if (globalization_mode === GlobalizationMode.INVARIANT) invariantMode = true; if (!invariantMode) { @@ -1296,19 +1289,19 @@ var MonoSupportLib = { }, // Used by the debugger to enumerate loaded dlls and pdbs - mono_wasm_get_loaded_files: function() { + mono_wasm_get_loaded_files: function(): string[] { if (!MONO.mono_wasm_set_is_debugger_attached) MONO.mono_wasm_set_is_debugger_attached = Module.cwrap ('mono_wasm_set_is_debugger_attached', 'void', ['bool']); MONO.mono_wasm_set_is_debugger_attached (true); return MONO.loaded_files; }, - mono_wasm_get_loaded_asset_table: function() { + mono_wasm_get_loaded_asset_table: function(): string[] { return MONO.loaded_assets; }, // FIXME: improve - _base64_to_uint8: function (base64String) { + _base64_to_uint8: function (base64String: string): Uint8Array { const byteCharacters = atob (base64String); const byteNumbers = new Array(byteCharacters.length); for (let i = 0; i < byteCharacters.length; i++) { @@ -1318,7 +1311,7 @@ var MonoSupportLib = { return new Uint8Array (byteNumbers); }, - mono_wasm_load_data_archive: function (data, prefix) { + mono_wasm_load_data_archive: function (data, prefix): boolean { if (data.length < 8) return false; @@ -1418,14 +1411,14 @@ var MonoSupportLib = { } } }, - schedule_background_exec: function () { + schedule_background_exec: function (): void { ++MONO.pump_count; if (typeof globalThis.setTimeout === 'function') { globalThis.setTimeout (MONO.pump_message, 0); } }, - mono_set_timeout: function (timeout, id) { + mono_set_timeout: function (timeout: number, id: number): void { if (!MONO.mono_set_timeout_exec) MONO.mono_set_timeout_exec = Module.cwrap ("mono_set_timeout_exec", null, [ 'number' ]); @@ -1441,12 +1434,12 @@ var MonoSupportLib = { } }, - mono_wasm_fire_debugger_agent_message: function () { + mono_wasm_fire_debugger_agent_message: function (): void { // eslint-disable-next-line no-debugger debugger; }, - mono_wasm_asm_loaded: function (assembly_name, assembly_ptr, assembly_len, pdb_ptr, pdb_len) { + mono_wasm_asm_loaded: function (assembly_name: number, assembly_ptr: number, assembly_len: number, pdb_ptr: number, pdb_len: number): void { // Only trigger this codepath for assemblies loaded after app is ready if (MONO.mono_wasm_runtime_is_ready !== true) return; diff --git a/src/mono/wasm/runtime/types/Module.d.ts b/src/mono/wasm/runtime/types/Module.d.ts index ecf253c80fedd..6fd0f4ead7f1e 100644 --- a/src/mono/wasm/runtime/types/Module.d.ts +++ b/src/mono/wasm/runtime/types/Module.d.ts @@ -42,7 +42,7 @@ declare namespace Module { function mono_method_get_call_signature (method: any, mono_obj?: any): ArgsMarshalString; function print (message: string): void; - function ccall (ident: string, returnType?: string, argTypes?: string[], args?: any[] , opts?: any): T; + function ccall (ident: string, returnType?: string, argTypes?: string[], args?: any[] , opts?: any): T; function cwrap (ident: string, returnType: string, argTypes?: string[], opts?: any): T; function cwrap (ident: string, ...args: any[]): T; @@ -67,7 +67,11 @@ type MonoConfig = { // Types of assets that can be in the mono-config.js/mono-config.json file (taken from /src/tasks/WasmAppBuilder/WasmAppBuilder.cs) type AssetEntry = { behavior: AssetBehaviours, - name: string + name: string, + virtual_path?: string, + culture?: Culture, + load_remote?: boolean, + is_optional?: boolean } interface AssemblyEntry extends AssetEntry { @@ -76,7 +80,7 @@ interface AssemblyEntry extends AssetEntry { interface SatelliteAssemblyEntry extends AssetEntry { name: "resource", - culture: string + culture: Culture } interface VfsEntry extends AssetEntry { @@ -97,3 +101,23 @@ declare const enum AssetBehaviours { ICU = "icu", VFS = "vfs", } + +type Culture = "ar_SA" | "am_ET" | "bg_BG" | "bn_BD" | "bn_IN" | "ca_AD" | "ca_ES" | "cs_CZ" | "da_DK" | +"de_AT" | "de_BE" | "de_CH" | "de_DE" | "de_IT" | "de_LI" | "de_LU" | "el_CY" | "el_GR" | "en_AE" | +"en_AG" | "en_AI" | "en_AS" | "en_AT" | "en_AU" | "en_BB" | "en_BE" | "en_BI" | "en_BM" | "en_BS" | +"en_BW" | "en_BZ" | "en_CA" | "en_CC" | "en_CH" | "en_CK" | "en_CM" | "en_CX" | "en_CY" | "en_DE" | +"en_DK" | "en_DM" | "en_ER" | "en_FI" | "en_FJ" | "en_FK" | "en_FM" | "en_GB" | "en_GD" | "en_GG" | +"en_GH" | "en_GI" | "en_GM" | "en_GU" | "en_GY" | "en_HK" | "en_IE" | "en_IL" | "en_IM" | "en_IN" | +"en_IO" | "en_JE" | "en_JM" | "en_KE" | "en_KI" | "en_KN" | "en_KY" | "en_LC" | "en_LR" | "en_LS" | +"en_MG" | "en_MH" | "en_MO" | "en_MP" | "en_MS" | "en_MT" | "en_MU" | "en_MW" | "en_MY" | "en_NA" | +"en_NF" | "en_NG" | "en_NL" | "en_NR" | "en_NU" | "en_NZ" | "en_PG" | "en_PH" | "en_PK" | "en_PN" | +"en_PR" | "en_PW" | "en_RW" | "en_SB" | "en_SC" | "en_SD" | "en_SE" | "en_SG" | "en_SH" | "en_SI" | +"en_SL" | "en_SS" | "en_SX" | "en_SZ" | "en_TC" | "en_TK" | "en_TO" | "en_TT" | "en_TV" | "en_TZ" | +"en_UG" | "en_UM" | "en_US" | "en_VC" | "en_VG" | "en_VI" | "en_VU" | "en_WS" | "en_ZA" | "en_ZM" | +"en_ZW" | "en_US" | "es_419" | "es_ES" | "es_MX" | "et_EE" | "fa_IR" | "fi_FI" | "fil_PH" | "fr_BE" | +"fr_CA" | "fr_CH" | "fr_FR" | "gu_IN" | "he_IL" | "hi_IN" | "hr_BA" | "hr_HR" | "hu_HU" | "id_ID" | +"it_CH" | "it_IT" | "ja_JP" | "kn_IN" | "ko_KR" | "lt_LT" | "lv_LV" | "ml_IN" | "mr_IN" | "ms_BN" | +"ms_MY" | "ms_SG" | "nl_AW" | "nl_BE" | "nl_NL" | "pl_PL" | "pt_BR" | "pt_PT" | "ro_RO" | "ru_RU" | +"sk_SK" | "sl_SI" | "sr_Cyrl_RS" | "sr_Latn_RS" | "sv_AX" | "sv_SE" | "sw_CD" | "sw_KE" | "sw_TZ" | +"sw_UG" | "ta_IN" | "ta_LK" | "ta_MY" | "ta_SG" | "te_IN" | "th_TH" | "tr_CY" | "tr_TR" | "uk_UA" | +"vi_VN" | "zh_CN" | "zh_Hans_HK" | "zh_SG" | "zh_HK" | "zh_TW"; diff --git a/src/mono/wasm/runtime/types/debugger-types.d.ts b/src/mono/wasm/runtime/types/debugger-types.d.ts new file mode 100644 index 0000000000000..8ba86f2d91e45 --- /dev/null +++ b/src/mono/wasm/runtime/types/debugger-types.d.ts @@ -0,0 +1,80 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +/******************************************************************************************* + This file just acts as a set of object definitions to help the TSC compiler understand + the various namespaces that we use. These namespaces are not defined explicitly until + the dotnet.js file is merged, so we pretend they exist by defining them here. + + THIS FILE IS NOT INCLUDED IN DOTNET.JS. ALL CODE HERE WILL BE IGNORED DURING THE BUILD +********************************************************************************************/ + +// VARIOUS C FUNCTIONS THAT WE CALL INTO //////////////////////////////////////////////////// +interface DEBUG_C_FUNCS { + mono_wasm_send_dbg_command (a: number, b:number, c: number, d: number, e: number): boolean; + mono_wasm_send_dbg_command_with_parms (a: number, b:number, c: number, d: number, e: number, f: number, g: string): boolean; + mono_wasm_set_is_debugger_attached (a: boolean): void; +} + +interface DEBUG_VARS { + _c_fn_table: { + [fn: string]: Function + }; + commands_received:{ + res_ok: number, + res: CommandResult + }; + _call_function_res_cache: object; + _next_call_function_res_id: number; + _next_id_var: number; + var_info: []; // always an empty list - Can it be removed? +} + +// NAMESPACES /////////////////////////////////////////////////////////////////////////////// +// Added in mono-types.d.ts + +// OTHER TYPES /////////////////////////////////////////////////////////////////////// + +type Proxy = { + name: string, + get: () => ((id: number, command_set: number, command: number, command_parameters: string) => CommandResult), + set: (newValue: number) => ((id: number, command_set: number, command: number, command_parameters: string, length: number, valtype: number, newvalue: string) => CommandResult) + [i: string]: any +} + +type CallRequest = { + arguments: undefined | Array, + objectId: string, + details: CallDetails[], + functionDeclaration: string + returnByValue: boolean, +} + +type CallDetails = { + value: string +}; + +type CallArgs = { + value: string +}; + +type CallResult = { + type: string, + subtype?: string, + className?: string, + description?: string, + objectId?: string, + value?: any +} + +type ChromeDevToolsArgs = { + ownProperties?: boolean, + objectId?: string, + generatePreview?: boolean, + accessorPropertiesOnly?: boolean +} + +type CommandResult = { + id: number, + value: string +}; diff --git a/src/mono/wasm/runtime/types/mono-types.d.ts b/src/mono/wasm/runtime/types/mono-types.d.ts index 73f84c7179014..e8734d2552651 100644 --- a/src/mono/wasm/runtime/types/mono-types.d.ts +++ b/src/mono/wasm/runtime/types/mono-types.d.ts @@ -23,29 +23,39 @@ interface MONO_C_FUNCS { mono_wasm_load_runtime (a: string, b: number): void; wasm_parse_runtime_options (a: number, b:number): void; mono_wasm_register_root (a: number, b: number, c: string | 0): number; - mono_wasm_send_dbg_command (a: number, b:number, c: number, d: number, e: number): boolean; - mono_wasm_send_dbg_command_with_parms (a: number, b:number, c: number, d: number, e: number, f: number, g: string): boolean; - mono_wasm_set_is_debugger_attached (a: boolean): void; wasm_setenv (a: string, b: string): void; mono_wasm_strdup (a: string): number; mono_wasm_string_get_data (a: number, b: number, c: number, d: number): void; } interface MONO_VARS { - _base64Table: string[]; - mono_wasm_string_decoder_buffer: number; - mono_wasm_empty_string: string; - _next_call_function_res_id: number; - _next_id_var: number; - _call_function_res_cache: any; + interned_string_table: Map; + _scratch_root_free_indices: Int32Array, + _scratch_root_free_indices_count: number; + _mono_wasm_root_prototype: WasmRoot; + _mono_wasm_root_buffer_prototype: WasmRootBuffer; + _scratch_root_buffer: WasmRootBuffer, + _scratch_root_free_instances: WasmRoot[], + loaded_files: string[]; + loaded_assets: string[]; } // NAMESPACES /////////////////////////////////////////////////////////////////////////////// -declare var MONO: typeof MonoSupportLib.$MONO & MONO_C_FUNCS & MONO_VARS; +declare var MONO: typeof MonoSupportLib.$MONO & MONO_C_FUNCS & MONO_VARS & DEBUG_C_FUNCS & DEBUG_VARS; // Debug ones are from debugger-types.d.ts // OTHER TYPES /////////////////////////////////////////////////////////////////////// -type GlobalizationMode = "icu" | "invarient" | "auto"; +type FetchRequest = (asset: string) => Promise<{ + ok: boolean, + url: string, + arrayBuffer: () => Promise +}>; + +declare const enum GlobalizationMode { + ICU = "icu", + INVARIANT = "invariant", + AUTO = "auto" +} type LoadedFiles = { url: string, @@ -55,14 +65,18 @@ type LoadedFiles = { type ManagedPointer = number; // - address in the managed heap type MonoRuntimeArgs = { - fetch_file_cb: (asset: string) => void, + fetch_file_cb: FetchRequest, loaded_cb: () => void, debug_level: number, assembly_root: string, - assets: { - name: string, - behavior: string, - }[], + assets: AssetEntry[], + globalization_mode?: GlobalizationMode, + enable_debugging?: number, + assembly_list?: any, + runtime_assets?: any, + runtime_asset_sources?: any, + diagnostic_tracing?: any + remote_sources?: string[] } type NativePointer = number; // - address in wasm memory From 500962edc49b117b6c3a3ffbe73fad4167ee16f3 Mon Sep 17 00:00:00 2001 From: Daniel-Genkin Date: Wed, 21 Jul 2021 12:11:47 -0400 Subject: [PATCH 13/19] More types --- src/mono/wasm/runtime/binding-support.ts | 56 +++++++++---------- src/mono/wasm/runtime/dotnet-support.ts | 10 ++-- src/mono/wasm/runtime/library-mono.ts | 24 ++++---- .../wasm/runtime/types/binding-types.d.ts | 29 +++++++--- .../wasm/runtime/types/debugger-types.d.ts | 4 ++ .../wasm/runtime/types/general-types.d.ts | 3 + src/mono/wasm/runtime/types/mono-types.d.ts | 6 +- 7 files changed, 74 insertions(+), 58 deletions(-) diff --git a/src/mono/wasm/runtime/binding-support.ts b/src/mono/wasm/runtime/binding-support.ts index 44c2436589987..3e99055a9936e 100644 --- a/src/mono/wasm/runtime/binding-support.ts +++ b/src/mono/wasm/runtime/binding-support.ts @@ -112,7 +112,7 @@ var BindingSupportLib = { return res; }; - var bind_runtime_method = function (method_name: string, signature: ArgsMarshalString): Function { + var bind_runtime_method = function (method_name: string, signature: ArgsMarshalString): T { var method = get_method (method_name); return BINDING.bind_method (method, 0, signature, "BINDINGS_" + method_name); }; @@ -396,7 +396,7 @@ var BindingSupportLib = { return promise; }, - _unbox_safehandle_root: function (root: WasmRoot) { + _unbox_safehandle_root: function (root: WasmRoot): number { var addRef = true; var js_handle = BINDING.call_method(BINDING.safehandle_get_handle, null, "mi", [ root.value, addRef ]); var requiredObject = BINDING.mono_wasm_require_handle (js_handle); @@ -766,28 +766,28 @@ var BindingSupportLib = { return js_obj | 0; }, - wasm_binding_obj_new: function (js_obj_id, ownsHandle, type): Function + wasm_binding_obj_new: function (js_obj_id: number, ownsHandle: boolean, type) { return BINDING._bind_js_obj (js_obj_id, ownsHandle, type); }, - wasm_bind_existing: function (mono_obj, js_id): Function + wasm_bind_existing: function (mono_obj: number, js_id: number): number { return BINDING._bind_existing_obj (mono_obj, js_id); }, - wasm_bind_core_clr_obj: function (js_id, gc_handle): Function + wasm_bind_core_clr_obj: function (js_id: number, gc_handle: number): number { return BINDING._bind_core_clr_obj (js_id, gc_handle); }, - wasm_get_js_id: function (mono_obj) + wasm_get_js_id: function (mono_obj: number): number { return BINDING._get_js_id (mono_obj); }, // when should_add_in_flight === true, the JSObject would be temporarily hold by Normal GCHandle, so that it would not get collected during transition to the managed stack. // its InFlight handle would be freed when the instance arrives to managed side via Interop.Runtime.ReleaseInFlight - wasm_get_raw_obj: function (gchandle, should_add_in_flight) + wasm_get_raw_obj: function (gchandle: number, should_add_in_flight) { if(!gchandle){ return 0; @@ -796,7 +796,7 @@ var BindingSupportLib = { return BINDING._get_raw_mono_obj (gchandle, should_add_in_flight ? 1 : 0); }, - try_extract_mono_obj: function (js_obj) { + try_extract_mono_obj: function (js_obj: JSObject) { if (js_obj === null || typeof js_obj === "undefined" || typeof js_obj.__mono_gchandle__ === "undefined") return 0; return BINDING.wasm_get_raw_obj (js_obj.__mono_gchandle__, true); @@ -813,7 +813,7 @@ var BindingSupportLib = { } }, - get_task_and_bind: function (tcs, js_obj) { + get_task_and_bind: function (tcs, js_obj: JSObject) { var gc_handle = BINDING.mono_wasm_free_list.length ? BINDING.mono_wasm_free_list.pop() : BINDING.mono_wasm_ref_counter++; var task_gchandle = BINDING.call_method (BINDING.tcs_get_task_and_bind, null, "oi", [ tcs, gc_handle + 1 ]); js_obj.__mono_gchandle__ = task_gchandle; @@ -836,7 +836,7 @@ var BindingSupportLib = { } }, - extract_mono_obj: function (js_obj) { + extract_mono_obj: function (js_obj: JSObject) { if (js_obj === null || typeof js_obj === "undefined") return 0; @@ -861,7 +861,7 @@ var BindingSupportLib = { return result; }, - extract_js_obj: function (mono_obj) { + extract_js_obj: function (mono_obj: number): JSObject { if (mono_obj === 0) return null; var root = MONO.mono_wasm_new_root (mono_obj); @@ -872,7 +872,7 @@ var BindingSupportLib = { } }, - extract_js_obj_root: function (root: WasmRoot) { + extract_js_obj_root: function (root: WasmRoot): JSObject { if (root.value === 0) return null; @@ -890,7 +890,7 @@ var BindingSupportLib = { return js_obj; }, - _create_named_function: function (name: string, argumentNames, body: string, closure): any { + _create_named_function: function (name: string, argumentNames, body: string, closure): T { var result = null, keys = null, closureArgumentList = null, closureArgumentNames = null; if (closure) { @@ -906,7 +906,7 @@ var BindingSupportLib = { return result; }, - _create_rebindable_named_function: function (name: string, argumentNames, body: string, closureArgNames): any { + _create_rebindable_named_function: function (name: string, argumentNames, body: string, closureArgNames): T { var strictPrefix = "\"use strict\";\r\n"; var uriPrefix = "", escapedFunctionIdentifier = ""; @@ -1348,7 +1348,7 @@ var BindingSupportLib = { return BINDING._handle_exception_and_produce_result_for_call (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer, is_result_marshaled); }, - bind_method: function (method: number, this_arg, args_marshal: ArgsMarshalString, friendly_name: string): Function { + bind_method: function (method: number, this_arg, args_marshal: ArgsMarshalString, friendly_name: string): T { BINDING.bindings_lazy_init (); this_arg = this_arg | 0; @@ -1550,7 +1550,7 @@ var BindingSupportLib = { return BINDING.call_method (method, null, signature, args); }, - bind_static_method: function (fqn: string, signature: ArgsMarshalString): Function { + bind_static_method: function (fqn: string, signature: ArgsMarshalString): T { BINDING.bindings_lazy_init (); var method = BINDING.resolve_method_fqn (fqn); @@ -1592,7 +1592,7 @@ var BindingSupportLib = { }, // Object wrapping helper functions to handle reference handles that will // be used in managed code. - mono_wasm_register_obj: function(js_obj) { + mono_wasm_register_obj: function(js_obj: JSObject): { gc_handle: number, should_add_in_flight: boolean } { var gc_handle = undefined; if (js_obj !== null && typeof js_obj !== "undefined") @@ -1646,7 +1646,7 @@ var BindingSupportLib = { } return obj; }, - mono_wasm_free_handle: function(handle) { + mono_wasm_free_handle: function(handle: number): void { BINDING.mono_wasm_unregister_obj(handle); }, mono_wasm_free_raw_object: function(js_id: number) { @@ -1669,7 +1669,7 @@ var BindingSupportLib = { } return obj; }, - mono_wasm_parse_args_root: function (argsRoot) { + mono_wasm_parse_args_root: function (argsRoot): any[] { var js_args = BINDING._mono_array_root_to_js_array(argsRoot); BINDING.mono_wasm_save_LMF(); return js_args; @@ -1701,7 +1701,7 @@ var BindingSupportLib = { }, }, - mono_wasm_invoke_js_with_args: function(js_handle, method_name, args, is_exception): number { + mono_wasm_invoke_js_with_args: function(js_handle: number, method_name, args, is_exception): number { let argsRoot = MONO.mono_wasm_new_root (args), nameRoot = MONO.mono_wasm_new_root (method_name); try { BINDING.bindings_lazy_init (); @@ -1741,7 +1741,7 @@ var BindingSupportLib = { nameRoot.release(); } }, - mono_wasm_get_object_property: function(js_handle, property_name, is_exception): number { + mono_wasm_get_object_property: function(js_handle: number, property_name, is_exception): number { BINDING.bindings_lazy_init (); var nameRoot = MONO.mono_wasm_new_root (property_name); @@ -1776,7 +1776,7 @@ var BindingSupportLib = { nameRoot.release(); } }, - mono_wasm_set_object_property: function (js_handle, property_name, value, createIfNotExist, hasOwnProperty, is_exception): number | boolean { + mono_wasm_set_object_property: function (js_handle: number, property_name, value, createIfNotExist, hasOwnProperty, is_exception): number | boolean { var valueRoot = MONO.mono_wasm_new_root (value), nameRoot = MONO.mono_wasm_new_root (property_name); try { BINDING.bindings_lazy_init (); @@ -1827,7 +1827,7 @@ var BindingSupportLib = { valueRoot.release(); } }, - mono_wasm_get_by_index: function(js_handle, property_index, is_exception): number { + mono_wasm_get_by_index: function(js_handle: number, property_index, is_exception): number { BINDING.bindings_lazy_init (); var obj = BINDING.mono_wasm_require_handle (js_handle); @@ -1847,7 +1847,7 @@ var BindingSupportLib = { return BINDING.js_string_to_mono_string (res); } }, - mono_wasm_set_by_index: function(js_handle, property_index, value, is_exception): number | boolean { + mono_wasm_set_by_index: function(js_handle: number, property_index, value, is_exception): number | boolean { var valueRoot = MONO.mono_wasm_new_root (value); try { BINDING.bindings_lazy_init (); @@ -2029,11 +2029,9 @@ var BindingSupportLib = { } var res = BINDING.typedarray_copy_from(requireObject, pinned_array, begin, end, bytes_per_element); - return BINDING.js_to_mono_obj (res) + return BINDING.js_to_mono_obj (res); }, }; -// @ts-ignore: TS2304 -autoAddDeps(BindingSupportLib, '$BINDING') -// @ts-ignore: TS2304 -mergeInto(LibraryManager.library, BindingSupportLib) +autoAddDeps(BindingSupportLib, '$BINDING'); +mergeInto(LibraryManager.library, BindingSupportLib); diff --git a/src/mono/wasm/runtime/dotnet-support.ts b/src/mono/wasm/runtime/dotnet-support.ts index 24967568d4b32..1431347795b32 100644 --- a/src/mono/wasm/runtime/dotnet-support.ts +++ b/src/mono/wasm/runtime/dotnet-support.ts @@ -3,11 +3,11 @@ var DotNetSupportLib = { $DOTNET: { - conv_string: function (mono_obj) { + conv_string: function (mono_obj: number): string { return MONO.string_decoder.copy (mono_obj); } }, - mono_wasm_invoke_js_blazor: function (exceptionMessage: number, callInfo, arg0, arg1, arg2) { + mono_wasm_invoke_js_blazor: function (exceptionMessage: number, callInfo, arg0, arg1, arg2): number { var mono_string = globalThis._mono_string_cached || (globalThis._mono_string_cached = Module.cwrap('mono_wasm_string_from_js', 'number', ['string'])); @@ -27,7 +27,7 @@ var DotNetSupportLib = { }, // This is for back-compat only and will eventually be removed - mono_wasm_invoke_js_marshalled: function (exceptionMessage: number, asyncHandleLongPtr, functionName, argsJson, treatResultAsVoid) { + mono_wasm_invoke_js_marshalled: function (exceptionMessage: number, asyncHandleLongPtr, functionName, argsJson, treatResultAsVoid): number { var mono_string = globalThis._mono_string_cached || (globalThis._mono_string_cached = Module.cwrap('mono_wasm_string_from_js', 'number', ['string'])); @@ -67,7 +67,7 @@ var DotNetSupportLib = { }, // This is for back-compat only and will eventually be removed - mono_wasm_invoke_js_unmarshalled: function (exceptionMessage: number, funcName, arg0, arg1, arg2) { + mono_wasm_invoke_js_unmarshalled: function (exceptionMessage: number, funcName, arg0, arg1, arg2): number { try { // Get the function you're trying to invoke var funcNameJsString = DOTNET.conv_string(funcName); @@ -88,7 +88,5 @@ var DotNetSupportLib = { } } -// @ts-ignore: TS2304 autoAddDeps(DotNetSupportLib, '$DOTNET'); -// @ts-ignore: TS2304 mergeInto(LibraryManager.library, DotNetSupportLib); diff --git a/src/mono/wasm/runtime/library-mono.ts b/src/mono/wasm/runtime/library-mono.ts index 57053285628b9..d3a5538119e82 100644 --- a/src/mono/wasm/runtime/library-mono.ts +++ b/src/mono/wasm/runtime/library-mono.ts @@ -203,10 +203,10 @@ var MonoSupportLib = { } }, - _scratch_root_buffer: null, - _scratch_root_free_indices: null, + _scratch_root_buffer: null as WasmRootBuffer, + _scratch_root_free_indices: null as Int32Array, _scratch_root_free_indices_count: 0, - _scratch_root_free_instances: [], + _scratch_root_free_instances: [] as number[], _mono_wasm_root_prototype: { get_address: function (): NativePointer { @@ -254,7 +254,7 @@ var MonoSupportLib = { MONO._scratch_root_free_indices_count++; }, - _mono_wasm_claim_scratch_index: function () { + _mono_wasm_claim_scratch_index: function (): number { if (!MONO._scratch_root_buffer) { const maxScratchRoots = 8192; MONO._scratch_root_buffer = MONO.mono_wasm_new_root_buffer (maxScratchRoots, "js roots"); @@ -563,7 +563,7 @@ var MonoSupportLib = { return res; }, - _get_cfo_res_details: function (objectId: string, args: ChromeDevToolsArgs): { __value_as_json_string__: string } { + _get_cfo_res_details: function (objectId: string, args: ChromeDevToolsArgs): CFOResultDetails { if (!(objectId in MONO._call_function_res_cache)) throw new Error(`Could not find any object with id ${objectId}`); @@ -621,11 +621,11 @@ var MonoSupportLib = { return { __value_as_json_string__: JSON.stringify (res_details) }; }, - mono_wasm_get_details: function (objectId: string, args: ChromeDevToolsArgs ={}) { + mono_wasm_get_details: function (objectId: string, args: ChromeDevToolsArgs = {}): CFOResultDetails { return MONO._get_cfo_res_details (`dotnet:cfo_res:${objectId}`, args); }, - _cache_call_function_res: function (obj): string { + _cache_call_function_res: function (obj: object): string { const id = `dotnet:cfo_res:${MONO._next_call_function_res_id++}`; MONO._call_function_res_cache[id] = obj; return id; @@ -847,7 +847,7 @@ var MonoSupportLib = { Module.ccall ('mono_wasm_load_profiler_coverage', null, ['string'], [arg]); }, - _apply_configuration_from_args: function (args): void { + _apply_configuration_from_args: function (args?: MonoRuntimeArgs): void { for (var k in (args.environment_variables || {})) MONO.mono_wasm_setenv (k, args.environment_variables[k]); @@ -861,7 +861,7 @@ var MonoSupportLib = { MONO.mono_wasm_init_coverage_profiler (args.coverage_profiler_options); }, - _get_fetch_file_cb_from_args: function (args?: {fetch_file_cb: FetchRequest}): FetchRequest { + _get_fetch_file_cb_from_args: function (args?: MonoRuntimeArgs): FetchRequest { if (typeof (args.fetch_file_cb) === "function") return args.fetch_file_cb; @@ -1464,7 +1464,5 @@ var MonoSupportLib = { } }; -// @ts-ignore: TS2304 -autoAddDeps(MonoSupportLib, '$MONO') -// @ts-ignore: TS2304 -mergeInto(LibraryManager.library, MonoSupportLib) +autoAddDeps(MonoSupportLib, '$MONO'); +mergeInto(LibraryManager.library, MonoSupportLib); diff --git a/src/mono/wasm/runtime/types/binding-types.d.ts b/src/mono/wasm/runtime/types/binding-types.d.ts index 6d6d1f0a140e7..8b0159c242633 100644 --- a/src/mono/wasm/runtime/types/binding-types.d.ts +++ b/src/mono/wasm/runtime/types/binding-types.d.ts @@ -59,15 +59,6 @@ interface BINDING_VARS { _signature_converters: Map; _primitive_converters: Map; scratchBuffer: number; - - _bind_js_obj: Function; - _bind_core_clr_obj: Function; - _bind_existing_obj: Function; - _unbind_raw_obj_and_free: Function; - _get_js_id: Function; - _get_raw_mono_obj: Function; - _is_simple_array: Function; - _object_to_string: Function; setup_js_cont: number; create_tcs: number; set_tcs_result: number; @@ -77,12 +68,32 @@ interface BINDING_VARS { get_date_value: number; create_date_time: number; create_uri: number; + mono_wasm_object_registry: JSObject[]; + + _unbind_raw_obj_and_free: (handle: number) => void; + _get_raw_mono_obj: (gchandle: number, should_add_in_flight: number) => number; + _get_js_id: (mono_id: number) => number; + _bind_existing_obj: (mono_obj: number, js_id: number) => number; + _bind_js_obj: (js_obj_id: number, ownsHandle: boolean, type: number) => number; + _bind_core_clr_obj: (js_id: number, gc_handle: number) => number; + _object_to_string: (obj: number) => any; + _is_simple_array: (obj: any) => boolean; } // NAMESPACES /////////////////////////////////////////////////////////////////////////////// declare var BINDING: typeof BindingSupportLib.$BINDING & BINDING_C_FUNCS & BINDING_VARS; // OTHER TYPES /////////////////////////////////////////////////////////////////////// +type JSObject = { + __mono_gchandle__?: number, + __mono_jshandle__?: number, + __mono_bound_tcs__?: number, + __owns_handle__?: boolean, + __mono_delegate_alive__?: boolean, + __mono_js_cont__?: number, + is_mono_bridged_obj?: boolean, +} + type Converter = { steps: { convert: boolean; diff --git a/src/mono/wasm/runtime/types/debugger-types.d.ts b/src/mono/wasm/runtime/types/debugger-types.d.ts index 8ba86f2d91e45..f76920b7ffca2 100644 --- a/src/mono/wasm/runtime/types/debugger-types.d.ts +++ b/src/mono/wasm/runtime/types/debugger-types.d.ts @@ -35,6 +35,10 @@ interface DEBUG_VARS { // OTHER TYPES /////////////////////////////////////////////////////////////////////// +type CFOResultDetails = { + __value_as_json_string__: string; +} + type Proxy = { name: string, get: () => ((id: number, command_set: number, command: number, command_parameters: string) => CommandResult), diff --git a/src/mono/wasm/runtime/types/general-types.d.ts b/src/mono/wasm/runtime/types/general-types.d.ts index 936e6fd782918..ed55719b5dc04 100644 --- a/src/mono/wasm/runtime/types/general-types.d.ts +++ b/src/mono/wasm/runtime/types/general-types.d.ts @@ -14,6 +14,7 @@ declare var ENVIRONMENT_IS_WEB: boolean; declare var ENVIRONMENT_IS_SHELL: boolean; declare var ENVIRONMENT_IS_NODE: boolean; declare var ENVIRONMENT_IS_WORKER: boolean; +declare var LibraryManager: any; declare function locateFile(path: string): string; @@ -21,6 +22,8 @@ declare function locateFile(path: string): string; declare function read (path: string): string; declare function load (path: string): string; declare function require (path: string): object; +declare function autoAddDeps(a: object, b: string); +declare function mergeInto(a: object, b: object); // Joins the various file specific C functions into 1 interface for easier access interface C_FUNCS extends BINDING_C_FUNCS, DOTNET_C_FUNCS, MONO_C_FUNCS {} diff --git a/src/mono/wasm/runtime/types/mono-types.d.ts b/src/mono/wasm/runtime/types/mono-types.d.ts index e8734d2552651..9d1fc75627e19 100644 --- a/src/mono/wasm/runtime/types/mono-types.d.ts +++ b/src/mono/wasm/runtime/types/mono-types.d.ts @@ -76,7 +76,11 @@ type MonoRuntimeArgs = { runtime_assets?: any, runtime_asset_sources?: any, diagnostic_tracing?: any - remote_sources?: string[] + remote_sources?: string[], + environment_variables?: object, + runtime_options?: object, + aot_profiler_options?: object, + coverage_profiler_options?: object, } type NativePointer = number; // - address in wasm memory From 1a0beadb18b6b13047e68855cdde6bdab105bc5a Mon Sep 17 00:00:00 2001 From: Daniel-Genkin Date: Wed, 21 Jul 2021 12:53:43 -0400 Subject: [PATCH 14/19] A bit more types + fix for windows ci build failure --- src/mono/wasm/runtime/binding-support.ts | 2 +- src/mono/wasm/runtime/types/Module.d.ts | 3 +-- src/mono/wasm/runtime/types/binding-types.d.ts | 4 ++-- src/mono/wasm/runtime/types/debugger-types.d.ts | 2 +- src/mono/wasm/wasm.proj | 2 +- 5 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/mono/wasm/runtime/binding-support.ts b/src/mono/wasm/runtime/binding-support.ts index 3e99055a9936e..426109bc8845d 100644 --- a/src/mono/wasm/runtime/binding-support.ts +++ b/src/mono/wasm/runtime/binding-support.ts @@ -802,7 +802,7 @@ var BindingSupportLib = { return BINDING.wasm_get_raw_obj (js_obj.__mono_gchandle__, true); }, - mono_method_get_call_signature: function(method: number, mono_obj): number { + mono_method_get_call_signature: function(method: number, mono_obj: number): number { let instanceRoot = MONO.mono_wasm_new_root (mono_obj); try { BINDING.bindings_lazy_init (); diff --git a/src/mono/wasm/runtime/types/Module.d.ts b/src/mono/wasm/runtime/types/Module.d.ts index 6fd0f4ead7f1e..3e5632c2c30bd 100644 --- a/src/mono/wasm/runtime/types/Module.d.ts +++ b/src/mono/wasm/runtime/types/Module.d.ts @@ -33,13 +33,12 @@ declare namespace Module { function locateFile (path: string, prefix: string): string; function onAbort (): void; function onRuntimeInitialized (): void; - function destroy (obj: any): void; function getPreloadedPackage (remotePackageName: string, remotePackageSize: number): void; function _malloc (amnt: number): number; function _free (amn: number): void; function addRunDependency(id: string): void; function removeRunDependency(id: string): void; - function mono_method_get_call_signature (method: any, mono_obj?: any): ArgsMarshalString; + function mono_method_get_call_signature (method: number, mono_obj?: number): ArgsMarshalString; function print (message: string): void; function ccall (ident: string, returnType?: string, argTypes?: string[], args?: any[] , opts?: any): T; diff --git a/src/mono/wasm/runtime/types/binding-types.d.ts b/src/mono/wasm/runtime/types/binding-types.d.ts index 8b0159c242633..9720da77211fc 100644 --- a/src/mono/wasm/runtime/types/binding-types.d.ts +++ b/src/mono/wasm/runtime/types/binding-types.d.ts @@ -109,8 +109,8 @@ type Converter = { needs_root_buffer?: boolean; name?: string; needs_root?: boolean; - compiled_variadic_function?: any; - compiled_function?: any; + compiled_variadic_function?: Function; + compiled_function?: Function; scratchRootBuffer?: WasmRootBuffer; scratchBuffer?: number; has_warned_about_signature?: boolean; diff --git a/src/mono/wasm/runtime/types/debugger-types.d.ts b/src/mono/wasm/runtime/types/debugger-types.d.ts index f76920b7ffca2..e1f86625770fd 100644 --- a/src/mono/wasm/runtime/types/debugger-types.d.ts +++ b/src/mono/wasm/runtime/types/debugger-types.d.ts @@ -27,7 +27,7 @@ interface DEBUG_VARS { _call_function_res_cache: object; _next_call_function_res_id: number; _next_id_var: number; - var_info: []; // always an empty list - Can it be removed? + var_info: []; } // NAMESPACES /////////////////////////////////////////////////////////////////////////////// diff --git a/src/mono/wasm/wasm.proj b/src/mono/wasm/wasm.proj index 1cc973127509e..b9842cb2ffa14 100644 --- a/src/mono/wasm/wasm.proj +++ b/src/mono/wasm/wasm.proj @@ -225,7 +225,7 @@ IgnoreStandardErrorWarningFormat="true" /> - + Date: Thu, 22 Jul 2021 12:25:24 -0400 Subject: [PATCH 15/19] Added more types --- src/mono/wasm/runtime/binding-support.ts | 68 +++--- src/mono/wasm/runtime/dotnet-support.ts | 4 +- src/mono/wasm/runtime/library-mono.ts | 199 +++++++++--------- src/mono/wasm/runtime/types/Module.d.ts | 21 +- .../wasm/runtime/types/binding-types.d.ts | 60 +++--- .../wasm/runtime/types/general-types.d.ts | 1 + 6 files changed, 183 insertions(+), 170 deletions(-) diff --git a/src/mono/wasm/runtime/binding-support.ts b/src/mono/wasm/runtime/binding-support.ts index 426109bc8845d..51aec9d443c28 100644 --- a/src/mono/wasm/runtime/binding-support.ts +++ b/src/mono/wasm/runtime/binding-support.ts @@ -309,7 +309,7 @@ var BindingSupportLib = { } }, - _mono_array_root_to_js_array: function (arrayRoot): any[] | null { + _mono_array_root_to_js_array: function (arrayRoot: WasmRoot): any[] | null { if (arrayRoot.value === 0) return null; @@ -354,7 +354,7 @@ var BindingSupportLib = { } }, - unbox_mono_obj: function (mono_obj: number): number { + unbox_mono_obj: function (mono_obj: number): any { if (mono_obj === 0) return undefined; @@ -398,7 +398,7 @@ var BindingSupportLib = { _unbox_safehandle_root: function (root: WasmRoot): number { var addRef = true; - var js_handle = BINDING.call_method(BINDING.safehandle_get_handle, null, "mi", [ root.value, addRef ]); + var js_handle = BINDING.call_method(BINDING.safehandle_get_handle, null, "mi", [ root.value, addRef ]); var requiredObject = BINDING.mono_wasm_require_handle (js_handle); if (addRef) { @@ -411,7 +411,7 @@ var BindingSupportLib = { }, /** @returns return type is determined by the type parameter */ - _unbox_mono_obj_root_with_known_nonprimitive_type: function (root: WasmRoot, type: CNonPrimativeTypes): any { + _unbox_mono_obj_root_with_known_nonprimitive_type: function (root: WasmRoot, type: CNonPrimativeTypes): number | string | boolean | JSObject | Promise | Date | Function { if (root.value === undefined) throw new Error(`Expected a root but got ${root}`); @@ -443,7 +443,7 @@ var BindingSupportLib = { case CNonPrimativeTypes.Float64Array: throw new Error ("Marshalling of primitive arrays are not supported. Use the corresponding TypedArray instead."); case CNonPrimativeTypes.DateTime: // clr .NET DateTime - var dateValue = BINDING.call_method(BINDING.get_date_value, null, "m", [ root.value ]); + var dateValue = BINDING.call_method(BINDING.get_date_value, null, "m", [ root.value ]); return new Date(dateValue); case CNonPrimativeTypes.DateTimeOffset: // clr .NET DateTimeOffset var dateoffsetValue = BINDING._object_to_string (root.value); @@ -460,7 +460,7 @@ var BindingSupportLib = { } }, - _unbox_mono_obj_root: function (root: WasmRoot): any { + _unbox_mono_obj_root: function (root: WasmRoot): number | string | boolean | JSObject | Promise | Date | Function { if (root.value === 0) return undefined; @@ -483,18 +483,18 @@ var BindingSupportLib = { } }, - create_task_completion_source: function (): number { + create_task_completion_source: function (): TaskCompletionSource { return BINDING.call_method (BINDING.create_tcs, null, "i", [ -1 ]); }, - set_task_result: function (tcs, result: string): void { + set_task_result: function (tcs: TaskCompletionSource, result: string): void { tcs.is_mono_tcs_result_set = true; BINDING.call_method (BINDING.set_tcs_result, null, "oo", [ tcs, result ]); if (tcs.is_mono_tcs_task_bound) BINDING.free_task_completion_source(tcs); }, - set_task_failure: function (tcs, reason): void { + set_task_failure: function (tcs: TaskCompletionSource, reason): void { tcs.is_mono_tcs_result_set = true; BINDING.call_method (BINDING.set_tcs_failure, null, "os", [ tcs, reason.toString () ]); if (tcs.is_mono_tcs_task_bound) @@ -502,7 +502,7 @@ var BindingSupportLib = { }, // https://github.com/Planeshifter/emscripten-examples/blob/master/01_PassingArrays/sum_post.js - js_typedarray_to_heap: function(typedArray): Uint8Array { + js_typedarray_to_heap: function(typedArray: TypedArray): Uint8Array { var numBytes = typedArray.length * typedArray.BYTES_PER_ELEMENT; var ptr = Module._malloc(numBytes); var heapBytes = new Uint8Array(Module.HEAPU8.buffer, ptr, numBytes); @@ -584,12 +584,12 @@ var BindingSupportLib = { return BINDING.get_task_and_bind (tcs, js_obj); case js_obj.constructor.name === "Date": // We may need to take into account the TimeZone Offset - return BINDING.call_method(BINDING.create_date_time, null, "d!", [ js_obj.getTime() ]); + return BINDING.call_method(BINDING.create_date_time, null, "d!", [ (js_obj as Date).getTime() ]); default: - return BINDING.extract_mono_obj (js_obj); + return BINDING.extract_mono_obj (js_obj as JSObject); } }, - js_to_mono_uri: function (js_obj: any): number { + js_to_mono_uri: function (js_obj: null | undefined | symbol | string | JSObject): number { BINDING.bindings_lazy_init (); switch (true) { @@ -600,7 +600,7 @@ var BindingSupportLib = { case typeof js_obj === "string": return BINDING.call_method(BINDING.create_uri, null, "s!", [ js_obj ]) default: - return BINDING.extract_mono_obj (js_obj); + return BINDING.extract_mono_obj (js_obj as JSObject); } }, has_backing_array_buffer: function (js_obj): boolean { @@ -635,7 +635,7 @@ var BindingSupportLib = { }, // Copy the existing typed array to the heap pointed to by the pinned array address // typed array memory -> copy to heap -> address of managed pinned array - typedarray_copy_to : function (typed_array, pinned_array: number, begin: number, end: number, bytes_per_element: number): number { + typedarray_copy_to : function (typed_array: TypedArray, pinned_array: number, begin: number, end: number, bytes_per_element: number): number { // JavaScript typed arrays are array-like objects and provide a mechanism for accessing // raw binary data. (...) To achieve maximum flexibility and efficiency, JavaScript typed arrays @@ -678,7 +678,7 @@ var BindingSupportLib = { }, // Copy the pinned array address from pinned_array allocated on the heap to the typed array. // adress of managed pinned array -> copy from heap -> typed array memory - typedarray_copy_from : function (typed_array, pinned_array: number, begin: number, end: number, bytes_per_element: number): number { + typedarray_copy_from : function (typed_array: TypedArray, pinned_array: number, begin: number, end: number, bytes_per_element: number): number { // JavaScript typed arrays are array-like objects and provide a mechanism for accessing // raw binary data. (...) To achieve maximum flexibility and efficiency, JavaScript typed arrays @@ -719,10 +719,10 @@ var BindingSupportLib = { }, // Creates a new typed array from pinned array address from pinned_array allocated on the heap to the typed array. // adress of managed pinned array -> copy from heap -> typed array memory - typed_array_from: function (pinned_array, begin: number, end: number, bytes_per_element: number, type: JSTypedArrays): ArrayBuffer { + typed_array_from: function (pinned_array: number, begin: number, end: number, bytes_per_element: number, type: JSTypedArrays): TypedArray { // typed array - var newTypedArray: ArrayBuffer; + var newTypedArray: TypedArray; switch (type) { @@ -758,7 +758,7 @@ var BindingSupportLib = { BINDING.typedarray_copy_from(newTypedArray, pinned_array, begin, end, bytes_per_element); return newTypedArray; }, - js_to_mono_enum: function (js_obj, method?: any/* todo unused var */, parmIdx?: any /* todo unused var */): number { + js_to_mono_enum: function (js_obj: number, method?: any/* todo unused var */, parmIdx?: any /* todo unused var */): number { BINDING.bindings_lazy_init (); if (typeof (js_obj) !== "number") @@ -766,7 +766,7 @@ var BindingSupportLib = { return js_obj | 0; }, - wasm_binding_obj_new: function (js_obj_id: number, ownsHandle: boolean, type) + wasm_binding_obj_new: function (js_obj_id: number, ownsHandle: boolean, type: number): number { return BINDING._bind_js_obj (js_obj_id, ownsHandle, type); }, @@ -787,7 +787,7 @@ var BindingSupportLib = { // when should_add_in_flight === true, the JSObject would be temporarily hold by Normal GCHandle, so that it would not get collected during transition to the managed stack. // its InFlight handle would be freed when the instance arrives to managed side via Interop.Runtime.ReleaseInFlight - wasm_get_raw_obj: function (gchandle: number, should_add_in_flight) + wasm_get_raw_obj: function (gchandle: number, should_add_in_flight: boolean): number { if(!gchandle){ return 0; @@ -813,9 +813,9 @@ var BindingSupportLib = { } }, - get_task_and_bind: function (tcs, js_obj: JSObject) { + get_task_and_bind: function (tcs: TaskCompletionSource, js_obj: JSObject): number { var gc_handle = BINDING.mono_wasm_free_list.length ? BINDING.mono_wasm_free_list.pop() : BINDING.mono_wasm_ref_counter++; - var task_gchandle = BINDING.call_method (BINDING.tcs_get_task_and_bind, null, "oi", [ tcs, gc_handle + 1 ]); + var task_gchandle = BINDING.call_method (BINDING.tcs_get_task_and_bind, null, "oi", [ tcs, gc_handle + 1 ]); js_obj.__mono_gchandle__ = task_gchandle; BINDING.mono_wasm_object_registry[gc_handle] = js_obj; BINDING.free_task_completion_source(tcs); @@ -825,7 +825,7 @@ var BindingSupportLib = { return BINDING.wasm_get_raw_obj (js_obj.__mono_gchandle__, true); }, - free_task_completion_source: function (tcs) { + free_task_completion_source: function (tcs: TaskCompletionSource): void { if (tcs.is_mono_tcs_result_set) { BINDING._unbind_raw_obj_and_free (tcs.__mono_gchandle__); @@ -836,7 +836,7 @@ var BindingSupportLib = { } }, - extract_mono_obj: function (js_obj: JSObject) { + extract_mono_obj: function (js_obj: JSObject): number { if (js_obj === null || typeof js_obj === "undefined") return 0; @@ -1264,7 +1264,7 @@ var BindingSupportLib = { } }, - call_method: function (method: number, this_arg, args_marshal: ArgsMarshalString, args: any[]): number { + call_method: function (method: number, this_arg, args_marshal: ArgsMarshalString, args: any[]): T { BINDING.bindings_lazy_init (); // HACK: Sometimes callers pass null or undefined, coerce it to 0 since that's what wasm expects @@ -1308,9 +1308,9 @@ var BindingSupportLib = { throw exc; }, - _handle_exception_and_produce_result_for_call: function ( - converter: Converter, buffer, resultRoot, exceptionRoot, argsRootBuffer, is_result_marshaled: boolean - ): number { + _handle_exception_and_produce_result_for_call: function ( + converter: Converter, buffer, resultRoot, exceptionRoot, argsRootBuffer: WasmRootBuffer, is_result_marshaled: boolean + ): T { BINDING._handle_exception_for_call (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer); let result = resultRoot.value; @@ -1322,7 +1322,7 @@ var BindingSupportLib = { return result; }, - _teardown_after_call: function (converter: Converter, buffer, resultRoot, exceptionRoot, argsRootBuffer): void { + _teardown_after_call: function (converter: Converter, buffer, resultRoot, exceptionRoot, argsRootBuffer: WasmRootBuffer): void { BINDING._release_args_root_buffer_from_method_call (converter, argsRootBuffer); BINDING._release_buffer_from_method_call (converter, buffer | 0); @@ -1342,7 +1342,7 @@ var BindingSupportLib = { return result; }, - _call_method_with_converted_args: function (method: number, this_arg, converter, buffer, is_result_marshaled: boolean, argsRootBuffer): number { + _call_method_with_converted_args: function (method: number, this_arg, converter: Converter, buffer, is_result_marshaled: boolean, argsRootBuffer: WasmRootBuffer): T { var resultRoot = MONO.mono_wasm_new_root (), exceptionRoot = MONO.mono_wasm_new_root (); resultRoot.value = BINDING.invoke_method (method, this_arg, buffer, exceptionRoot.get_address ()); return BINDING._handle_exception_and_produce_result_for_call (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer, is_result_marshaled); @@ -1539,7 +1539,7 @@ var BindingSupportLib = { return method; }, - call_static_method: function (fqn: string, args: any[] | null, signature: ArgsMarshalString | null): number { + call_static_method: function (fqn: string, args: any[], signature: ArgsMarshalString | null): number { BINDING.bindings_lazy_init (); var method = BINDING.resolve_method_fqn (fqn); @@ -1561,7 +1561,7 @@ var BindingSupportLib = { return BINDING.bind_method (method, null, signature, fqn); }, - bind_assembly_entry_point: function (assembly: string, signature: ArgsMarshalString): (...args: any) => Promise { + bind_assembly_entry_point: function (assembly: string, signature: ArgsMarshalString): (...args: any) => Promise { BINDING.bindings_lazy_init (); var asm = BINDING.assembly_load (assembly); @@ -2014,7 +2014,7 @@ var BindingSupportLib = { var res = BINDING.typedarray_copy_to(requireObject, pinned_array, begin, end, bytes_per_element); return BINDING.js_to_mono_obj (res) }, - mono_wasm_typed_array_from: function(pinned_array: number, begin: number, end: number, bytes_per_element: number, type, is_exception): number { + mono_wasm_typed_array_from: function(pinned_array: number, begin: number, end: number, bytes_per_element: number, type, is_exception?: any /* unused */): number { BINDING.bindings_lazy_init (); var res = BINDING.typed_array_from(pinned_array, begin, end, bytes_per_element, type); return BINDING.js_to_mono_obj (res) diff --git a/src/mono/wasm/runtime/dotnet-support.ts b/src/mono/wasm/runtime/dotnet-support.ts index 1431347795b32..a79e9def84d34 100644 --- a/src/mono/wasm/runtime/dotnet-support.ts +++ b/src/mono/wasm/runtime/dotnet-support.ts @@ -27,7 +27,7 @@ var DotNetSupportLib = { }, // This is for back-compat only and will eventually be removed - mono_wasm_invoke_js_marshalled: function (exceptionMessage: number, asyncHandleLongPtr, functionName, argsJson, treatResultAsVoid): number { + mono_wasm_invoke_js_marshalled: function (exceptionMessage: number, asyncHandleLongPtr: number, functionName: number, argsJson, treatResultAsVoid): number { var mono_string = globalThis._mono_string_cached || (globalThis._mono_string_cached = Module.cwrap('mono_wasm_string_from_js', 'number', ['string'])); @@ -67,7 +67,7 @@ var DotNetSupportLib = { }, // This is for back-compat only and will eventually be removed - mono_wasm_invoke_js_unmarshalled: function (exceptionMessage: number, funcName, arg0, arg1, arg2): number { + mono_wasm_invoke_js_unmarshalled: function (exceptionMessage: number, funcName: number, arg0, arg1, arg2): number { try { // Get the function you're trying to invoke var funcNameJsString = DOTNET.conv_string(funcName); diff --git a/src/mono/wasm/runtime/library-mono.ts b/src/mono/wasm/runtime/library-mono.ts index d3a5538119e82..c2fdb7236eeae 100644 --- a/src/mono/wasm/runtime/library-mono.ts +++ b/src/mono/wasm/runtime/library-mono.ts @@ -5,17 +5,21 @@ var MonoSupportLib = { $MONO__postset: 'MONO.export_functions (Module);', $MONO: { pump_count: 0, - timeout_queue: [], - _vt_stack: [], + timeout_queue: [] as ((id?: number) => void)[], mono_wasm_runtime_is_ready : false, mono_wasm_ignore_pdb_load_errors: true, - - /** @type {object.} */ + mono_text_decoder: undefined, + num_icu_assets_loaded_successfully: 0, + _vt_stack: [], + _scratch_root_buffer: null as WasmRootBuffer, + _scratch_root_free_indices: null as Int32Array, + _scratch_root_free_indices_count: 0, + _scratch_root_free_instances: [] as number[], _id_table: {}, - - pump_message: function () { + + pump_message: function (): void { if (!MONO.mono_background_exec) - MONO.mono_background_exec = Module.cwrap ("mono_background_exec", null); + MONO.mono_background_exec = Module.cwrap ("mono_background_exec", null); while (MONO.timeout_queue.length > 0) { --MONO.pump_count; MONO.timeout_queue.shift()(); @@ -26,7 +30,7 @@ var MonoSupportLib = { } }, - export_functions: function (module: typeof Module) { + export_functions: function (module: typeof Module): void { module ["pump_message"] = MONO.pump_message.bind(MONO); module ["mono_load_runtime_and_bcl"] = MONO.mono_load_runtime_and_bcl.bind(MONO); module ["mono_load_runtime_and_bcl_args"] = MONO.mono_load_runtime_and_bcl_args.bind(MONO); @@ -203,11 +207,6 @@ var MonoSupportLib = { } }, - _scratch_root_buffer: null as WasmRootBuffer, - _scratch_root_free_indices: null as Int32Array, - _scratch_root_free_indices_count: 0, - _scratch_root_free_instances: [] as number[], - _mono_wasm_root_prototype: { get_address: function (): NativePointer { return this.__buffer.get_address (this.__index); @@ -244,6 +243,85 @@ var MonoSupportLib = { return "[root @" + this.get_address () + "]"; } }, + + string_decoder: { + copy: function (mono_string: number): string { + if (mono_string === 0) + return null; + + if (!this.mono_wasm_string_root) + this.mono_wasm_string_root = MONO.mono_wasm_new_root (); + this.mono_wasm_string_root.value = mono_string; + + if (!this.mono_wasm_string_get_data) + this.mono_wasm_string_get_data = Module.cwrap ("mono_wasm_string_get_data", null, ['number', 'number', 'number', 'number']); + + if (!this.mono_wasm_string_decoder_buffer) + this.mono_wasm_string_decoder_buffer = Module._malloc(12); + + let ppChars = this.mono_wasm_string_decoder_buffer + 0, + pLengthBytes = this.mono_wasm_string_decoder_buffer + 4, + pIsInterned = this.mono_wasm_string_decoder_buffer + 8; + + this.mono_wasm_string_get_data (mono_string, ppChars, pLengthBytes, pIsInterned); + + // TODO: Is this necessary? + if (!this.mono_wasm_empty_string) + this.mono_wasm_empty_string = ""; + + let result = this.mono_wasm_empty_string; + let lengthBytes = Module.HEAP32[pLengthBytes / 4], + pChars = Module.HEAP32[ppChars / 4], + isInterned = Module.HEAP32[pIsInterned / 4]; + + if (pLengthBytes && pChars) { + if ( + isInterned && + MONO.interned_string_table && + MONO.interned_string_table.has(mono_string) + ) { + result = MONO.interned_string_table.get(mono_string); + // console.log("intern table cache hit", mono_string, result.length); + } else { + result = this.decode(pChars, pChars + lengthBytes, false); + if (isInterned) { + if (!MONO.interned_string_table) + MONO.interned_string_table = new Map(); + // console.log("interned", mono_string, result.length); + MONO.interned_string_table.set(mono_string, result); + } + } + } + + this.mono_wasm_string_root.value = 0; + return result; + }, + decode: function (start: number, end: number, save: boolean): string { + if (!MONO.mono_text_decoder) { + MONO.mono_text_decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-16le') : undefined; + } + + var str = ""; + if (MONO.mono_text_decoder) { + // When threading is enabled, TextDecoder does not accept a view of a + // SharedArrayBuffer, we must make a copy of the array first. + var subArray = typeof SharedArrayBuffer !== 'undefined' && Module.HEAPU8.buffer instanceof SharedArrayBuffer + ? Module.HEAPU8.slice(start, end) + : Module.HEAPU8.subarray(start, end); + + str = MONO.mono_text_decoder.decode(subArray); + } else { + for (var i = 0; i < end - start; i+=2) { + var char = Module.getValue (start + i, 'i16'); + str += String.fromCharCode (char); + } + } + if (save) + this.result = str; + + return str; + }, + }, _mono_wasm_release_scratch_index: function (index: number): void { if (index === undefined) @@ -403,7 +481,7 @@ var MonoSupportLib = { * @param {(number | ManagedPointer[])} count_or_values - either a number of roots or an array of pointers * @returns {WasmRoot[]} */ - mono_wasm_new_roots: function (count_or_values: number | ManagedPointer[]): WasmRoot[] { + mono_wasm_new_roots: function (count_or_values: ManagedPointer[]): WasmRoot[] { var result; if (Array.isArray (count_or_values)) { @@ -437,85 +515,6 @@ var MonoSupportLib = { } }, - mono_text_decoder: undefined, - string_decoder: { - copy: function (mono_string: number): string { - if (mono_string === 0) - return null; - - if (!this.mono_wasm_string_root) - this.mono_wasm_string_root = MONO.mono_wasm_new_root (); - this.mono_wasm_string_root.value = mono_string; - - if (!this.mono_wasm_string_get_data) - this.mono_wasm_string_get_data = Module.cwrap ("mono_wasm_string_get_data", null, ['number', 'number', 'number', 'number']); - - if (!this.mono_wasm_string_decoder_buffer) - this.mono_wasm_string_decoder_buffer = Module._malloc(12); - - let ppChars = this.mono_wasm_string_decoder_buffer + 0, - pLengthBytes = this.mono_wasm_string_decoder_buffer + 4, - pIsInterned = this.mono_wasm_string_decoder_buffer + 8; - - this.mono_wasm_string_get_data (mono_string, ppChars, pLengthBytes, pIsInterned); - - // TODO: Is this necessary? - if (!this.mono_wasm_empty_string) - this.mono_wasm_empty_string = ""; - - let result = this.mono_wasm_empty_string; - let lengthBytes = Module.HEAP32[pLengthBytes / 4], - pChars = Module.HEAP32[ppChars / 4], - isInterned = Module.HEAP32[pIsInterned / 4]; - - if (pLengthBytes && pChars) { - if ( - isInterned && - MONO.interned_string_table && - MONO.interned_string_table.has(mono_string) - ) { - result = MONO.interned_string_table.get(mono_string); - // console.log("intern table cache hit", mono_string, result.length); - } else { - result = this.decode(pChars, pChars + lengthBytes, false); - if (isInterned) { - if (!MONO.interned_string_table) - MONO.interned_string_table = new Map(); - // console.log("interned", mono_string, result.length); - MONO.interned_string_table.set(mono_string, result); - } - } - } - - this.mono_wasm_string_root.value = 0; - return result; - }, - decode: function (start: number, end: number, save: boolean): string { - if (!MONO.mono_text_decoder) { - MONO.mono_text_decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-16le') : undefined; - } - - var str = ""; - if (MONO.mono_text_decoder) { - // When threading is enabled, TextDecoder does not accept a view of a - // SharedArrayBuffer, we must make a copy of the array first. - var subArray = typeof SharedArrayBuffer !== 'undefined' && Module.HEAPU8.buffer instanceof SharedArrayBuffer - ? Module.HEAPU8.slice(start, end) - : Module.HEAPU8.subarray(start, end); - - str = MONO.mono_text_decoder.decode(subArray); - } else { - for (var i = 0; i < end - start; i+=2) { - var char = Module.getValue (start + i, 'i16'); - str += String.fromCharCode (char); - } - } - if (save) - this.result = str; - - return str; - }, - }, mono_wasm_add_dbg_command_received: function(res_ok: number, id: number, buffer: number, buffer_len: number): void { const assembly_data = new Uint8Array(Module.HEAPU8.buffer, buffer, buffer_len); @@ -896,13 +895,13 @@ var MonoSupportLib = { } }, - _handle_loaded_asset: function (ctx, asset: AssetEntry, url: string, blob: Iterable): void { + _handle_loaded_asset: function (ctx: Context, asset: AssetEntry, url: string, blob: Iterable): void { var bytes = new Uint8Array (blob); if (ctx.tracing) console.log ("MONO_WASM: Loaded:", asset.name, "size", bytes.length, "from", url); var virtualName = asset.virtual_path || asset.name; - var offset = null; + var offset: number = null; switch (asset.behavior) { case AssetBehaviours.Resource: @@ -1040,7 +1039,7 @@ var MonoSupportLib = { // "invariant": operate in invariant globalization mode. // "auto" (default): if "icu" behavior assets are present, use ICU, otherwise invariant. // diagnostic_tracing: (optional) enables diagnostic log messages during startup - mono_load_runtime_and_bcl_args: function (args) { + mono_load_runtime_and_bcl_args: function (args: MonoRuntimeArgs): void { try { return MONO._load_assets_and_runtime (args); } catch (exc) { @@ -1058,8 +1057,6 @@ var MonoSupportLib = { return memoryOffset; }, - num_icu_assets_loaded_successfully: 0, - // @offset must be the address of an ICU data archive in the native heap. // returns true on success. mono_wasm_load_icu_data: function (offset: number): boolean { @@ -1078,7 +1075,7 @@ var MonoSupportLib = { return Module.ccall ('mono_wasm_get_icudt_name', 'string', ['string'], [culture]); }, - _finalize_startup: function (args: MonoRuntimeArgs, ctx): void { + _finalize_startup: function (args: MonoRuntimeArgs, ctx: Context): void { var loaded_files_with_debug_info = []; MONO.loaded_assets = ctx.loaded_assets; @@ -1131,7 +1128,7 @@ var MonoSupportLib = { if (!args.loaded_cb) throw new Error ("loaded_cb not provided"); - var ctx = { + var ctx: Context = { tracing: args.diagnostic_tracing || false, pending_count: args.assets.length, mono_wasm_add_assembly: Module.cwrap ('mono_wasm_add_assembly', 'number', ['string', 'number', 'number']), @@ -1311,7 +1308,7 @@ var MonoSupportLib = { return new Uint8Array (byteNumbers); }, - mono_wasm_load_data_archive: function (data, prefix): boolean { + mono_wasm_load_data_archive: function (data: TypedArray, prefix: string): boolean { if (data.length < 8) return false; diff --git a/src/mono/wasm/runtime/types/Module.d.ts b/src/mono/wasm/runtime/types/Module.d.ts index 3e5632c2c30bd..e4a19a5ef5905 100644 --- a/src/mono/wasm/runtime/types/Module.d.ts +++ b/src/mono/wasm/runtime/types/Module.d.ts @@ -7,9 +7,6 @@ THIS FILE IS NOT INCLUDED IN DOTNET.JS. ALL CODE HERE WILL BE IGNORED DURING THE BUILD ********************************************************************************************/ - -// TODO PROPERLY SET THESE ANYS - declare namespace Module { let config: MonoConfig; let HEAP8: Int8Array; @@ -45,13 +42,13 @@ declare namespace Module { function cwrap (ident: string, returnType: string, argTypes?: string[], opts?: any): T; function cwrap (ident: string, ...args: any[]): T; - function FS_createPath (parent: string | any, path: string, canRead?: boolean /* unused */, canWrite?: boolean /* unused */): string; - function FS_createDataFile (parent: string | any, name: string, data: string, canRead: boolean, canWrite: boolean, canOwn?: boolean): string; + function FS_createPath (parent: string, path: string, canRead?: boolean /* unused */, canWrite?: boolean /* unused */): string; + function FS_createDataFile (parent: string, name: string, data: TypedArray, canRead: boolean, canWrite: boolean, canOwn?: boolean): string; function setValue (ptr: number, value: number, type: string, noSafe?: number | boolean): void; function getValue (ptr: number, type: string, noSafe?: number | boolean ): number; function UTF8ToString (ptr: number, maxBytesToRead?: number): string; function UTF8ToString (arg: string): string; - function UTF8ArrayToString (str: string, heap: number[] | number, outIdx: number, maxBytesToWrite?: number): string; + function UTF8ArrayToString (str: TypedArray, heap: number[] | number, outIdx: number, maxBytesToWrite?: number): string; function addFunction (func: Function, sig: string): void; } @@ -120,3 +117,15 @@ type Culture = "ar_SA" | "am_ET" | "bg_BG" | "bn_BD" | "bn_IN" | "ca_AD" | "ca_E "sk_SK" | "sl_SI" | "sr_Cyrl_RS" | "sr_Latn_RS" | "sv_AX" | "sv_SE" | "sw_CD" | "sw_KE" | "sw_TZ" | "sw_UG" | "ta_IN" | "ta_LK" | "ta_MY" | "ta_SG" | "te_IN" | "th_TH" | "tr_CY" | "tr_TR" | "uk_UA" | "vi_VN" | "zh_CN" | "zh_Hans_HK" | "zh_SG" | "zh_HK" | "zh_TW"; + +type Context = { + tracing: boolean, + pending_count: number, + num_icu_assets_loaded_successfully?: number, + mono_wasm_add_assembly: (a: string, b: number, c:number) => number, + mono_wasm_add_satellite_assembly: (a: string, b:string, c:number, d:number) => void, + loaded_files: {url: string, file: string}[], + loaded_assets: string[], + createPath: Function, + createDataFile: Function +} diff --git a/src/mono/wasm/runtime/types/binding-types.d.ts b/src/mono/wasm/runtime/types/binding-types.d.ts index 9720da77211fc..05d5f91c7840a 100644 --- a/src/mono/wasm/runtime/types/binding-types.d.ts +++ b/src/mono/wasm/runtime/types/binding-types.d.ts @@ -92,7 +92,8 @@ type JSObject = { __mono_delegate_alive__?: boolean, __mono_js_cont__?: number, is_mono_bridged_obj?: boolean, -} + then?: Function +}; type Converter = { steps: { @@ -125,32 +126,6 @@ declare const enum ConverterStepIndirects { Int64 = "i64", } -declare const enum ArgsMarshal { - Int32 = "i", // int32 - Int32Enum = "j", // int32 - Enum with underlying type of int32 - Int64 = "l", // int64 - Int64Enum = "k", // int64 - Enum with underlying type of int64 - Float32 = "f", // float - Float64 = "d", // double - String = "s", // string - Char = "s", // interned string - JSObj = "o", // js object will be converted to a C# object (this will box numbers/bool/promises) - MONOObj = "m", // raw mono object. Don't use it unless you know what you're doing -} - -// to suppress marshaling of the return value, place '!' at the end of args_marshal, i.e. 'ii!' instead of 'ii' -type _ExtraArgsMarshalOperators = "!" | ""; - -// TODO make this more efficient so we can add more parameters (currently it only checks up to 4). One option is to add a -// blank to the ArgsMarshal enum but that doesn't solve the TS limit of number of options in 1 type -// Take the 2 marshaling enums and convert to all the valid strings for type checking. -type ArgsMarshalString = - `${ArgsMarshal}${_ExtraArgsMarshalOperators}` - | `${ArgsMarshal}${ArgsMarshal}${_ExtraArgsMarshalOperators}` - | `${ArgsMarshal}${ArgsMarshal}${ArgsMarshal}${_ExtraArgsMarshalOperators}` - | `${ArgsMarshal}${ArgsMarshal}${ArgsMarshal}${ArgsMarshal}${_ExtraArgsMarshalOperators}`; - - declare const enum CNonPrimativeTypes { String = 3, VTS = 4, // throws errors due to "no idea on how to unbox value types" @@ -196,3 +171,34 @@ declare const enum JSTypedArrays { Float64Array = 14, Uint8ClampedArray = 15, } + +declare const enum ArgsMarshal { + Int32 = "i", // int32 + Int32Enum = "j", // int32 - Enum with underlying type of int32 + Int64 = "l", // int64 + Int64Enum = "k", // int64 - Enum with underlying type of int64 + Float32 = "f", // float + Float64 = "d", // double + String = "s", // string + Char = "s", // interned string + JSObj = "o", // js object will be converted to a C# object (this will box numbers/bool/promises) + MONOObj = "m", // raw mono object. Don't use it unless you know what you're doing +} + +// to suppress marshaling of the return value, place '!' at the end of args_marshal, i.e. 'ii!' instead of 'ii' +type _ExtraArgsMarshalOperators = "!" | ""; + +// TODO make this more efficient so we can add more parameters (currently it only checks up to 4). One option is to add a +// blank to the ArgsMarshal enum but that doesn't solve the TS limit of number of options in 1 type +// Take the marshaling enums and convert to all the valid strings for type checking. +type ArgsMarshalString = `${ArgsMarshal}${_ExtraArgsMarshalOperators}` + | `${ArgsMarshal}${ArgsMarshal}${_ExtraArgsMarshalOperators}` + | `${ArgsMarshal}${ArgsMarshal}${ArgsMarshal}${_ExtraArgsMarshalOperators}` + | `${ArgsMarshal}${ArgsMarshal}${ArgsMarshal}${ArgsMarshal}${_ExtraArgsMarshalOperators}`; + +type TaskCompletionSource = { // TODO what should this be called? + is_mono_tcs_result_set: boolean; + is_mono_tcs_task_bound: boolean; + __mono_bound_task__: number; + __mono_gchandle__: number; +}; diff --git a/src/mono/wasm/runtime/types/general-types.d.ts b/src/mono/wasm/runtime/types/general-types.d.ts index ed55719b5dc04..153e8babd8fd9 100644 --- a/src/mono/wasm/runtime/types/general-types.d.ts +++ b/src/mono/wasm/runtime/types/general-types.d.ts @@ -27,3 +27,4 @@ declare function mergeInto(a: object, b: object); // Joins the various file specific C functions into 1 interface for easier access interface C_FUNCS extends BINDING_C_FUNCS, DOTNET_C_FUNCS, MONO_C_FUNCS {} +type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array From a57bd53499497987ba11bee3edae7cf33406b8d7 Mon Sep 17 00:00:00 2001 From: Daniel-Genkin Date: Thu, 22 Jul 2021 15:30:53 -0400 Subject: [PATCH 16/19] Added more types --- src/mono/wasm/runtime/binding-support.ts | 96 +++++++++---------- src/mono/wasm/runtime/library-mono.ts | 65 ++----------- src/mono/wasm/runtime/types/Module.d.ts | 20 ++-- .../wasm/runtime/types/binding-types.d.ts | 10 +- .../wasm/runtime/types/general-types.d.ts | 3 +- src/mono/wasm/runtime/types/mono-types.d.ts | 62 +++++++----- 6 files changed, 113 insertions(+), 143 deletions(-) diff --git a/src/mono/wasm/runtime/binding-support.ts b/src/mono/wasm/runtime/binding-support.ts index 51aec9d443c28..512be984751e7 100644 --- a/src/mono/wasm/runtime/binding-support.ts +++ b/src/mono/wasm/runtime/binding-support.ts @@ -5,11 +5,11 @@ var BindingSupportLib = { $BINDING__postset: 'BINDING.export_functions (Module);', $BINDING: { BINDING_ASM: "[System.Private.Runtime.InteropServices.JavaScript]System.Runtime.InteropServices.JavaScript.Runtime", - mono_wasm_object_registry: [], + mono_wasm_object_registry: [] as JSObject[], mono_wasm_ref_counter: 0, - mono_wasm_free_list: [], - mono_wasm_owned_objects_frames: [], - mono_wasm_owned_objects_LMF: [], + mono_wasm_free_list: [] as number[], + mono_wasm_owned_objects_frames: [] as number[][], + mono_wasm_owned_objects_LMF: [] as number[], mono_wasm_marshal_enum_as_int: true, mono_bindings_init: function (binding_asm: string): void { BINDING.BINDING_ASM = binding_asm; @@ -376,7 +376,7 @@ var BindingSupportLib = { }; }, - _unbox_task_root: function (root: WasmRoot): Promise { + _unbox_task_root: function (root: WasmRoot): Promise { if (!BINDING._are_promises_supported) throw new Error ("Promises are not supported thus 'System.Threading.Tasks.Task' can not work in this context."); @@ -396,7 +396,7 @@ var BindingSupportLib = { return promise; }, - _unbox_safehandle_root: function (root: WasmRoot): number { + _unbox_safehandle_root: function (root: WasmRoot): JSObject { var addRef = true; var js_handle = BINDING.call_method(BINDING.safehandle_get_handle, null, "mi", [ root.value, addRef ]); var requiredObject = BINDING.mono_wasm_require_handle (js_handle); @@ -494,7 +494,7 @@ var BindingSupportLib = { BINDING.free_task_completion_source(tcs); }, - set_task_failure: function (tcs: TaskCompletionSource, reason): void { + set_task_failure: function (tcs: TaskCompletionSource, reason: any): void { tcs.is_mono_tcs_result_set = true; BINDING.call_method (BINDING.set_tcs_failure, null, "os", [ tcs, reason.toString () ]); if (tcs.is_mono_tcs_task_bound) @@ -603,13 +603,13 @@ var BindingSupportLib = { return BINDING.extract_mono_obj (js_obj as JSObject); } }, - has_backing_array_buffer: function (js_obj): boolean { + has_backing_array_buffer: function (js_obj: any): boolean { return typeof SharedArrayBuffer !== 'undefined' ? js_obj.buffer instanceof ArrayBuffer || js_obj.buffer instanceof SharedArrayBuffer : js_obj.buffer instanceof ArrayBuffer; }, - js_typed_array_to_array : function (js_obj): number { + js_typed_array_to_array : function (js_obj: TypedArray): number { // JavaScript typed arrays are array-like objects and provide a mechanism for accessing // raw binary data. (...) To achieve maximum flexibility and efficiency, JavaScript typed arrays @@ -796,7 +796,7 @@ var BindingSupportLib = { return BINDING._get_raw_mono_obj (gchandle, should_add_in_flight ? 1 : 0); }, - try_extract_mono_obj: function (js_obj: JSObject) { + try_extract_mono_obj: function (js_obj: JSObject): number { if (js_obj === null || typeof js_obj === "undefined" || typeof js_obj.__mono_gchandle__ === "undefined") return 0; return BINDING.wasm_get_raw_obj (js_obj.__mono_gchandle__, true); @@ -890,7 +890,7 @@ var BindingSupportLib = { return js_obj; }, - _create_named_function: function (name: string, argumentNames, body: string, closure): T { + _create_named_function: function (name: string, argumentNames: string[], body: string, closure: object): T { var result = null, keys = null, closureArgumentList = null, closureArgumentNames = null; if (closure) { @@ -906,7 +906,7 @@ var BindingSupportLib = { return result; }, - _create_rebindable_named_function: function (name: string, argumentNames, body: string, closureArgNames): T { + _create_rebindable_named_function: function (name: string, argumentNames: string[], body: string, closureArgNames: string[]): T { var strictPrefix = "\"use strict\";\r\n"; var uriPrefix = "", escapedFunctionIdentifier = ""; @@ -1157,7 +1157,7 @@ var BindingSupportLib = { return converter; }, - _verify_args_for_method_call: function (args_marshal: ArgsMarshalString, args: any[]): boolean { + _verify_args_for_method_call: function (args_marshal: ArgsMarshalString, args?: any): boolean { var has_args = args && (typeof args === "object") && args.length > 0; var has_args_marshal = typeof args_marshal === "string"; @@ -1202,7 +1202,7 @@ var BindingSupportLib = { return result; }, - _release_args_root_buffer_from_method_call: function (converter: Converter, argsRootBuffer): void { + _release_args_root_buffer_from_method_call: function (converter: Converter, argsRootBuffer: WasmRootBuffer): void { if (!argsRootBuffer || !converter) return; @@ -1264,10 +1264,10 @@ var BindingSupportLib = { } }, - call_method: function (method: number, this_arg, args_marshal: ArgsMarshalString, args: any[]): T { + call_method: function (method: number, this_arg: number, args_marshal: ArgsMarshalString, args: any[]): T { BINDING.bindings_lazy_init (); - // HACK: Sometimes callers pass null or undefined, coerce it to 0 since that's what wasm expects + // @ts-ignore: HACK: Sometimes callers pass null or undefined, coerce it to 0 since that's what wasm expects this_arg = this_arg | 0; // Detect someone accidentally passing the wrong type of value to method @@ -1298,7 +1298,7 @@ var BindingSupportLib = { }, _handle_exception_for_call: function ( - converter: Converter, buffer, resultRoot, exceptionRoot, argsRootBuffer + converter: Converter, buffer: number, resultRoot: WasmRoot, exceptionRoot: WasmRoot, argsRootBuffer: WasmRootBuffer ): void { var exc = BINDING._convert_exception_for_method_call (resultRoot.value, exceptionRoot.value); if (!exc) @@ -1308,12 +1308,12 @@ var BindingSupportLib = { throw exc; }, - _handle_exception_and_produce_result_for_call: function ( - converter: Converter, buffer, resultRoot, exceptionRoot, argsRootBuffer: WasmRootBuffer, is_result_marshaled: boolean - ): T { + _handle_exception_and_produce_result_for_call: function ( + converter: Converter, buffer: number, resultRoot: WasmRoot, exceptionRoot: WasmRoot, argsRootBuffer: WasmRootBuffer, is_result_marshaled: boolean + ): any { BINDING._handle_exception_for_call (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer); - let result = resultRoot.value; + let result: any = resultRoot.value; // the any stops tsc from complaining that here it is a number and later it can be something else if (is_result_marshaled) result = BINDING._unbox_mono_obj_root (resultRoot); @@ -1322,7 +1322,7 @@ var BindingSupportLib = { return result; }, - _teardown_after_call: function (converter: Converter, buffer, resultRoot, exceptionRoot, argsRootBuffer: WasmRootBuffer): void { + _teardown_after_call: function (converter: Converter, buffer: number, resultRoot: WasmRoot, exceptionRoot: WasmRoot, argsRootBuffer: WasmRootBuffer): void { BINDING._release_args_root_buffer_from_method_call (converter, argsRootBuffer); BINDING._release_buffer_from_method_call (converter, buffer | 0); @@ -1342,15 +1342,16 @@ var BindingSupportLib = { return result; }, - _call_method_with_converted_args: function (method: number, this_arg, converter: Converter, buffer, is_result_marshaled: boolean, argsRootBuffer: WasmRootBuffer): T { + _call_method_with_converted_args: function (method: number, this_arg: number, converter: Converter, buffer: number, is_result_marshaled: boolean, argsRootBuffer: WasmRootBuffer): T { var resultRoot = MONO.mono_wasm_new_root (), exceptionRoot = MONO.mono_wasm_new_root (); resultRoot.value = BINDING.invoke_method (method, this_arg, buffer, exceptionRoot.get_address ()); return BINDING._handle_exception_and_produce_result_for_call (converter, buffer, resultRoot, exceptionRoot, argsRootBuffer, is_result_marshaled); }, - bind_method: function (method: number, this_arg, args_marshal: ArgsMarshalString, friendly_name: string): T { + bind_method: function (method: number, this_arg: number, args_marshal: ArgsMarshalString, friendly_name: string): T { BINDING.bindings_lazy_init (); + // @ts-ignore: HACK: Sometimes callers pass null or undefined, coerce it to 0 since that's what wasm expects this_arg = this_arg | 0; var converter = null; @@ -1470,7 +1471,7 @@ var BindingSupportLib = { return BINDING._create_named_function(displayName, argumentNames, bodyJs, closure); }, - invoke_delegate: function (delegate_obj, js_args): number { + invoke_delegate: function (delegate_obj: JSObject, js_args: any): number { BINDING.bindings_lazy_init (); // Check to make sure the delegate is still alive on the CLR side of things. @@ -1561,7 +1562,7 @@ var BindingSupportLib = { return BINDING.bind_method (method, null, signature, fqn); }, - bind_assembly_entry_point: function (assembly: string, signature: ArgsMarshalString): (...args: any) => Promise { + bind_assembly_entry_point: function (assembly: string, signature: ArgsMarshalString): (...args: any) => Promise { BINDING.bindings_lazy_init (); var asm = BINDING.assembly_load (assembly); @@ -1587,13 +1588,12 @@ var BindingSupportLib = { } }; }, - call_assembly_entry_point: function (assembly: string, args: any[], signature: ArgsMarshalString) { + call_assembly_entry_point: function (assembly: string, args: any[], signature: ArgsMarshalString): any { return BINDING.bind_assembly_entry_point (assembly, signature) (...args); }, // Object wrapping helper functions to handle reference handles that will // be used in managed code. mono_wasm_register_obj: function(js_obj: JSObject): { gc_handle: number, should_add_in_flight: boolean } { - var gc_handle = undefined; if (js_obj !== null && typeof js_obj !== "undefined") { @@ -1615,12 +1615,12 @@ var BindingSupportLib = { // this is pre-existing instance, we need to add Inflight strong GCHandle before passing it to managed return { gc_handle, should_add_in_flight: true }; }, - mono_wasm_require_handle: function(handle: number) { + mono_wasm_require_handle: function(handle: number): JSObject | null { if (handle > 0) return BINDING.mono_wasm_object_registry[handle - 1]; return null; }, - mono_wasm_unregister_obj: function(js_id: number) { + mono_wasm_unregister_obj: function(js_id: number): JSObject { var obj = BINDING.mono_wasm_object_registry[js_id - 1]; if (typeof obj !== "undefined" && obj !== null) { // if this is the global object then do not @@ -1669,7 +1669,7 @@ var BindingSupportLib = { } return obj; }, - mono_wasm_parse_args_root: function (argsRoot): any[] { + mono_wasm_parse_args_root: function (argsRoot: WasmRoot): any[] { var js_args = BINDING._mono_array_root_to_js_array(argsRoot); BINDING.mono_wasm_save_LMF(); return js_args; @@ -1695,13 +1695,13 @@ var BindingSupportLib = { //console.log("restore LMF: " + BINDING.mono_wasm_owned_objects_frames.length) }, - mono_wasm_convert_return_value: function (ret): number { + mono_wasm_convert_return_value: function (ret: any): number { BINDING.mono_wasm_unwind_LMF(); return BINDING.js_to_mono_obj (ret); }, }, - mono_wasm_invoke_js_with_args: function(js_handle: number, method_name, args, is_exception): number { + mono_wasm_invoke_js_with_args: function(js_handle: number, method_name: number, args: number, is_exception: number): number { let argsRoot = MONO.mono_wasm_new_root (args), nameRoot = MONO.mono_wasm_new_root (method_name); try { BINDING.bindings_lazy_init (); @@ -1741,7 +1741,7 @@ var BindingSupportLib = { nameRoot.release(); } }, - mono_wasm_get_object_property: function(js_handle: number, property_name, is_exception): number { + mono_wasm_get_object_property: function(js_handle: number, property_name: number, is_exception: number): number { BINDING.bindings_lazy_init (); var nameRoot = MONO.mono_wasm_new_root (property_name); @@ -1776,7 +1776,7 @@ var BindingSupportLib = { nameRoot.release(); } }, - mono_wasm_set_object_property: function (js_handle: number, property_name, value, createIfNotExist, hasOwnProperty, is_exception): number | boolean { + mono_wasm_set_object_property: function (js_handle: number, property_name: number, value: number, createIfNotExist: boolean, hasOwnProperty: boolean, is_exception: number): number | boolean { var valueRoot = MONO.mono_wasm_new_root (value), nameRoot = MONO.mono_wasm_new_root (property_name); try { BINDING.bindings_lazy_init (); @@ -1827,7 +1827,7 @@ var BindingSupportLib = { valueRoot.release(); } }, - mono_wasm_get_by_index: function(js_handle: number, property_index, is_exception): number { + mono_wasm_get_by_index: function(js_handle: number, property_index: number, is_exception: number): number { BINDING.bindings_lazy_init (); var obj = BINDING.mono_wasm_require_handle (js_handle); @@ -1847,7 +1847,7 @@ var BindingSupportLib = { return BINDING.js_string_to_mono_string (res); } }, - mono_wasm_set_by_index: function(js_handle: number, property_index, value, is_exception): number | boolean { + mono_wasm_set_by_index: function(js_handle: number, property_index: number, value: number, is_exception: number): number | boolean { var valueRoot = MONO.mono_wasm_new_root (value); try { BINDING.bindings_lazy_init (); @@ -1876,7 +1876,7 @@ var BindingSupportLib = { valueRoot.release(); } }, - mono_wasm_get_global_object: function(global_name, is_exception): number { + mono_wasm_get_global_object: function(global_name: number, is_exception: number): number { var nameRoot = MONO.mono_wasm_new_root (global_name); try { BINDING.bindings_lazy_init (); @@ -1912,7 +1912,7 @@ var BindingSupportLib = { BINDING.mono_wasm_free_raw_object(js_handle); }, - mono_wasm_bind_core_object: function(js_handle: number, gc_handle: number, is_exception): number { + mono_wasm_bind_core_object: function(js_handle: number, gc_handle: number, is_exception: number): number { BINDING.bindings_lazy_init (); var requireObject = BINDING.mono_wasm_require_handle (js_handle); @@ -1926,7 +1926,7 @@ var BindingSupportLib = { requireObject.__js_handle__ = js_handle; return gc_handle; }, - mono_wasm_bind_host_object: function(js_handle: number, gc_handle: number, is_exception): number { + mono_wasm_bind_host_object: function(js_handle: number, gc_handle: number, is_exception: number): number { BINDING.bindings_lazy_init (); var requireObject = BINDING.mono_wasm_require_handle (js_handle); @@ -1939,7 +1939,7 @@ var BindingSupportLib = { requireObject.__mono_gchandle__ = gc_handle; return gc_handle; }, - mono_wasm_new: function (core_name, args, is_exception): number { + mono_wasm_new: function (core_name: number, args: number, is_exception: number): number { var argsRoot = MONO.mono_wasm_new_root (args), nameRoot = MONO.mono_wasm_new_root (core_name); try { BINDING.bindings_lazy_init (); @@ -1991,7 +1991,7 @@ var BindingSupportLib = { } }, - mono_wasm_typed_array_to_array: function(js_handle: number, is_exception) { + mono_wasm_typed_array_to_array: function(js_handle: number, is_exception: number): number { BINDING.bindings_lazy_init (); var requireObject = BINDING.mono_wasm_require_handle (js_handle); @@ -2000,9 +2000,9 @@ var BindingSupportLib = { return BINDING.js_string_to_mono_string ("Invalid JS object handle '" + js_handle + "'"); } - return BINDING.js_typed_array_to_array(requireObject); + return BINDING.js_typed_array_to_array(requireObject as TypedArray); }, - mono_wasm_typed_array_copy_to: function(js_handle: number, pinned_array: number, begin: number, end: number, bytes_per_element: number, is_exception): number { + mono_wasm_typed_array_copy_to: function(js_handle: number, pinned_array: number, begin: number, end: number, bytes_per_element: number, is_exception: number): number { BINDING.bindings_lazy_init (); var requireObject = BINDING.mono_wasm_require_handle (js_handle); @@ -2011,15 +2011,15 @@ var BindingSupportLib = { return BINDING.js_string_to_mono_string ("Invalid JS object handle '" + js_handle + "'"); } - var res = BINDING.typedarray_copy_to(requireObject, pinned_array, begin, end, bytes_per_element); + var res = BINDING.typedarray_copy_to(requireObject as TypedArray, pinned_array, begin, end, bytes_per_element); return BINDING.js_to_mono_obj (res) }, - mono_wasm_typed_array_from: function(pinned_array: number, begin: number, end: number, bytes_per_element: number, type, is_exception?: any /* unused */): number { + mono_wasm_typed_array_from: function(pinned_array: number, begin: number, end: number, bytes_per_element: number, type: JSTypedArrays, is_exception?: any /* unused */): number { BINDING.bindings_lazy_init (); var res = BINDING.typed_array_from(pinned_array, begin, end, bytes_per_element, type); return BINDING.js_to_mono_obj (res) }, - mono_wasm_typed_array_copy_from: function(js_handle: number, pinned_array: number, begin: number, end: number, bytes_per_element: number, is_exception): number { + mono_wasm_typed_array_copy_from: function(js_handle: number, pinned_array: number, begin: number, end: number, bytes_per_element: number, is_exception: number): number { BINDING.bindings_lazy_init (); var requireObject = BINDING.mono_wasm_require_handle (js_handle); @@ -2028,7 +2028,7 @@ var BindingSupportLib = { return BINDING.js_string_to_mono_string ("Invalid JS object handle '" + js_handle + "'"); } - var res = BINDING.typedarray_copy_from(requireObject, pinned_array, begin, end, bytes_per_element); + var res = BINDING.typedarray_copy_from(requireObject as TypedArray, pinned_array, begin, end, bytes_per_element); return BINDING.js_to_mono_obj (res); }, }; diff --git a/src/mono/wasm/runtime/library-mono.ts b/src/mono/wasm/runtime/library-mono.ts index c2fdb7236eeae..227de7ad6dc0b 100644 --- a/src/mono/wasm/runtime/library-mono.ts +++ b/src/mono/wasm/runtime/library-mono.ts @@ -8,14 +8,14 @@ var MonoSupportLib = { timeout_queue: [] as ((id?: number) => void)[], mono_wasm_runtime_is_ready : false, mono_wasm_ignore_pdb_load_errors: true, - mono_text_decoder: undefined, + mono_text_decoder: undefined as TextDecoder, num_icu_assets_loaded_successfully: 0, - _vt_stack: [], _scratch_root_buffer: null as WasmRootBuffer, _scratch_root_free_indices: null as Int32Array, _scratch_root_free_indices_count: 0, _scratch_root_free_instances: [] as number[], - _id_table: {}, + _vt_stack: [], // TODO what are the types of these? + _id_table: {}, // TODO what are the types of these? pump_message: function (): void { if (!MONO.mono_background_exec) @@ -797,11 +797,11 @@ var MonoSupportLib = { MONO.wasm_setenv (name, value); }, - mono_wasm_set_runtime_options: function (options): void { + mono_wasm_set_runtime_options: function (options: RuntimeOptions): void { if (!MONO.wasm_parse_runtime_options) MONO.wasm_parse_runtime_options = Module.cwrap ('mono_wasm_parse_runtime_options', null, ['number', 'number']); var argv = Module._malloc (options.length * 4); - var wasm_strdup = Module.cwrap ('mono_wasm_strdup', 'number', ['string']); + var wasm_strdup = Module.cwrap<(a: string) => number> ('mono_wasm_strdup', 'number', ['string']); let aindex = 0; for (var i = 0; i < options.length; ++i) { Module.setValue (argv + (aindex * 4), wasm_strdup (options [i]), "i32"); @@ -810,16 +810,8 @@ var MonoSupportLib = { MONO.wasm_parse_runtime_options (options.length, argv); }, - // - // Initialize the AOT profiler with OPTIONS. - // Requires the AOT profiler to be linked into the app. - // options = { write_at: "", send_to: "" } - // should be in the format ::. - // write_at defaults to 'WebAssembly.Runtime::StopProfile'. - // send_to defaults to 'WebAssembly.Runtime::DumpAotProfileData'. // DumpAotProfileData stores the data into Module.aot_profile_data. - // - mono_wasm_init_aot_profiler: function (options): void { + mono_wasm_init_aot_profiler: function (options: AOTProfilerOptions): void { if (options == null) options = {} if (!('write_at' in options)) @@ -830,12 +822,9 @@ var MonoSupportLib = { Module.ccall ('mono_wasm_load_profiler_aot', null, ['string'], [arg]); }, - // options = { write_at: "", send_to: "" } - // should be in the format ::. - // write_at defaults to 'WebAssembly.Runtime::StopProfile'. - // send_to defaults to 'WebAssembly.Runtime::DumpCoverageProfileData'. + // DumpCoverageProfileData stores the data into Module.coverage_profile_data. - mono_wasm_init_coverage_profiler: function (options): void { + mono_wasm_init_coverage_profiler: function (options: AOTProfilerOptions): void { if (options == null) options = {} if (!('write_at' in options)) @@ -1001,44 +990,6 @@ var MonoSupportLib = { }, // Initializes the runtime and loads assemblies, debug information, and other files. - // @args is a dictionary-style Object with the following properties: - // assembly_root: (required) the subfolder containing managed assemblies and pdbs - // debug_level or enable_debugging: (required) - // assets: (required) a list of assets to load along with the runtime. each asset - // is a dictionary-style Object with the following properties: - // name: (required) the name of the asset, including extension. - // behavior: (required) determines how the asset will be handled once loaded: - // "heap": store asset into the native heap - // "assembly": load asset as a managed assembly (or debugging information) - // "resource": load asset as a managed resource assembly - // "icu": load asset as an ICU data archive - // "vfs": load asset into the virtual filesystem (for fopen, File.Open, etc) - // load_remote: (optional) if true, an attempt will be made to load the asset - // from each location in @args.remote_sources. - // virtual_path: (optional) if specified, overrides the path of the asset in - // the virtual filesystem and similar data structures once loaded. - // is_optional: (optional) if true, any failure to load this asset will be ignored. - // loaded_cb: (required) a function () invoked when loading has completed. - // fetch_file_cb: (optional) a function (string) invoked to fetch a given file. - // If no callback is provided a default implementation appropriate for the current - // environment will be selected (readFileSync in node, fetch elsewhere). - // If no default implementation is available this call will fail. - // remote_sources: (optional) additional search locations for assets. - // sources will be checked in sequential order until the asset is found. - // the string "./" indicates to load from the application directory (as with the - // files in assembly_list), and a fully-qualified URL like "https://example.com/" indicates - // that asset loads can be attempted from a remote server. Sources must end with a "/". - // environment_variables: (optional) dictionary-style Object containing environment variables - // runtime_options: (optional) array of runtime options as strings - // aot_profiler_options: (optional) dictionary-style Object. see the comments for - // mono_wasm_init_aot_profiler. If omitted, aot profiler will not be initialized. - // coverage_profiler_options: (optional) dictionary-style Object. see the comments for - // mono_wasm_init_coverage_profiler. If omitted, coverage profiler will not be initialized. - // globalization_mode: (optional) configures the runtime's globalization mode: - // "icu": load ICU globalization data from any runtime assets with behavior "icu". - // "invariant": operate in invariant globalization mode. - // "auto" (default): if "icu" behavior assets are present, use ICU, otherwise invariant. - // diagnostic_tracing: (optional) enables diagnostic log messages during startup mono_load_runtime_and_bcl_args: function (args: MonoRuntimeArgs): void { try { return MONO._load_assets_and_runtime (args); diff --git a/src/mono/wasm/runtime/types/Module.d.ts b/src/mono/wasm/runtime/types/Module.d.ts index e4a19a5ef5905..78e90d460c06d 100644 --- a/src/mono/wasm/runtime/types/Module.d.ts +++ b/src/mono/wasm/runtime/types/Module.d.ts @@ -62,12 +62,12 @@ type MonoConfig = { // Types of assets that can be in the mono-config.js/mono-config.json file (taken from /src/tasks/WasmAppBuilder/WasmAppBuilder.cs) type AssetEntry = { - behavior: AssetBehaviours, - name: string, - virtual_path?: string, + name: string, // the name of the asset, including extension. + behavior: AssetBehaviours, // determines how the asset will be handled once loaded + virtual_path?: string, // if specified, overrides the path of the asset in the virtual filesystem and similar data structures once loaded. culture?: Culture, - load_remote?: boolean, - is_optional?: boolean + load_remote?: boolean, // if true, an attempt will be made to load the asset from each location in @args.remote_sources. + is_optional?: boolean // if true, any failure to load this asset will be ignored. } interface AssemblyEntry extends AssetEntry { @@ -91,11 +91,11 @@ interface IcuData extends AssetEntry { // Note that since these are annoated as `declare const enum` they are replaces by tsc with their raw value during compilation declare const enum AssetBehaviours { - Resource = "resource", - Assembly = "assembly", - Heap = "heap", - ICU = "icu", - VFS = "vfs", + Resource = "resource", // load asset as a managed resource assembly + Assembly = "assembly", // load asset as a managed assembly (or debugging information) + Heap = "heap", // store asset into the native heap + ICU = "icu", // load asset as an ICU data archive + VFS = "vfs", // load asset into the virtual filesystem (for fopen, File.Open, etc) } type Culture = "ar_SA" | "am_ET" | "bg_BG" | "bn_BD" | "bn_IN" | "ca_AD" | "ca_ES" | "cs_CZ" | "da_DK" | diff --git a/src/mono/wasm/runtime/types/binding-types.d.ts b/src/mono/wasm/runtime/types/binding-types.d.ts index 05d5f91c7840a..4c5f9d7107293 100644 --- a/src/mono/wasm/runtime/types/binding-types.d.ts +++ b/src/mono/wasm/runtime/types/binding-types.d.ts @@ -85,14 +85,18 @@ declare var BINDING: typeof BindingSupportLib.$BINDING & BINDING_C_FUNCS & BINDI // OTHER TYPES /////////////////////////////////////////////////////////////////////// type JSObject = { + __js_handle__?: number, + __mono_js_cont__?: number, __mono_gchandle__?: number, __mono_jshandle__?: number, __mono_bound_tcs__?: number, + __mono_delegate_invoke__?: number, __owns_handle__?: boolean, - __mono_delegate_alive__?: boolean, - __mono_js_cont__?: number, + __is_mono_proxied__?: boolean, is_mono_bridged_obj?: boolean, - then?: Function + __mono_delegate_alive__?: boolean, + __mono_delegate_invoke_sig__?: ArgsMarshalString + then?: Function, }; type Converter = { diff --git a/src/mono/wasm/runtime/types/general-types.d.ts b/src/mono/wasm/runtime/types/general-types.d.ts index 153e8babd8fd9..5d94481c7e6c1 100644 --- a/src/mono/wasm/runtime/types/general-types.d.ts +++ b/src/mono/wasm/runtime/types/general-types.d.ts @@ -27,4 +27,5 @@ declare function mergeInto(a: object, b: object); // Joins the various file specific C functions into 1 interface for easier access interface C_FUNCS extends BINDING_C_FUNCS, DOTNET_C_FUNCS, MONO_C_FUNCS {} -type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array + +type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; diff --git a/src/mono/wasm/runtime/types/mono-types.d.ts b/src/mono/wasm/runtime/types/mono-types.d.ts index 9d1fc75627e19..3157051408a29 100644 --- a/src/mono/wasm/runtime/types/mono-types.d.ts +++ b/src/mono/wasm/runtime/types/mono-types.d.ts @@ -44,45 +44,58 @@ interface MONO_VARS { declare var MONO: typeof MonoSupportLib.$MONO & MONO_C_FUNCS & MONO_VARS & DEBUG_C_FUNCS & DEBUG_VARS; // Debug ones are from debugger-types.d.ts // OTHER TYPES /////////////////////////////////////////////////////////////////////// +type RuntimeOptions = string[]; +type EnvVars = { + [i: string]: string; +} +type AOTProfilerOptions = { + write_at?: string, // should be in the format ::, default: 'WebAssembly.Runtime::StopProfile' + send_to?: string // should be in the format ::, default: 'WebAssembly.Runtime::DumpAotProfileData' (DumpAotProfileData stores the data into Module.aot_profile_data.) +} +type CoverageProfilerOptions = { + write_at?: string, // should be in the format ::, default: 'WebAssembly.Runtime::StopProfile' + send_to?: string // should be in the format ::, default: 'WebAssembly.Runtime::DumpCoverageProfileData' (DumpCoverageProfileData stores the data into Module.coverage_profile_data.) +} type FetchRequest = (asset: string) => Promise<{ ok: boolean, url: string, arrayBuffer: () => Promise -}>; +}> declare const enum GlobalizationMode { - ICU = "icu", - INVARIANT = "invariant", - AUTO = "auto" + ICU = "icu", // load ICU globalization data from any runtime assets with behavior "icu". + INVARIANT = "invariant", // operate in invariant globalization mode. + AUTO = "auto" // (default): if "icu" behavior assets are present, use ICU, otherwise invariant. } -type LoadedFiles = { - url: string, - file: string, -}[]; type ManagedPointer = number; // - address in the managed heap type MonoRuntimeArgs = { - fetch_file_cb: FetchRequest, - loaded_cb: () => void, - debug_level: number, - assembly_root: string, - assets: AssetEntry[], - globalization_mode?: GlobalizationMode, - enable_debugging?: number, - assembly_list?: any, - runtime_assets?: any, - runtime_asset_sources?: any, - diagnostic_tracing?: any - remote_sources?: string[], - environment_variables?: object, - runtime_options?: object, - aot_profiler_options?: object, - coverage_profiler_options?: object, + assembly_root: string, // the subfolder containing managed assemblies and pdbs + assets: AssetEntry[], // a list of assets to load along with the runtime. each asset is a dictionary-style Object with the following properties: + loaded_cb: () => void, // a function invoked when loading has completed + debug_level?: number, // Either this or the next one needs to be set + enable_debugging?: number, // Either this or the previous one needs to be set + fetch_file_cb?: FetchRequest, // a function (string) invoked to fetch a given file. If no callback is provided a default implementation appropriate for the current environment will be selected (readFileSync in node, fetch elsewhere). If no default implementation is available this call will fail. + globalization_mode?: GlobalizationMode, // configures the runtime's globalization mode + assembly_list?: any, // obsolete but necessary for the check + runtime_assets?: any, // obsolete but necessary for the check + runtime_asset_sources?: any, // obsolete but necessary for the check + diagnostic_tracing?: boolean // enables diagnostic log messages during startup + remote_sources?: string[], // additional search locations for assets. Sources will be checked in sequential order until the asset is found. The string "./" indicates to load from the application directory (as with the files in assembly_list), and a fully-qualified URL like "https://example.com/" indicates that asset loads can be attempted from a remote server. Sources must end with a "/". + environment_variables?: EnvVars, // dictionary-style Object containing environment variables + runtime_options?: RuntimeOptions, // array of runtime options as strings + aot_profiler_options?: AOTProfilerOptions, // dictionary-style Object. If omitted, aot profiler will not be initialized. + coverage_profiler_options?: CoverageProfilerOptions, // dictionary-style Object. If omitted, coverage profiler will not be initialized. } +type LoadedFiles = { + url: string, + file: string, +}[]; + type NativePointer = number; // - address in wasm memory type WasmEvent = { @@ -116,6 +129,7 @@ type WasmRootBuffer = { get: (index: number) => ManagedPointer, set: (index: number, value: number) => void, release: () => void, + clear: () => void, } type ByteReader = { From e93c8f5a644354d62356418c7fd409263d332a9a Mon Sep 17 00:00:00 2001 From: Daniel-Genkin Date: Mon, 26 Jul 2021 10:56:43 -0400 Subject: [PATCH 17/19] Addressed PR comments --- src/mono/wasm/runtime/binding-support.ts | 66 +++++++++---------- .../wasm/runtime/types/binding-types.d.ts | 6 +- 2 files changed, 36 insertions(+), 36 deletions(-) diff --git a/src/mono/wasm/runtime/binding-support.ts b/src/mono/wasm/runtime/binding-support.ts index 512be984751e7..44b1f9a6d9864 100644 --- a/src/mono/wasm/runtime/binding-support.ts +++ b/src/mono/wasm/runtime/binding-support.ts @@ -411,49 +411,49 @@ var BindingSupportLib = { }, /** @returns return type is determined by the type parameter */ - _unbox_mono_obj_root_with_known_nonprimitive_type: function (root: WasmRoot, type: CNonPrimativeTypes): number | string | boolean | JSObject | Promise | Date | Function { + _unbox_mono_obj_root_with_known_nonprimitive_type: function (root: WasmRoot, type: CNonPrimitiveTypes): number | string | boolean | JSObject | Promise | Date | Function { if (root.value === undefined) throw new Error(`Expected a root but got ${root}`); //See MARSHAL_TYPE_ defines in driver.c switch (type) { - case CNonPrimativeTypes.Int64: - case CNonPrimativeTypes.UInt64: + case CNonPrimitiveTypes.Int64: + case CNonPrimitiveTypes.UInt64: // TODO: Fix this once emscripten offers HEAPI64/HEAPU64 or can return them throw new Error ("int64 not available"); - case CNonPrimativeTypes.String: - case CNonPrimativeTypes.Char: // interned string + case CNonPrimitiveTypes.String: + case CNonPrimitiveTypes.Char: // interned string return BINDING.conv_string (root.value); - case CNonPrimativeTypes.VTS: + case CNonPrimitiveTypes.VTS: throw new Error ("no idea on how to unbox value types"); - case CNonPrimativeTypes.Delegate: + case CNonPrimitiveTypes.Delegate: return BINDING._unbox_delegate_root (root); - case CNonPrimativeTypes.Task: + case CNonPrimitiveTypes.Task: return BINDING._unbox_task_root (root); - case CNonPrimativeTypes.Ref: + case CNonPrimitiveTypes.Ref: return BINDING.extract_js_obj_root (root); - case CNonPrimativeTypes.Int8Array: - case CNonPrimativeTypes.Uint8Array: - case CNonPrimativeTypes.Uint8ClampedArray: - case CNonPrimativeTypes.Int16Array: - case CNonPrimativeTypes.UInt16Array: - case CNonPrimativeTypes.Int32Array: - case CNonPrimativeTypes.UInt32Array: - case CNonPrimativeTypes.Float32Array: - case CNonPrimativeTypes.Float64Array: + case CNonPrimitiveTypes.Int8Array: + case CNonPrimitiveTypes.Uint8Array: + case CNonPrimitiveTypes.Uint8ClampedArray: + case CNonPrimitiveTypes.Int16Array: + case CNonPrimitiveTypes.UInt16Array: + case CNonPrimitiveTypes.Int32Array: + case CNonPrimitiveTypes.UInt32Array: + case CNonPrimitiveTypes.Float32Array: + case CNonPrimitiveTypes.Float64Array: throw new Error ("Marshalling of primitive arrays are not supported. Use the corresponding TypedArray instead."); - case CNonPrimativeTypes.DateTime: // clr .NET DateTime + case CNonPrimitiveTypes.DateTime: // clr .NET DateTime var dateValue = BINDING.call_method(BINDING.get_date_value, null, "m", [ root.value ]); return new Date(dateValue); - case CNonPrimativeTypes.DateTimeOffset: // clr .NET DateTimeOffset + case CNonPrimitiveTypes.DateTimeOffset: // clr .NET DateTimeOffset var dateoffsetValue = BINDING._object_to_string (root.value); return dateoffsetValue; - case CNonPrimativeTypes.Uri: // clr .NET Uri + case CNonPrimitiveTypes.Uri: // clr .NET Uri var uriValue = BINDING._object_to_string (root.value); return uriValue; - case CNonPrimativeTypes.SafeHandle: // clr .NET SafeHandle + case CNonPrimitiveTypes.SafeHandle: // clr .NET SafeHandle return BINDING._unbox_safehandle_root (root); - case CNonPrimativeTypes.Undefined: + case CNonPrimitiveTypes.Undefined: return undefined; default: throw new Error (`no idea on how to unbox object kind ${type} at offset ${root.value} (root address is ${root.get_address()})`); @@ -466,17 +466,17 @@ var BindingSupportLib = { var type = BINDING.mono_wasm_try_unbox_primitive_and_get_type (root.value, BINDING._unbox_buffer); switch (type) { - case CPrimativeTypes.Int: + case CPrimitiveTypes.Int: return Module.HEAP32[BINDING._unbox_buffer / 4]; - case CPrimativeTypes.UInt32: + case CPrimitiveTypes.UInt32: return Module.HEAPU32[BINDING._unbox_buffer / 4]; - case CPrimativeTypes.Float32: + case CPrimitiveTypes.Float32: return Module.HEAPF32[BINDING._unbox_buffer / 4]; - case CPrimativeTypes.Float64: + case CPrimitiveTypes.Float64: return Module.HEAPF64[BINDING._unbox_buffer / 8]; - case CPrimativeTypes.Bool: + case CPrimitiveTypes.Bool: return (Module.HEAP32[BINDING._unbox_buffer / 4]) !== 0; - case CPrimativeTypes.Char: + case CPrimitiveTypes.Char: return String.fromCharCode(Module.HEAP32[BINDING._unbox_buffer / 4]); default: return BINDING._unbox_mono_obj_root_with_known_nonprimitive_type (root, type); @@ -1276,7 +1276,7 @@ var BindingSupportLib = { if (!method) throw new Error ("no method specified"); - var needs_converter = BINDING._verify_args_for_method_call (args_marshal, args); + const needs_converter = BINDING._verify_args_for_method_call (args_marshal, args); var buffer = 0, converter = null, argsRootBuffer = null; var is_result_marshaled = true; @@ -1289,7 +1289,7 @@ var BindingSupportLib = { argsRootBuffer = BINDING._get_args_root_buffer_for_method_call (converter); - var scratchBuffer = BINDING._get_buffer_for_method_call (converter); + const scratchBuffer = BINDING._get_buffer_for_method_call (converter); buffer = converter.compiled_variadic_function (scratchBuffer, argsRootBuffer, method, args); } @@ -1486,7 +1486,7 @@ var BindingSupportLib = { } } - var delegateRoot = MONO.mono_wasm_new_root (BINDING.extract_mono_obj (delegate_obj)); + const delegateRoot = MONO.mono_wasm_new_root (BINDING.extract_mono_obj (delegate_obj)); try { if (typeof delegate_obj.__mono_delegate_invoke__ === "undefined") delegate_obj.__mono_delegate_invoke__ = BINDING.mono_wasm_get_delegate_invoke(delegateRoot.value); @@ -1543,7 +1543,7 @@ var BindingSupportLib = { call_static_method: function (fqn: string, args: any[], signature: ArgsMarshalString | null): number { BINDING.bindings_lazy_init (); - var method = BINDING.resolve_method_fqn (fqn); + const method = BINDING.resolve_method_fqn (fqn); if (typeof signature === "undefined") signature = Module.mono_method_get_call_signature (method); diff --git a/src/mono/wasm/runtime/types/binding-types.d.ts b/src/mono/wasm/runtime/types/binding-types.d.ts index 4c5f9d7107293..258e1e01c75c0 100644 --- a/src/mono/wasm/runtime/types/binding-types.d.ts +++ b/src/mono/wasm/runtime/types/binding-types.d.ts @@ -31,7 +31,7 @@ interface BINDING_C_FUNCS { mono_wasm_register_bundled_satellite_assemblies (): void; mono_wasm_string_array_new (a: number): number; mono_wasm_string_from_utf16 (a: number, b: number): number; - mono_wasm_try_unbox_primitive_and_get_type (a: number, b: number): CPrimativeTypes; + mono_wasm_try_unbox_primitive_and_get_type (a: number, b: number): CPrimitiveTypes; mono_typed_array_new (a: number, b: number, c: number, d: number): number; } @@ -130,7 +130,7 @@ declare const enum ConverterStepIndirects { Int64 = "i64", } -declare const enum CNonPrimativeTypes { +declare const enum CNonPrimitiveTypes { String = 3, VTS = 4, // throws errors due to "no idea on how to unbox value types" Delegate = 5, @@ -155,7 +155,7 @@ declare const enum CNonPrimativeTypes { Undefined = 30 } -declare const enum CPrimativeTypes { +declare const enum CPrimitiveTypes { Int = 1, Float64 = 2, Bool = 8, From 359856e5dacff623b4cee6265a3a0050ebe5182b Mon Sep 17 00:00:00 2001 From: Daniel-Genkin Date: Mon, 26 Jul 2021 17:21:14 -0400 Subject: [PATCH 18/19] Added typescript to windows build (Thanks Radek) --- eng/pipelines/common/global-build-job.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/eng/pipelines/common/global-build-job.yml b/eng/pipelines/common/global-build-job.yml index 84f1786bd2171..0981f4ff0c5dc 100644 --- a/eng/pipelines/common/global-build-job.yml +++ b/eng/pipelines/common/global-build-job.yml @@ -130,6 +130,13 @@ jobs: displayName: Disk Usage before Build - ${{ if eq(parameters.nameSuffix, 'Browser_wasm_Windows') }}: + - task: NodeTool@0 + inputs: + versionSpec: 14.x + + - script: npm install -g typescript + displayName: Install typescript + # Update machine certs - task: PowerShell@2 displayName: Update machine certs From 380cfa2abd2f7a398fca765334cf921a0f5a8e82 Mon Sep 17 00:00:00 2001 From: Daniel-Genkin Date: Thu, 29 Jul 2021 10:45:33 -0400 Subject: [PATCH 19/19] Slightly better type for function --- src/mono/wasm/runtime/binding-support.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/mono/wasm/runtime/binding-support.ts b/src/mono/wasm/runtime/binding-support.ts index aac8f0896e5c5..504307a4f8bf4 100644 --- a/src/mono/wasm/runtime/binding-support.ts +++ b/src/mono/wasm/runtime/binding-support.ts @@ -161,7 +161,7 @@ var BindingSupportLib = { BINDING._js_owned_object_registry = new FinalizationRegistry(BINDING._js_owned_object_finalized.bind(this)); }, - _get_weak_delegate_from_handle: function (id: number): Function { + _get_weak_delegate_from_handle: function (id: number): (a: JSObject) => void { var result = null; // Look up this handle in the weak delegate table, and if we find a matching weakref, @@ -183,7 +183,7 @@ var BindingSupportLib = { // and register it with the finalization registry so that the C# side can release // the associated object references if (!result) { - result = (arg1) => { + result = (arg1: JSObject): void => { if (!BINDING.try_invoke_js_owned_delegate_by_handle(id, arg1)) // Because lifetime is managed by JavaScript, it *is* an error for this // invocation to ever fail. If we have a JS wrapper for an ID, there