[Wasm] Add ability to choose flavor for the wasm launcher

This commit is contained in:
Igor Laevsky
2021-10-22 20:07:42 +03:00
parent cb10bd3a95
commit 43eeaa925f
3 changed files with 31 additions and 1 deletions
@@ -235,6 +235,13 @@ class K2JSCompilerArguments : CommonCompilerArguments() {
@Argument(value = "-Xwasm-debug-info", description = "Add debug info to WebAssembly compiled module")
var wasmDebug: Boolean by FreezableVar(false)
@Argument(
value = "-Xwasm-launcher",
valueDescription = "esm|nodejs",
description = "Picks flavor for the wasm launcher. Default is ESM."
)
var wasmLauncher: String? by NullableStringFreezableVar("esm")
override fun configureLanguageFeatures(collector: MessageCollector): MutableMap<LanguageFeature, LanguageFeature.State> {
return super.configureLanguageFeatures(collector).apply {
if (extensionFunctionsInExternals) {
@@ -61,6 +61,7 @@ import org.jetbrains.kotlin.utils.fileUtils.withReplacedExtensionOrNull
import org.jetbrains.kotlin.utils.join
import java.io.File
import java.io.IOException
import java.lang.IllegalArgumentException
enum class ProduceKind {
DEFAULT, // Determine what to produce based on js-v1 options
@@ -320,7 +321,7 @@ class K2JsIrCompiler : CLICompiler<K2JSCompilerArguments>() {
val outputWatFile = outputFile.withReplacedExtensionOrNull(outputFile.extension, "wat")!!
outputWatFile.writeText(res.wat)
val runner = """
val esmRunner = """
export default WebAssembly.instantiateStreaming(fetch('${outputWasmFile.name}'), { runtime, js_code }).then((it) => {
wasmInstance = it.instance;
wasmInstance.exports.__init?.();
@@ -330,6 +331,27 @@ class K2JsIrCompiler : CLICompiler<K2JSCompilerArguments>() {
});
""".trimIndent()
val nodeRunner = """
const fs = require('fs');
var path = require('path');
const wasmBuffer = fs.readFileSync(path.resolve(__dirname, './${outputWasmFile.name}'));
module.exports = WebAssembly.instantiate(wasmBuffer, { runtime, js_code }).then(wasm => {
wasmInstance = wasm.instance;
wasmInstance.exports.__init?.();
wasmInstance.exports.startUnitTests?.();
return wasmInstance.exports
});
""".trimIndent()
val runner = when (arguments.wasmLauncher) {
"esm" -> esmRunner
"nodejs" -> nodeRunner
else -> throw IllegalArgumentException("Unrecognized flavor for the wasm launcher")
}
outputFile.writeText(res.js + "\n" + runner)
return OK
}
+1
View File
@@ -37,6 +37,7 @@ where advanced options include:
-Xtyped-arrays Translate primitive arrays to JS typed arrays
-Xwasm Use experimental WebAssembly compiler backend
-Xwasm-debug-info Add debug info to WebAssembly compiled module
-Xwasm-launcher=esm|nodejs Picks flavor for the wasm launcher. Default is ESM.
-Xallow-kotlin-package Allow compiling code in package 'kotlin' and allow not requiring kotlin.stdlib in module-info
-Xallow-result-return-type Allow compiling code when `kotlin.Result` is used as a return type
-Xbuiltins-from-sources Compile builtIns from sources