TExcelTAD
Home › WebAssembly › AssemblyScript

AssemblyScript

AssemblyScript is a language designed specifically for WebAssembly. Its syntax is TypeScript's, but its types are Wasm's: i32, u32, i64, f32, f64, bool, plus managed string, arrays and classes. For JavaScript developers it's the gentlest way to write Wasm without learning C++ or Rust.

bash
npm install --save-dev assemblyscript
npx asinit .                         # creates assembly/index.ts, asconfig.json, tests
npm run asbuild                      # -> build/release.wasm (+ .wat, .js bindings, .d.ts)

Looks like TypeScript, compiles like C

ts
// assembly/index.ts
export function fib(n: i32): i32 {
  let a: i32 = 0, b: i32 = 1;
  for (let i = 0; i < n; i++) {
    const t = a + b;
    a = b;
    b = t;
  }
  return a;
}

export function average(values: Float64Array): f64 {
  let sum = 0.0;
  for (let i = 0; i < values.length; i++) sum += values[i];
  return sum / values.length;
}

Because every type is static and maps to a Wasm type, fib compiles almost one-to-one. The --textFile option (build/release.wat) shows something very close to this:

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (func $fib (export "fib") (param $n i32) (result i32)
    (local $a i32) (local $b i32) (local $i i32) (local $t i32)
    (local.set $b (i32.const 1))
    (block $break
      (loop $continue
        (br_if $break (i32.ge_s (local.get $i) (local.get $n)))
        (local.set $t (i32.add (local.get $a) (local.get $b)))
        (local.set $a (local.get $b))
        (local.set $b (local.get $t))
        (local.set $i (i32.add (local.get $i) (i32.const 1)))
        (br $continue)))
    (local.get $a))
  (func (export "main")
    (call $log (call $fib (i32.const 10)))
    (call $log (call $fib (i32.const 40)))
    (call $log (call $fib (i32.const 47)))))     ;; overflows i32, just like the AS code would
55
102334155
-1323752223

fib(47) is 2971215073, which exceeds the i32 range, so it wraps, exactly as the AssemblyScript type i32 promises. In TypeScript the same code would produce a float; that's the big semantic difference.

Differences from TypeScript

TypeScript AssemblyScript
number (always f64) choose i32, u8, i64, f32, f64, … (number is an alias for f64)
any, union types, undefined not supported: everything is statically typed
objects are dynamic classes have a fixed layout in linear memory
5 / 2 === 2.5 5 / 2 with i32 operands is 2
closures capturing locals limited support
JS standard library an AssemblyScript standard library (Math, String, Array, Map, …) compiled into the module

Strings are UTF-16 in memory

AssemblyScript strings live in linear memory in UTF-16, like JavaScript strings, with a hidden header that stores the byte length just before the string's address. The generated JS bindings read them like this:

js · try it yourself
// Simulate an AssemblyScript string in linear memory:
// [ ... header: rtSize (byte length) at ptr - 4 ... ][ UTF-16LE code units at ptr ... ]
const memory = new ArrayBuffer(64);
const text = 'Grüße!';
const ptr = 20;
const view = new DataView(memory);
view.setUint32(ptr - 4, text.length * 2, true);           // byte length
for (let i = 0; i < text.length; i++) view.setUint16(ptr + i * 2, text.charCodeAt(i), true);

// What the loader does to "lift" the string into JS:
function liftString(buffer, pointer) {
  const byteLength = new DataView(buffer).getUint32(pointer - 4, true);
  return new TextDecoder('utf-16le').decode(new Uint8Array(buffer, pointer, byteLength));
}
console.log(liftString(memory, ptr));
console.log('bytes in memory:', new DataView(memory).getUint32(ptr - 4, true));
console.log([...new Uint8Array(memory, ptr, 6)]);         // G, r, ü as UTF-16LE
Grüße!
bytes in memory: 12
[ 71, 0, 114, 0, 252, 0 ]

Since AssemblyScript and JavaScript share the UTF-16 representation, converting strings is a straight copy with no re-encoding.

Memory management

AssemblyScript has a built-in garbage collector (the incremental --runtime incremental, or minimal/stub for small modules). Unlike Rust or C you don't free objects yourself. The collector runs inside the module, in linear memory: it's not the browser's GC.

Using it from JavaScript

The compiler emits ES module bindings that handle strings and arrays:

js
import { fib, average } from './build/release.js';
console.log(fib(10));                                   // 55
console.log(average(new Float64Array([1, 2, 3, 4])));   // 2.5

When to choose AssemblyScript

  • Good fit: number-crunching kernels (image filters, codecs, physics), small plug-ins, teams that know TypeScript.
  • Less suited: code that depends on the npm ecosystem or dynamic JavaScript patterns; huge applications where Rust or C++ libraries already exist.

Test yourself

In AssemblyScript, what is 7 / 2 when both operands are i32?

  1. 3.5
  2. 3
  3. 4
  4. It doesn't compile

How are AssemblyScript strings stored?

  1. As JS strings outside Wasm
  2. UTF-8 with a zero terminator
  3. UTF-16 in linear memory, with the length in a header before the pointer
  4. As externref

Which TypeScript feature is NOT available in AssemblyScript?

  1. Classes
  2. Generics
  3. any and union types
  4. for loops