Chasm is a WebAssembly runtime built on Kotlin Multiplatform.
The runtime targets the latest wasm specification and supports all instructions with the exception of VectorInstructions.
Additionally, the runtime supports the following proposals
- Tail Call
- Extended Constant Expressions
- Typed Function References
- Wasm GC
- Multiple Memories
- Exception Handling
dependencies {
implementation("io.github.charlietap.chasm:chasm:0.9.2")
}
Webassembly compilations output a Module encoded as either a .wasm or .wat file, currently chasm supports decoding only .wasm binaries
val wasmFileAsByteArray = ...
val result = module(wasmFileAsByteArray)
Once a module has been decoded you'll need to instantiate it, and for that you'll need also need a store
val store = store()
val result = instance(store, module)
Instances allow you to invoke functions that are exported from the module
val result = invoke(store, instance, "fibonacci")
Modules often depend on imports, imports can be one of the following:
- Functions
- Globals
- Memories
- Tables
- Tags
For the most part imports will actually be exports from other modules, this is the mechanism that wasm uses to share data/behaviour between modules. However you can also allocate them separately using the factory functions:
val function = function(store, functionType, hostFunction)
val global = global(store, globalType, initialValue)
val memory = memory(store, memoryType)
val table = table(store, tableType, initialValue)
val tag = tag(store, tagType)
Once you have your importables you can pass them in at instantiation time.
val import = Import(
"import module name",
"import entity name",
function,
)
val result = instance(store, module, listOf(import))
Host functions are kotlin functions that can be called by wasm programs at runtime. The majority of host functions represent system calls, WASI for example is intended to be integrated as imports of host functions.
Allocation of a host function requires a FunctionType
The function type describes the inputs and outputs of your function so the runtime can call it and use its results
Once you have defined a function type you can allocate the host function like so
val functionType = FunctionType(emptyList(), listOf(ValueType.Number.I32))
val hostFunction = HostFunction { params ->
println("Hello world")
listOf(Value.Number.I32(117))
}
val result = function(store, funcType, hostFunction)
This project is dual-licensed under both the MIT and Apache 2.0 licenses. You can choose which one you want to use the software under.
- For details on the MIT license, please see the LICENSE-MIT file.
- For details on the Apache 2.0 license, please see the LICENSE-APACHE file.