description |
---|
Let's attempt the unthinkable, shall we? |
AssemblyScript compiles a strict subset of TypeScript (a typed superset of JavaScript) to WebAssembly using Binaryen, looking like:
{% tabs %} {% tab title="fib.ts" %}
export function fib(n: i32): i32 {
var a = 0, b = 1
for (let i = 0; i < n; i++) {
let t = a + b; a = b; b = t
}
return b
}
{% endtab %} {% endtabs %}
$> asc fib.ts -b fib.wasm -O3
Its architecture differs from a JavaScript VM in that it compiles a program ahead of time, quite similar to other static compilers. On top of WebAssembly types, it provides both low-level built-ins to access WebAssembly features directly as well as a JavaScript-like standard library on top of a relatively small managed runtime enabling the creation of programs that look and feel much like TypeScript.
For example, on the lowest level, memory can be accessed using the load<T>(offset)
and store<T>(offset, value)
built-ins that compile to WebAssembly instructions directly
store<i32>(8, load<i32>(0) + load<i32>(4))
while the standard library provides implementations of ArrayBuffer
, Uint8Array
, String
, Map
etc. on a higher level:
var view = new Int32Array(12)
view[2] = view[0] + view[1]
The compiler still has its limitations and we are still waiting for WebAssembly features that are currently undergoing specification (marked as ๐ฆ throughout the documentation) to unleash its full potential. But it is open source and everyone can contribute, so we are getting there.
Sounds appealing to you? Read on!