iTranslated by AI
Trying Out WasmGC
The year 2023 was a landmark year as WasmGC, the specification for adding Garbage Collection (GC) to WebAssembly, was implemented in Chrome and Firefox. WasmGC has been a long-held dream for compiler writers (according to my own mental research), making it easier to run GC-dependent languages on WebAssembly. In 2024, WasmGC is likely to become available in even broader environments. It wouldn't be an exaggeration to call it the "First Year of WasmGC" (and you can never have too many "First Years," after all).
This article is a survey of the current state of WasmGC as of January 2024, from the perspective of a compiler writer. I am a novice regarding WebAssembly myself and am writing this while researching.
Overview and Specifications
For an overview of WasmGC, the following articles by people in the Chrome/V8 community are helpful:
-
A new way to bring garbage collected programming languages efficiently to WebAssembly · V8
- Article by kripken
-
WebAssembly Garbage Collection (WasmGC) now enabled by default in Chrome | Blog | Chrome for Developers
- Seems to be an article for a general audience (overview only)
Traditional Wasm was a low-level affair, as the name "Assembly" suggests, but WasmGC feels like it has completely stepped into the territory of high-level VMs (reminiscent of JVM and others). Is it even "Assembly" anymore?
Several articles have also been published in Japanese:
- WasmGCについて予習する
- WasmGCで導入される型や命令のお勉強
-
Kotlin/Wasmが生成するWasmGCコードを眺める
- The actual code snippets are very informative.
Of course, the specification is the most important part. You can find the specifications here:
- WebAssembly Specifications
-
gc/proposals/gc/MVP.md at main · WebAssembly/gc
- Overview.md in the same directory seems a bit outdated.
Support Status
The support status for WebAssembly feature extensions across various runtimes is summarized here:
The support status I have investigated as of the time of writing this article is as follows:
- Chrome 119 or later
- Firefox 120 or later
- Safari: Not supported
- Wasmtime: Not supported
- Wasmer: Not supported
- Node.js v21.5.0: With
--experimental-wasm-gcflag - Deno v1.39.1/v8 12.0.267.8: Supported?
- Bun v1.0.21: Not supported
While Node.js is supposed to work with the flag, I encountered an error during validation or somewhere else when I actually tried it. For Deno, support isn't explicitly stated, but it worked when I tried it.
With Wasmtime and Wasmer not supporting it, a suspicion begins to grow: "Is WasmGC only being implemented by those who already have a JavaScript engine?" I hope the day comes when independent (?) Wasm runtimes also support GC.
Toolchains
When building a compiler, the compiler itself rarely outputs machine code directly; such tasks are often left to an assembler (with the exception of JIT compilers). Similarly, when targeting WebAssembly, you might want to outsource the part that converts text format (WAT) to binary format. Even if not, having a tool to convert from binary to text format is useful for debugging. Alternatively, when experimenting, you might follow a workflow of writing WAT, converting it, and then running it.
So, I looked for a few tools that might do the job.
-
WebAssembly/wabt: The WebAssembly Binary Toolkit
- It feels like it doesn't properly support the GC proposal yet. Or rather, is only
wasm2cstill active?
- It feels like it doesn't properly support the GC proposal yet. Or rather, is only
-
WebAssembly/binaryen: Optimizer and compiler/toolchain library for WebAssembly
- This looks good. Includes
wasm-opt,wasm-as,wasm-dis, etc. - The input for
wasm-asseems to be a subset of WAT.
- This looks good. Includes
-
WebAssembly/gc: Branch of the spec repo scoped to discussion of GC integration in WebAssembly
- Reference implementation. It seems capable of converting WAT to Wasm.
- Written in OCaml. If you're a compiler developer, you probably have OCaml installed, right?
Simple Example: Boxing an i32
First, let's try creating a struct consisting of a single i32. One way to implement languages with parametric polymorphism is to box primitives like this.
;; test.wat
;; Comments start with two semicolons
(module
(type $boxed-i32 (struct (field i32)))
(func (export "make")
(param $i i32)
(result (ref $boxed-i32))
(struct.new $boxed-i32 (local.get $i))
;; wasm-as doesn't seem to
;; accept writing it like:
;; local.get $i
;; struct.new $boxed-i32
)
(func (export "get")
(param $o (ref $boxed-i32))
(result i32)
(struct.get $boxed-i32 0 (local.get $o))
)
)
Save this as test.wat and assemble it.
$ # When using the reference implementation
$ wasm -d test.wat -o test.wasm
$ # When using binaryen
$ wasm-as --enable-gc --enable-reference-types test.wat
Prepare the JavaScript code to call it as follows:
// run.mjs
import { readFileSync } from "node:fs";
const wasmBuffer = readFileSync("test.wasm");
const wasmModule = await WebAssembly.instantiate(wasmBuffer);
const { make, get } = wasmModule.instance.exports;
const o = make(42);
console.log(o, get(o));
Since node --experimental-wasm-gc --experimental-wasm-stringref run.mjs didn't work well on Node.js, I'll run it with Deno.
$ deno --version
deno 1.39.1 (release, aarch64-apple-darwin)
v8 12.0.267.8
typescript 5.3.3
$ deno run --allow-read run.mjs
[Object: null prototype] {} 42
Looks good.
Closure Example
What is an essential language feature for high-level languages? That's right, closures.
A closure implementation would look like this in a C-like language:
// Implementation corresponding to a type like int -> int
typedef int (*CODE)(struct Closure *c, int);
struct Closure {
CODE code;
void *payload[]; // I've used void * here as a placeholder, but in practice, the types and numbers would correspond to the function's free variables.
};
In other words, it is a pair consisting of a function pointer and an environment. When calling it, the closure itself is passed as the first argument.
Here, we consider a function similar to int -> int. The type definition and invocation process in Wasm can be written as follows:
(module
(rec
(type $code (func (param (ref $closure) i32) (result i32)))
;; (sub ...) is a marker to enable creating subtypes. Without this, it is treated as final.
(type $closure (sub (struct (field (ref $code)))))
)
(func (export "call")
(param $f (ref $closure))
(param $x i32)
(result i32)
(call_ref $code
(local.get $f)
(local.get $x)
(struct.get $closure 0 ;; get f.code
(local.get $f)
)
)
)
;; Continued
Let's also create a function that returns a closure. Here, we will implement a curried version of addition (what would be x => y => x + y in TypeScript).
;; Continued
;; When creating a subtype, enumerate the supertype fields again
(type $closure-with-i32 (sub final $closure (struct (field (ref $code)) (field i32))))
(func $adder-impl
(type $code)
(param $closure (ref $closure))
(param $y i32)
(result i32)
(i32.add
(struct.get $closure-with-i32 1 ;; get env.payload
(ref.cast (ref $closure-with-i32)
(local.get $closure)
)
)
(local.get $y)
)
)
;; Some magic to allow taking a reference to a function (I'm not entirely sure about this)
(elem (ref null $code) (ref.func $adder-impl))
(func (export "adder")
(param $x i32)
(result (ref $closure-with-i32))
(struct.new $closure-with-i32
(ref.func $adder-impl)
(local.get $x)
)
)
)
Prepare the code to call it from JavaScript as well.
// run-closure.mjs
import { readFileSync } from "node:fs";
const wasmBuffer = readFileSync("closure.wasm");
const wasmModule = await WebAssembly.instantiate(wasmBuffer);
const { call, adder } = wasmModule.instance.exports;
const a = adder(42);
console.log(a, call(a, 37));
$ wasm-as --enable-gc --enable-reference-types closure.wat
$ deno run --allow-read run-closure.mjs
[Object: null prototype] {} 79
It worked.
Sum Types
What is another essential language feature for high-level languages? That's right, sum types (tagged unions).
First, an option type like this:
datatype 'a option = NONE | SOME of 'a
might look something like this in WasmGC:
(type $option (sub (struct (field $tag i32))))
(type $option.NONE (sub final $option (struct (field $tag i32))))
(type $option.SOME (sub final $option (struct (field $tag i32) (field $payload anyref))))
Alternatively, using null might be another way.
A general-purpose sum type like this:
datatype ('a,'b) either = LEFT of 'a | RIGHT of 'b
might look like this:
(type $either (sub (struct (field $tag i32))))
(type $either.LEFT (sub final $either (struct (field $tag i32) (field $payload anyref))))
(type $either.RIGHT (sub final $either (struct (field $tag i32) (field $payload anyref))))
Reflections
WasmGC has a decent type system compared to Wasm MVP, so it feels like a significantly different target from a compiler writer's perspective.
Currently, it seems that the only full-fledged runtimes supporting WasmGC are JavaScript engines. This makes me wonder how much merit there is in targeting WasmGC compared to targeting JavaScript directly. Perhaps things like shorter parsing times, faster JIT compilation startup, casual use of i64, SIMD, and so on?
I wish there were tutorials for compiler writers who have only recently become interested in Wasm through WasmGC.
My Standard ML implementation, "LunarML", has already implemented Lua and JavaScript backends, but I am also considering supporting WasmGC. I suspect structural records will be a challenge when compiling data types. I'll have to find a way to manage within the constraints of WasmGC.
Discussion
さっと検索してヒットする https://github.com/bytecodealliance/wasmtime/issues/5032 を読む限り、実装するプランはあるみたいですね。
この記事では言及されてませんがWasmEdgeも進めているようです。