Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 38 ยท The Text Format

Functions, Locals and Calls

Learn WebAssembly functions: signatures, call, recursion, mutual recursion, multiple return values, early return, exports by name, and what happens on stack overflow.

Functions are the unit of code in WebAssembly. Every function has a signature (its parameter types and result types), a set of locals and a body of instructions. Functions are always module-level: there are no nested or anonymous functions, and no closures. A function can call any other function of the same module (or an imported one) by index, directly with call, or indirectly through a table with call_indirect.

Anatomy of a function

WAT
(func $name (export "exportName")
  (param $a i32) (param $b f64)
  (result i64)
  (local $tmp i32)
  ;; instructions...
)
  • $name is the optional identifier; it is how other functions call this one.
  • (export "exportName") is the shorthand for exporting it. You can also write (export "other" (func $name)) as a separate field, which lets you export the same function under several names.
  • (param ...) and (result ...) build the type. Identical signatures share one entry in the type section.
  • Parameters are locals 0..n-1. Declared locals follow and start at zero (or null for references).

Calling is simple: push the arguments in order, then call $name. The callee pops them and pushes its results.

WAT
(func $square (param $x i32) (result i32)
  (i32.mul (local.get $x) (local.get $x)))

(func (export "sumSquares") (param $a i32) (param $b i32) (result i32)
  (i32.add (call $square (local.get $a)) (call $square (local.get $b))))

Recursion

Functions may call themselves, and mutually recursive functions may call each other, in any order of definition. Names are resolved after the whole module has been read, so $isEven can call $isOdd before it is declared.

WAT
(func $fib (export "fib") (param $n i32) (result i32)
  (if (result i32) (i32.lt_s (local.get $n) (i32.const 2))
    (then (local.get $n))
    (else
      (i32.add
        (call $fib (i32.sub (local.get $n) (i32.const 1)))
        (call $fib (i32.sub (local.get $n) (i32.const 2)))))))

Recursion depth is limited by the engine's call stack, which is separate from the module's linear memory. Infinite recursion does not crash the browser tab or corrupt anything; the engine throws a catchable error, as you will see below.

Several results

Since the multi-value feature (supported by all current engines), a function can return more than one value. The results are left on the stack, in order:

WAT
(func (export "divmod") (param $a i32) (param $b i32) (result i32 i32)
  (i32.div_s (local.get $a) (local.get $b))
  (i32.rem_s (local.get $a) (local.get $b)))

From JavaScript a multi-value export returns an array. Compilers use this to return small structs (a Rust (u32, u32) tuple, for instance) without going through memory.

Early exit

return leaves the function immediately with the values currently on top of the stack. It is the same as branching to the function's outermost label, and it works from inside blocks and loops:

WAT
(func (export "early") (param $x i32) (result i32)
  (if (i32.lt_s (local.get $x) (i32.const 0))
    (then (return (i32.const -1))))
  (i32.mul (local.get $x) (i32.const 2)))

Running the module

The hex below is the output of wat2wasm for a module with all of the functions above, plus swap (returns its two parameters in reverse order), isEven and isOdd (mutual recursion) and a forever function that calls itself without end.

Node.js call, recursion, multi-value and stack overflow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two safety rules showed up. Integer division by zero traps (RuntimeError), unlike floating-point division, which gives Infinity. And unbounded recursion ends with a RangeError thrown by the host, because stack depth is a resource of the engine, not of the module.

Building a call by hand

In the binary, call is opcode 0x10 followed by a function index. Remember that imports come first in the function index space. Here is a small module made with the byte builder: a hidden helper function double, an exported quad that calls it twice, and a swap with two results.

Node.js The call opcode and multiple results in raw bytes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Design advice

  • Keep exported functions few and coarse. Each call between JavaScript and Wasm has a cost; one call that processes a whole array beats a thousand calls on single numbers.
  • Prefer pure computation in Wasm. Functions that take and return numbers are the cheapest to call.
  • Remember the type of every parameter. JavaScript will happily coerce a string into an i32; the module cannot tell the difference between a deliberate zero and a bad argument.

Exported functions have a length equal to their parameter count and a name equal to their function index as a string, which can make stack traces look like wasm-function[3] unless a name section is present.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a function with (result i32 i32) return to JavaScript?

    Multi-value results come back as a JavaScript array.
  2. 2. What happens on infinite recursion?

    The engine's call stack is bounded and separate from the module's memory, so overflow is caught safely.
  3. 3. What does i32.div_s do when the divisor is 0?

    Integer division by zero traps. Only floating-point division yields Infinity or NaN.
  4. 4. In a function with two parameters and one declared local, what is the local's index?

    Parameters occupy indexes 0 and 1, so the first declared local is 2.

Summary

  • A function has a signature, locals and a body; call it with call, arguments pushed in order.
  • Functions may be recursive and mutually recursive; names resolve after the whole module is read.
  • Functions can have several results, which JavaScript receives as an array.
  • return exits early from anywhere, including inside loops.
  • Integer division by zero traps; runaway recursion throws a RangeError from the host.
  • Fewer, coarser exported functions are faster than many tiny ones.

Next: Memory Instructions