WASM: Crude println implementation with the wasm-native strings

This commit is contained in:
Igor Laevsky
2021-07-23 20:42:48 +03:00
committed by TeamCityServer
parent fc0ae851a2
commit ebde1e5491
3 changed files with 17 additions and 15 deletions
@@ -95,6 +95,8 @@ fun compileWasm(
fun WasmCompiledModuleFragment.generateJs(): String {
val runtime = """
var wasmInstance = null;
const runtime = {
String_getChar(str, index) {
return str.charCodeAt(index);
@@ -130,19 +132,19 @@ fun WasmCompiledModuleFragment.generateJs(): String {
return x;
},
println(value) {
console.log(">>> " + value)
},
importStringToJs(addr, wasmMem) {
const mem16 = new Uint16Array(wasmMem.buffer);
const mem32 = new Int32Array(wasmMem.buffer);
const len = mem32[addr / 4];
const str_start_addr = (addr + 4) / 2
const slice = mem16.slice(str_start_addr, str_start_addr + len);
return String.fromCharCode.apply(null, slice);
println(valueAddr) {
console.log(">>> " + importStringToJs(valueAddr));
}
};
function importStringToJs(addr) {
const mem16 = new Uint16Array(wasmInstance.exports.memory.buffer);
const mem32 = new Int32Array(wasmInstance.exports.memory.buffer);
const len = mem32[addr / 4];
const str_start_addr = (addr + 4) / 2;
const slice = mem16.slice(str_start_addr, str_start_addr + len);
return String.fromCharCode.apply(null, slice);
}
""".trimIndent()
val jsCode =
@@ -149,9 +149,9 @@ abstract class BasicWasmBoxTest(
val testRunner = """
const wasmBinary = read(String.raw`${outputWasmFile.absoluteFile}`, 'binary');
const wasmModule = new WebAssembly.Module(wasmBinary);
const wasmInstance = new WebAssembly.Instance(wasmModule, { runtime, js_code });
wasmInstance = new WebAssembly.Instance(wasmModule, { runtime, js_code });
const actualResult = runtime.importStringToJs(wasmInstance.exports.$testFunction(), wasmInstance.exports.memory);
const actualResult = importStringToJs(wasmInstance.exports.$testFunction());
if (actualResult !== "OK")
throw `Wrong box result '${'$'}{actualResult}'; Expected "OK"`;
""".trimIndent()
+2 -2
View File
@@ -14,7 +14,7 @@ public actual fun println() {
/** Prints the given [message] and the line separator to the standard output stream. */
public actual fun println(message: Any?) {
printlnImpl(message.toString())
printlnImpl(exportStringRet(message.toString()))
}
/** Prints the given [message] to the standard output stream. */
@@ -27,5 +27,5 @@ public actual fun print(message: Any?) {
internal actual interface Serializable
@WasmImport("runtime", "println")
private fun printlnImpl(message: String): Unit =
private fun printlnImpl(messageAddr: Int): Unit =
implementedAsIntrinsic